From ee1eadee0f50922d9d88692bbc5ea12a16e0d1fc Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Fri, 13 Mar 2015 07:36:52 +0100 Subject: [PATCH 001/145] add: start to support Topaz tags - hf 14a reader now exits gracefully in case of proprietary anticollision sequence - changed miller decoder to handle Topaz 8 data bits/no parity frames from reader - started to implement hf list topaz --- armsrc/iso14443a.c | 5 +++ armsrc/iso14443a.h | 2 +- client/cmdhf.c | 97 ++++++++++++++++++++++++++++++---------------- client/cmdhf14a.c | 14 ++++++- common/protocols.h | 17 ++++++-- 5 files changed, 96 insertions(+), 39 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index ac839cfd..f52e3eb8 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -1719,6 +1719,11 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u 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. diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index 1e978e88..d99236b2 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -56,7 +56,7 @@ typedef struct { // DROP_FIRST_HALF, } state; uint16_t shiftReg; - uint16_t bitCount; + int16_t bitCount; uint16_t len; uint16_t byteCntMax; uint16_t posCnt; diff --git a/client/cmdhf.c b/client/cmdhf.c index 22063bbb..03d89c0b 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -141,6 +141,23 @@ void annotateIso15693(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) } } + +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; + default: snprintf(exp,size,"?"); break; + } +} + + /** 06 00 = INITIATE 0E xx = SELECT ID (xx = Chip-ID) @@ -255,11 +272,18 @@ uint8_t iclass_CRC_check(bool isResponse, uint8_t* data, uint8_t len) } } + +uint16_t merge_topaz_reader_frames(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t *topaz_reader_command, uint16_t *data_len) +{ + return tracepos; +} + + uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles) { bool isResponse; uint16_t duration, data_len, parity_len; - + uint8_t topaz_reader_command[9]; uint32_t timestamp, first_timestamp, EndOfTransmissionTimestamp; char explanation[30] = {0}; @@ -290,29 +314,35 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui uint8_t *parityBytes = trace + tracepos; tracepos += parity_len; + if (protocol == TOPAZ && !isResponse) { + // topaz reader commands come in 1 or 9 separate frames with 8 Bits each. + // merge them: + tracepos = merge_topaz_reader_frames(tracepos, traceLen, trace, topaz_reader_command, &data_len); + } + //Check the CRC status uint8_t crcStatus = 2; if (data_len > 2) { uint8_t b1, b2; - if(protocol == ICLASS) - { - crcStatus = iclass_CRC_check(isResponse, frame, data_len); - - }else if (protocol == ISO_14443B) - { - 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))) - { + switch (protocol) { + case ICLASS: + crcStatus = iclass_CRC_check(isResponse, frame, data_len); + break; + case ISO_14443B: + case TOPAZ: + crcStatus = iso14443B_CRC_check(isResponse, topaz_reader_command, data_len); + break; + case 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; + default: + break; } } //0 CRC-command, CRC not ok @@ -361,12 +391,13 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui 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); @@ -382,7 +413,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui } else { PrintAndLog(" | | | %-64s| %s| %s", line[j], - (j == num_lines-1)?crc:" ", + (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); } } @@ -425,20 +456,17 @@ int CmdHFList(const char *Cmd) } if(!errors) { - if(strcmp(type, "iclass") == 0) - { + 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{ + } else { errors = true; } } @@ -452,6 +480,7 @@ int CmdHFList(const char *Cmd) 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"); diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index d36ebb8b..8978f43d 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -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,18 @@ int CmdHF14AReader(const char *Cmd) 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]); diff --git a/common/protocols.h b/common/protocols.h index 01b738c2..e687ca7a 100644 --- a/common/protocols.h +++ b/common/protocols.h @@ -168,9 +168,20 @@ NXP/Philips CUSTOM COMMANDS #define ISO15693_READ_MULTI_SECSTATUS 0x2C -#define ISO_14443A 0 -#define ICLASS 1 -#define ISO_14443B 2 +// Topaz command set: +#define TOPAZ_REQA 0x26 // Request +#define TOPAZ_WUPA 0x52 // WakeUp +#define TOPAZ_RID 0x78 // Read ID +#define TOPAZ_RALL 0x00 // Read All (all bytes) +#define TOPAZ_READ 0x01 // Read (a single byte) +#define TOPAZ_WRITE_E 0x53 // Write-with-erase (a single byte) +#define TOPAZ_WRITE_NE 0x1a // Write-no-erase (a single byte) + + +#define ISO_14443A 0 +#define ICLASS 1 +#define ISO_14443B 2 +#define TOPAZ 3 //-- Picopass fuses #define FUSE_FPERS 0x80 From a8904ebd46d747753c9f639f1577694c149ca5c2 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Sun, 15 Mar 2015 16:40:34 +0100 Subject: [PATCH 002/145] Change "hf list topaz" to "hf list nfc" fix: reduce length of expected unmodulated signal in Miller decoder in order to allow decoding of NFC reader communications add: hf list nfc: aggregate reader commands into one line add: hf list nfc: CRC check for NFC communications --- armsrc/iso14443a.c | 2 +- client/cmdhf.c | 72 ++++++++++++++++++++++++++++++++++------------ 2 files changed, 55 insertions(+), 19 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index f52e3eb8..a78dae6e 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -269,7 +269,7 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) if (Uart.state == STATE_UNSYNCD) { // not yet synced - if (Uart.highCnt < 2) { // wait for a stable unmodulated signal + if (Uart.highCnt < 1) { // wait for a stable unmodulated signal if (Uart.twoBits == 0xffff) { Uart.highCnt++; } else { diff --git a/client/cmdhf.c b/client/cmdhf.c index 03d89c0b..f4d76210 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -273,16 +273,55 @@ uint8_t iclass_CRC_check(bool isResponse, uint8_t* data, uint8_t len) } -uint16_t merge_topaz_reader_frames(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t *topaz_reader_command, uint16_t *data_len) +bool is_last_record(uint16_t tracepos, uint8_t *trace, uint16_t traceLen) { - return tracepos; + 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); +} + + +void 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 9 + + uint32_t last_timestamp = timestamp + *duration; + + memcpy(topaz_reader_command, frame, MIN(*data_len, MAX_TOPAZ_READER_CMD_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); + last_timestamp = next_timestamp + *((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 (*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; + } + uint16_t next_parity_len = (next_data_len-1)/8 + 1; + *tracepos += next_parity_len; + } + + *duration = last_timestamp - timestamp; } uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles) { bool isResponse; - uint16_t duration, data_len, parity_len; + 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}; @@ -317,7 +356,8 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui if (protocol == TOPAZ && !isResponse) { // topaz reader commands come in 1 or 9 separate frames with 8 Bits each. // merge them: - tracepos = merge_topaz_reader_frames(tracepos, traceLen, trace, topaz_reader_command, &data_len); + merge_topaz_reader_frames(timestamp, &duration, &tracepos, traceLen, trace, frame, topaz_reader_command, &data_len); + frame = topaz_reader_command; } //Check the CRC status @@ -331,7 +371,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui break; case ISO_14443B: case TOPAZ: - crcStatus = iso14443B_CRC_check(isResponse, topaz_reader_command, data_len); + crcStatus = iso14443B_CRC_check(isResponse, frame, data_len); break; case ISO_14443A: ComputeCrc14443(CRC_14443_A, frame, data_len-2, &b1, &b2); @@ -370,7 +410,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui } } - if(crcStatus == 1) + if(crcStatus == 1 || crcStatus == 2) {//CRC-command char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4)-1; (*pos1) = '['; @@ -418,19 +458,15 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui } } - 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)); - } + PrintAndLog(" %9d | %9d | %s | fdt (Frame Delay Time): %d", + (EndOfTransmissionTimestamp - first_timestamp), + (next_timestamp - first_timestamp), + " ", + (next_timestamp - EndOfTransmissionTimestamp)); } return tracepos; @@ -462,7 +498,7 @@ int CmdHFList(const char *Cmd) protocol = ISO_14443A; } else if(strcmp(type, "14b") == 0) { protocol = ISO_14443B; - } else if(strcmp(type,"topaz")== 0) { + } else if(strcmp(type,"nfc")== 0) { protocol = TOPAZ; } else if(strcmp(type,"raw")== 0) { protocol = -1;//No crc, no annotations From ef00343cb1f6ab306020c4108cd414e8df6b132f Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Tue, 17 Mar 2015 07:41:08 +0100 Subject: [PATCH 003/145] revert change "hf list topaz" to "hf list nfc" refactored Startbit detection in MillerDecoding() relaxed startbit detection in MillerDecoding() fixed CRC checking and CRC bytes marking in hf list fixed topaz multi frame command listing in hf list topaz --- armsrc/iso14443a.c | 55 ++++++++++++---------------- armsrc/iso14443a.h | 3 +- client/cmdhf.c | 89 +++++++++++++++++++++++++++++++--------------- 3 files changed, 84 insertions(+), 63 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index a78dae6e..06a134f6 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -248,8 +248,7 @@ void UartReset() 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.fourBits = 0x00000000; // buffer for 4 Bits Uart.startTime = 0; Uart.endTime = 0; } @@ -265,40 +264,34 @@ void UartInit(uint8_t *data, uint8_t *parity) 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 < 1) { // 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.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8); - Uart.startTime -= Uart.syncBit; - Uart.endTime = Uart.startTime; - Uart.state = STATE_START_OF_COMMUNICATION; - } + Uart.syncBit = 9999; // not set + // we look for a ...xxxx1111111100x11111xxxxxx pattern + // (unmodulated, followed by the start bit = 8 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's) +#define ISO14443A_STARTBIT_MASK 0x007FEF80 // mask is 00000000 01111111 11101111 10000000 +#define ISO14443A_STARTBIT_PATTERN 0x007F8F80 // pattern is 00000000 01111111 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 +315,7 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) } } } 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 +351,10 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) 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 diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index d99236b2..ec99ab99 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -63,8 +63,7 @@ typedef struct { 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 --git a/client/cmdhf.c b/client/cmdhf.c index f4d76210..960dcf7f 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -189,7 +189,34 @@ void annotateIso14443b(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) } /** - * @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 @@ -206,9 +233,10 @@ uint8_t iso14443B_CRC_check(bool isResponse, uint8_t* data, uint8_t len) ComputeCrc14443(CRC_14443_B, data, len-2, &b1, &b2); if(b1 != data[len-2] || b2 != data[len-1]) { - return 0; + return 0; + } else { + return 1; } - return 1; } /** @@ -287,33 +315,42 @@ bool next_record_is_response(uint16_t tracepos, uint8_t *trace) } -void 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) +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 9 uint32_t last_timestamp = timestamp + *duration; - memcpy(topaz_reader_command, frame, MIN(*data_len, MAX_TOPAZ_READER_CMD_LEN)); + 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); - last_timestamp = next_timestamp + *((uint16_t *)(trace + *tracepos)); + 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 (*data_len + next_data_len <= MAX_TOPAZ_READER_CMD_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; } @@ -354,32 +391,27 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui tracepos += parity_len; if (protocol == TOPAZ && !isResponse) { - // topaz reader commands come in 1 or 9 separate frames with 8 Bits each. + // topaz reader commands come in 1 or 9 separate frames with 7 or 8 Bits each. // merge them: - merge_topaz_reader_frames(timestamp, &duration, &tracepos, traceLen, trace, frame, topaz_reader_command, &data_len); - frame = topaz_reader_command; + 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; switch (protocol) { case ICLASS: crcStatus = iclass_CRC_check(isResponse, frame, data_len); break; case ISO_14443B: - case TOPAZ: + case TOPAZ: crcStatus = iso14443B_CRC_check(isResponse, frame, data_len); break; case 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; - } - } + crcStatus = iso14443A_CRC_check(isResponse, frame, data_len); break; default: break; @@ -403,19 +435,18 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui } 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]); - + snprintf(line[j/16]+(( j % 16) * 4), 110, " %02x!", frame[j]); } else { - snprintf(line[j/16]+(( j % 16) * 4),110, "%02x ", frame[j]); + snprintf(line[j/16]+(( j % 16) * 4), 110, " %02x ", frame[j]); } } - if(crcStatus == 1 || crcStatus == 2) + 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) { @@ -443,7 +474,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui 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(" %9d | %9d | %s |%-64s | %s| %s", (timestamp - first_timestamp), (EndOfTransmissionTimestamp - first_timestamp), (isResponse ? "Tag" : "Rdr"), @@ -451,7 +482,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); } else { - PrintAndLog(" | | | %-64s| %s| %s", + PrintAndLog(" | | |%-64s | %s| %s", line[j], (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); @@ -498,7 +529,7 @@ int CmdHFList(const char *Cmd) protocol = ISO_14443A; } else if(strcmp(type, "14b") == 0) { protocol = ISO_14443B; - } else if(strcmp(type,"nfc")== 0) { + } else if(strcmp(type,"topaz")== 0) { protocol = TOPAZ; } else if(strcmp(type,"raw")== 0) { protocol = -1;//No crc, no annotations From 05ddb52c43f932db852e18fe6836bee71e91f74e Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 18 Mar 2015 17:12:09 +0100 Subject: [PATCH 004/145] fix: introduced a stupid error when refactoring the start bit detector in MillerDecoding() chg: use -O2 instead of -Os when compiling ARM sources chg: don't clear the Miller decoders input buffer on reset chg: be more specific for the Miller decoders start bit pattern add: new option c in hf list: mark CRC bytes (default is off) --- armsrc/Makefile | 2 +- armsrc/iso14443a.c | 49 ++++++++++++++++------------ client/Makefile | 71 +++++++++++++++++++++-------------------- client/cmdhf.c | 72 +++++++++++++++++++++++++----------------- client/cmdhftopaz.c | 71 +++++++++++++++++++++++++++++++++++++++++ client/cmdhftopaz.h | 16 ++++++++++ common/Makefile.common | 2 +- 7 files changed, 197 insertions(+), 86 deletions(-) create mode 100644 client/cmdhftopaz.c create mode 100644 client/cmdhftopaz.h diff --git a/armsrc/Makefile b/armsrc/Makefile index 75ccdece..03541d61 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -10,7 +10,7 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line #in the next section to remove that particular feature from compilation -APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -fno-strict-aliasing +APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -fno-strict-aliasing -O2 #-DWITH_LCD #SRC_LCD = fonts.c LCD.c diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 06a134f6..0bd681d9 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -232,13 +232,19 @@ void AppendCrc14443a(uint8_t* data, int len) 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 +// 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,7 +254,6 @@ void UartReset() 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.fourBits = 0x00000000; // buffer for 4 Bits Uart.startTime = 0; Uart.endTime = 0; } @@ -257,6 +262,7 @@ void UartInit(uint8_t *data, uint8_t *parity) { Uart.output = data; Uart.parity = parity; + Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits UartReset(); } @@ -269,18 +275,21 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) if (Uart.state == STATE_UNSYNCD) { // not yet synced Uart.syncBit = 9999; // not set - // we look for a ...xxxx1111111100x11111xxxxxx pattern - // (unmodulated, followed by the start bit = 8 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's) -#define ISO14443A_STARTBIT_MASK 0x007FEF80 // mask is 00000000 01111111 11101111 10000000 -#define ISO14443A_STARTBIT_PATTERN 0x007F8F80 // pattern is 00000000 01111111 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; + // 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; @@ -646,7 +655,7 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { TRUE)) break; } /* And ready to receive another command. */ - UartReset(); + UartInit(receivedCmd, receivedCmdPar); /* And also reset the demod code, which might have been */ /* false-triggered by the commands from the reader. */ DemodReset(); @@ -2798,7 +2807,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(); diff --git a/client/Makefile b/client/Makefile index 6ec34469..2e1c2092 100644 --- a/client/Makefile +++ b/client/Makefile @@ -65,41 +65,42 @@ CMDSRCS = nonce2key/crapto1.c\ loclass/ikeys.c \ loclass/elite_crack.c\ loclass/fileutils.c\ - mifarehost.c\ - crc16.c \ - iso14443crc.c \ - iso15693tools.c \ - data.c \ - graph.c \ - ui.c \ - cmddata.c \ - lfdemod.c \ - cmdhf.c \ - cmdhf14a.c \ - cmdhf14b.c \ - cmdhf15.c \ - cmdhfepa.c \ - cmdhflegic.c \ - cmdhficlass.c \ - cmdhfmf.c \ - cmdhfmfu.c \ - cmdhw.c \ - cmdlf.c \ - cmdlfio.c \ - cmdlfhid.c \ - cmdlfem4x.c \ - cmdlfhitag.c \ - cmdlfti.c \ - cmdparser.c \ - cmdmain.c \ - cmdlft55xx.c \ - cmdlfpcf7931.c\ - pm3_binlib.c\ - scripting.c\ - cmdscript.c\ - pm3_bitlib.c\ - aes.c\ - protocols.c\ + mifarehost.c\ + crc16.c \ + iso14443crc.c \ + iso15693tools.c \ + data.c \ + graph.c \ + ui.c \ + cmddata.c \ + lfdemod.c \ + cmdhf.c \ + cmdhf14a.c \ + cmdhf14b.c \ + cmdhf15.c \ + cmdhfepa.c \ + cmdhflegic.c \ + cmdhficlass.c \ + cmdhfmf.c \ + cmdhfmfu.c \ + cmdhftopaz.c \ + cmdhw.c \ + cmdlf.c \ + cmdlfio.c \ + cmdlfhid.c \ + cmdlfem4x.c \ + cmdlfhitag.c \ + cmdlfti.c \ + cmdparser.c \ + cmdmain.c \ + cmdlft55xx.c \ + cmdlfpcf7931.c\ + pm3_binlib.c\ + scripting.c\ + cmdscript.c\ + pm3_bitlib.c\ + aes.c\ + protocols.c\ COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) diff --git a/client/cmdhf.c b/client/cmdhf.c index 960dcf7f..0d678ab6 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -23,6 +23,7 @@ #include "cmdhficlass.h" #include "cmdhfmf.h" #include "cmdhfmfu.h" +#include "cmdhftopaz.h" #include "protocols.h" static int CmdHelp(const char *Cmd); @@ -354,7 +355,7 @@ bool merge_topaz_reader_frames(uint32_t timestamp, uint32_t *duration, uint16_t } -uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles) +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; @@ -441,13 +442,17 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui } } - if(crcStatus == 0 || crcStatus == 1) - {//CRC-command - char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4); - (*pos1) = '['; - char *pos2 = line[(data_len)/16]+(((data_len) % 16) * 4); - sprintf(pos2, "%c", ']'); + + if (markCRCBytes) { + if(crcStatus == 0 || crcStatus == 1) + {//CRC-command + char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4); + (*pos1) = '['; + char *pos2 = line[(data_len)/16]+(((data_len) % 16) * 4); + sprintf(pos2, "%c", ']'); + } } + if(data_len == 0) { if(data_len == 0){ @@ -507,22 +512,26 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui 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(!errors) { if(strcmp(type, "iclass") == 0) { protocol = ICLASS; } else if(strcmp(type, "14a") == 0) { @@ -540,8 +549,9 @@ int CmdHFList(const char *Cmd) 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"); @@ -555,10 +565,13 @@ int CmdHFList(const char *Cmd) } - if (param == 'f') { + if (param1 == 'f' || param2 == 'f') { showWaitCycles = true; } + if (param1 == 'c' || param2 == 'c') { + markCRCBytes = true; + } uint8_t *trace; uint16_t tracepos = 0; @@ -592,7 +605,7 @@ int CmdHFList(const char *Cmd) while(tracepos < traceLen) { - tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles); + tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles, markCRCBytes); } free(trace); @@ -602,18 +615,19 @@ int CmdHFList(const char *Cmd) static command_t CommandTable[] = { - {"help", CmdHelp, 1, "This help"}, - {"14a", CmdHF14A, 1, "{ ISO14443A RFIDs... }"}, - {"14b", CmdHF14B, 1, "{ ISO14443B RFIDs... }"}, - {"15", CmdHF15, 1, "{ ISO15693 RFIDs... }"}, - {"epa", CmdHFEPA, 1, "{ German Identification Card... }"}, - {"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"}, - {NULL, NULL, 0, NULL} + {"help", CmdHelp, 1, "This help"}, + {"14a", CmdHF14A, 1, "{ ISO14443A RFIDs... }"}, + {"14b", CmdHF14B, 1, "{ ISO14443B RFIDs... }"}, + {"15", CmdHF15, 1, "{ ISO15693 RFIDs... }"}, + {"epa", CmdHFEPA, 1, "{ German Identification Card... }"}, + {"legic", CmdHFLegic, 0, "{ LEGIC RFIDs... }"}, + {"iclass", CmdHFiClass, 1, "{ ICLASS RFIDs... }"}, + {"mf", CmdHFMF, 1, "{ MIFARE RFIDs... }"}, + {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight 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} }; int CmdHF(const char *Cmd) diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c new file mode 100644 index 00000000..d747ed05 --- /dev/null +++ b/client/cmdhftopaz.c @@ -0,0 +1,71 @@ +//----------------------------------------------------------------------------- +// Copyright (C) 2015 Piwi +// +// 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 Topaz (NFC Type 1) commands +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include "cmdmain.h" +#include "cmdparser.h" +#include "cmdhftopaz.h" +#include "cmdhf14a.h" +#include "ui.h" + +int CmdHFTopazReader(const char *Cmd) +{ + PrintAndLog("not yet implemented"); + return 0; +} + + +int CmdHFTopazSim(const char *Cmd) +{ + PrintAndLog("not yet implemented"); + return 0; +} + + +int CmdHFTopazCmdRaw(const char *Cmd) +{ + PrintAndLog("not yet implemented"); + return 0; +} + + +static int CmdHelp(const char *Cmd); + + +static command_t CommandTable[] = +{ + {"help", CmdHelp, 1, "This help"}, + {"reader", CmdHFTopazReader, 0, "Act like a Topaz reader"}, + {"sim", CmdHFTopazSim, 0, " -- Simulate Topaz tag"}, + {"snoop", CmdHF14ASnoop, 0, "Eavesdrop a Topaz reader-tag communication"}, + {"raw", CmdHFTopazCmdRaw, 0, "Send raw hex data to tag"}, + {NULL, NULL, 0, NULL} +}; + + +int CmdHFTopaz(const char *Cmd) { + // flush + WaitForResponseTimeout(CMD_ACK,NULL,100); + + // parse + CmdsParse(CommandTable, Cmd); + return 0; +} + +static int CmdHelp(const char *Cmd) +{ + CmdsHelp(CommandTable); + return 0; +} + + diff --git a/client/cmdhftopaz.h b/client/cmdhftopaz.h new file mode 100644 index 00000000..8d5428dd --- /dev/null +++ b/client/cmdhftopaz.h @@ -0,0 +1,16 @@ +//----------------------------------------------------------------------------- +// Copyright (C) 2015 Piwi +// +// 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 Topaz (NFC Type 1) commands +//----------------------------------------------------------------------------- + +#ifndef CMDHFTOPAZ_H__ +#define CMDHFTOPAZ_H__ + +int CmdHFTopaz(const char *Cmd); + +#endif diff --git a/common/Makefile.common b/common/Makefile.common index 2b2bb2fb..7e264d28 100644 --- a/common/Makefile.common +++ b/common/Makefile.common @@ -66,7 +66,7 @@ VPATH = . ../common/ ../fpga/ INCLUDES = ../include/proxmark3.h ../include/at91sam7s512.h ../include/config_gpio.h ../include/usb_cmd.h $(APP_INCLUDES) -CFLAGS = -c $(INCLUDE) -Wall -Werror -pedantic -std=c99 $(APP_CFLAGS) -Os +CFLAGS = -c $(INCLUDE) -Wall -Werror -pedantic -std=c99 -Os $(APP_CFLAGS) LDFLAGS = -nostartfiles -nodefaultlibs -Wl,-gc-sections -n LIBS = -lgcc From 48ece4a750b41536ba2c56dfd9a088b192976c82 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Fri, 20 Mar 2015 21:06:51 +0100 Subject: [PATCH 005/145] add: Topaz mode for "hf 14a raw" (new option -T) chg: allow tracing without parity chg: make "hf list topaz" aware of additional commands for Dynamic Memory Model --- armsrc/BigBuf.c | 17 +++++++----- armsrc/iso14443a.c | 60 ++++++++++++++++++++++++++++++++--------- client/cmdhf.c | 11 +++++--- client/cmdhf14a.c | 58 ++++++++++++++++++++++++++-------------- client/cmdhftopaz.c | 65 +++++++++++++++++++++++++++++++++++++++++++++ common/protocols.h | 5 ++++ include/mifare.h | 17 ++++++------ 7 files changed, 182 insertions(+), 51 deletions(-) diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index 703ade65..51fafdeb 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -171,18 +171,19 @@ bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_ traceLen += iLen; // parity bytes - if (parity != NULL && iLen != 0) { - memcpy(trace + traceLen, parity, num_paritybytes); + 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 +225,8 @@ int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwP return TRUE; } + + // Emulator memory uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length){ uint8_t* mem = BigBuf_get_EM_addr(); diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 0bd681d9..81cb9728 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -213,6 +213,12 @@ void AppendCrc14443a(uint8_t* data, int len) 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 //============================================================================= @@ -238,8 +244,6 @@ static tUart Uart; // 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 }; @@ -279,8 +283,8 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) // 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 + #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; @@ -655,7 +659,7 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { TRUE)) break; } /* And ready to receive another command. */ - UartInit(receivedCmd, receivedCmdPar); + UartReset(); /* And also reset the demod code, which might have been */ /* false-triggered by the commands from the reader. */ DemodReset(); @@ -680,6 +684,9 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { // 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 +1344,7 @@ void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8 } // 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 +1638,7 @@ static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receive } } + void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t *timing) { CodeIso14443aBitsAsReaderPar(frame, bits, par); @@ -1646,11 +1654,13 @@ 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 ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect @@ -1659,6 +1669,7 @@ void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) ReaderTransmitBitsPar(frame, len, par, timing); } + void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect @@ -1932,15 +1943,38 @@ void ReaderIso14443a(UsbCommand *c) if(param & ISO14A_RAW) { if(param & ISO14A_APPEND_CRC) { - AppendCrc14443a(cmd,len); + if(param & ISO14A_TOPAZMODE) { + AppendCrc14443b(cmd,len); + } else { + AppendCrc14443a(cmd,len); + } len += 2; if (lenbits) lenbits += 16; } - if(lenbits>0) { - GetParity(cmd, lenbits/8, par); - ReaderTransmitBitsPar(cmd, lenbits, par, NULL); - } else { - ReaderTransmit(cmd,len, NULL); + 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); // 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); // 8 bits, odd parity + } } arg0 = ReaderReceive(buf, par); cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf)); @@ -2824,6 +2858,8 @@ void RAMFUNC SniffMifare(uint8_t param) { // 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 --git a/client/cmdhf.c b/client/cmdhf.c index 0d678ab6..66c8e53c 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -145,7 +145,6 @@ void annotateIso15693(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) 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; @@ -154,6 +153,10 @@ void annotateTopaz(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) 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; } } @@ -319,7 +322,7 @@ bool next_record_is_response(uint16_t tracepos, uint8_t *trace) 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 9 +#define MAX_TOPAZ_READER_CMD_LEN 16 uint32_t last_timestamp = timestamp + *duration; @@ -479,7 +482,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui 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"), @@ -487,7 +490,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); } else { - PrintAndLog(" | | |%-64s | %s| %s", + PrintAndLog(" | | |%-64s | %s| %s", line[j], (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index 8978f43d..214ff1ec 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -509,20 +509,22 @@ 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; - uint16_t numbits=0; - uint32_t timeout=0; - uint8_t bTimeout=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; + bool topazmode = FALSE; char buf[5]=""; - int i=0; + int i = 0; uint8_t data[USB_CMD_DATA_SIZE]; - uint16_t datalen=0; + uint16_t datalen = 0; uint32_t temp; if (strlen(cmd)<2) { @@ -534,9 +536,11 @@ int CmdHF14ACmdRaw(const char *cmd) { 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++; @@ -545,19 +549,19 @@ int CmdHF14ACmdRaw(const char *cmd) { 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); @@ -567,13 +571,16 @@ int CmdHF14ACmdRaw(const char *cmd) { 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; @@ -603,10 +610,15 @@ int CmdHF14ACmdRaw(const char *cmd) { PrintAndLog("Invalid char on input"); return 0; } + if(crc && datalen>0 && datalen MAX_TIMEOUT) { timeout = MAX_TIMEOUT; @@ -627,11 +639,16 @@ int CmdHF14ACmdRaw(const char *cmd) { } 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) + + 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); @@ -647,6 +664,7 @@ int CmdHF14ACmdRaw(const char *cmd) { return 0; } + static void waitCmd(uint8_t iSelect) { uint8_t *recv; @@ -656,7 +674,7 @@ static void waitCmd(uint8_t iSelect) if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { recv = resp.d.asBytes; uint8_t iLen = iSelect ? resp.arg[1] : resp.arg[0]; - PrintAndLog("received %i octets",iLen); + PrintAndLog("received %i octets", iLen); if(!iLen) return; hexout = (char *)malloc(iLen * 3 + 1); diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c index d747ed05..aed5f023 100644 --- a/client/cmdhftopaz.c +++ b/client/cmdhftopaz.c @@ -17,6 +17,71 @@ #include "cmdhftopaz.h" #include "cmdhf14a.h" #include "ui.h" +#include "mifare.h" +#include "proxmark3.h" +#include "iso14443crc.h" +#include "protocols.h" + + + +static void topaz_switch_on_field(void) +{ + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_SELECT | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, 0, 0}}; + SendCommand(&c); + + UsbCommand resp; + WaitForResponse(CMD_ACK, &resp); +} + + +static void topaz_switch_off_field(void) +{ + UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; + SendCommand(&c); + + UsbCommand resp; + WaitForResponse(CMD_ACK, &resp); +} + + +static void topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) +{ + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, len, 0}}; + memcpy(c.d.asBytes, cmd, len); + SendCommand(&c); + + UsbCommand resp; + WaitForResponse(CMD_ACK, &resp); + + memcpy(response, resp.d.asBytes, resp.arg[0]); +} + + +static void topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) +{ + if (len > 1) { + uint8_t first, second; + ComputeCrc14443(CRC_14443_B, cmd, len, &first, &second); + cmd[len] = first; + cmd[len+1] = second; + } + + topaz_send_cmd_raw(cmd, len+2, response); +} + + +static void topaz_select(uint8_t *atqa, uint8_t *uid) +{ + // ToDo: implement anticollision + uint8_t rid_cmd[] = {TOPAZ_RID, 0, 0, 0, 0, 0, 0, 0, 0}; + uint8_t wupa_cmd[] = {TOPAZ_WUPA}; + + topaz_switch_on_field(); + topaz_send_cmd(wupa_cmd, sizeof(wupa_cmd), atqa); + topaz_send_cmd(rid_cmd, sizeof(rid_cmd) - 2, uid); + topaz_switch_off_field(); +} + int CmdHFTopazReader(const char *Cmd) { diff --git a/common/protocols.h b/common/protocols.h index e687ca7a..b0f16570 100644 --- a/common/protocols.h +++ b/common/protocols.h @@ -176,6 +176,11 @@ NXP/Philips CUSTOM COMMANDS #define TOPAZ_READ 0x01 // Read (a single byte) #define TOPAZ_WRITE_E 0x53 // Write-with-erase (a single byte) #define TOPAZ_WRITE_NE 0x1a // Write-no-erase (a single byte) +// additional commands for Dynamic Memory Model +#define TOPAZ_RSEG 0x10 // Read segment +#define TOPAZ_READ8 0x02 // Read (eight bytes) +#define TOPAZ_WRITE_E8 0x54 // Write-with-erase (eight bytes) +#define TOPAZ_WRITE_NE8 0x1B // Write-no-erase (eight bytes) #define ISO_14443A 0 diff --git a/include/mifare.h b/include/mifare.h index e2b7a7c5..ad86886d 100644 --- a/include/mifare.h +++ b/include/mifare.h @@ -26,14 +26,15 @@ typedef struct { } __attribute__((__packed__)) iso14a_card_select_t; typedef enum ISO14A_COMMAND { - ISO14A_CONNECT = 1, - ISO14A_NO_DISCONNECT = 2, - ISO14A_APDU = 4, - ISO14A_RAW = 8, - ISO14A_REQUEST_TRIGGER = 0x10, - ISO14A_APPEND_CRC = 0x20, - ISO14A_SET_TIMEOUT = 0x40, - ISO14A_NO_SELECT = 0x80 + ISO14A_CONNECT = (1 << 0), + ISO14A_NO_DISCONNECT = (1 << 1), + ISO14A_APDU = (1 << 2), + ISO14A_RAW = (1 << 3), + ISO14A_REQUEST_TRIGGER = (1 << 4), + ISO14A_APPEND_CRC = (1 << 5), + ISO14A_SET_TIMEOUT = (1 << 6), + ISO14A_NO_SELECT = (1 << 7), + ISO14A_TOPAZMODE = (1 << 8) } iso14a_command_t; #endif // _MIFARE_H_ From de15fc5fe3090a95cf100c48af340e93a738576a Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Tue, 24 Mar 2015 07:17:00 +0100 Subject: [PATCH 006/145] add: hf topaz reader (basic functionality) --- client/cmdhf.c | 4 +- client/cmdhftopaz.c | 306 +++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 288 insertions(+), 22 deletions(-) diff --git a/client/cmdhf.c b/client/cmdhf.c index 66c8e53c..ad8e5369 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -603,8 +603,8 @@ int CmdHFList(const char *Cmd) PrintAndLog("iso14443a - All times are in carrier periods (1/13.56Mhz)"); PrintAndLog("iClass - Timings are not as accurate"); PrintAndLog(""); - PrintAndLog(" Start | End | Src | Data (! denotes parity error) | CRC | Annotation |"); - PrintAndLog("-----------|-----------|-----|-----------------------------------------------------------------|-----|--------------------|"); + PrintAndLog(" Start | End | Src | Data (! denotes parity error) | CRC | Annotation |"); + PrintAndLog("------------|------------|-----|-----------------------------------------------------------------|-----|--------------------|"); while(tracepos < traceLen) { diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c index aed5f023..95e988ed 100644 --- a/client/cmdhftopaz.c +++ b/client/cmdhftopaz.c @@ -24,13 +24,11 @@ + static void topaz_switch_on_field(void) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_SELECT | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, 0, 0}}; SendCommand(&c); - - UsbCommand resp; - WaitForResponse(CMD_ACK, &resp); } @@ -38,13 +36,10 @@ static void topaz_switch_off_field(void) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; SendCommand(&c); - - UsbCommand resp; - WaitForResponse(CMD_ACK, &resp); } -static void topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) +static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, len, 0}}; memcpy(c.d.asBytes, cmd, len); @@ -53,39 +48,310 @@ static void topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) UsbCommand resp; WaitForResponse(CMD_ACK, &resp); - memcpy(response, resp.d.asBytes, resp.arg[0]); + if (resp.arg[0] > 0) { + memcpy(response, resp.d.asBytes, resp.arg[0]); + } + + return resp.arg[0]; } -static void topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) +static int topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) { if (len > 1) { uint8_t first, second; - ComputeCrc14443(CRC_14443_B, cmd, len, &first, &second); - cmd[len] = first; - cmd[len+1] = second; + ComputeCrc14443(CRC_14443_B, cmd, len-2, &first, &second); + cmd[len-2] = first; + cmd[len-1] = second; } - topaz_send_cmd_raw(cmd, len+2, response); + return topaz_send_cmd_raw(cmd, len, response); } -static void topaz_select(uint8_t *atqa, uint8_t *uid) +static int topaz_select(uint8_t *atqa, uint8_t *rid_response) { // ToDo: implement anticollision - uint8_t rid_cmd[] = {TOPAZ_RID, 0, 0, 0, 0, 0, 0, 0, 0}; + uint8_t wupa_cmd[] = {TOPAZ_WUPA}; - + uint8_t rid_cmd[] = {TOPAZ_RID, 0, 0, 0, 0, 0, 0, 0, 0}; + topaz_switch_on_field(); - topaz_send_cmd(wupa_cmd, sizeof(wupa_cmd), atqa); - topaz_send_cmd(rid_cmd, sizeof(rid_cmd) - 2, uid); - topaz_switch_off_field(); + + if (!topaz_send_cmd(wupa_cmd, sizeof(wupa_cmd), atqa)) { + topaz_switch_off_field(); + return -1; // WUPA failed + } + + if (!topaz_send_cmd(rid_cmd, sizeof(rid_cmd), rid_response)) { + topaz_switch_off_field(); + return -2; // RID failed + } + + return 0; // OK } +static int topaz_rall(uint8_t *uid, uint8_t *rall_response) +{ + uint8_t rall_cmd[] = {TOPAZ_RALL, 0, 0, 0, 0, 0, 0, 0, 0}; + + memcpy(&rall_cmd[3], uid, 4); + if (!topaz_send_cmd(rall_cmd, sizeof(rall_cmd), rall_response)) { + topaz_switch_off_field(); + return -1; // RALL failed + } + + return 0; +} + + +static bool topaz_block_is_locked(uint8_t blockno, uint8_t *lockbits) +{ + if(lockbits[blockno/8] >> (blockno % 8) & 0x01) { + return true; + } else { + return false; + } +} + + +static int topaz_print_CC(uint8_t *data) +{ + if(data[0] != 0xe1) { + return -1; // no NDEF message + } + + PrintAndLog("Capability Container: %02x %02x %02x %02x", data[0], data[1], data[2], data[3]); + PrintAndLog(" %02x: NDEF Magic Number", data[0]); + PrintAndLog(" %02x: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); + PrintAndLog(" %02x: Physical Memory Size of this tag: %d bytes", data[2], (data[2] + 1) * 8); + PrintAndLog(" %02x: %s / %s", data[3], + (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", + (data[3] & 0x0F)==0 ? "Write access granted without any security" : (data[3] & 0x0F)==0x0F ? "No write access granted at all" : "(RFU)"); + return 0; +} + + +static void get_TLV(uint8_t **TLV_ptr, uint8_t *tag, uint16_t *length, uint8_t **value) +{ + *length = 0; + *value = NULL; + + *tag = **TLV_ptr; + *TLV_ptr += 1; + switch (*tag) { + case 0x00: // NULL TLV. + case 0xFE: // Terminator TLV. + break; + case 0x01: // Lock Control TLV + case 0x02: // Reserved Memory TLV + case 0x03: // NDEF message TLV + case 0xFD: // proprietary TLV + *length = **TLV_ptr; + *TLV_ptr += 1; + if (*length == 0xff) { + *length = **TLV_ptr << 8; + *TLV_ptr += 1; + *length |= **TLV_ptr; + *TLV_ptr += 1; + } + *value = *TLV_ptr; + *TLV_ptr += *length; + break; + default: // RFU + break; + } +} + + +static bool topaz_print_lock_control_TLVs(uint8_t *memory) +{ + uint8_t *TLV_ptr = memory; + uint8_t tag = 0; + uint16_t length; + uint8_t *value; + bool lock_TLV_present = false; + + while(*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { + // all Lock Control TLVs shall be present before the NDEF message TLV, the proprietary TLV (and the Terminator TLV) + get_TLV(&TLV_ptr, &tag, &length, &value); + if (tag == 0x01) { // the Lock Control TLV + uint8_t pages_addr = value[0] >> 4; + uint8_t byte_offset = value[0] & 0x0f; + uint8_t size_in_bits = value[1] ? value[1] : 256; + uint8_t bytes_per_page = 1 << (value[2] & 0x0f); + uint8_t bytes_locked_per_bit = 1 << (value[2] >> 4); + PrintAndLog("Lock Area of %d bits at byte offset 0x%02x. Each Lock Bit locks %d bytes.", + size_in_bits, + pages_addr * bytes_per_page + byte_offset, + bytes_locked_per_bit); + lock_TLV_present = true; + } + } + + if (!lock_TLV_present) { + PrintAndLog("(No Lock Control TLV present)"); + return -1; + } else { + return 0; + } +} + + +static int topaz_print_reserved_memory_control_TLVs(uint8_t *memory) +{ + uint8_t *TLV_ptr = memory; + uint8_t tag = 0; + uint16_t length; + uint8_t *value; + bool reserved_memory_control_TLV_present = false; + + while(*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { + // all Reserved Memory Control TLVs shall be present before the NDEF message TLV, the proprietary TLV (and the Terminator TLV) + get_TLV(&TLV_ptr, &tag, &length, &value); + if (tag == 0x02) { // the Reserved Memory Control TLV + uint8_t pages_addr = value[0] >> 4; + uint8_t byte_offset = value[0] & 0x0f; + uint8_t size_in_bytes = value[1] ? value[1] : 256; + uint8_t bytes_per_page = 1 << (value[2] & 0x0f); + PrintAndLog("Reserved Memory of %d bytes at byte offset 0x%02x.", + size_in_bytes, + pages_addr * bytes_per_page + byte_offset); + reserved_memory_control_TLV_present = true; + } + } + + if (!reserved_memory_control_TLV_present) { + PrintAndLog("(No Reserved Memory Control TLV present)"); + return -1; + } else { + return 0; + } +} + + +static void topaz_print_lifecycle_state(uint8_t *data) +{ + +} + + +static void topaz_print_NDEF(uint8_t *data) +{ + +} + + int CmdHFTopazReader(const char *Cmd) { - PrintAndLog("not yet implemented"); + int status; + uint8_t atqa[2]; + uint8_t rid_response[8]; + uint8_t *uid_echo = &rid_response[2]; + union { + uint8_t raw_content[124]; + struct { + uint8_t HR[2]; + uint8_t data_block[15][8]; + uint8_t CRC[2]; + } static_memory; + } rall_response; + uint8_t *static_lock_bytes = rall_response.static_memory.data_block[0x0e]; + + status = topaz_select(atqa, rid_response); + + if (status == -1) { + PrintAndLog("Error: couldn't receive ATQA"); + return -1; + } + + PrintAndLog("ATQA : %02x %02x", atqa[1], atqa[0]); + if (atqa[1] != 0x0c && atqa[0] != 0x00) { + PrintAndLog("Tag doesn't support the Topaz protocol."); + topaz_switch_off_field(); + return -1; + } + + if (status == -2) { + PrintAndLog("Error: tag didn't answer to RID"); + topaz_switch_off_field(); + return -1; + } + + // ToDo: CRC check + PrintAndLog("HR0 : %02x (%sa Topaz tag (%scapable of carrying a NDEF message), %s memory map)", rid_response[0], + (rid_response[0] & 0xF0) == 0x10 ? "" : "not ", + (rid_response[0] & 0xF0) == 0x10 ? "" : "not ", + (rid_response[0] & 0x0F) == 0x10 ? "static" : "dynamic"); + PrintAndLog("HR1 : %02x", rid_response[1]); + + status = topaz_rall(uid_echo, rall_response.raw_content); + + if(status == -1) { + PrintAndLog("Error: tag didn't answer to RALL"); + topaz_switch_off_field(); + return -1; + } + + PrintAndLog("UID : %02x %02x %02x %02x %02x %02x %02x", + rall_response.static_memory.data_block[0][6], + rall_response.static_memory.data_block[0][5], + rall_response.static_memory.data_block[0][4], + rall_response.static_memory.data_block[0][3], + rall_response.static_memory.data_block[0][2], + rall_response.static_memory.data_block[0][1], + rall_response.static_memory.data_block[0][0]); + PrintAndLog(" UID[6] (Manufacturer Byte) = %02x, Manufacturer: %s", + rall_response.static_memory.data_block[0][6], + getTagInfo(rall_response.static_memory.data_block[0][6])); + + PrintAndLog(""); + PrintAndLog("Static Data blocks 00 to 0c:"); + PrintAndLog("block# | offset | Data | Locked?"); + char line[80]; + for (uint16_t i = 0; i <= 0x0c; i++) { + for (uint16_t j = 0; j < 8; j++) { + sprintf(&line[3*j], "%02x ", rall_response.static_memory.data_block[i][j] /*rall_response[2 + 8*i + j]*/); + } + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, topaz_block_is_locked(i, static_lock_bytes) ? "yes" : "no"); + } + + PrintAndLog(""); + PrintAndLog("Static Reserved block 0d:"); + for (uint16_t j = 0; j < 8; j++) { + sprintf(&line[3*j], "%02x ", rall_response.static_memory.data_block[0x0d][j]); + } + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); + + PrintAndLog(""); + PrintAndLog("Static Lockbits / OTP block 0e:"); + for (uint16_t j = 0; j < 8; j++) { + sprintf(&line[3*j], "%02x ", static_lock_bytes[j]); + } + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0e, 0x0e*8, line, "n/a"); + + PrintAndLog(""); + + status = topaz_print_CC(&rall_response.static_memory.data_block[1][0]); + + if (status == -1) { + PrintAndLog("No NDEF message present"); + topaz_switch_off_field(); + return 0; + } + + PrintAndLog(""); + bool lock_TLV_present = topaz_print_lock_control_TLVs(&rall_response.static_memory.data_block[1][4]); + + PrintAndLog(""); + bool reserved_mem_present = topaz_print_reserved_memory_control_TLVs(&rall_response.static_memory.data_block[1][4]); + + topaz_print_lifecycle_state(&rall_response.static_memory.data_block[1][0]); + + topaz_print_NDEF(&rall_response.static_memory.data_block[1][0]); + + topaz_switch_off_field(); return 0; } From c5847ae8af8d567da6cb905bd59c886e3d0c040b Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Sat, 28 Mar 2015 18:06:21 +0100 Subject: [PATCH 007/145] refactoring hf topaz reader --- client/cmdhftopaz.c | 70 ++++++++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 32 deletions(-) diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c index 95e988ed..e76b3fb5 100644 --- a/client/cmdhftopaz.c +++ b/client/cmdhftopaz.c @@ -22,7 +22,16 @@ #include "iso14443crc.h" #include "protocols.h" +#define TOPAZ_MAX_MEMORY 2048 +static struct { + uint8_t HR01[2]; + uint8_t uid[7]; + uint8_t size; + uint8_t data_blocks[TOPAZ_MAX_MEMORY/8][8]; + uint8_t *dynamic_lock_areas; + uint8_t *dynamic_reserved_areas; +} topaz_tag; static void topaz_switch_on_field(void) @@ -92,12 +101,12 @@ static int topaz_select(uint8_t *atqa, uint8_t *rid_response) } -static int topaz_rall(uint8_t *uid, uint8_t *rall_response) +static int topaz_rall(uint8_t *uid, uint8_t *response) { uint8_t rall_cmd[] = {TOPAZ_RALL, 0, 0, 0, 0, 0, 0, 0, 0}; memcpy(&rall_cmd[3], uid, 4); - if (!topaz_send_cmd(rall_cmd, sizeof(rall_cmd), rall_response)) { + if (!topaz_send_cmd(rall_cmd, sizeof(rall_cmd), response)) { topaz_switch_off_field(); return -1; // RALL failed } @@ -249,15 +258,7 @@ int CmdHFTopazReader(const char *Cmd) uint8_t atqa[2]; uint8_t rid_response[8]; uint8_t *uid_echo = &rid_response[2]; - union { - uint8_t raw_content[124]; - struct { - uint8_t HR[2]; - uint8_t data_block[15][8]; - uint8_t CRC[2]; - } static_memory; - } rall_response; - uint8_t *static_lock_bytes = rall_response.static_memory.data_block[0x0e]; + uint8_t rall_response[124]; status = topaz_select(atqa, rid_response); @@ -279,6 +280,9 @@ int CmdHFTopazReader(const char *Cmd) return -1; } + topaz_tag.HR01[0] = rid_response[0]; + topaz_tag.HR01[1] = rid_response[1]; + // ToDo: CRC check PrintAndLog("HR0 : %02x (%sa Topaz tag (%scapable of carrying a NDEF message), %s memory map)", rid_response[0], (rid_response[0] & 0xF0) == 0x10 ? "" : "not ", @@ -286,7 +290,7 @@ int CmdHFTopazReader(const char *Cmd) (rid_response[0] & 0x0F) == 0x10 ? "static" : "dynamic"); PrintAndLog("HR1 : %02x", rid_response[1]); - status = topaz_rall(uid_echo, rall_response.raw_content); + status = topaz_rall(uid_echo, rall_response); if(status == -1) { PrintAndLog("Error: tag didn't answer to RALL"); @@ -294,46 +298,48 @@ int CmdHFTopazReader(const char *Cmd) return -1; } + memcpy(topaz_tag.uid, rall_response+2, 7); PrintAndLog("UID : %02x %02x %02x %02x %02x %02x %02x", - rall_response.static_memory.data_block[0][6], - rall_response.static_memory.data_block[0][5], - rall_response.static_memory.data_block[0][4], - rall_response.static_memory.data_block[0][3], - rall_response.static_memory.data_block[0][2], - rall_response.static_memory.data_block[0][1], - rall_response.static_memory.data_block[0][0]); + topaz_tag.uid[6], + topaz_tag.uid[5], + topaz_tag.uid[4], + topaz_tag.uid[3], + topaz_tag.uid[2], + topaz_tag.uid[1], + topaz_tag.uid[0]); PrintAndLog(" UID[6] (Manufacturer Byte) = %02x, Manufacturer: %s", - rall_response.static_memory.data_block[0][6], - getTagInfo(rall_response.static_memory.data_block[0][6])); - + topaz_tag.uid[6], + getTagInfo(topaz_tag.uid[6])); + + memcpy(topaz_tag.data_blocks, rall_response+2, 0x10*8); PrintAndLog(""); PrintAndLog("Static Data blocks 00 to 0c:"); PrintAndLog("block# | offset | Data | Locked?"); char line[80]; for (uint16_t i = 0; i <= 0x0c; i++) { for (uint16_t j = 0; j < 8; j++) { - sprintf(&line[3*j], "%02x ", rall_response.static_memory.data_block[i][j] /*rall_response[2 + 8*i + j]*/); + sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[i][j] /*rall_response[2 + 8*i + j]*/); } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, topaz_block_is_locked(i, static_lock_bytes) ? "yes" : "no"); + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, topaz_block_is_locked(i, &topaz_tag.data_blocks[0x0d][0]) ? "yes" : "no"); } PrintAndLog(""); PrintAndLog("Static Reserved block 0d:"); for (uint16_t j = 0; j < 8; j++) { - sprintf(&line[3*j], "%02x ", rall_response.static_memory.data_block[0x0d][j]); + sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0d][j]); } PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); PrintAndLog(""); - PrintAndLog("Static Lockbits / OTP block 0e:"); + PrintAndLog("Static Lockbits and OTP Bytes:"); for (uint16_t j = 0; j < 8; j++) { - sprintf(&line[3*j], "%02x ", static_lock_bytes[j]); + sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0e][j]); } PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0e, 0x0e*8, line, "n/a"); PrintAndLog(""); - status = topaz_print_CC(&rall_response.static_memory.data_block[1][0]); + status = topaz_print_CC(&topaz_tag.data_blocks[1][0]); if (status == -1) { PrintAndLog("No NDEF message present"); @@ -342,14 +348,14 @@ int CmdHFTopazReader(const char *Cmd) } PrintAndLog(""); - bool lock_TLV_present = topaz_print_lock_control_TLVs(&rall_response.static_memory.data_block[1][4]); + bool lock_TLV_present = topaz_print_lock_control_TLVs(&topaz_tag.data_blocks[1][4]); PrintAndLog(""); - bool reserved_mem_present = topaz_print_reserved_memory_control_TLVs(&rall_response.static_memory.data_block[1][4]); + bool reserved_mem_present = topaz_print_reserved_memory_control_TLVs(&topaz_tag.data_blocks[1][4]); - topaz_print_lifecycle_state(&rall_response.static_memory.data_block[1][0]); + topaz_print_lifecycle_state(&topaz_tag.data_blocks[1][0]); - topaz_print_NDEF(&rall_response.static_memory.data_block[1][0]); + topaz_print_NDEF(&topaz_tag.data_blocks[1][0]); topaz_switch_off_field(); return 0; From dc8ba239fbc1b8f50f572e84adfcfdf52bd0d0da Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 24 Jun 2015 07:48:36 +0200 Subject: [PATCH 008/145] (implementing suggestion #94) hf mf mifare: gracefully exit if tag isn't vulnerable to this attack hf mf nested: dito --- armsrc/iso14443a.c | 27 ++++++++++++++++++++------- armsrc/mifarecmd.c | 22 +++++++++++++++++----- client/cmdhfmf.c | 39 ++++++++++++++++++++++++++++----------- client/mifarehost.c | 38 ++++++++++++++++++-------------------- 4 files changed, 83 insertions(+), 43 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index cf64da2f..2fd568b9 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -1971,7 +1971,7 @@ int32_t dist_nt(uint32_t nt1, uint32_t nt2) { nttmp1 = prng_successor(nttmp1, 1); if (nttmp1 == nt2) return i; nttmp2 = prng_successor(nttmp2, 1); - if (nttmp2 == nt1) return -i; + if (nttmp2 == nt1) return -i; } return(-99999); // either nt1 or nt2 are invalid nonces @@ -2040,18 +2040,21 @@ void ReaderMifare(bool first_try) LED_B_OFF(); LED_C_OFF(); - + + #define DARKSIDE_MAX_TRIES 32 // number of tries to sync on PRNG cycle. Then give up. + uint16_t unsuccessfull_tries = 0; + for(uint16_t i = 0; TRUE; i++) { + LED_C_ON(); WDT_HIT(); // Test if the action was cancelled if(BUTTON_PRESS()) { + isOK = -1; break; } - LED_C_ON(); - if(!iso14443a_select_card(uid, NULL, &cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card"); continue; @@ -2086,8 +2089,14 @@ void ReaderMifare(bool first_try) nt_attacked = nt; } else { - if (nt_distance == -99999) { // invalid nonce received, try again - continue; + if (nt_distance == -99999) { // invalid nonce received + unsuccessfull_tries++; + if (!nt_attacked && unsuccessfull_tries > DARKSIDE_MAX_TRIES) { + isOK = -3; // Card has an unpredictable PRNG. Give up + break; + } else { + continue; // continue trying... + } } sync_cycles = (sync_cycles - nt_distance); if (MF_DBGLEVEL >= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i, nt_distance, sync_cycles); @@ -2149,6 +2158,10 @@ void ReaderMifare(bool first_try) if (nt_diff == 0 && first_try) { par[0]++; + if (par[0] == 0x00) { // tried all 256 possible parities without success. Card doesn't send NACK. + isOK = -2; + break; + } } else { par[0] = ((par[0] & 0x1F) + 1) | par_low; } @@ -2165,7 +2178,7 @@ void ReaderMifare(bool first_try) memcpy(buf + 16, ks_list, 8); memcpy(buf + 24, mf_nr_ar, 4); - cmd_send(CMD_ACK,isOK,0,0,buf,28); + cmd_send(CMD_ACK, isOK, 0, 0, buf, 28); // Thats it... FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 939c9002..14d2b68a 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -645,6 +645,9 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // statistics on nonce distance + int16_t isOK = 0; + #define NESTED_MAX_TRIES 12 + uint16_t unsuccessfull_tries = 0; if (calibrate) { // for first call only. Otherwise reuse previous calibration LED_B_ON(); WDT_HIT(); @@ -655,6 +658,12 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat for (rtr = 0; rtr < 17; rtr++) { + // Test if the action was cancelled + if(BUTTON_PRESS()) { + isOK = -2; + break; + } + // prepare next select. No need to power down the card. if(mifare_classic_halt(pcs, cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Halt error"); @@ -702,14 +711,17 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat delta_time = auth2_time - auth1_time + 32; // allow some slack for proper timing } if (MF_DBGLEVEL >= 3) Dbprintf("Nested: calibrating... ntdist=%d", i); + } else { + unsuccessfull_tries++; + if (unsuccessfull_tries > NESTED_MAX_TRIES) { // card isn't vulnerable to nested attack (random numbers are not predictable) + isOK = -3; + } } } - - if (rtr <= 1) return; davg = (davg + (rtr - 1)/2) / (rtr - 1); - if (MF_DBGLEVEL >= 3) Dbprintf("min=%d max=%d avg=%d, delta_time=%d", dmin, dmax, davg, delta_time); + if (MF_DBGLEVEL >= 3) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time); dmin = davg - 2; dmax = davg + 2; @@ -722,7 +734,7 @@ 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; 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) { // continue until we have an unambiguous nonce @@ -800,7 +812,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat memcpy(buf+16, &target_ks[1], 4); LED_B_ON(); - cmd_send(CMD_ACK, 0, 2, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); + cmd_send(CMD_ACK, isOK, 0, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); LED_B_OFF(); if (MF_DBGLEVEL >= 3) DbpString("NESTED FINISHED"); diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 5abda060..5ef5273a 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -17,7 +17,7 @@ int CmdHF14AMifare(const char *Cmd) uint32_t uid = 0; uint32_t nt = 0, nr = 0; uint64_t par_list = 0, ks_list = 0, r_key = 0; - uint8_t isOK = 0; + int16_t isOK = 0; uint8_t keyBlock[8] = {0}; UsbCommand c = {CMD_READER_MIFARE, {true, 0, 0}}; @@ -25,7 +25,7 @@ int CmdHF14AMifare(const char *Cmd) // message printf("-------------------------------------------------------------------------\n"); printf("Executing command. Expected execution time: 25sec on average :-)\n"); - printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n"); + printf("Press button on the proxmark3 device to abort both proxmark3 and client.\n"); printf("-------------------------------------------------------------------------\n"); @@ -47,15 +47,20 @@ start: } UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { - isOK = resp.arg[0] & 0xff; + if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { + isOK = resp.arg[0]; uid = (uint32_t)bytes_to_num(resp.d.asBytes + 0, 4); nt = (uint32_t)bytes_to_num(resp.d.asBytes + 4, 4); par_list = bytes_to_num(resp.d.asBytes + 8, 8); ks_list = bytes_to_num(resp.d.asBytes + 16, 8); nr = bytes_to_num(resp.d.asBytes + 24, 4); printf("\n\n"); - if (!isOK) PrintAndLog("Proxmark can't get statistic info. Execution aborted.\n"); + switch (isOK) { + case -1 : PrintAndLog("Button pressed. Aborted.\n"); break; + case -2 : PrintAndLog("Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests).\n"); break; + case -3 : PrintAndLog("Card is not vulnerable to Darkside attack (its random number generator is not predictable).\n"); break; + default: ; + } break; } } @@ -622,8 +627,14 @@ int CmdHF14AMfNested(const char *Cmd) if (cmdp == 'o') { PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A'); - if (mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true)) { - PrintAndLog("Nested error."); + int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true); + if (isOK) { + switch (isOK) { + case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; + case -2 : PrintAndLog("Button pressed. Aborted.\n"); break; + case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break; + default : PrintAndLog("Unknown Error.\n"); + } return 2; } key64 = bytes_to_num(keyBlock, 6); @@ -696,11 +707,17 @@ int CmdHF14AMfNested(const char *Cmd) for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) { if (e_sector[sectorNo].foundKey[trgKeyType]) continue; PrintAndLog("-----------------------------------------------"); - if(mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate)) { - PrintAndLog("Nested error.\n"); + int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); + if(isOK) { + switch (isOK) { + case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; + case -2 : PrintAndLog("Button pressed. Aborted.\n"); break; + case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break; + default : PrintAndLog("Unknown Error.\n"); + } free(e_sector); - return 2; } - else { + return 2; + } else { calibrate = false; } diff --git a/client/mifarehost.c b/client/mifarehost.c index 237979c1..95453ebf 100644 --- a/client/mifarehost.c +++ b/client/mifarehost.c @@ -69,7 +69,7 @@ void* nested_worker_thread(void *arg) int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * resultKey, bool calibrate) { - uint16_t i, len; + uint16_t i; uint32_t uid; UsbCommand resp; @@ -77,31 +77,29 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo struct Crypto1State *p1, *p2, *p3, *p4; // flush queue - WaitForResponseTimeout(CMD_ACK,NULL,100); + WaitForResponseTimeout(CMD_ACK, NULL, 100); UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}}; memcpy(c.d.asBytes, key, 6); SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - len = resp.arg[1]; - if (len == 2) { - memcpy(&uid, resp.d.asBytes, 4); - PrintAndLog("uid:%08x len=%d trgbl=%d trgkey=%x", uid, len, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8); - - for (i = 0; i < 2; i++) { - statelists[i].blockNo = resp.arg[2] & 0xff; - statelists[i].keyType = (resp.arg[2] >> 8) & 0xff; - statelists[i].uid = uid; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + return -1; + } - memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4); - memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4); - } - } - else { - PrintAndLog("Got 0 keys from proxmark."); - return 1; - } + if (resp.arg[0]) { + return resp.arg[0]; // error during nested + } + + memcpy(&uid, resp.d.asBytes, 4); + PrintAndLog("uid:%08x trgbl=%d trgkey=%x", uid, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8); + + for (i = 0; i < 2; i++) { + 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].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4); } // calc keys From b29d55f24b7bbdfad0e4c1644d06a046336c07ae Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 27 Jun 2015 22:49:26 -0400 Subject: [PATCH 009/145] change lf config threshold, hf 14b reader, adjust lf config threshold to coincide with graph values and trigger on highs over the threshold or lows under the threshold * -1 split general hf 14b reader from full info printing --- CHANGELOG.md | 6 ++-- armsrc/lfsampling.c | 9 ++++-- client/cmdhf14b.c | 76 +++++++++++++++++++++++++++++++++++++-------- client/cmdlf.c | 2 +- 4 files changed, 74 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f9546d9..0f420915 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,11 +5,13 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] ### Changed +- Changed lf config's `threshold` to a graph (signed) metric and it will trigger on + or - value set to. (example: set to 50 and recording would begin at first graphed value of >= 50 or <= -50) (marshmellow) - Changed `hf 14b write` to `hf 14b sriwrite` as it only applied to sri tags (marshmellow) -- Added `hf 14b info` to `hf search` (marshmellow) +- Added `hf 14b reader` to `hf search` (marshmellow) ### Added -- Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) +- Add `hf 14b reader` to find and print general info about known 14b tags (marshmellow) +- Add `hf 14b info` to find and print full info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) - Add PACE replay functionality (frederikmoellers) ### Fixed diff --git a/armsrc/lfsampling.c b/armsrc/lfsampling.c index 120c0801..662ebf24 100644 --- a/armsrc/lfsampling.c +++ b/armsrc/lfsampling.c @@ -119,8 +119,7 @@ void LFSetupFPGAForADC(int divisor, bool lf_field) * @param silent - is true, now outputs are made. If false, dbprints the status * @return the number of bits occupied by the samples. */ - -uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averaging, int trigger_threshold,bool silent) +uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averaging, int trigger_threshold, bool silent) { //. uint8_t *dest = BigBuf_get_addr(); @@ -151,8 +150,12 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; LED_D_OFF(); - if (trigger_threshold > 0 && sample < trigger_threshold) + // threshold either high or low values 128 = center 0. if trigger = 178 + if ((trigger_threshold > 0) && (sample < (trigger_threshold+128)) && (sample > (128-trigger_threshold))) // continue; + + //if (trigger_threshold > 0 && sample < trigger_threshold) // + //continue; trigger_threshold = 0; sample_total_numbers++; diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index d1d668e9..acbd0c2c 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -197,6 +197,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); } +// print full atqb info static void print_atqb_resp(uint8_t *data){ PrintAndLog (" UID: %s", sprint_hex(data+1,4)); PrintAndLog (" App Data: %s", sprint_hex(data+5,4)); @@ -245,6 +246,7 @@ static void print_atqb_resp(uint8_t *data){ return; } +// get SRx chip model (from UID) // from ST Microelectronics char *get_ST_Chip_Model(uint8_t data){ static char model[20]; char *retStr = model; @@ -263,7 +265,8 @@ char *get_ST_Chip_Model(uint8_t data){ return retStr; } -static void print_st_info(uint8_t *data){ +// print UID info from SRx chips (ST Microelectronics) +static void print_st_general_info(uint8_t *data){ //uid = first 8 bytes in data PrintAndLog(" UID: %s", sprint_hex(SwapEndian64(data,8,8),8)); PrintAndLog(" MFG: %02X, %s", data[6], getTagInfo(data[6])); @@ -271,8 +274,18 @@ static void print_st_info(uint8_t *data){ return; } +// 14b get and print Full Info (as much as we know) int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ + if (!HF14BStdReader(data,datalen)) return 0; + //add more info here + print_atqb_resp(data); + + return 1; +} + +// 14b get and print UID only (general info) +int HF14BStdReader(uint8_t *data, uint8_t *datalen){ //05 00 00 = find one tag in field //1d xx xx xx xx 20 00 08 01 00 = attrib xx=crc //a3 = ? (resp 03 e2 c2) @@ -294,19 +307,30 @@ int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ //std read cmd data[0] = 0x05; data[1] = 0x00; - data[2] = 0x00; + data[2] = 0x08; if (HF14BCmdRaw(true, &crc, false, data, datalen, false)==0) return 0; if (data[0] != 0x50 || *datalen != 14 || !crc) return 0; PrintAndLog ("\n14443-3b tag found:"); - print_atqb_resp(data); + PrintAndLog (" UID: %s", sprint_hex(data+1,4)); return 1; } +// SRx get and print full info (needs more info...) int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ + if (!HF14B_ST_Reader(data, datalen)) return 0; + + //add locking bit information here. + + + return 1; +} + +// SRx get and print general info about SRx chip from UID +int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen){ bool crc = true; *datalen = 2; //wake cmd @@ -342,12 +366,12 @@ int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ if (*datalen != 10 || !crc) return 0; PrintAndLog("\n14443-3b ST tag found:"); - print_st_info(data); + print_st_general_info(data); return 1; } // test for other 14b type tags (mimic another reader - don't have tags to identify) -int HF14B_Other_Info(uint8_t *data, uint8_t *datalen){ +int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ bool crc = true; *datalen = 4; //std read cmd @@ -356,7 +380,7 @@ int HF14B_Other_Info(uint8_t *data, uint8_t *datalen){ data[2] = 0x3f; data[3] = 0x80; - if (HF14BCmdRaw(true, &crc, false, data, datalen, false)!=0) { + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { if (*datalen > 2 || !crc) { PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x000b3f80 command ans:"); @@ -369,7 +393,7 @@ int HF14B_Other_Info(uint8_t *data, uint8_t *datalen){ *datalen = 1; data[0] = 0x0a; - if (HF14BCmdRaw(true, &crc, false, data, datalen, false)!=0) { + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { if (*datalen > 0) { PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x0A command ans:"); @@ -382,7 +406,7 @@ int HF14B_Other_Info(uint8_t *data, uint8_t *datalen){ *datalen = 1; data[0] = 0x0c; - if (HF14BCmdRaw(true, &crc, false, data, datalen, false)!=0) { + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { if (*datalen > 0) { PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x0C command ans:"); @@ -390,11 +414,11 @@ int HF14B_Other_Info(uint8_t *data, uint8_t *datalen){ return 1; } } - + rawClose(); return 0; - } +// get and print all info known about any known 14b tag int HF14BInfo(bool verbose){ uint8_t data[100]; uint8_t datalen = 5; @@ -407,16 +431,41 @@ int HF14BInfo(bool verbose){ // try unknown 14b read commands (to be identified later) // could be read of calypso, CEPAS, moneo, or pico pass. - if (HF14B_Other_Info(data, &datalen)) return 1; + if (HF14B_Other_Reader(data, &datalen)) return 1; if (verbose) PrintAndLog("no 14443B tag found"); return 0; } +// menu command to get and print all info known about any known 14b tag int CmdHF14Binfo(const char *Cmd){ return HF14BInfo(true); } +// get and print general info about all known 14b chips +int HF14BReader(bool verbose){ + uint8_t data[100]; + uint8_t datalen = 5; + + // try std 14b (atqb) + if (HF14BStdReader(data, &datalen)) return 1; + + // try st 14b + if (HF14B_ST_Reader(data, &datalen)) return 1; + + // try unknown 14b read commands (to be identified later) + // could be read of calypso, CEPAS, moneo, or pico pass. + if (HF14B_Other_Reader(data, &datalen)) return 1; + + if (verbose) PrintAndLog("no 14443B tag found"); + return 0; +} + +// menu command to get and print general info about all known 14b chips +int CmdHF14BReader(const char *Cmd){ + return HF14BReader(true); +} + int CmdSriWrite( const char *Cmd){ /* * For SRIX4K blocks 00 - 7F @@ -487,8 +536,9 @@ int CmdSriWrite( const char *Cmd){ static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"info", CmdHF14Binfo, 0, "Find and print info about a 14b type tag (HF ISO 14443b)"}, - {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443b history"}, + {"info", CmdHF14Binfo, 0, "Find and print details about a 14443B tag"}, + {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443B history"}, + {"reader", CmdHF14BReader, 0, "Act as a 14443B reader to identify a tag"}, {"sim", CmdHF14BSim, 0, "Fake ISO 14443B tag"}, {"snoop", CmdHF14BSnoop, 0, "Eavesdrop ISO 14443B"}, {"sri512read", CmdSri512Read, 0, "Read contents of a SRI512 tag"}, diff --git a/client/cmdlf.c b/client/cmdlf.c index edf02932..1acee39b 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -388,7 +388,7 @@ int usage_lf_config() PrintAndLog(" b Sets resolution of bits per sample. Default (max): 8"); PrintAndLog(" d Sets decimation. A value of N saves only 1 in N samples. Default: 1"); PrintAndLog(" a [0|1] Averaging - if set, will average the stored sample value when decimating. Default: 1"); - PrintAndLog(" t Sets trigger threshold. 0 means no threshold"); + PrintAndLog(" t Sets trigger threshold. 0 means no threshold (range: 0-128)"); PrintAndLog("Examples:"); PrintAndLog(" lf config b 8 L"); PrintAndLog(" Samples at 125KHz, 8bps."); From 8a258b5880f37ecabd81de9920b6a41e47699a50 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 27 Jun 2015 23:10:00 -0400 Subject: [PATCH 010/145] re-order 14b reader/info functions to avoid warnings --- client/cmdhf14b.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index acbd0c2c..f1568b94 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -274,16 +274,6 @@ static void print_st_general_info(uint8_t *data){ return; } -// 14b get and print Full Info (as much as we know) -int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ - if (!HF14BStdReader(data,datalen)) return 0; - - //add more info here - print_atqb_resp(data); - - return 1; -} - // 14b get and print UID only (general info) int HF14BStdReader(uint8_t *data, uint8_t *datalen){ //05 00 00 = find one tag in field @@ -319,12 +309,12 @@ int HF14BStdReader(uint8_t *data, uint8_t *datalen){ return 1; } -// SRx get and print full info (needs more info...) -int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ - if (!HF14B_ST_Reader(data, datalen)) return 0; - - //add locking bit information here. +// 14b get and print Full Info (as much as we know) +int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ + if (!HF14BStdReader(data,datalen)) return 0; + //add more info here + print_atqb_resp(data); return 1; } @@ -370,6 +360,16 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen){ return 1; } +// SRx get and print full info (needs more info...) +int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ + if (!HF14B_ST_Reader(data, datalen)) return 0; + + //add locking bit information here. + + + return 1; +} + // test for other 14b type tags (mimic another reader - don't have tags to identify) int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ bool crc = true; From cc34cc7b56a7c6cedb123303ce6ed2f10b544bb8 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 28 Jun 2015 23:47:30 -0400 Subject: [PATCH 011/145] add SRx tag lock bit to hf 14b info --- client/cmdhf14b.c | 93 +++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 81 insertions(+), 12 deletions(-) diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index f1568b94..8e0c54ba 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -265,12 +265,77 @@ char *get_ST_Chip_Model(uint8_t data){ return retStr; } +int print_ST_Lock_info(uint8_t model){ + //assume connection open and tag selected... + uint8_t data[8] = {0x00}; + uint8_t datalen = 2; + bool crc = true; + uint8_t resplen; + uint8_t blk1; + data[0] = 0x08; + + if (model == 0x2) { //SR176 has special command: + data[1] = 0xf; + resplen = 4; + } else { + data[1] = 0xff; + resplen = 6; + } + + //std read cmd + if (HF14BCmdRaw(true, &crc, true, data, &datalen, false)==0) return rawClose(); + + if (datalen != resplen || !crc) return rawClose(); + + PrintAndLog("Chip Write Protection Bits:"); + // now interpret the data + switch (model){ + case 0x0: //fall through (SRIX4K special) + case 0x3: //fall through (SRIx4K) + case 0x7: // (SRI4K) + //only need data[3] + blk1 = 9; + PrintAndLog(" raw: %s",printBits(8,data+3)); + PrintAndLog(" 07/08: %slocked", blk1, (data[3] & 1) ? "not " : "" ); + for (uint8_t i = 1; i<8; i++){ + PrintAndLog(" %02u: %slocked", blk1, (data[3] & (1 << i)) ? "not " : "" ); + blk1++; + } + break; + case 0x4: //fall through (SRIX512) + case 0x6: //fall through (SRI512) + case 0xC: // (SRT512) + //need data[2] and data[3] + blk1 = 0; + PrintAndLog(" raw: %s",printBits(16,data+2)); + for (uint8_t b=2; b<4; b++){ + for (uint8_t i=0; i<8; i++){ + PrintAndLog(" %02u: %slocked", blk1, (data[b] & (1 << i)) ? "not " : "" ); + blk1++; + } + } + break; + case 0x2: // (SR176) + //need data[2] + blk1 = 0; + PrintAndLog(" raw: %s",printBits(8,data+2)); + for (uint8_t i = 0; i<8; i++){ + PrintAndLog(" %02u/%02u: %slocked", blk1, blk1+1, (data[2] & (1 << i)) ? "" : "not " ); + blk1+=2; + } + break; + default: + return rawClose(); + } + return 1; +} + // print UID info from SRx chips (ST Microelectronics) static void print_st_general_info(uint8_t *data){ //uid = first 8 bytes in data - PrintAndLog(" UID: %s", sprint_hex(SwapEndian64(data,8,8),8)); - PrintAndLog(" MFG: %02X, %s", data[6], getTagInfo(data[6])); - PrintAndLog("Chip: %02X, %s", data[5]>>2, get_ST_Chip_Model(data[5]>>2)); + PrintAndLog(" UID: %s", sprint_hex(SwapEndian64(data,8,8),8)); + PrintAndLog(" MFG: %02X, %s", data[6], getTagInfo(data[6])); + PrintAndLog(" Chip: %02X, %s", data[5]>>2, get_ST_Chip_Model(data[5]>>2)); return; } @@ -320,7 +385,7 @@ int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ } // SRx get and print general info about SRx chip from UID -int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen){ +int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ bool crc = true; *datalen = 2; //wake cmd @@ -340,7 +405,6 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen){ *datalen = 2; //leave power on - // verbose on for now for testing - turn off when functional if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); if (*datalen != 3 || !crc || data[0] != chipID) return rawClose(); @@ -349,10 +413,11 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen){ data[0] = 0x0B; *datalen = 1; - //power off - // verbose on for now for testing - turn off when functional - if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return 0; - rawClose(); + //leave power on + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + //power off ? + if (closeCon) rawClose(); + if (*datalen != 10 || !crc) return 0; PrintAndLog("\n14443-3b ST tag found:"); @@ -362,10 +427,11 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen){ // SRx get and print full info (needs more info...) int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ - if (!HF14B_ST_Reader(data, datalen)) return 0; + if (!HF14B_ST_Reader(data, datalen, false)) return 0; //add locking bit information here. - + if (print_ST_Lock_info(data[5]>>2)) + rawClose(); return 1; } @@ -385,6 +451,7 @@ int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x000b3f80 command ans:"); PrintAndLog ("%s",sprint_hex(data,*datalen)); + rawClose(); return 1; } } @@ -398,6 +465,7 @@ int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x0A command ans:"); PrintAndLog ("%s",sprint_hex(data,*datalen)); + rawClose(); return 1; } } @@ -411,6 +479,7 @@ int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ PrintAndLog ("\n14443-3b tag found:"); PrintAndLog ("Unknown tag type answered to a 0x0C command ans:"); PrintAndLog ("%s",sprint_hex(data,*datalen)); + rawClose(); return 1; } } @@ -451,7 +520,7 @@ int HF14BReader(bool verbose){ if (HF14BStdReader(data, &datalen)) return 1; // try st 14b - if (HF14B_ST_Reader(data, &datalen)) return 1; + if (HF14B_ST_Reader(data, &datalen, true)) return 1; // try unknown 14b read commands (to be identified later) // could be read of calypso, CEPAS, moneo, or pico pass. From 09ffd16ee2d0d6d43fc562035487226cf4f58b86 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Mon, 29 Jun 2015 09:07:54 +0200 Subject: [PATCH 012/145] - fix: ensure that FpgaDownloadAndGo() is always called before requesting any memory from BigBuf[]. This is required because FpgaDownloadAndGo() might allocate, use, and free most of BigBuf[] when decompressing FPGA configs. - cleanup: remove rests of deprecated "end of trace markers" (0x44) --- armsrc/BigBuf.c | 10 ++---- armsrc/hitag2.c | 25 ++++++++------ armsrc/iclass.c | 2 -- armsrc/iso14443a.c | 57 ++++++++++++++++--------------- armsrc/iso14443b.c | 10 +++--- armsrc/iso15693.c | 28 +++++++--------- armsrc/mifarecmd.c | 84 ++++++++++++++++++++++++---------------------- 7 files changed, 105 insertions(+), 111 deletions(-) diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index 703ade65..510f7bef 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -96,9 +96,6 @@ uint16_t BigBuf_max_traceLen(void) } void clear_trace() { - uint8_t *trace = BigBuf_get_addr(); - uint16_t max_traceLen = BigBuf_max_traceLen(); - memset(trace, 0x44, max_traceLen); traceLen = 0; } @@ -176,13 +173,10 @@ bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_ } 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) { /** diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index 4b173d6f..719164d1 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -710,22 +710,24 @@ void SnoopHitag(uint32_t type) { byte_t rx[HITAG_FRAME_LEN]; size_t rxlen=0; - auth_table_len = 0; - auth_table_pos = 0; - BigBuf_free(); - auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); - memset(auth_table, 0x00, AUTH_TABLE_LENGTH); + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); // Clean up trace and prepare it for storing frames set_tracing(TRUE); clear_trace(); + auth_table_len = 0; + auth_table_pos = 0; + + BigBuf_free(); + auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); + memset(auth_table, 0x00, AUTH_TABLE_LENGTH); + DbpString("Starting Hitag2 snoop"); LED_D_ON(); // Set up eavesdropping mode, frequency divisor which will drive the FPGA // and analog mux selection. - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); @@ -922,6 +924,12 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { bool bQuitTraceFull = false; bQuiet = false; + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + // Clean up trace and prepare it for storing frames + set_tracing(TRUE); + clear_trace(); + auth_table_len = 0; auth_table_pos = 0; byte_t* auth_table; @@ -929,10 +937,6 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); memset(auth_table, 0x00, AUTH_TABLE_LENGTH); - // Clean up trace and prepare it for storing frames - set_tracing(TRUE); - clear_trace(); - DbpString("Starting Hitag2 simulation"); LED_D_ON(); hitag2_init(); @@ -953,7 +957,6 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { // Set up simulator mode, frequency divisor which will drive the FPGA // and analog mux selection. - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 9139d3bd..97c62bb6 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1125,7 +1125,6 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) int resp_cc_len; uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - memset(receivedCmd, 0x44, MAX_FRAME_SIZE); int len; // Prepare card messages @@ -1336,7 +1335,6 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) } } - memset(receivedCmd, 0x44, MAX_FRAME_SIZE); } //Dbprintf("%x", cmdsRecvd); diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 2fd568b9..5c7367a1 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -551,12 +551,8 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { LEDsoff(); - // We won't start recording the frames that we acquire until we trigger; - // a good trigger condition to get started is probably when we see a - // response from the tag. - // triggered == FALSE -- to wait first for card - bool triggered = !(param & 0x03); - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); @@ -583,8 +579,6 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { bool TagIsActive = FALSE; bool ReaderIsActive = FALSE; - iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse, receivedResponsePar); @@ -594,6 +588,12 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { // Setup and start DMA. FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); + // We won't start recording the frames that we acquire until we trigger; + // a good trigger condition to get started is probably when we see a + // response from the tag. + // triggered == FALSE -- to wait first for card + bool triggered = !(param & 0x03); + // And now we loop, receiving samples. for(uint32_t rsamples = 0; TRUE; ) { @@ -1026,6 +1026,9 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) .modulation_n = 0 }; + // We need to listen to the high-frequency, peak-detected path. + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + BigBuf_free_keep_EM(); // allocate buffers: @@ -1054,9 +1057,6 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) int happened2 = 0; int cmdsRecvd = 0; - // We need to listen to the high-frequency, peak-detected path. - iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - cmdsRecvd = 0; tag_response_info_t* p_response; @@ -1994,6 +1994,10 @@ void ReaderMifare(bool first_try) uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; + if (first_try) { + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + } + // free eventually allocated BigBuf memory. We want all for tracing. BigBuf_free(); @@ -2022,7 +2026,6 @@ void ReaderMifare(bool first_try) if (first_try) { mf_nr_ar3 = 0; - iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); sync_time = GetCountSspClk() & 0xfffffff8; sync_cycles = 65536; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). nt_attacked = 0; @@ -2239,13 +2242,6 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * uint32_t ar_nr_responses[] = {0,0,0,0,0,0,0,0}; uint8_t ar_nr_collected = 0; - // free eventually allocated BigBuf memory but keep Emulator Memory - BigBuf_free_keep_EM(); - - // clear trace - clear_trace(); - set_tracing(TRUE); - // Authenticate response - nonce uint32_t nonce = bytes_to_num(rAUTH_NT, 4); @@ -2287,10 +2283,6 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; } - // We need to listen to the high-frequency, peak-detected path. - iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - - if (MF_DBGLEVEL >= 1) { if (!_7BUID) { Dbprintf("4B UID: %02x%02x%02x%02x", @@ -2302,6 +2294,17 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * } } + // We need to listen to the high-frequency, peak-detected path. + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + + // free eventually allocated BigBuf memory but keep Emulator Memory + BigBuf_free_keep_EM(); + + // clear trace + clear_trace(); + set_tracing(TRUE); + + bool finished = FALSE; while (!BUTTON_PRESS() && !finished) { WDT_HIT(); @@ -2720,10 +2723,8 @@ void RAMFUNC SniffMifare(uint8_t param) { uint8_t receivedResponse[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedResponsePar[MAX_MIFARE_PARITY_SIZE]; - // As we receive stuff, we copy it from receivedCmd or receivedResponse - // into trace, along with its length and other annotations. - //uint8_t *trace = (uint8_t *)BigBuf; - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + // free eventually allocated BigBuf memory BigBuf_free(); // allocate the DMA buffer, used to stream samples from the FPGA @@ -2735,8 +2736,6 @@ void RAMFUNC SniffMifare(uint8_t param) { bool ReaderIsActive = FALSE; bool TagIsActive = FALSE; - iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse, receivedResponsePar); diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 416c31f9..33c047d8 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -334,6 +334,8 @@ void SimulateIso14443bTag(void) 0x00, 0x21, 0x85, 0x5e, 0xd7 }; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + clear_trace(); set_tracing(TRUE); @@ -348,8 +350,6 @@ void SimulateIso14443bTag(void) uint16_t len; uint16_t cmdsRecvd = 0; - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); uint8_t *resp1Code = BigBuf_malloc(ToSendMax); @@ -908,9 +908,6 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) //----------------------------------------------------------------------------- void ReadSTMemoryIso14443b(uint32_t dwLast) { - clear_trace(); - set_tracing(TRUE); - uint8_t i = 0x00; FpgaDownloadAndGo(FPGA_BITSTREAM_HF); @@ -929,6 +926,9 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); SpinDelay(200); + clear_trace(); + set_tracing(TRUE); + // First command: wake up the tag using the INITIATE command uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index 94040a85..e7145c5c 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -877,12 +877,12 @@ int SendDataTag(uint8_t *send, int sendlen, int init, int speed, uint8_t **recv) LED_C_OFF(); LED_D_OFF(); + if (init) Iso15693InitReader(); + int answerLen=0; uint8_t *answer = BigBuf_get_addr() + 3660; if (recv != NULL) memset(answer, 0, 100); - if (init) Iso15693InitReader(); - if (!speed) { // low speed (1 out of 256) CodeIso15693AsReader256(send, sendlen); @@ -999,10 +999,6 @@ void ReaderIso15693(uint32_t parameter) LED_C_OFF(); LED_D_OFF(); - uint8_t *answer1 = BigBuf_get_addr() + 3660; - uint8_t *answer2 = BigBuf_get_addr() + 3760; - uint8_t *answer3 = BigBuf_get_addr() + 3860; - int answerLen1 = 0; int answerLen2 = 0; int answerLen3 = 0; @@ -1013,19 +1009,21 @@ void ReaderIso15693(uint32_t parameter) int elapsed = 0; uint8_t TagUID[8] = {0x00}; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + uint8_t *answer1 = BigBuf_get_addr() + 3660; + uint8_t *answer2 = BigBuf_get_addr() + 3760; + uint8_t *answer3 = BigBuf_get_addr() + 3860; // Blank arrays memset(answer1, 0x00, 300); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Setup SSC FpgaSetupSsc(); // Start from off (no field generated) - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); // Give the tags time to energize FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); @@ -1111,24 +1109,22 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) LED_C_OFF(); LED_D_OFF(); - uint8_t *buf = BigBuf_get_addr() + 3660; - int answerLen1 = 0; int samples = 0; int tsamples = 0; int wait = 0; int elapsed = 0; - memset(buf, 0x00, 100); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + uint8_t *buf = BigBuf_get_addr() + 3660; + memset(buf, 0x00, 100); + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); // Start from off (no field generated) - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelay(200); LED_A_OFF(); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 14d2b68a..c2d85abb 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -44,10 +44,10 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -95,9 +95,11 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes){ bool turnOffField = (arg0 == 1); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); OnError(0); @@ -129,9 +131,10 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + int len = iso14443a_select_card(NULL, NULL, NULL); if(!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%02X)",len); @@ -199,11 +202,10 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -252,6 +254,10 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) // datain = KEY bytes void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { + LEDsoff(); + LED_A_ON(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + // free eventually allocated BigBuf memory BigBuf_free(); clear_trace(); @@ -269,10 +275,6 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) return; } - LEDsoff(); - LED_A_ON(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - int len = iso14443a_select_card(NULL, NULL, NULL); if (!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%d)",len); @@ -366,11 +368,10 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -472,9 +473,10 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -530,9 +532,10 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ memcpy(pwd, datain, 16); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -632,18 +635,16 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat uint32_t auth1_time, auth2_time; static uint16_t delta_time; + LED_A_ON(); + LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + // free eventually allocated BigBuf memory BigBuf_free(); - // clear trace + clear_trace(); set_tracing(false); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - - LED_A_ON(); - LED_C_OFF(); - - // statistics on nonce distance int16_t isOK = 0; #define NESTED_MAX_TRIES 12 @@ -847,15 +848,13 @@ void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) int OLD_MF_DBGLEVEL = MF_DBGLEVEL; MF_DBGLEVEL = MF_DBG_NONE; - // clear trace - clear_trace(); - set_tracing(TRUE); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + clear_trace(); + set_tracing(TRUE); for (i = 0; i < keyCount; i++) { if(mifare_classic_halt(pcs, cuid)) { @@ -902,16 +901,23 @@ void MifareSetDbgLvl(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai //----------------------------------------------------------------------------- // Work with emulator memory // +// Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not +// involved in dealing with emulator memory. But if it is called later, it might +// destroy the Emulator Memory. //----------------------------------------------------------------------------- + void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); emlClearMem(); } void MifareEMemSet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); emlSetMem(datain, arg0, arg1); // data, block num, blocks count } void MifareEMemGet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); byte_t buf[USB_CMD_DATA_SIZE]; emlGetMem(buf, arg0, arg1); // data, block num, blocks count (max 4) @@ -938,15 +944,13 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai byte_t dataoutbuf2[16]; uint8_t uid[10]; - // clear trace - clear_trace(); - set_tracing(false); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + clear_trace(); + set_tracing(false); bool isOK = true; @@ -1040,10 +1044,10 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(TRUE); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } while (true) { @@ -1158,10 +1162,10 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); set_tracing(TRUE); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } while (true) { @@ -1236,7 +1240,7 @@ void MifareCIdent(){ cmd_send(CMD_ACK,isOK,0,0,0,0); } - // +// // DESFIRE // @@ -1246,8 +1250,8 @@ void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain){ uint8_t uid[10] = {0x00}; uint32_t cuid; - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); int len = iso14443a_select_card(uid, NULL, &cuid); if(!len) { From 8e00825a3491113508085b4ea949b10aa47499b9 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 29 Jun 2015 14:33:44 -0400 Subject: [PATCH 013/145] fixed improper printBits usage. --- client/cmdhf14b.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 8e0c54ba..fafe92ca 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -295,7 +295,7 @@ int print_ST_Lock_info(uint8_t model){ case 0x7: // (SRI4K) //only need data[3] blk1 = 9; - PrintAndLog(" raw: %s",printBits(8,data+3)); + PrintAndLog(" raw: %s",printBits(1,data+3)); PrintAndLog(" 07/08: %slocked", blk1, (data[3] & 1) ? "not " : "" ); for (uint8_t i = 1; i<8; i++){ PrintAndLog(" %02u: %slocked", blk1, (data[3] & (1 << i)) ? "not " : "" ); @@ -307,7 +307,7 @@ int print_ST_Lock_info(uint8_t model){ case 0xC: // (SRT512) //need data[2] and data[3] blk1 = 0; - PrintAndLog(" raw: %s",printBits(16,data+2)); + PrintAndLog(" raw: %s",printBits(2,data+2)); for (uint8_t b=2; b<4; b++){ for (uint8_t i=0; i<8; i++){ PrintAndLog(" %02u: %slocked", blk1, (data[b] & (1 << i)) ? "not " : "" ); @@ -318,7 +318,7 @@ int print_ST_Lock_info(uint8_t model){ case 0x2: // (SR176) //need data[2] blk1 = 0; - PrintAndLog(" raw: %s",printBits(8,data+2)); + PrintAndLog(" raw: %s",printBits(1,data+2)); for (uint8_t i = 0; i<8; i++){ PrintAndLog(" %02u/%02u: %slocked", blk1, blk1+1, (data[2] & (1 << i)) ? "" : "not " ); blk1+=2; From c3ebcce424827a2ae8e4321d06db2bfacc4df183 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 29 Jun 2015 16:34:41 -0400 Subject: [PATCH 014/145] fixed output bug in sri4k info output. too many parameters line 299 --- client/cmdhf14b.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index fafe92ca..bfec86c5 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -267,7 +267,7 @@ char *get_ST_Chip_Model(uint8_t data){ int print_ST_Lock_info(uint8_t model){ //assume connection open and tag selected... - uint8_t data[8] = {0x00}; + uint8_t data[16] = {0x00}; uint8_t datalen = 2; bool crc = true; uint8_t resplen; @@ -296,9 +296,9 @@ int print_ST_Lock_info(uint8_t model){ //only need data[3] blk1 = 9; PrintAndLog(" raw: %s",printBits(1,data+3)); - PrintAndLog(" 07/08: %slocked", blk1, (data[3] & 1) ? "not " : "" ); + PrintAndLog(" 07/08:%slocked", (data[3] & 1) ? " not " : " " ); for (uint8_t i = 1; i<8; i++){ - PrintAndLog(" %02u: %slocked", blk1, (data[3] & (1 << i)) ? "not " : "" ); + PrintAndLog(" %02u:%slocked", blk1, (data[3] & (1 << i)) ? " not " : " " ); blk1++; } break; @@ -310,7 +310,7 @@ int print_ST_Lock_info(uint8_t model){ PrintAndLog(" raw: %s",printBits(2,data+2)); for (uint8_t b=2; b<4; b++){ for (uint8_t i=0; i<8; i++){ - PrintAndLog(" %02u: %slocked", blk1, (data[b] & (1 << i)) ? "not " : "" ); + PrintAndLog(" %02u:%slocked", blk1, (data[b] & (1 << i)) ? " not " : " " ); blk1++; } } @@ -320,7 +320,7 @@ int print_ST_Lock_info(uint8_t model){ blk1 = 0; PrintAndLog(" raw: %s",printBits(1,data+2)); for (uint8_t i = 0; i<8; i++){ - PrintAndLog(" %02u/%02u: %slocked", blk1, blk1+1, (data[2] & (1 << i)) ? "" : "not " ); + PrintAndLog(" %02u/%02u:%slocked", blk1, blk1+1, (data[2] & (1 << i)) ? " " : " not " ); blk1+=2; } break; @@ -415,11 +415,12 @@ int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ //leave power on if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (*datalen != 10 || !crc) return rawClose(); + //power off ? if (closeCon) rawClose(); - if (*datalen != 10 || !crc) return 0; - PrintAndLog("\n14443-3b ST tag found:"); print_st_general_info(data); return 1; From b8edab0f831881c8a2aa13e9df45177ed092663b Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 29 Jun 2015 21:33:10 -0400 Subject: [PATCH 015/145] add -s to hf 14b raw to select a std 14b tag first --- client/cmdhf14b.c | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index bfec86c5..9c65bb2f 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -132,6 +132,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { bool reply = true; bool crc = false; bool power = false; + bool select = false; char buf[5] = ""; uint8_t data[100] = {0x00}; uint8_t datalen = 0; @@ -142,7 +143,8 @@ int CmdHF14BCmdRaw (const char *Cmd) { PrintAndLog(" -r do not read response"); PrintAndLog(" -c calculate and append CRC"); PrintAndLog(" -p leave the field on after receive"); - return 0; + PrintAndLog(" -s active signal field ON with select"); + return 0; } // strip @@ -164,6 +166,10 @@ int CmdHF14BCmdRaw (const char *Cmd) { case 'P': power = true; break; + case 's': + case 'S': + select = true; + break; default: PrintAndLog("Invalid option"); return 0; @@ -194,6 +200,30 @@ int CmdHF14BCmdRaw (const char *Cmd) { return 0; } + if (select){ + uint8_t cmd2[16]; + uint8_t cmdLen = 3; + bool crc2 = true; + cmd2[0] = 0x05; + cmd2[1] = 0x00; + cmd2[2] = 0x08; + + if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + + if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); + + data[0] = 0x1D; + data[5] = 0x00; + data[6] = 0x08; + data[7] = 0x01; + data[8] = 0x00; + + cmdLen = 9; + if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + + if (cmd2[0] != 0x10 || cmdLen != 3 || !crc2) return rawClose(); + } + return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); } @@ -342,9 +372,9 @@ static void print_st_general_info(uint8_t *data){ // 14b get and print UID only (general info) int HF14BStdReader(uint8_t *data, uint8_t *datalen){ //05 00 00 = find one tag in field - //1d xx xx xx xx 20 00 08 01 00 = attrib xx=crc - //a3 = ? (resp 03 e2 c2) - //02 = ? (resp 02 6a d3) + //1d xx xx xx xx 00 08 01 00 = attrib xx=UID (resp 10 [f9 e0]) + //a3 = ? (resp 03 [e2 c2]) + //02 = ? (resp 02 [6a d3]) // 022b (resp 02 67 00 [29 5b]) // 0200a40400 (resp 02 67 00 [29 5b]) // 0200a4040c07a0000002480300 (resp 02 67 00 [29 5b]) @@ -366,7 +396,7 @@ int HF14BStdReader(uint8_t *data, uint8_t *datalen){ if (HF14BCmdRaw(true, &crc, false, data, datalen, false)==0) return 0; - if (data[0] != 0x50 || *datalen != 14 || !crc) return 0; + if (data[0] != 0x50 || *datalen != 14 || !crc) return 0; PrintAndLog ("\n14443-3b tag found:"); PrintAndLog (" UID: %s", sprint_hex(data+1,4)); From 1c7d367e249f6ac133950b65d48d740c36859a65 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 29 Jun 2015 21:41:48 -0400 Subject: [PATCH 016/145] update comments and changelog --- CHANGELOG.md | 7 +++---- client/cmdhf14b.c | 9 ++++++--- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f420915..75b9ad9b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,13 +5,12 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] ### Changed -- Changed lf config's `threshold` to a graph (signed) metric and it will trigger on + or - value set to. (example: set to 50 and recording would begin at first graphed value of >= 50 or <= -50) (marshmellow) +- Added `hf 14b raw -s` option to auto select a 14b std tag before raw command - Changed `hf 14b write` to `hf 14b sriwrite` as it only applied to sri tags (marshmellow) -- Added `hf 14b reader` to `hf search` (marshmellow) +- Added `hf 14b info` to `hf search` (marshmellow) ### Added -- Add `hf 14b reader` to find and print general info about known 14b tags (marshmellow) -- Add `hf 14b info` to find and print full info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) +- Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) - Add PACE replay functionality (frederikmoellers) ### Fixed diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 9c65bb2f..6bc5daf2 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -200,7 +200,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { return 0; } - if (select){ + if (select){ //auto select 14b tag uint8_t cmd2[16]; uint8_t cmdLen = 3; bool crc2 = true; @@ -208,17 +208,20 @@ int CmdHF14BCmdRaw (const char *Cmd) { cmd2[1] = 0x00; cmd2[2] = 0x08; + // REQB if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); - data[0] = 0x1D; + data[0] = 0x1D; + // UID from data[1 - 4] data[5] = 0x00; data[6] = 0x08; data[7] = 0x01; data[8] = 0x00; - cmdLen = 9; + + // attrib if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); if (cmd2[0] != 0x10 || cmdLen != 3 || !crc2) return rawClose(); From 9d84e689647c7f5b3bae29de8f2dce4781aa63b4 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 30 Jun 2015 09:46:37 -0400 Subject: [PATCH 017/145] fix 14b raw -s option, + get rid of... --- armsrc/iso14443b.c | 30 ++++++++++++++++-------------- client/cmdhf14b.c | 10 +++++----- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 33c047d8..7a0fc8e0 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -334,8 +334,6 @@ void SimulateIso14443bTag(void) 0x00, 0x21, 0x85, 0x5e, 0xd7 }; - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - clear_trace(); set_tracing(TRUE); @@ -350,6 +348,8 @@ void SimulateIso14443bTag(void) uint16_t len; uint16_t cmdsRecvd = 0; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); uint8_t *resp1Code = BigBuf_malloc(ToSendMax); @@ -908,6 +908,9 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) //----------------------------------------------------------------------------- void ReadSTMemoryIso14443b(uint32_t dwLast) { + clear_trace(); + set_tracing(TRUE); + uint8_t i = 0x00; FpgaDownloadAndGo(FPGA_BITSTREAM_HF); @@ -926,9 +929,6 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); SpinDelay(200); - clear_trace(); - set_tracing(TRUE); - // First command: wake up the tag using the INITIATE command uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); @@ -1199,17 +1199,19 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u FpgaDownloadAndGo(FPGA_BITSTREAM_HF); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); FpgaSetupSsc(); - - set_tracing(TRUE); - CodeAndTransmit14443bAsReader(data, datalen); + if (datalen){ + set_tracing(TRUE); + + CodeAndTransmit14443bAsReader(data, datalen); + + if(recv) { + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE); + cmd_send(CMD_ACK, iLen, 0, 0, Demod.output, iLen); + } + } - if(recv) { - GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); - uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE); - cmd_send(CMD_ACK, iLen, 0, 0, Demod.output, iLen); - } - if(!powerfield) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LED_D_OFF(); diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 6bc5daf2..77dba684 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -213,12 +213,12 @@ int CmdHF14BCmdRaw (const char *Cmd) { if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); - data[0] = 0x1D; + cmd2[0] = 0x1D; // UID from data[1 - 4] - data[5] = 0x00; - data[6] = 0x08; - data[7] = 0x01; - data[8] = 0x00; + cmd2[5] = 0x00; + cmd2[6] = 0x08; + cmd2[7] = 0x01; + cmd2[8] = 0x00; cmdLen = 9; // attrib From 5f605b8fc859f495ecf25184fbee9f8eca1f96d2 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 30 Jun 2015 13:00:51 -0400 Subject: [PATCH 018/145] re-add piwi's trace memory fixes --- armsrc/iso14443b.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 7a0fc8e0..10b9e953 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -334,6 +334,8 @@ void SimulateIso14443bTag(void) 0x00, 0x21, 0x85, 0x5e, 0xd7 }; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + clear_trace(); set_tracing(TRUE); @@ -348,8 +350,6 @@ void SimulateIso14443bTag(void) uint16_t len; uint16_t cmdsRecvd = 0; - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); uint8_t *resp1Code = BigBuf_malloc(ToSendMax); @@ -908,9 +908,6 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) //----------------------------------------------------------------------------- void ReadSTMemoryIso14443b(uint32_t dwLast) { - clear_trace(); - set_tracing(TRUE); - uint8_t i = 0x00; FpgaDownloadAndGo(FPGA_BITSTREAM_HF); @@ -929,6 +926,9 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); SpinDelay(200); + clear_trace(); + set_tracing(TRUE); + // First command: wake up the tag using the INITIATE command uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); @@ -1199,7 +1199,7 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u FpgaDownloadAndGo(FPGA_BITSTREAM_HF); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); FpgaSetupSsc(); - + if (datalen){ set_tracing(TRUE); From 6e6f1099c83989b45c494d18cf701ffcff4af5ee Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 1 Jul 2015 07:12:10 +0200 Subject: [PATCH 019/145] hf topaz reader: add support for dynamic lock areas --- client/cmdhftopaz.c | 93 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 80 insertions(+), 13 deletions(-) diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c index 4e515f78..ebe3a571 100644 --- a/client/cmdhftopaz.c +++ b/client/cmdhftopaz.c @@ -22,15 +22,25 @@ #include "iso14443crc.h" #include "protocols.h" -#define TOPAZ_MAX_MEMORY 2048 +#define TOPAZ_STATIC_MEMORY (0x0f * 8) + +typedef struct dynamic_lock_area { + struct dynamic_lock_area *next; + uint16_t byte_offset; + uint16_t size_in_bits; + uint16_t first_locked_byte; + uint16_t bytes_locked_per_bit; +} dynamic_lock_area_t; + static struct { uint8_t HR01[2]; uint8_t uid[7]; uint8_t size; - uint8_t data_blocks[TOPAZ_MAX_MEMORY/8][8]; - uint8_t *dynamic_lock_areas; + uint8_t data_blocks[TOPAZ_STATIC_MEMORY/8][8]; + dynamic_lock_area_t *dynamic_lock_areas; uint8_t *dynamic_reserved_areas; + uint8_t *dynamic_memory; } topaz_tag; @@ -115,8 +125,46 @@ static int topaz_rall(uint8_t *uid, uint8_t *response) } -static bool topaz_block_is_locked(uint8_t blockno, uint8_t *lockbits) +static dynamic_lock_area_t *get_dynamic_lock_area(uint16_t byteno) { + dynamic_lock_area_t *lock_area; + + lock_area = topaz_tag.dynamic_lock_areas; + + while (lock_area != NULL) { + if (byteno < lock_area->first_locked_byte) { + lock_area = lock_area->next; + } else { + return lock_area; + } + } + + return NULL; +} + + +// check if a memory block (8 Bytes) is locked. +// TODO: support other sizes of locked_bytes_per_bit (current assumption: each lock bit locks 8 Bytes) +static bool topaz_byte_is_locked(uint16_t byteno) +{ + uint8_t *lockbits; + uint16_t locked_bytes_per_bit; + dynamic_lock_area_t *lock_area; + + if (byteno < TOPAZ_STATIC_MEMORY) { + lockbits = &topaz_tag.data_blocks[0x0e][0]; + locked_bytes_per_bit = 8; + } else { + lock_area = get_dynamic_lock_area(byteno); + if (lock_area == NULL) { + return false; + } + locked_bytes_per_bit = lock_area->bytes_locked_per_bit; + byteno = byteno - lock_area->first_locked_byte; + lockbits = &topaz_tag.dynamic_memory[lock_area->byte_offset - TOPAZ_STATIC_MEMORY]; + } + + uint16_t blockno = byteno / locked_bytes_per_bit; if(lockbits[blockno/8] >> (blockno % 8) & 0x01) { return true; } else { @@ -134,7 +182,9 @@ static int topaz_print_CC(uint8_t *data) PrintAndLog("Capability Container: %02x %02x %02x %02x", data[0], data[1], data[2], data[3]); PrintAndLog(" %02x: NDEF Magic Number", data[0]); PrintAndLog(" %02x: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); - PrintAndLog(" %02x: Physical Memory Size of this tag: %d bytes", data[2], (data[2] + 1) * 8); + uint16_t memsize = (data[2] + 1) * 8; + topaz_tag.dynamic_memory = malloc(memsize - TOPAZ_STATIC_MEMORY); + PrintAndLog(" %02x: Physical Memory Size of this tag: %d bytes", data[2], memsize); PrintAndLog(" %02x: %s / %s", data[3], (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", (data[3] & 0x0F)==0 ? "Write access granted without any security" : (data[3] & 0x0F)==0x0F ? "No write access granted at all" : "(RFU)"); @@ -181,6 +231,7 @@ static bool topaz_print_lock_control_TLVs(uint8_t *memory) uint16_t length; uint8_t *value; bool lock_TLV_present = false; + uint16_t first_locked_byte = 0x0f * 8; while(*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { // all Lock Control TLVs shall be present before the NDEF message TLV, the proprietary TLV (and the Terminator TLV) @@ -188,14 +239,30 @@ static bool topaz_print_lock_control_TLVs(uint8_t *memory) if (tag == 0x01) { // the Lock Control TLV uint8_t pages_addr = value[0] >> 4; uint8_t byte_offset = value[0] & 0x0f; - uint8_t size_in_bits = value[1] ? value[1] : 256; - uint8_t bytes_per_page = 1 << (value[2] & 0x0f); - uint8_t bytes_locked_per_bit = 1 << (value[2] >> 4); - PrintAndLog("Lock Area of %d bits at byte offset 0x%02x. Each Lock Bit locks %d bytes.", + uint16_t size_in_bits = value[1] ? value[1] : 256; + uint16_t bytes_per_page = 1 << (value[2] & 0x0f); + uint16_t bytes_locked_per_bit = 1 << (value[2] >> 4); + PrintAndLog("Lock Area of %d bits at byte offset 0x%04x. Each Lock Bit locks %d bytes.", size_in_bits, pages_addr * bytes_per_page + byte_offset, bytes_locked_per_bit); lock_TLV_present = true; + dynamic_lock_area_t *old = topaz_tag.dynamic_lock_areas; + dynamic_lock_area_t *new = topaz_tag.dynamic_lock_areas; + if (old == NULL) { + new = topaz_tag.dynamic_lock_areas = (dynamic_lock_area_t *)malloc(sizeof(dynamic_lock_area_t)); + } else { + while(old->next != NULL) { + old = old->next; + } + new = old->next = (dynamic_lock_area_t *)malloc(sizeof(dynamic_lock_area_t)); + } + new->next = NULL; + new->first_locked_byte = first_locked_byte; + new->byte_offset = pages_addr * bytes_per_page + byte_offset; + new->size_in_bits = size_in_bits; + new->bytes_locked_per_bit = bytes_locked_per_bit; + first_locked_byte = first_locked_byte + size_in_bits*bytes_locked_per_bit; } } @@ -314,13 +381,13 @@ int CmdHFTopazReader(const char *Cmd) memcpy(topaz_tag.data_blocks, rall_response+2, 0x10*8); PrintAndLog(""); PrintAndLog("Static Data blocks 00 to 0c:"); - PrintAndLog("block# | offset | Data | Locked?"); + PrintAndLog("block# | offset | Data | Locked(y/n)"); char line[80]; for (uint16_t i = 0; i <= 0x0c; i++) { for (uint16_t j = 0; j < 8; j++) { sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[i][j] /*rall_response[2 + 8*i + j]*/); } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, topaz_block_is_locked(i, &topaz_tag.data_blocks[0x0e][0]) ? "yes" : "no"); + PrintAndLog(" 0x%02x | 0x%04x | %s| %-3s", i, i*8, line, topaz_byte_is_locked(i*8) ? "yyyyyyyy" : "nnnnnnnn"); } PrintAndLog(""); @@ -328,14 +395,14 @@ int CmdHFTopazReader(const char *Cmd) for (uint16_t j = 0; j < 8; j++) { sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0d][j]); } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); + PrintAndLog(" 0x%02x | 0x%04x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); PrintAndLog(""); PrintAndLog("Static Lockbits and OTP Bytes:"); for (uint16_t j = 0; j < 8; j++) { sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0e][j]); } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0e, 0x0e*8, line, "n/a"); + PrintAndLog(" 0x%02x | 0x%04x | %s| %-3s", 0x0e, 0x0e*8, line, "n/a"); PrintAndLog(""); From f3b83bee837314a4d2bf97bc5e17cd3705a21fde Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 2 Jul 2015 15:04:09 -0400 Subject: [PATCH 020/145] small fixes to 14b info, added 14b sim cmds --- armsrc/iso14443b.c | 52 ++++++++++++++++++++++++++++++++++++---------- client/cmdhf14b.c | 42 ++++++++++++++++++++++++++++++------- 2 files changed, 75 insertions(+), 19 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 10b9e953..76ad9e9a 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -321,10 +321,16 @@ static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) //----------------------------------------------------------------------------- void SimulateIso14443bTag(void) { - // the only commands we understand is REQB, AFI=0, Select All, N=0: - static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; + // the only commands we understand is REQB, AFI=0, Select All, N=8: + static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // REQB // ... and REQB, AFI=0, Normal Request, N=0: - static const uint8_t cmd2[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; + static const uint8_t cmd2[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; // REQB + // ... and WUPB, AFI=0, N=8: + static const uint8_t cmd3[] = { 0x05, 0x08, 0x08, 0xF9, 0xBD }; // WUPB + // ... and HLTB + static const uint8_t cmd4[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB + // ... and ATTRIB + static const uint8_t cmd5[] = { 0x1D, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB // ... and we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922, // supports only 106kBit/s in both directions, max frame size = 32Bytes, @@ -333,6 +339,9 @@ void SimulateIso14443bTag(void) 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 }; + // response to HLTB and ATTRIB + static const uint8_t response2[] = {0x00, 0x78, 0xF0}; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); @@ -356,6 +365,12 @@ void SimulateIso14443bTag(void) memcpy(resp1Code, ToSend, ToSendMax); uint16_t resp1CodeLen = ToSendMax; + // prepare the (other) tag answer: + CodeIso14443bAsTag(response2, sizeof(response2)); + uint8_t *resp2Code = BigBuf_malloc(ToSendMax); + memcpy(resp2Code, ToSend, ToSendMax); + uint16_t resp2CodeLen = ToSendMax; + // We need to listen to the high-frequency, peak-detected path. SetAdcMuxFor(GPIO_MUXSEL_HIPKD); FpgaSetupSsc(); @@ -376,23 +391,38 @@ void SimulateIso14443bTag(void) // Good, look at the command now. if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) - || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) { + || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) + || (len == sizeof(cmd3) && memcmp(receivedCmd, cmd3, len) == 0) ) { resp = response1; respLen = sizeof(response1); respCode = resp1Code; respCodeLen = resp1CodeLen; + } else if ( (len == sizeof(cmd4) && receivedCmd[0] == cmd4[0]) + || (len == sizeof(cmd5) && receivedCmd[0] == cmd5[0]) ) { + resp = response2; + respLen = sizeof(response2); + respCode = resp2Code; + respCodeLen = resp2CodeLen; } else { Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); // And print whether the CRC fails, just for good measure uint8_t b1, b2; - ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2); - if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) { - // Not so good, try again. - DbpString("+++CRC fail"); - } else { - DbpString("CRC passes"); + if (len >= 3){ // if crc exists + ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2); + if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) { + // Not so good, try again. + DbpString("+++CRC fail"); + } else { + DbpString("CRC passes"); + } } - break; + //get rid of compiler warning + respCodeLen = 0; + resp = response1; + respLen = 0; + respCode = resp1Code; + //don't crash at new command just wait and see if reader will send other new cmds. + //break; } cmdsRecvd++; diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 77dba684..bec1d19c 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -206,7 +206,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { bool crc2 = true; cmd2[0] = 0x05; cmd2[1] = 0x00; - cmd2[2] = 0x08; + cmd2[2] = 0x00; // REQB if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); @@ -224,7 +224,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { // attrib if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); - if (cmd2[0] != 0x10 || cmdLen != 3 || !crc2) return rawClose(); + if (cmdLen != 3 || !crc2) return rawClose(); } return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); @@ -232,7 +232,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { // print full atqb info static void print_atqb_resp(uint8_t *data){ - PrintAndLog (" UID: %s", sprint_hex(data+1,4)); + //PrintAndLog (" UID: %s", sprint_hex(data+1,4)); PrintAndLog (" App Data: %s", sprint_hex(data+5,4)); PrintAndLog (" Protocol: %s", sprint_hex(data+9,3)); uint8_t BitRate = data[9]; @@ -267,14 +267,15 @@ static void print_atqb_resp(uint8_t *data){ else maxFrame = 257; - PrintAndLog ("Max Frame Size: %d%s",maxFrame, (maxFrame == 257) ? "+ RFU" : ""); + PrintAndLog ("Max Frame Size: %u%s",maxFrame, (maxFrame == 257) ? "+ RFU" : ""); uint8_t protocolT = data[10] & 0xF; PrintAndLog (" Protocol Type: Protocol is %scompliant with ISO/IEC 14443-4",(protocolT) ? "" : "not " ); - PrintAndLog ("Frame Wait Int: %d", data[11]>>4); + PrintAndLog ("Frame Wait Int: %u", data[11]>>4); PrintAndLog (" App Data Code: Application is %s",(data[11]&4) ? "Standard" : "Proprietary"); PrintAndLog (" Frame Options: NAD is %ssupported",(data[11]&2) ? "" : "not "); PrintAndLog (" Frame Options: CID is %ssupported",(data[11]&1) ? "" : "not "); + PrintAndLog ("Max Buf Length: %u (MBLI) %s",data[14]>>4, (data[14] & 0xF0) ? "" : "not supported"); return; } @@ -390,20 +391,44 @@ int HF14BStdReader(uint8_t *data, uint8_t *datalen){ //03 = ? (resp 03 [e3 c2]) //c2 = ? (resp c2 [66 15]) //b2 = ? (resp a3 [e9 67]) + //a2 = ? (resp 02 [6a d3]) bool crc = true; *datalen = 3; //std read cmd data[0] = 0x05; data[1] = 0x00; - data[2] = 0x08; + data[2] = 0x00; - if (HF14BCmdRaw(true, &crc, false, data, datalen, false)==0) return 0; + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); - if (data[0] != 0x50 || *datalen != 14 || !crc) return 0; + if (data[0] != 0x50 || *datalen != 14 || !crc) return rawClose(); PrintAndLog ("\n14443-3b tag found:"); PrintAndLog (" UID: %s", sprint_hex(data+1,4)); + uint8_t cmd2[16]; + uint8_t cmdLen = 3; + bool crc2 = true; + + cmd2[0] = 0x1D; + // UID from data[1 - 4] + cmd2[1] = data[1]; + cmd2[2] = data[2]; + cmd2[3] = data[3]; + cmd2[4] = data[4]; + cmd2[5] = 0x00; + cmd2[6] = 0x08; + cmd2[7] = 0x01; + cmd2[8] = 0x00; + cmdLen = 9; + + // attrib + if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + + if (cmdLen != 3 || !crc2) return rawClose(); + // add attrib responce to data + data[14] = cmd2[0]; + rawClose(); return 1; } @@ -414,6 +439,7 @@ int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ //add more info here print_atqb_resp(data); + return 1; } From 146600578c1ab840c33321662ee91ce169bb9086 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 3 Jul 2015 22:35:03 -0400 Subject: [PATCH 021/145] fix my understanding of REQB vs WUPB --- armsrc/iso14443b.c | 20 +++++++++----------- client/cmdhf14b.c | 4 ++-- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 76ad9e9a..31634a83 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -321,16 +321,14 @@ static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) //----------------------------------------------------------------------------- void SimulateIso14443bTag(void) { - // the only commands we understand is REQB, AFI=0, Select All, N=8: - static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // REQB - // ... and REQB, AFI=0, Normal Request, N=0: + // the only commands we understand is WUPB, AFI=0, Select All, N=1: + static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // WUPB + // ... and REQB, AFI=0, Normal Request, N=1: static const uint8_t cmd2[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; // REQB - // ... and WUPB, AFI=0, N=8: - static const uint8_t cmd3[] = { 0x05, 0x08, 0x08, 0xF9, 0xBD }; // WUPB // ... and HLTB - static const uint8_t cmd4[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB + static const uint8_t cmd3[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB // ... and ATTRIB - static const uint8_t cmd5[] = { 0x1D, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB + static const uint8_t cmd4[] = { 0x1D, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB // ... and we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922, // supports only 106kBit/s in both directions, max frame size = 32Bytes, @@ -391,14 +389,13 @@ void SimulateIso14443bTag(void) // Good, look at the command now. if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) - || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) - || (len == sizeof(cmd3) && memcmp(receivedCmd, cmd3, len) == 0) ) { + || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) { resp = response1; respLen = sizeof(response1); respCode = resp1Code; respCodeLen = resp1CodeLen; - } else if ( (len == sizeof(cmd4) && receivedCmd[0] == cmd4[0]) - || (len == sizeof(cmd5) && receivedCmd[0] == cmd5[0]) ) { + } else if ( (len == sizeof(cmd3) && receivedCmd[0] == cmd3[0]) + || (len == sizeof(cmd4) && receivedCmd[0] == cmd4[0]) ) { resp = response2; respLen = sizeof(response2); respCode = resp2Code; @@ -412,6 +409,7 @@ void SimulateIso14443bTag(void) if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) { // Not so good, try again. DbpString("+++CRC fail"); + } else { DbpString("CRC passes"); } diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index bec1d19c..4b69ab4c 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -206,7 +206,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { bool crc2 = true; cmd2[0] = 0x05; cmd2[1] = 0x00; - cmd2[2] = 0x00; + cmd2[2] = 0x08; // REQB if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); @@ -397,7 +397,7 @@ int HF14BStdReader(uint8_t *data, uint8_t *datalen){ //std read cmd data[0] = 0x05; data[1] = 0x00; - data[2] = 0x00; + data[2] = 0x08; if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); From 7ce6e2c0b5612eaca77f4e7b1450ee168432f14a Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 3 Jul 2015 23:15:08 -0400 Subject: [PATCH 022/145] add -ss to hf 14b raw for select of SRx chips --- client/cmdhf14b.c | 61 +++++++++++++++++++++++++++++++++-------------- 1 file changed, 43 insertions(+), 18 deletions(-) diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 4b69ab4c..36932cbd 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -133,17 +133,19 @@ int CmdHF14BCmdRaw (const char *Cmd) { bool crc = false; bool power = false; bool select = false; + bool SRx = false; char buf[5] = ""; uint8_t data[100] = {0x00}; uint8_t datalen = 0; unsigned int temp; int i = 0; if (strlen(Cmd)<3) { - PrintAndLog("Usage: hf 14b raw [-r] [-c] [-p] <0A 0B 0C ... hex>"); + PrintAndLog("Usage: hf 14b raw [-r] [-c] [-p] [-s || -ss] <0A 0B 0C ... hex>"); PrintAndLog(" -r do not read response"); PrintAndLog(" -c calculate and append CRC"); PrintAndLog(" -p leave the field on after receive"); PrintAndLog(" -s active signal field ON with select"); + PrintAndLog(" -ss active signal field ON with select for SRx ST Microelectronics tags"); return 0; } @@ -169,6 +171,10 @@ int CmdHF14BCmdRaw (const char *Cmd) { case 's': case 'S': select = true; + if (Cmd[i+2]=='s' || Cmd[i+2]=='S') { + SRx = true; + i++; + } break; default: PrintAndLog("Invalid option"); @@ -192,7 +198,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { continue; } PrintAndLog("Invalid char on input"); - return 1; + return 0; } if (datalen == 0) { @@ -202,31 +208,50 @@ int CmdHF14BCmdRaw (const char *Cmd) { if (select){ //auto select 14b tag uint8_t cmd2[16]; - uint8_t cmdLen = 3; bool crc2 = true; - cmd2[0] = 0x05; - cmd2[1] = 0x00; - cmd2[2] = 0x08; + uint8_t cmdLen; + + if (SRx) { + // REQ SRx + cmdLen = 2; + cmd2[0] = 0x06; + cmd2[1] = 0x00; + } else { + cmdLen = 3; + // REQB + cmd2[0] = 0x05; + cmd2[1] = 0x00; + cmd2[2] = 0x08; + } - // REQB if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); - if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); + if ( SRx && (cmdLen != 3 || !crc2) ) return rawClose(); + else if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); + + uint8_t chipID = 0; + if (SRx) { + // select + chipID = cmd2[0]; + cmd2[0] = 0x0E; + cmd2[1] = chipID; + cmdLen = 2; + } else { + // attrib + cmd2[0] = 0x1D; + // UID from cmd2[1 - 4] + cmd2[5] = 0x00; + cmd2[6] = 0x08; + cmd2[7] = 0x01; + cmd2[8] = 0x00; + cmdLen = 9; + } - cmd2[0] = 0x1D; - // UID from data[1 - 4] - cmd2[5] = 0x00; - cmd2[6] = 0x08; - cmd2[7] = 0x01; - cmd2[8] = 0x00; - cmdLen = 9; - - // attrib if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); if (cmdLen != 3 || !crc2) return rawClose(); + if (SRx && cmd2[0] != chipID) return rawClose(); } - return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); } From 29b6cacc6ffece36f48bb8634b590cd82d96bf8b Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 5 Jul 2015 23:35:00 -0400 Subject: [PATCH 023/145] more verification on FDX-B tag demod - reduce... ... false positives --- client/cmddata.c | 4 ++-- common/lfdemod.c | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index bec1b5aa..bf10a6ec 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1491,9 +1491,9 @@ int CmdFDXBdemodBI(const char *Cmd){ setDemodBuf(BitStream, 128, preambleIndex); - // remove but don't verify parity. (pType = 2) + // remove marker bits (1's every 9th digit after preamble) (pType = 2) size = removeParity(BitStream, preambleIndex + 11, 9, 2, 117); - if ( size <= 103 ) { + if ( size != 104 ) { if (g_debugMode) PrintAndLog("Error removeParity:: %d", size); return 0; } diff --git a/common/lfdemod.c b/common/lfdemod.c index f13a567c..a3a7a500 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -580,7 +580,7 @@ int IOdemodFSK(uint8_t *dest, size_t size) // by marshmellow // takes a array of binary values, start position, length of bits per parity (includes parity bit), -// Parity Type (1 for odd; 0 for even; 2 for just drop it), and binary Length (length to run) +// Parity Type (1 for odd; 0 for even; 2 Always 1's), and binary Length (length to run) size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) { uint32_t parityWd = 0; @@ -590,10 +590,12 @@ size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t p parityWd = (parityWd << 1) | BitStream[startIdx+word+bit]; BitStream[j++] = (BitStream[startIdx+word+bit]); } - j--; + j--; // overwrite parity with next data // if parity fails then return 0 - if (pType != 2) { - if (parityTest(parityWd, pLen, pType) == 0) return -1; + if (pType == 2) { // then marker bit which should be a 1 + if (!BitStream[j]) return 0; + } else { + if (parityTest(parityWd, pLen, pType) == 0) return 0; } bitCnt+=(pLen-1); parityWd = 0; From bee99bbf906d04f234c1f47ac84dfc8ce19b89ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20M=C3=B6llers?= Date: Mon, 6 Jul 2015 17:59:23 +0200 Subject: [PATCH 024/145] Small spacing-related cleanups --- armsrc/Makefile | 18 +++++++++--------- armsrc/iso14443b.c | 28 ++++++++++++++-------------- 2 files changed, 23 insertions(+), 23 deletions(-) diff --git a/armsrc/Makefile b/armsrc/Makefile index 1214c949..141cf0ec 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -9,17 +9,17 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line -#in the next section to remove that particular feature from compilation +#in the next section to remove that particular feature from compilation APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE \ -fno-strict-aliasing -ffunction-sections -fdata-sections -#-DWITH_LCD +#-DWITH_LCD #SRC_LCD = fonts.c LCD.c SRC_LF = lfops.c hitag2.c lfsampling.c SRC_ISO15693 = iso15693.c iso15693tools.c SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c SRC_ISO14443b = iso14443b.c -SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c +SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c #the FPGA bitstream files. Note: order matters! @@ -65,7 +65,7 @@ ARMSRC = fpgaloader.c \ # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common/Makefile.common -OBJS = $(OBJDIR)/fullimage.s19 +OBJS = $(OBJDIR)/fullimage.s19 FPGA_COMPRESSOR = ../client/fpga_compress all: $(OBJS) @@ -80,13 +80,13 @@ $(OBJDIR)/fpga_all.bit.z: $(FPGA_BITSTREAMS) $(FPGA_COMPRESSOR) $(FPGA_COMPRESSOR): make -C ../client $(notdir $(FPGA_COMPRESSOR)) - + $(OBJDIR)/fullimage.stage1.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_all.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) $(OBJDIR)/fullimage.nodata.bin: $(OBJDIR)/fullimage.stage1.elf $(OBJCOPY) -O binary -I elf32-littlearm --remove-section .data $^ $@ - + $(OBJDIR)/fullimage.nodata.o: $(OBJDIR)/fullimage.nodata.bin $(OBJCOPY) -O elf32-littlearm -I binary -B arm --rename-section .data=stage1_image $^ $@ @@ -94,14 +94,14 @@ $(OBJDIR)/fullimage.data.bin: $(OBJDIR)/fullimage.stage1.elf $(OBJCOPY) -O binary -I elf32-littlearm --only-section .data $^ $@ $(OBJDIR)/fullimage.data.bin.z: $(OBJDIR)/fullimage.data.bin $(FPGA_COMPRESSOR) - $(FPGA_COMPRESSOR) $(filter %.bin,$^) $@ - + $(FPGA_COMPRESSOR) $(filter %.bin,$^) $@ + $(OBJDIR)/fullimage.data.o: $(OBJDIR)/fullimage.data.bin.z $(OBJCOPY) -O elf32-littlearm -I binary -B arm --rename-section .data=compressed_data $^ $@ $(OBJDIR)/fullimage.elf: $(OBJDIR)/fullimage.nodata.o $(OBJDIR)/fullimage.data.o $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ - + tarbin: $(OBJS) $(TAR) $(TARFLAGS) ../proxmark3-$(platform)-bin.tar $(OBJS:%=armsrc/%) $(OBJS:%.s19=armsrc/%.elf) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 33c047d8..1b5e07e1 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -311,7 +311,7 @@ static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) } } } - + return FALSE; } @@ -353,7 +353,7 @@ void SimulateIso14443bTag(void) // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); uint8_t *resp1Code = BigBuf_malloc(ToSendMax); - memcpy(resp1Code, ToSend, ToSendMax); + memcpy(resp1Code, ToSend, ToSendMax); uint16_t resp1CodeLen = ToSendMax; // We need to listen to the high-frequency, peak-detected path. @@ -377,9 +377,9 @@ void SimulateIso14443bTag(void) // Good, look at the command now. if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) { - resp = response1; + resp = response1; respLen = sizeof(response1); - respCode = resp1Code; + respCode = resp1Code; respCodeLen = resp1CodeLen; } else { Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); @@ -429,13 +429,13 @@ void SimulateIso14443bTag(void) (void)b; } } - + // trace the response: if (tracing) { uint8_t parity[MAX_PARITY_SIZE]; LogTrace(resp, respLen, 0, 0, parity, FALSE); } - + } } @@ -513,7 +513,7 @@ static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) } else { \ v -= cq; \ } \ - } + } */ // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq))) #define CHECK_FOR_SUBCARRIER() { \ @@ -547,7 +547,7 @@ static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) } \ } \ } - + switch(Demod.state) { case DEMOD_UNSYNCD: CHECK_FOR_SUBCARRIER(); @@ -645,7 +645,7 @@ static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) Demod.metric -= Demod.thisBit; } (Demod.metricN)++; -*/ +*/ Demod.shiftReg >>= 1; if(Demod.thisBit > 0) { // logic '1' @@ -713,10 +713,10 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); - + // The response (tag -> reader) that we're receiving. uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); - + // The DMA buffer, used to stream samples from the FPGA int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); @@ -1090,7 +1090,7 @@ void RAMFUNC SnoopIso14443b(void) bool TagIsActive = FALSE; bool ReaderIsActive = FALSE; - + // And now we loop, receiving samples. for(;;) { int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & @@ -1201,7 +1201,7 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u FpgaSetupSsc(); set_tracing(TRUE); - + CodeAndTransmit14443bAsReader(data, datalen); if(recv) { @@ -1209,7 +1209,7 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE); cmd_send(CMD_ACK, iLen, 0, 0, Demod.output, iLen); } - + if(!powerfield) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LED_D_OFF(); From 4be2708381b07e36c4ced1393c99ef845aec90f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20M=C3=B6llers?= Date: Mon, 6 Jul 2015 18:01:34 +0200 Subject: [PATCH 025/145] ISO 14443 type B support for EPA functionality Added iso14443b_setup and iso14443b_apdu for general setup and communication with ISO 14443 type B tags. Updated EPA (German electronic ID card) functionality to support both card types. --- armsrc/epa.c | 76 +++++++++++++++++++++++++++---------- armsrc/epa.h | 2 +- armsrc/iso14443b.c | 95 ++++++++++++++++++++++++++++++++++++++++++++++ armsrc/iso14443b.h | 21 ++++++++++ 4 files changed, 173 insertions(+), 21 deletions(-) create mode 100644 armsrc/iso14443b.h diff --git a/armsrc/epa.c b/armsrc/epa.c index 6bd8692e..50c7d878 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -12,10 +12,11 @@ //----------------------------------------------------------------------------- #include "iso14443a.h" +#include "iso14443b.h" #include "epa.h" #include "cmd.h" -// Protocol and Parameter Selection Request +// Protocol and Parameter Selection Request for ISO 14443 type A cards // use regular (1x) speed in both directions // CRC is already included static const uint8_t pps[] = {0xD0, 0x11, 0x00, 0x52, 0xA6}; @@ -100,6 +101,28 @@ static struct { // lengths of the replay APDUs static uint8_t apdu_lengths_replay[5]; +// type of card (ISO 14443 A or B) +static char iso_type = 0; + +//----------------------------------------------------------------------------- +// Wrapper for sending APDUs to type A and B cards +//----------------------------------------------------------------------------- +int EPA_APDU(uint8_t *apdu, size_t length, uint8_t *response) +{ + switch(iso_type) + { + case 'a': + return iso14_apdu(apdu, (uint16_t) length, response); + break; + case 'b': + return iso14443b_apdu(apdu, length, response); + break; + default: + return 0; + break; + } +} + //----------------------------------------------------------------------------- // Closes the communication channel and turns off the field //----------------------------------------------------------------------------- @@ -107,6 +130,7 @@ void EPA_Finish() { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); + iso_type = 0; } //----------------------------------------------------------------------------- @@ -204,26 +228,26 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) int rapdu_length = 0; // select the file EF.CardAccess - rapdu_length = iso14_apdu((uint8_t *)apdu_select_binary_cardaccess, + rapdu_length = EPA_APDU((uint8_t *)apdu_select_binary_cardaccess, sizeof(apdu_select_binary_cardaccess), response_apdu); - if (rapdu_length != 6 + if (rapdu_length < 6 || response_apdu[rapdu_length - 4] != 0x90 || response_apdu[rapdu_length - 3] != 0x00) { - Dbprintf("epa - no select cardaccess"); + DbpString("Failed to select EF.CardAccess!"); return -1; } // read the file - rapdu_length = iso14_apdu((uint8_t *)apdu_read_binary, + rapdu_length = EPA_APDU((uint8_t *)apdu_read_binary, sizeof(apdu_read_binary), response_apdu); if (rapdu_length <= 6 || response_apdu[rapdu_length - 4] != 0x90 || response_apdu[rapdu_length - 3] != 0x00) { - Dbprintf("epa - no read cardaccess"); + Dbprintf("Failed to read EF.CardAccess!"); return -1; } @@ -338,7 +362,7 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) // send it uint8_t response_apdu[262]; - int send_return = iso14_apdu(apdu, + int send_return = EPA_APDU(apdu, sizeof(apdu), response_apdu); // check if the command succeeded @@ -409,7 +433,7 @@ int EPA_PACE_MSE_Set_AT(pace_version_info_t pace_version_info, uint8_t password) apdu[4] = apdu_length - 5; // send it uint8_t response_apdu[6]; - int send_return = iso14_apdu(apdu, + int send_return = EPA_APDU(apdu, apdu_length, response_apdu); // check if the command succeeded @@ -460,16 +484,13 @@ void EPA_PACE_Replay(UsbCommand *c) return; } - // increase the timeout (at least some cards really do need this!)///////////// - // iso14a_set_timeout(0x0003FFFF); - // response APDU uint8_t response_apdu[300] = {0}; // now replay the data and measure the timings for (int i = 0; i < sizeof(apdu_lengths_replay); i++) { StartCountUS(); - func_return = iso14_apdu(apdus_replay[i].data, + func_return = EPA_APDU(apdus_replay[i].data, apdu_lengths_replay[i], response_apdu); timings[i] = GetCountUS(); @@ -501,18 +522,33 @@ int EPA_Setup() uint8_t pps_response_par[1]; iso14a_card_select_t card_select_info; + // first, look for type A cards // power up the field iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); // select the card return_code = iso14443a_select_card(uid, &card_select_info, NULL); - if (return_code != 1) { - return 1; + if (return_code == 1) { + // send the PPS request + ReaderTransmit((uint8_t *)pps, sizeof(pps), NULL); + return_code = ReaderReceive(pps_response, pps_response_par); + if (return_code != 3 || pps_response[0] != 0xD0) { + return return_code == 0 ? 2 : return_code; + } + Dbprintf("ISO 14443 Type A"); + iso_type = 'a'; + return 0; } - // send the PPS request - ReaderTransmit((uint8_t *)pps, sizeof(pps), NULL); - return_code = ReaderReceive(pps_response, pps_response_par); - if (return_code != 3 || pps_response[0] != 0xD0) { - return return_code == 0 ? 2 : return_code; + + // if we're here, there is no type A card, so we look for type B + // power up the field + iso14443b_setup(); + // select the card + return_code = iso14443b_select_card(); + if (return_code == 1) { + Dbprintf("ISO 14443 Type B"); + iso_type = 'b'; + return 0; } - return 0; + Dbprintf("No card found."); + return 1; } diff --git a/armsrc/epa.h b/armsrc/epa.h index 0c580205..d2ebed57 100644 --- a/armsrc/epa.h +++ b/armsrc/epa.h @@ -19,7 +19,7 @@ typedef struct { uint8_t parameter_id; } pace_version_info_t; -// note: EPA_PACE_Collect_Nonce is declared in apps.h +// note: EPA_PACE_Collect_Nonce and EPA_PACE_Replay are declared in apps.h // general functions void EPA_Finish(); diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 1b5e07e1..f8e6046c 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -19,6 +19,9 @@ #define RECEIVE_SAMPLES_TIMEOUT 2000 #define ISO14443B_DMA_BUFFER_SIZE 256 +// PCB Block number for APDUs +static uint8_t pcb_blocknum = 0; + //============================================================================= // An ISO 14443 Type B tag. We listen for commands from the reader, using // a UART kind of thing that's implemented in software. When we get a @@ -896,6 +899,98 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) } } +/* Sends an APDU to the tag + * TODO: check CRC and preamble + */ +int iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response) +{ + uint8_t message_frame[message_length + 4]; + // PCB + message_frame[0] = 0x0A | pcb_blocknum; + pcb_blocknum ^= 1; + // CID + message_frame[1] = 0; + // INF + memcpy(message_frame + 2, message, message_length); + // EDC (CRC) + ComputeCrc14443(CRC_14443_B, message_frame, message_length + 2, &message_frame[message_length + 2], &message_frame[message_length + 3]); + // send + CodeAndTransmit14443bAsReader(message_frame, message_length + 4); + // get response + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT*100, TRUE); + if(Demod.len < 3) + { + return 0; + } + // TODO: Check CRC + // copy response contents + if(response != NULL) + { + memcpy(response, Demod.output, Demod.len); + } + return Demod.len; +} + +/* Perform the ISO 14443 B Card Selection procedure + * Currently does NOT do any collision handling. + * It expects 0-1 cards in the device's range. + * TODO: Support multiple cards (perform anticollision) + * TODO: Verify CRC checksums + */ +int iso14443b_select_card() +{ + // WUPB command (including CRC) + // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state + static const uint8_t wupb[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; + // ATTRIB command (with space for CRC) + uint8_t attrib[] = { 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00}; + + // first, wake up the tag + CodeAndTransmit14443bAsReader(wupb, sizeof(wupb)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + // ATQB too short? + if (Demod.len < 14) + { + return 2; + } + + // select the tag + // copy the PUPI to ATTRIB + memcpy(attrib + 1, Demod.output + 1, 4); + /* copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into + ATTRIB (Param 3) */ + attrib[7] = Demod.output[10] & 0x0F; + ComputeCrc14443(CRC_14443_B, attrib, 9, attrib + 9, attrib + 10); + CodeAndTransmit14443bAsReader(attrib, sizeof(attrib)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + // Answer to ATTRIB too short? + if(Demod.len < 3) + { + return 2; + } + // reset PCB block number + pcb_blocknum = 0; + return 1; +} + +// Set up ISO 14443 Type B communication (similar to iso14443a_setup) +void iso14443b_setup() { + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // Set up the synchronous serial port + FpgaSetupSsc(); + // connect Demodulated Signal to ADC: + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + + // Signal field is on with the appropriate LED + LED_D_ON(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); + + // Start the timer + StartCountSspClk(); + + DemodReset(); + UartReset(); +} //----------------------------------------------------------------------------- // Read a SRI512 ISO 14443B tag. diff --git a/armsrc/iso14443b.h b/armsrc/iso14443b.h new file mode 100644 index 00000000..f90c54f3 --- /dev/null +++ b/armsrc/iso14443b.h @@ -0,0 +1,21 @@ +//----------------------------------------------------------------------------- +// Merlok - June 2011 +// Gerhard de Koning Gans - May 2008 +// Hagen Fritsch - June 2010 +// +// 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. +//----------------------------------------------------------------------------- +// Routines to support ISO 14443 type A. +//----------------------------------------------------------------------------- + +#ifndef __ISO14443B_H +#define __ISO14443B_H +#include "common.h" + +int iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response); +void iso14443b_setup(); +int iso14443b_select_card(); + +#endif /* __ISO14443B_H */ From dd57061c11954b952ecc181d3857f94dc8d349a6 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 6 Jul 2015 15:47:03 -0400 Subject: [PATCH 026/145] fix white spaces --- armsrc/iso14443b.c | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 31634a83..bfbd7bf5 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -360,13 +360,13 @@ void SimulateIso14443bTag(void) // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); uint8_t *resp1Code = BigBuf_malloc(ToSendMax); - memcpy(resp1Code, ToSend, ToSendMax); + memcpy(resp1Code, ToSend, ToSendMax); uint16_t resp1CodeLen = ToSendMax; // prepare the (other) tag answer: CodeIso14443bAsTag(response2, sizeof(response2)); uint8_t *resp2Code = BigBuf_malloc(ToSendMax); - memcpy(resp2Code, ToSend, ToSendMax); + memcpy(resp2Code, ToSend, ToSendMax); uint16_t resp2CodeLen = ToSendMax; // We need to listen to the high-frequency, peak-detected path. @@ -390,15 +390,15 @@ void SimulateIso14443bTag(void) // Good, look at the command now. if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) { - resp = response1; + resp = response1; respLen = sizeof(response1); - respCode = resp1Code; + respCode = resp1Code; respCodeLen = resp1CodeLen; } else if ( (len == sizeof(cmd3) && receivedCmd[0] == cmd3[0]) || (len == sizeof(cmd4) && receivedCmd[0] == cmd4[0]) ) { - resp = response2; + resp = response2; respLen = sizeof(response2); - respCode = resp2Code; + respCode = resp2Code; respCodeLen = resp2CodeLen; } else { Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); @@ -457,13 +457,13 @@ void SimulateIso14443bTag(void) (void)b; } } - + // trace the response: if (tracing) { uint8_t parity[MAX_PARITY_SIZE]; LogTrace(resp, respLen, 0, 0, parity, FALSE); } - + } } @@ -541,7 +541,7 @@ static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) } else { \ v -= cq; \ } \ - } + } */ // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq))) #define CHECK_FOR_SUBCARRIER() { \ @@ -575,7 +575,7 @@ static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) } \ } \ } - + switch(Demod.state) { case DEMOD_UNSYNCD: CHECK_FOR_SUBCARRIER(); @@ -673,7 +673,7 @@ static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) Demod.metric -= Demod.thisBit; } (Demod.metricN)++; -*/ +*/ Demod.shiftReg >>= 1; if(Demod.thisBit > 0) { // logic '1' @@ -741,10 +741,10 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); - + // The response (tag -> reader) that we're receiving. uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); - + // The DMA buffer, used to stream samples from the FPGA int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); @@ -1118,7 +1118,7 @@ void RAMFUNC SnoopIso14443b(void) bool TagIsActive = FALSE; bool ReaderIsActive = FALSE; - + // And now we loop, receiving samples. for(;;) { int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & @@ -1238,7 +1238,7 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE); cmd_send(CMD_ACK, iLen, 0, 0, Demod.output, iLen); } - } + } if(!powerfield) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); From 5330f5329f68fa6a95658ebd946d5eefc74e10c4 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 2 Jul 2015 08:49:34 +0200 Subject: [PATCH 027/145] - fix: trace of hf mf mifare had always been cleared by mfCheckKeys() in nonce2key() - fix: parity was not checked for reader commands in hf list 14a - add: enable tracing for hf mf nested --- armsrc/BigBuf.h | 14 +++++++------- armsrc/apps.h | 2 +- armsrc/mifarecmd.c | 14 +++++++------- client/cmdhf.c | 2 +- client/cmdhfmf.c | 22 ++++++---------------- client/mifarehost.c | 6 +++--- client/mifarehost.h | 2 +- client/nonce2key/nonce2key.c | 2 +- 8 files changed, 27 insertions(+), 37 deletions(-) diff --git a/armsrc/BigBuf.h b/armsrc/BigBuf.h index b44a1263..0e2f1744 100644 --- a/armsrc/BigBuf.h +++ b/armsrc/BigBuf.h @@ -24,15 +24,15 @@ extern uint8_t *BigBuf_get_addr(void); extern uint8_t *BigBuf_get_EM_addr(void); extern uint16_t BigBuf_max_traceLen(void); -void BigBuf_Clear(void); +extern void BigBuf_Clear(void); extern uint8_t *BigBuf_malloc(uint16_t); extern void BigBuf_free(void); extern void BigBuf_free_keep_EM(void); -uint16_t BigBuf_get_traceLen(void); -void clear_trace(); -void set_tracing(bool enable); -bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag); -int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int bReader); -uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length); +extern uint16_t BigBuf_get_traceLen(void); +extern void clear_trace(); +extern void set_tracing(bool enable); +extern bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag); +extern int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int bReader); +extern uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length); #endif /* __BIGBUF_H */ diff --git a/armsrc/apps.h b/armsrc/apps.h index bb094b33..42efd118 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -121,7 +121,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) //void MifareUWriteBlockCompat(uint8_t arg0,uint8_t *datain); void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); -void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); +void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareSetDbgLvl(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index c2d85abb..fd6fde63 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -642,8 +642,8 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // free eventually allocated BigBuf memory BigBuf_free(); - clear_trace(); - set_tracing(false); + if (calibrate) clear_trace(); + set_tracing(true); // statistics on nonce distance int16_t isOK = 0; @@ -820,18 +820,18 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); - set_tracing(TRUE); } //----------------------------------------------------------------------------- // MIFARE check keys. key count up to 85. // //----------------------------------------------------------------------------- -void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) +void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { // params - uint8_t blockNo = arg0; - uint8_t keyType = arg1; + uint8_t blockNo = arg0 & 0xff; + uint8_t keyType = (arg0 >> 8) & 0xff; + bool clearTrace = arg1; uint8_t keyCount = arg2; uint64_t ui64Key = 0; @@ -853,7 +853,7 @@ void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LED_C_OFF(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - clear_trace(); + if (clearTrace) clear_trace(); set_tracing(TRUE); for (i = 0; i < keyCount; i++) { diff --git a/client/cmdhf.c b/client/cmdhf.c index 4c5db589..f8daff7e 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -378,7 +378,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui oddparity ^= (((frame[j] & 0xFF) >> k) & 0x01); } uint8_t parityBits = parityBytes[j>>3]; - if (protocol != ISO_14443B && isResponse && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { + if (protocol != ISO_14443B && (isResponse || protocol == ISO_14443A) && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { snprintf(line[j/16]+(( j % 16) * 4),110, "%02x! ", frame[j]); } else { diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 5ef5273a..16612cba 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -18,7 +18,6 @@ int CmdHF14AMifare(const char *Cmd) uint32_t nt = 0, nr = 0; uint64_t par_list = 0, ks_list = 0, r_key = 0; int16_t isOK = 0; - uint8_t keyBlock[8] = {0}; UsbCommand c = {CMD_READER_MIFARE, {true, 0, 0}}; @@ -74,22 +73,13 @@ start: if (nonce2key(uid, nt, nr, par_list, ks_list, &r_key)) { isOK = 2; PrintAndLog("Key not found (lfsr_common_prefix list is null). Nt=%08x", nt); - } else { - printf("------------------------------------------------------------------\n"); - PrintAndLog("Key found:%012"llx" \n", r_key); - - num_to_bytes(r_key, 6, keyBlock); - isOK = mfCheckKeys(0, 0, 1, keyBlock, &r_key); - } - - if (!isOK) - PrintAndLog("Found valid key:%012"llx, r_key); - else - { - if (isOK != 2) PrintAndLog("Found invalid key. "); PrintAndLog("Failing is expected to happen in 25%% of all cases. Trying again with a different reader nonce..."); c.arg[0] = false; goto start; + } else { + isOK = 0; + printf("------------------------------------------------------------------\n"); + PrintAndLog("Found valid key:%012"llx" \n", r_key); } PrintAndLog(""); @@ -689,7 +679,7 @@ int CmdHF14AMfNested(const char *Cmd) for (j = 0; j < 2; j++) { if (e_sector[i].foundKey[j]) continue; - res = mfCheckKeys(FirstBlockOfSector(i), j, 6, keyBlock, &key64); + res = mfCheckKeys(FirstBlockOfSector(i), j, true, 6, keyBlock, &key64); if (!res) { e_sector[i].Key[j] = key64; @@ -973,7 +963,7 @@ int CmdHF14AMfChk(const char *Cmd) uint32_t max_keys = keycnt>USB_CMD_DATA_SIZE/6?USB_CMD_DATA_SIZE/6:keycnt; for (uint32_t c = 0; c < keycnt; c+=max_keys) { uint32_t size = keycnt-c>max_keys?max_keys:keycnt-c; - res = mfCheckKeys(b, t, size, &keyBlock[6*c], &key64); + res = mfCheckKeys(b, t, true, size, &keyBlock[6*c], &key64); if (res != 1) { if (!res) { PrintAndLog("Found valid key:[%012"llx"]",key64); diff --git a/client/mifarehost.c b/client/mifarehost.c index 95453ebf..eb145123 100644 --- a/client/mifarehost.c +++ b/client/mifarehost.c @@ -181,7 +181,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo crypto1_get_lfsr(statelists[0].head.slhead + i, &key64); num_to_bytes(key64, 6, keyBlock); key64 = 0; - if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, 1, keyBlock, &key64)) { + if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) { num_to_bytes(key64, 6, resultKey); break; } @@ -193,11 +193,11 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo return 0; } -int mfCheckKeys (uint8_t blockNo, uint8_t keyType, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ +int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ *key = 0; - UsbCommand c = {CMD_MIFARE_CHKKEYS, {blockNo, keyType, keycnt}}; + UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType&0xff)<<8)), clear_trace, keycnt}}; memcpy(c.d.asBytes, keyBlock, 6 * keycnt); SendCommand(&c); diff --git a/client/mifarehost.h b/client/mifarehost.h index a11f11d5..f6ffab3f 100644 --- a/client/mifarehost.h +++ b/client/mifarehost.h @@ -50,7 +50,7 @@ typedef struct { extern char logHexFileName[FILE_PATH_SIZE]; int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * ResultKeys, bool calibrate); -int mfCheckKeys (uint8_t blockNo, uint8_t keyType, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key); +int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key); int mfEmlGetMem(uint8_t *data, int blockNum, int blocksCount); int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount); diff --git a/client/nonce2key/nonce2key.c b/client/nonce2key/nonce2key.c index 111f58cd..70d874fe 100644 --- a/client/nonce2key/nonce2key.c +++ b/client/nonce2key/nonce2key.c @@ -133,7 +133,7 @@ int nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint64_t par_info, uint64_ key64 = *(last_keylist + i); num_to_bytes(key64, 6, keyBlock); key64 = 0; - if (!mfCheckKeys(0, 0, 1, keyBlock, &key64)) { + if (!mfCheckKeys(0, 0, false, 1, keyBlock, &key64)) { *key = key64; free(last_keylist); last_keylist = NULL; From b362de62621f17b297f08bd53082b3aea45219e6 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 11 Jul 2015 00:35:27 -0400 Subject: [PATCH 028/145] initialize global variables. --- client/cmddata.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index bf10a6ec..cb1c7cd4 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -26,8 +26,8 @@ #include "crc16.h" uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; -uint8_t g_debugMode; -size_t DemodBufferLen; +uint8_t g_debugMode=0; +size_t DemodBufferLen=0; static int CmdHelp(const char *Cmd); //set the demod buffer with given array of binary (one bit per byte) From 40c514454d80a396e9efcf80950aa631f6647755 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Sun, 12 Jul 2015 23:38:52 +0200 Subject: [PATCH 029/145] Fixed issue #94, so lua-script 'mifare_autopwn' reacts correctly to card that are not vulnerable to darkside-attacks --- client/scripts/mifare_autopwn.lua | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/client/scripts/mifare_autopwn.lua b/client/scripts/mifare_autopwn.lua index eb98ffbf..9cc865f0 100644 --- a/client/scripts/mifare_autopwn.lua +++ b/client/scripts/mifare_autopwn.lua @@ -88,10 +88,33 @@ function mfcrack_inner() while not core.ukbhit() do local result = core.WaitForResponseTimeout(cmds.CMD_ACK,1000) if result then - -- Unpacking the three arg-parameters - local count,cmd,isOK = bin.unpack('LL',result) - if isOK ~= 1 then return nil, "Error occurred" end + --[[ + I don't understand, they cmd and args are defined as uint32_t, however, + looking at the returned data, they all look like 64-bit things: + + print("result", bin.unpack("HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH", result)) + + FF 00 00 00 00 00 00 00 <-- 64 bits of data + FE FF FF FF 00 00 00 00 <-- 64 bits of data + 00 00 00 00 00 00 00 00 <-- 64 bits of data + 00 00 00 00 00 00 00 00 <-- 64 bits of data + 04 7F 12 E2 00 <-- this is where 'data' starts + + So below I use LI to pick out the "FEFF FFFF", don't know why it works.. + --]] + -- Unpacking the arg-parameters + local count,cmd,isOK = bin.unpack('LI',result) + --print("response", isOK)--FF FF FF FF + if isOK == 0xFFFFFFFF then + return nil, "Button pressed. Aborted." + elseif isOK == 0xFFFFFFFE then + return nil, "Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests). You can try 'script run mfkeys' or 'hf mf chk' to test various known keys." + elseif isOK == 0xFFFFFFFD then + return nil, "Card is not vulnerable to Darkside attack (its random number generator is not predictable). You can try 'script run mfkeys' or 'hf mf chk' to test various known keys." + elseif isOK ~= 1 then + return nil, "Error occurred" + end -- The data-part is left From 60034782f92e3f8d59a2a56b32663ca16cc59524 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Sun, 12 Jul 2015 23:39:27 +0200 Subject: [PATCH 030/145] Some info in the changelog --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3f9546d9..8d1cd548 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ### Changed - Changed `hf 14b write` to `hf 14b sriwrite` as it only applied to sri tags (marshmellow) - Added `hf 14b info` to `hf search` (marshmellow) +- Added compression of fpga config and data, *BOOTROM REFLASH REQUIRED* (piwi) +- Implemeted better detection of mifare-tags that are not vulnerable to classic attacks (`hf mf mifare`, `hf mf nested`) (piwi) ### Added - Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) From 5ebdce44c014ae29d688367508d0a6f6e6ebc673 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Sun, 12 Jul 2015 23:44:34 +0200 Subject: [PATCH 031/145] New release with FPGA compression --- CHANGELOG.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8d1cd548..02431d03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,13 +2,16 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... -## [Unreleased][unreleased] +## [unreleased][unreleased] + + +## [2.2.0][2015-07-12] ### Changed - Changed `hf 14b write` to `hf 14b sriwrite` as it only applied to sri tags (marshmellow) - Added `hf 14b info` to `hf search` (marshmellow) - Added compression of fpga config and data, *BOOTROM REFLASH REQUIRED* (piwi) -- Implemeted better detection of mifare-tags that are not vulnerable to classic attacks (`hf mf mifare`, `hf mf nested`) (piwi) +- Implemented better detection of mifare-tags that are not vulnerable to classic attacks (`hf mf mifare`, `hf mf nested`) (piwi) ### Added - Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) From 2c3c08bd2fe9cce76ff5f56029bdcef961639606 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20M=C3=B6llers?= Date: Mon, 13 Jul 2015 11:37:28 +0200 Subject: [PATCH 032/145] Mention EPA Type A/B support in CHANGELOG.md --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02431d03..b0135cc2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] +### Changed +- EPA functions (`hf epa`) now support both ISO 14443-A and 14443-B cards (frederikmoellers) ## [2.2.0][2015-07-12] From dbf6e824f932b0d5e88fbd0c24de529511fb5c05 Mon Sep 17 00:00:00 2001 From: Craig Young Date: Mon, 13 Jul 2015 15:45:28 -0400 Subject: [PATCH 033/145] Adding support for AWID26 realtime demodulation as well as cloning and simulation from facility code and card number --- armsrc/appmain.c | 3 + armsrc/apps.h | 1 + armsrc/lfops.c | 96 +++++++++++++++++- client/Makefile | 1 + client/cmdlfawid.c | 191 +++++++++++++++++++++++++++++++++++ client/cmdlfawid.h | 21 ++++ client/hid-flasher/usb_cmd.h | 1 + include/usb_cmd.h | 1 + 8 files changed, 314 insertions(+), 1 deletion(-) create mode 100644 client/cmdlfawid.c create mode 100644 client/cmdlfawid.h diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 0cbfa249..37899f57 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -681,6 +681,9 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_EM4X_WRITE_WORD: EM4xWriteWord(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes[0]); break; + case CMD_AWID_DEMOD_FSK: // Set realtime AWID demodulation + CmdAWIDdemodFSK(c->arg[0], 0, 0, 1); + break; #endif #ifdef WITH_HITAG diff --git a/armsrc/apps.h b/armsrc/apps.h index 42efd118..b5638ee1 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -69,6 +69,7 @@ void CmdFSKsimTAG(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream) void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream); void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream); void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol); +void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol); // Realtime demodulation mode for AWID26 void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol); void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol); void CopyIOtoT55x7(uint32_t hi, uint32_t lo, uint8_t longFMT); // Clone an ioProx card to T5557/T5567 diff --git a/armsrc/lfops.c b/armsrc/lfops.c index 7e53d4a5..188d7280 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -399,10 +399,14 @@ void SimulateTagLowFrequency(int period, int gap, int ledcontrol) #define OPEN_COIL() HIGH(GPIO_SSC_DOUT) i = 0; + byte_t rx[sizeof(UsbCommand)]; // Storage for usb_read call in loop for(;;) { //wait until SSC_CLK goes HIGH while(!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)) { - if(BUTTON_PRESS() || usb_poll()) { + // Craig Young - Adding a usb_read() here to avoid abort on empty UsbCommand + // My OS X client does this preventing simulation. + // Performance hit should be non-existent since the read is only performed if usb_poll is true + if(BUTTON_PRESS() || (usb_poll() && usb_read(rx,sizeof(UsbCommand)))) { DbpString("Stopped"); return; } @@ -841,6 +845,96 @@ void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol) if (ledcontrol) LED_A_OFF(); } +// loop to get raw HID waveform then FSK demodulate the TAG ID from it +void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol) +{ + uint8_t *dest = BigBuf_get_addr(); + //const size_t sizeOfBigBuff = BigBuf_max_traceLen(); + size_t size; + int idx=0; + // Configure to go in 125Khz listen mode + LFSetupFPGAForADC(95, true); + + while(!BUTTON_PRESS()) { + + WDT_HIT(); + if (ledcontrol) LED_A_ON(); + + DoAcquisition_default(-1,true); + // FSK demodulator + //size = sizeOfBigBuff; //variable size will change after demod so re initialize it before use + size = 50*128*2; //big enough to catch 2 sequences of largest format + idx = AWIDdemodFSK(dest, &size); + + if (idx>0 && size==96){ + // Index map + // 0 10 20 30 40 50 60 + // | | | | | | | + // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96 + // ----------------------------------------------------------------------------- + // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1 + // premable bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96 + // |---26 bit---| |-----117----||-------------142-------------| + // b = format bit len, o = odd parity of last 3 bits + // f = facility code, c = card number + // w = wiegand parity + // (26 bit format shown) + + //get raw ID before removing parities + uint32_t rawLo = bytebits_to_byte(dest+idx+64,32); + uint32_t rawHi = bytebits_to_byte(dest+idx+32,32); + uint32_t rawHi2 = bytebits_to_byte(dest+idx,32); + + size = removeParity(dest, idx+8, 4, 1, 88); + // ok valid card found! + + // Index map + // 0 10 20 30 40 50 60 + // | | | | | | | + // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456 + // ----------------------------------------------------------------------------- + // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000 + // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + // |26 bit| |-117--| |-----142------| + // b = format bit len, o = odd parity of last 3 bits + // f = facility code, c = card number + // w = wiegand parity + // (26 bit format shown) + + uint32_t fc = 0; + uint32_t cardnum = 0; + uint32_t code1 = 0; + uint32_t code2 = 0; + uint8_t fmtLen = bytebits_to_byte(dest,8); + if (fmtLen==26){ + fc = bytebits_to_byte(dest+9, 8); + cardnum = bytebits_to_byte(dest+17, 16); + code1 = bytebits_to_byte(dest+8,fmtLen); + Dbprintf("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo); + } else { + cardnum = bytebits_to_byte(dest+8+(fmtLen-17), 16); + if (fmtLen>32){ + code1 = bytebits_to_byte(dest+8,fmtLen-32); + code2 = bytebits_to_byte(dest+8+(fmtLen-32),32); + Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo); + } else{ + code1 = bytebits_to_byte(dest+8,fmtLen); + Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo); + } + } + if (findone){ + if (ledcontrol) LED_A_OFF(); + return; + } + // reset + } + idx = 0; + WDT_HIT(); + } + DbpString("Stopped"); + if (ledcontrol) LED_A_OFF(); +} + void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol) { uint8_t *dest = BigBuf_get_addr(); diff --git a/client/Makefile b/client/Makefile index c454533d..15b1cbca 100644 --- a/client/Makefile +++ b/client/Makefile @@ -89,6 +89,7 @@ CMDSRCS = nonce2key/crapto1.c\ cmdlf.c \ cmdlfio.c \ cmdlfhid.c \ + cmdlfawid.c \ cmdlfem4x.c \ cmdlfhitag.c \ cmdlfti.c \ diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c new file mode 100644 index 00000000..cf021552 --- /dev/null +++ b/client/cmdlfawid.c @@ -0,0 +1,191 @@ +//----------------------------------------------------------------------------- +// Authored by Craig Young based on cmdlfhid.c structure +// +// cmdlfhid.c is Copyright (C) 2010 iZsh +// +// 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. +//----------------------------------------------------------------------------- +// Low frequency AWID26 commands +//----------------------------------------------------------------------------- + +#include // sscanf +#include "proxmark3.h" // Definitions, USB controls, etc +#include "ui.h" // PrintAndLog +#include "cmdparser.h" // CmdsParse, CmdsHelp +#include "cmdlfawid.h" // AWID function declarations +#include "lfdemod.h" // parityTest + +static int CmdHelp(const char *Cmd); + +int CmdAWIDDemodFSK(const char *Cmd) +{ + int findone=0; + if(Cmd[0]=='1') findone=1; + UsbCommand c={CMD_AWID_DEMOD_FSK}; + c.arg[0]=findone; + SendCommand(&c); + return 0; +} + +int getAWIDBits(unsigned int fc, unsigned int cn, uint8_t *AWIDBits) +{ + int i; + uint32_t fcode=(fc & 0x000000FF), cnum=(cn & 0x0000FFFF), uBits=0; + if (fcode != fc) + PrintAndLog("NOTE: Facility code truncated for AWID26 format (8-bit facility code)"); + if (cnum!=cn) + PrintAndLog("NOTE: Card number was truncated for AWID26 format (16-bit card number)"); + + AWIDBits[0] = 0x01; // 6-bit Preamble with 2 parity bits + AWIDBits[1] = 0x1D; // First byte from card format (26-bit) plus parity bits + AWIDBits[2] = 0x80; // Set the next two bits as 0b10 to finish card format + uBits = (fcode<<4) + (cnum>>12); + if (!parityTest(uBits,12,0)) + AWIDBits[2] |= (1<<5); // If not already even parity, set bit to make even + uBits = AWIDBits[2]>>5; + if (!parityTest(uBits, 3, 1)) + AWIDBits[2] |= (1<<4); + uBits = fcode>>5; // first 3 bits of facility-code + AWIDBits[2] += (uBits<<1); + if (!parityTest(uBits, 3, 1)) + AWIDBits[2]++; // Set parity bit to make odd parity + uBits = (fcode & 0x1C)>>2; + AWIDBits[3] = 0; + if (!parityTest(uBits,3,1)) + AWIDBits[3] |= (1<<4); + AWIDBits[3] += (uBits<<5); + uBits = ((fcode & 0x3)<<1) + ((cnum & 0x8000)>>15); // Grab/shift 2 LSBs from facility code and add shifted MSB from cardnum + if (!parityTest(uBits,3,1)) + AWIDBits[3]++; // Set LSB for parity + AWIDBits[3]+= (uBits<<1); + uBits = (cnum & 0x7000)>>12; + AWIDBits[4] = uBits<<5; + if (!parityTest(uBits,3,1)) + AWIDBits[4] |= (1<<4); + uBits = (cnum & 0x0E00)>>9; + AWIDBits[4] += (uBits<<1); + if (!parityTest(uBits,3,1)) + AWIDBits[4]++; // Set LSB for parity + uBits = (cnum & 0x1C0)>>6; // Next bits from card number + AWIDBits[5]=(uBits<<5); + if (!parityTest(uBits,3,1)) + AWIDBits[5] |= (1<<4); // Set odd parity bit as needed + uBits = (cnum & 0x38)>>3; + AWIDBits[5]+= (uBits<<1); + if (!parityTest(uBits,3,1)) + AWIDBits[5]++; // Set odd parity bit as needed + uBits = (cnum & 0x7); // Last three bits from card number! + AWIDBits[6] = (uBits<<5); + if (!parityTest(uBits,3,1)) + AWIDBits[6] |= (1<<4); + uBits = (cnum & 0x0FFF); + if (!parityTest(uBits,12,1)) + AWIDBits[6] |= (1<<3); + else + AWIDBits[6]++; + for (i = 7; i<12; i++) + AWIDBits[i]=0x11; + return 1; +} + +int CmdAWIDSim(const char *Cmd) +{ + uint32_t fcode = 0, cnum = 0, fc=0, cn=0, i=0; + uint8_t *BS, BitStream[12]; + uint64_t arg1 = (10<<8) + 8; // fcHigh = 10, fcLow = 8 + uint64_t arg2 = 50; // clk RF/50 invert=0 + BS = BitStream; + if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { + PrintAndLog("Usage: lf awid sim "); + return 0; + } + + fcode=(fc & 0x000000FF); + cnum=(cn & 0x0000FFFF); + if (fc!=fcode) + PrintAndLog("Facility-Code (%u) truncated to 8-bits: %u",fc,fcode); + if (cn!=cnum) + PrintAndLog("Card number (%u) truncated to 16-bits: %u",cn,cnum); + PrintAndLog("Emulating AWID26 -- FC: %u; CN: %u\n",fcode,cnum); + PrintAndLog("Press pm3-button to abort simulation or run another command"); + // AWID uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 0 + if (getAWIDBits(fc, cn, BS)) { + PrintAndLog("Running 'lf simfsk c 50 H 10 L 8 d %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x'", + BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6], + BS[7],BS[8],BS[9],BS[10],BS[11]); + } else + PrintAndLog("Error with tag bitstream generation."); + UsbCommand c; + c.cmd = CMD_FSK_SIM_TAG; + c.arg[0] = arg1; // fcHigh<<8 + fcLow + c.arg[1] = arg2; // Inversion and clk setting + c.arg[2] = 96; // Bitstream length: 96-bits == 12 bytes + for (i=0; i < 96; i++) + c.d.asBytes[i] = (BS[i/8] & (1<<(7-(i%8))))?1:0; + SendCommand(&c); + return 0; +} + +int CmdAWIDClone(const char *Cmd) +{ + uint32_t fc=0,cn=0,blocks[4] = {0x00107060, 0, 0, 0x11111111}, i=0; + uint8_t BitStream[12]; + uint8_t *BS=BitStream; + UsbCommand c; + + + if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { + PrintAndLog("Usage: lf awid clone "); + return 0; + } + + if ((fc & 0xFF) != fc) { + fc &= 0xFF; + PrintAndLog("Facility-Code Truncated to 8-bits (AWID26): %u", fc); + } + if ((cn & 0xFFFF) != cn) { + cn &= 0xFFFF; + PrintAndLog("Card Number Truncated to 16-bits (AWID26): %u", cn); + } + if (getAWIDBits(fc,cn,BS)) { + PrintAndLog("Preparing to clone AWID26 to T55x7 with FC: %u, CN: %u (Raw: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x)", + fc,cn, BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6],BS[7],BS[8],BS[9],BS[10],BS[11]); + blocks[1] = (BS[0]<<24) + (BS[1]<<16) + (BS[2]<<8) + (BS[3]); + blocks[2] = (BS[4]<<24) + (BS[5]<<16) + (BS[6]<<8) + (BS[7]); + PrintAndLog("Block 0: 0x%08x", blocks[0]); + PrintAndLog("Block 1: 0x%08x", blocks[1]); + PrintAndLog("Block 2: 0x%08x", blocks[2]); + PrintAndLog("Block 3: 0x%08x", blocks[3]); + for (i=0; i<4; i++) { + c.cmd = CMD_T55XX_WRITE_BLOCK; + c.arg[0] = blocks[i]; + c.arg[1] = i; + c.arg[2] = 0; + SendCommand(&c); + } + } + return 0; +} + +static command_t CommandTable[] = +{ + {"help", CmdHelp, 1, "This help"}, + {"fskdemod", CmdAWIDDemodFSK, 0, "['1'] Realtime AWID FSK demodulator (option '1' for one tag only)"}, + {"sim", CmdAWIDSim, 0, " -- AWID tag simulator"}, + {"clone", CmdAWIDClone, 0, " -- Clone AWID to T55x7 (tag must be in range of antenna)"}, + {NULL, NULL, 0, NULL} +}; + +int CmdLFAWID(const char *Cmd) +{ + CmdsParse(CommandTable, Cmd); + return 0; +} + +int CmdHelp(const char *Cmd) +{ + CmdsHelp(CommandTable); + return 0; +} diff --git a/client/cmdlfawid.h b/client/cmdlfawid.h new file mode 100644 index 00000000..603c92c7 --- /dev/null +++ b/client/cmdlfawid.h @@ -0,0 +1,21 @@ +//----------------------------------------------------------------------------- +// Copyright (C) 2010 iZsh +// +// 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. +//----------------------------------------------------------------------------- +// Low frequency AWID commands +//----------------------------------------------------------------------------- + +#ifndef CMDLFAWID_H__ +#define CMDLFAWID_H__ + +int CmdLFAWID(const char *Cmd); +//int CmdAWIDDemod(const char *Cmd); +int CmdAWIDDemodFSK(const char *Cmd); +int CmdAWIDSim(const char *Cmd); +int CmdAWIDClone(const char *Cmd); +int getAWIDBits(unsigned int fc, unsigned int cn, uint8_t *AWIDBits); + +#endif diff --git a/client/hid-flasher/usb_cmd.h b/client/hid-flasher/usb_cmd.h index b3a7f4ec..f4013bab 100644 --- a/client/hid-flasher/usb_cmd.h +++ b/client/hid-flasher/usb_cmd.h @@ -84,6 +84,7 @@ typedef struct { #define CMD_FSK_SIM_TAG 0x021E #define CMD_ASK_SIM_TAG 0x021F #define CMD_PSK_SIM_TAG 0x0220 +#define CMD_AWID_DEMOD_FSK 0x0221 /* CMD_SET_ADC_MUX: ext1 is 0 for lopkd, 1 for loraw, 2 for hipkd, 3 for hiraw */ diff --git a/include/usb_cmd.h b/include/usb_cmd.h index 524554e9..e45bf35e 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -95,6 +95,7 @@ typedef struct{ #define CMD_FSK_SIM_TAG 0x021E #define CMD_ASK_SIM_TAG 0x021F #define CMD_PSK_SIM_TAG 0x0220 +#define CMD_AWID_DEMOD_FSK 0x0221 /* CMD_SET_ADC_MUX: ext1 is 0 for lopkd, 1 for loraw, 2 for hipkd, 3 for hiraw */ From c0c35f9bb674b5dcaa5cf89b65cc9a5fdc7997ab Mon Sep 17 00:00:00 2001 From: Craig Young Date: Mon, 13 Jul 2015 16:18:59 -0400 Subject: [PATCH 034/145] Adding CMD_AWID_DEMOD_FSK to commands.lua --- client/lualibs/commands.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/client/lualibs/commands.lua b/client/lualibs/commands.lua index 4c7bc638..127508e6 100644 --- a/client/lualibs/commands.lua +++ b/client/lualibs/commands.lua @@ -54,6 +54,7 @@ local _commands = { CMD_FSK_SIM_TAG = 0x021E, CMD_ASK_SIM_TAG = 0x021F, CMD_PSK_SIM_TAG = 0x0220, + CMD_AWID_DEMOD_FSK = 0x0221, --/* CMD_SET_ADC_MUX: ext1 is 0 for lopkd, 1 for loraw, 2 for hipkd, 3 for hiraw */ From 769791d440e5be7a0e4213f56276aabee6233f8c Mon Sep 17 00:00:00 2001 From: Craig Young Date: Mon, 13 Jul 2015 16:41:50 -0400 Subject: [PATCH 035/145] Updated CHANGELOG.md --- CHANGELOG.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index b0135cc2..edf0a310 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] +### Added +- AWID26 command context added as 'lf awid' containing realtime demodulation as well as cloning/simulation based on tag numbers (Craig Young) + ### Changed - EPA functions (`hf epa`) now support both ISO 14443-A and 14443-B cards (frederikmoellers) From d6b455ed4eee2730091ed0a636ed753138adec0b Mon Sep 17 00:00:00 2001 From: Craig Young Date: Mon, 13 Jul 2015 16:47:11 -0400 Subject: [PATCH 036/145] Adding 'lf awid' context to cmdlf.c --- client/cmdlf.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/client/cmdlf.c b/client/cmdlf.c index edf02932..6dae5164 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -22,6 +22,7 @@ #include "util.h" #include "cmdlf.h" #include "cmdlfhid.h" +#include "cmdlfawid.h" #include "cmdlfti.h" #include "cmdlfem4x.h" #include "cmdlfhitag.h" @@ -1130,6 +1131,7 @@ static command_t CommandTable[] = {"config", CmdLFSetConfig, 0, "Set config for LF sampling, bit/sample, decimation, frequency"}, {"flexdemod", CmdFlexdemod, 1, "Demodulate samples for FlexPass"}, {"hid", CmdLFHID, 1, "{ HID RFIDs... }"}, + {"awid", CmdLFAWID, 1, "{ AWID 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"}, From bcffcca25fe44473640cce8342173217c987ec52 Mon Sep 17 00:00:00 2001 From: Craig Young Date: Mon, 13 Jul 2015 18:14:12 -0400 Subject: [PATCH 037/145] Adding usage information to 'lf awid' commands --- client/cmdlfawid.c | 52 +++++++++++++++++++++++++++++++++++++++++----- client/cmdlfawid.h | 3 +++ 2 files changed, 50 insertions(+), 5 deletions(-) diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c index cf021552..233eb72c 100644 --- a/client/cmdlfawid.c +++ b/client/cmdlfawid.c @@ -19,10 +19,54 @@ static int CmdHelp(const char *Cmd); + +int usage_lf_awid_fskdemod(void) { + PrintAndLog("Enables AWID26 compatible reader mode printing details of scanned AWID26 tags."); + PrintAndLog("By default, values are printed and logged until the button is pressed or another USB command is issued."); + PrintAndLog("If the ['1'] option is provided, reader mode is exited after reading a single AWID26 card."); + PrintAndLog(""); + PrintAndLog("Usage: lf awid fskdemod ['1']"); + PrintAndLog(" Options : "); + PrintAndLog(" 1 : (optional) stop after reading a single card"); + PrintAndLog(""); + PrintAndLog(" sample : lf awid fskdemod"); + PrintAndLog(" : lf awid fskdemod 1"); + return 0; +} + +int usage_lf_awid_sim(void) { + PrintAndLog("Enables simulation of AWID26 card with specified facility-code and card number."); + PrintAndLog("Simulation runs until the button is pressed or another USB command is issued."); + PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit. Larger values are truncated."); + PrintAndLog(""); + PrintAndLog("Usage: lf awid sim "); + PrintAndLog(" Options : "); + PrintAndLog(" : 8-bit value representing the AWID facility code"); + PrintAndLog(" : 16-bit value representing the AWID card number"); + PrintAndLog(""); + PrintAndLog(" sample : lf awid sim 224 1337"); + return 0; +} + +int usage_lf_awid_clone(void) { + PrintAndLog("Enables cloning of AWID26 card with specified facility-code and card number onto T55x7."); + PrintAndLog("The T55x7 must be on the antenna when issuing this command. T55x7 blocks are calculated and printed in the process."); + PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit. Larger values are truncated."); + PrintAndLog(""); + PrintAndLog("Usage: lf awid clone "); + PrintAndLog(" Options : "); + PrintAndLog(" : 8-bit value representing the AWID facility code"); + PrintAndLog(" : 16-bit value representing the AWID card number"); + PrintAndLog(""); + PrintAndLog(" sample : lf awid clone 224 1337"); + return 0; +} + int CmdAWIDDemodFSK(const char *Cmd) { int findone=0; - if(Cmd[0]=='1') findone=1; + if(Cmd[0]=='1') findone=1; + if (Cmd[0]=='h' || Cmd[0] == 'H') return usage_lf_awid_fskdemod(); UsbCommand c={CMD_AWID_DEMOD_FSK}; c.arg[0]=findone; SendCommand(&c); @@ -98,8 +142,7 @@ int CmdAWIDSim(const char *Cmd) uint64_t arg2 = 50; // clk RF/50 invert=0 BS = BitStream; if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { - PrintAndLog("Usage: lf awid sim "); - return 0; + return usage_lf_awid_sim(); } fcode=(fc & 0x000000FF); @@ -137,8 +180,7 @@ int CmdAWIDClone(const char *Cmd) if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { - PrintAndLog("Usage: lf awid clone "); - return 0; + return usage_lf_awid_clone(); } if ((fc & 0xFF) != fc) { diff --git a/client/cmdlfawid.h b/client/cmdlfawid.h index 603c92c7..00622927 100644 --- a/client/cmdlfawid.h +++ b/client/cmdlfawid.h @@ -17,5 +17,8 @@ int CmdAWIDDemodFSK(const char *Cmd); int CmdAWIDSim(const char *Cmd); int CmdAWIDClone(const char *Cmd); int getAWIDBits(unsigned int fc, unsigned int cn, uint8_t *AWIDBits); +int usage_lf_awid_fskdemod(void); +int usage_lf_awid_clone(void); +int usage_lf_awid_sim(void); #endif From e46fe044301490953e98776b70e0acd1117e2b20 Mon Sep 17 00:00:00 2001 From: Craig Young Date: Mon, 13 Jul 2015 18:46:42 -0400 Subject: [PATCH 038/145] Introducing a stand-alone mode for working with NFC (ISO14443a) tag UIDs. --- CHANGELOG.md | 3 + armsrc/Makefile | 2 +- armsrc/appmain.c | 226 +++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 230 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index edf0a310..dc015c92 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [unreleased][unreleased] +### Added +- ISO14443a stand-alone operation with ARM CFLAG="WITH_ISO14443a_StandAlone". This code can read & emulate two banks of 14a tag UIDs and write to "magic" cards (Craig Young) + ### Added - AWID26 command context added as 'lf awid' containing realtime demodulation as well as cloning/simulation based on tag numbers (Craig Young) diff --git a/armsrc/Makefile b/armsrc/Makefile index 141cf0ec..a59fa073 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -10,7 +10,7 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line #in the next section to remove that particular feature from compilation -APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE \ +APP_CFLAGS = -DWITH_ISO14443a_StandAlone -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE \ -fno-strict-aliasing -ffunction-sections -fdata-sections #-DWITH_LCD diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 37899f57..40df5f5f 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -29,6 +29,11 @@ #include "LCD.h" #endif +// Craig Young - 14a stand-alone code +#ifdef WITH_ISO14443a_StandAlone + #include "iso14443a.h" +#endif + #define abs(x) ( ((x)<0) ? -(x) : (x) ) //============================================================================= @@ -294,6 +299,7 @@ void SendVersion(void) } #ifdef WITH_LF +#ifndef WITH_ISO14443a_StandAlone // samy's sniff and repeat routine void SamyRun() { @@ -440,7 +446,219 @@ void SamyRun() } } #endif +#endif +#ifdef WITH_ISO14443a +#ifdef WITH_ISO14443a_StandAlone +void StandAloneMode14a() +{ + DbpString("Stand-alone mode! No PC necessary."); + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // 3 possible options? no just 1 for now +#undef OPTS +#define OPTS 2 + // Oooh pretty -- notify user we're in elite samy mode now + LED(LED_RED, 200); + LED(LED_ORANGE, 200); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + LED(LED_RED, 200); + LED(LED_ORANGE, 200); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + LED(LED_RED, 200); + + int selected = 0; + int playing = 0; + int cardRead[OPTS] = {0}; + uint8_t readUID[10] = {0}; + int uid_1st[OPTS]={0}; + int uid_2nd[OPTS]={0}; + + LED(selected + 1, 0); + + for (;;) + { + usb_poll(); + WDT_HIT(); + + // Was our button held down or pressed? + int button_pressed = BUTTON_HELD(1000); + + SpinDelay(300); + + // Button was held for a second, begin recording + if (button_pressed > 0 && cardRead[selected] == 0) + { + LEDsoff(); + LED(selected + 1, 0); + LED(LED_RED2, 0); + + // record + Dbprintf("Enabling iso14443a reader mode for [Bank: %u]...", selected); + + // wait for button to be released + while(BUTTON_PRESS()) + WDT_HIT(); + /* need this delay to prevent catching some weird data */ + SpinDelay(500); + /* Code for reading from 14a tag */ + uint8_t uid[10] ={0}; + uint32_t cuid; + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + + for ( ; ; ) + { + if (!iso14443a_select_card(uid, NULL, &cuid)) + continue; + else + { + Dbprintf("Read UID:"); Dbhexdump(10,uid,0); + memcpy(readUID,uid,10*sizeof(uint8_t)); + uint8_t *dst = (uint8_t *)&uid_1st[selected]; + // Set UID byte order + for (int i=0; i<4; i++) + dst[i] = uid[3-i]; + dst = (uint8_t *)&uid_2nd[selected]; + for (int i=0; i<4; i++) + dst[i] = uid[7-i]; + break; + } + } + LEDsoff(); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + + LEDsoff(); + LED(selected + 1, 0); + // Finished recording + + // If we were previously playing, set playing off + // so next button push begins playing what we recorded + playing = 0; + + cardRead[selected] = 1; + + } +/* MF UID clone */ + else if (button_pressed > 0 && cardRead[selected] == 1) + { + LEDsoff(); + LED(selected + 1, 0); + LED(LED_ORANGE, 250); + + + // record + Dbprintf("Preparing to Clone card [Bank: %x]; uid: %08x", selected, uid_1st[selected]); + + // wait for button to be released + while(BUTTON_PRESS()) + { + // Delay cloning until card is in place + WDT_HIT(); + } + Dbprintf("Starting clone. [Bank: %u]", selected); + // need this delay to prevent catching some weird data + SpinDelay(500); + // Begin clone function here: + /* Example from client/mifarehost.c for commanding a block write for "magic Chinese" cards: + UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}}; + memcpy(c.d.asBytes, data, 16); + SendCommand(&c); + + Block read is similar: + UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}}; + We need to imitate that call with blockNo 0 to set a uid. + + The get and set commands are handled in this file: + // Work with "magic Chinese" card + case CMD_MIFARE_CSETBLOCK: + MifareCSetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + break; + case CMD_MIFARE_CGETBLOCK: + MifareCGetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + // + break; + + mfCSetUID provides example logic for UID set workflow: + -Read block0 from card in field with MifareCGetBlock() + -Configure new values without replacing reserved bytes + memcpy(block0, uid, 4); // Copy UID bytes from byte array + // Mifare UID BCC + block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 + Bytes 5-7 are reserved SAK and ATQA for mifare classic + -Use mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER) to write it + */ + uint8_t oldBlock0[16] = {0}, newBlock0[16] = {0}, testBlock0[16] = {0}; + // arg0 = Flags == CSETBLOCK_SINGLE_OPER=0x1F, arg1=returnSlot, arg2=blockNo + MifareCGetBlock(0x1F, 1, 0, oldBlock0); + Dbprintf("UID from target tag: %02X%02X%02X%02X", oldBlock0[0],oldBlock0[1],oldBlock0[2],oldBlock0[3]); + memcpy(newBlock0,oldBlock0,16); + // Copy uid_1st for bank (2nd is for longer UIDs not supported if classic) + newBlock0[0] = uid_1st[selected]>>24; + newBlock0[1] = 0xFF & (uid_1st[selected]>>16); + newBlock0[2] = 0xFF & (uid_1st[selected]>>8); + newBlock0[3] = 0xFF & (uid_1st[selected]); + newBlock0[4] = newBlock0[0]^newBlock0[1]^newBlock0[2]^newBlock0[3]; + // arg0 = needWipe, arg1 = workFlags, arg2 = blockNo, datain + MifareCSetBlock(0, 0xFF,0, newBlock0); + MifareCGetBlock(0x1F, 1, 0, testBlock0); + if (memcmp(testBlock0,newBlock0,16)==0) + { + DbpString("Cloned successfull!"); + cardRead[selected] = 0; // Only if the card was cloned successfully should we clear it + } + LEDsoff(); + LED(selected + 1, 0); + // Finished recording + + // If we were previously playing, set playing off + // so next button push begins playing what we recorded + playing = 0; + + } + // Change where to record (or begin playing) + else if (button_pressed && cardRead[selected]) + { + // Next option if we were previously playing + if (playing) + selected = (selected + 1) % OPTS; + playing = !playing; + + LEDsoff(); + LED(selected + 1, 0); + + // Begin transmitting + if (playing) + { + LED(LED_GREEN, 0); + DbpString("Playing"); + while (!BUTTON_HELD(500)) { // Loop simulating tag until the button is held a half-sec + Dbprintf("Simulating ISO14443a tag with uid[0]: %08x, uid[1]: %08x [Bank: %u]", uid_1st[selected],uid_2nd[selected],selected); + SimulateIso14443aTag(1,uid_1st[selected],uid_2nd[selected],NULL); + } + //cardRead[selected] = 1; + Dbprintf("Done playing [Bank: %u]",selected); + + /* We pressed a button so ignore it here with a delay */ + SpinDelay(300); + + // when done, we're done playing, move to next option + selected = (selected + 1) % OPTS; + playing = !playing; + LEDsoff(); + LED(selected + 1, 0); + } + else + while(BUTTON_PRESS()) + WDT_HIT(); + } + } +} +#endif +#endif /* OBJECTIVE Listen and detect an external reader. Determine the best location @@ -1031,8 +1249,16 @@ void __attribute__((noreturn)) AppMain(void) WDT_HIT(); #ifdef WITH_LF +#ifndef WITH_ISO14443a_StandAlone if (BUTTON_HELD(1000) > 0) SamyRun(); +#endif +#endif +#ifdef WITH_ISO14443a +#ifdef WITH_ISO14443a_StandAlone + if (BUTTON_HELD(1000) > 0) + StandAloneMode14a(); +#endif #endif } } From 37824afe63d044fbaa37aaa5c0f84164216cb9c4 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Thu, 16 Jul 2015 22:47:14 +0200 Subject: [PATCH 039/145] Changed indentation to tabs --- client/cmdlfawid.c | 342 ++++++++++++++++++++++----------------------- 1 file changed, 171 insertions(+), 171 deletions(-) diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c index 233eb72c..17837a11 100644 --- a/client/cmdlfawid.c +++ b/client/cmdlfawid.c @@ -21,213 +21,213 @@ static int CmdHelp(const char *Cmd); int usage_lf_awid_fskdemod(void) { - PrintAndLog("Enables AWID26 compatible reader mode printing details of scanned AWID26 tags."); - PrintAndLog("By default, values are printed and logged until the button is pressed or another USB command is issued."); - PrintAndLog("If the ['1'] option is provided, reader mode is exited after reading a single AWID26 card."); - PrintAndLog(""); - PrintAndLog("Usage: lf awid fskdemod ['1']"); - PrintAndLog(" Options : "); - PrintAndLog(" 1 : (optional) stop after reading a single card"); - PrintAndLog(""); - PrintAndLog(" sample : lf awid fskdemod"); - PrintAndLog(" : lf awid fskdemod 1"); - return 0; + PrintAndLog("Enables AWID26 compatible reader mode printing details of scanned AWID26 tags."); + PrintAndLog("By default, values are printed and logged until the button is pressed or another USB command is issued."); + PrintAndLog("If the ['1'] option is provided, reader mode is exited after reading a single AWID26 card."); + PrintAndLog(""); + PrintAndLog("Usage: lf awid fskdemod ['1']"); + PrintAndLog(" Options : "); + PrintAndLog(" 1 : (optional) stop after reading a single card"); + PrintAndLog(""); + PrintAndLog(" sample : lf awid fskdemod"); + PrintAndLog(" : lf awid fskdemod 1"); + return 0; } int usage_lf_awid_sim(void) { - PrintAndLog("Enables simulation of AWID26 card with specified facility-code and card number."); - PrintAndLog("Simulation runs until the button is pressed or another USB command is issued."); - PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit. Larger values are truncated."); - PrintAndLog(""); - PrintAndLog("Usage: lf awid sim "); - PrintAndLog(" Options : "); - PrintAndLog(" : 8-bit value representing the AWID facility code"); - PrintAndLog(" : 16-bit value representing the AWID card number"); - PrintAndLog(""); - PrintAndLog(" sample : lf awid sim 224 1337"); - return 0; + PrintAndLog("Enables simulation of AWID26 card with specified facility-code and card number."); + PrintAndLog("Simulation runs until the button is pressed or another USB command is issued."); + PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit. Larger values are truncated."); + PrintAndLog(""); + PrintAndLog("Usage: lf awid sim "); + PrintAndLog(" Options : "); + PrintAndLog(" : 8-bit value representing the AWID facility code"); + PrintAndLog(" : 16-bit value representing the AWID card number"); + PrintAndLog(""); + PrintAndLog(" sample : lf awid sim 224 1337"); + return 0; } int usage_lf_awid_clone(void) { - PrintAndLog("Enables cloning of AWID26 card with specified facility-code and card number onto T55x7."); - PrintAndLog("The T55x7 must be on the antenna when issuing this command. T55x7 blocks are calculated and printed in the process."); - PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit. Larger values are truncated."); - PrintAndLog(""); - PrintAndLog("Usage: lf awid clone "); - PrintAndLog(" Options : "); - PrintAndLog(" : 8-bit value representing the AWID facility code"); - PrintAndLog(" : 16-bit value representing the AWID card number"); - PrintAndLog(""); - PrintAndLog(" sample : lf awid clone 224 1337"); - return 0; + PrintAndLog("Enables cloning of AWID26 card with specified facility-code and card number onto T55x7."); + PrintAndLog("The T55x7 must be on the antenna when issuing this command. T55x7 blocks are calculated and printed in the process."); + PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit. Larger values are truncated."); + PrintAndLog(""); + PrintAndLog("Usage: lf awid clone "); + PrintAndLog(" Options : "); + PrintAndLog(" : 8-bit value representing the AWID facility code"); + PrintAndLog(" : 16-bit value representing the AWID card number"); + PrintAndLog(""); + PrintAndLog(" sample : lf awid clone 224 1337"); + return 0; } int CmdAWIDDemodFSK(const char *Cmd) { - int findone=0; - if(Cmd[0]=='1') findone=1; - if (Cmd[0]=='h' || Cmd[0] == 'H') return usage_lf_awid_fskdemod(); - UsbCommand c={CMD_AWID_DEMOD_FSK}; - c.arg[0]=findone; - SendCommand(&c); - return 0; + int findone=0; + if(Cmd[0]=='1') findone=1; + if (Cmd[0]=='h' || Cmd[0] == 'H') return usage_lf_awid_fskdemod(); + UsbCommand c={CMD_AWID_DEMOD_FSK}; + c.arg[0]=findone; + SendCommand(&c); + return 0; } int getAWIDBits(unsigned int fc, unsigned int cn, uint8_t *AWIDBits) { - int i; - uint32_t fcode=(fc & 0x000000FF), cnum=(cn & 0x0000FFFF), uBits=0; - if (fcode != fc) - PrintAndLog("NOTE: Facility code truncated for AWID26 format (8-bit facility code)"); - if (cnum!=cn) - PrintAndLog("NOTE: Card number was truncated for AWID26 format (16-bit card number)"); + int i; + uint32_t fcode=(fc & 0x000000FF), cnum=(cn & 0x0000FFFF), uBits=0; + if (fcode != fc) + PrintAndLog("NOTE: Facility code truncated for AWID26 format (8-bit facility code)"); + if (cnum!=cn) + PrintAndLog("NOTE: Card number was truncated for AWID26 format (16-bit card number)"); - AWIDBits[0] = 0x01; // 6-bit Preamble with 2 parity bits - AWIDBits[1] = 0x1D; // First byte from card format (26-bit) plus parity bits - AWIDBits[2] = 0x80; // Set the next two bits as 0b10 to finish card format - uBits = (fcode<<4) + (cnum>>12); - if (!parityTest(uBits,12,0)) - AWIDBits[2] |= (1<<5); // If not already even parity, set bit to make even - uBits = AWIDBits[2]>>5; - if (!parityTest(uBits, 3, 1)) - AWIDBits[2] |= (1<<4); - uBits = fcode>>5; // first 3 bits of facility-code - AWIDBits[2] += (uBits<<1); - if (!parityTest(uBits, 3, 1)) - AWIDBits[2]++; // Set parity bit to make odd parity - uBits = (fcode & 0x1C)>>2; - AWIDBits[3] = 0; - if (!parityTest(uBits,3,1)) - AWIDBits[3] |= (1<<4); - AWIDBits[3] += (uBits<<5); - uBits = ((fcode & 0x3)<<1) + ((cnum & 0x8000)>>15); // Grab/shift 2 LSBs from facility code and add shifted MSB from cardnum - if (!parityTest(uBits,3,1)) - AWIDBits[3]++; // Set LSB for parity - AWIDBits[3]+= (uBits<<1); - uBits = (cnum & 0x7000)>>12; - AWIDBits[4] = uBits<<5; - if (!parityTest(uBits,3,1)) - AWIDBits[4] |= (1<<4); - uBits = (cnum & 0x0E00)>>9; - AWIDBits[4] += (uBits<<1); - if (!parityTest(uBits,3,1)) - AWIDBits[4]++; // Set LSB for parity - uBits = (cnum & 0x1C0)>>6; // Next bits from card number - AWIDBits[5]=(uBits<<5); - if (!parityTest(uBits,3,1)) - AWIDBits[5] |= (1<<4); // Set odd parity bit as needed - uBits = (cnum & 0x38)>>3; - AWIDBits[5]+= (uBits<<1); - if (!parityTest(uBits,3,1)) - AWIDBits[5]++; // Set odd parity bit as needed - uBits = (cnum & 0x7); // Last three bits from card number! - AWIDBits[6] = (uBits<<5); - if (!parityTest(uBits,3,1)) - AWIDBits[6] |= (1<<4); - uBits = (cnum & 0x0FFF); - if (!parityTest(uBits,12,1)) - AWIDBits[6] |= (1<<3); - else - AWIDBits[6]++; - for (i = 7; i<12; i++) - AWIDBits[i]=0x11; - return 1; + AWIDBits[0] = 0x01; // 6-bit Preamble with 2 parity bits + AWIDBits[1] = 0x1D; // First byte from card format (26-bit) plus parity bits + AWIDBits[2] = 0x80; // Set the next two bits as 0b10 to finish card format + uBits = (fcode<<4) + (cnum>>12); + if (!parityTest(uBits,12,0)) + AWIDBits[2] |= (1<<5); // If not already even parity, set bit to make even + uBits = AWIDBits[2]>>5; + if (!parityTest(uBits, 3, 1)) + AWIDBits[2] |= (1<<4); + uBits = fcode>>5; // first 3 bits of facility-code + AWIDBits[2] += (uBits<<1); + if (!parityTest(uBits, 3, 1)) + AWIDBits[2]++; // Set parity bit to make odd parity + uBits = (fcode & 0x1C)>>2; + AWIDBits[3] = 0; + if (!parityTest(uBits,3,1)) + AWIDBits[3] |= (1<<4); + AWIDBits[3] += (uBits<<5); + uBits = ((fcode & 0x3)<<1) + ((cnum & 0x8000)>>15); // Grab/shift 2 LSBs from facility code and add shifted MSB from cardnum + if (!parityTest(uBits,3,1)) + AWIDBits[3]++; // Set LSB for parity + AWIDBits[3]+= (uBits<<1); + uBits = (cnum & 0x7000)>>12; + AWIDBits[4] = uBits<<5; + if (!parityTest(uBits,3,1)) + AWIDBits[4] |= (1<<4); + uBits = (cnum & 0x0E00)>>9; + AWIDBits[4] += (uBits<<1); + if (!parityTest(uBits,3,1)) + AWIDBits[4]++; // Set LSB for parity + uBits = (cnum & 0x1C0)>>6; // Next bits from card number + AWIDBits[5]=(uBits<<5); + if (!parityTest(uBits,3,1)) + AWIDBits[5] |= (1<<4); // Set odd parity bit as needed + uBits = (cnum & 0x38)>>3; + AWIDBits[5]+= (uBits<<1); + if (!parityTest(uBits,3,1)) + AWIDBits[5]++; // Set odd parity bit as needed + uBits = (cnum & 0x7); // Last three bits from card number! + AWIDBits[6] = (uBits<<5); + if (!parityTest(uBits,3,1)) + AWIDBits[6] |= (1<<4); + uBits = (cnum & 0x0FFF); + if (!parityTest(uBits,12,1)) + AWIDBits[6] |= (1<<3); + else + AWIDBits[6]++; + for (i = 7; i<12; i++) + AWIDBits[i]=0x11; + return 1; } int CmdAWIDSim(const char *Cmd) { - uint32_t fcode = 0, cnum = 0, fc=0, cn=0, i=0; - uint8_t *BS, BitStream[12]; - uint64_t arg1 = (10<<8) + 8; // fcHigh = 10, fcLow = 8 - uint64_t arg2 = 50; // clk RF/50 invert=0 - BS = BitStream; - if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { - return usage_lf_awid_sim(); - } + uint32_t fcode = 0, cnum = 0, fc=0, cn=0, i=0; + uint8_t *BS, BitStream[12]; + uint64_t arg1 = (10<<8) + 8; // fcHigh = 10, fcLow = 8 + uint64_t arg2 = 50; // clk RF/50 invert=0 + BS = BitStream; + if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { + return usage_lf_awid_sim(); + } - fcode=(fc & 0x000000FF); - cnum=(cn & 0x0000FFFF); - if (fc!=fcode) - PrintAndLog("Facility-Code (%u) truncated to 8-bits: %u",fc,fcode); - if (cn!=cnum) - PrintAndLog("Card number (%u) truncated to 16-bits: %u",cn,cnum); - PrintAndLog("Emulating AWID26 -- FC: %u; CN: %u\n",fcode,cnum); - PrintAndLog("Press pm3-button to abort simulation or run another command"); - // AWID uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 0 - if (getAWIDBits(fc, cn, BS)) { - PrintAndLog("Running 'lf simfsk c 50 H 10 L 8 d %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x'", - BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6], - BS[7],BS[8],BS[9],BS[10],BS[11]); - } else - PrintAndLog("Error with tag bitstream generation."); - UsbCommand c; - c.cmd = CMD_FSK_SIM_TAG; - c.arg[0] = arg1; // fcHigh<<8 + fcLow - c.arg[1] = arg2; // Inversion and clk setting - c.arg[2] = 96; // Bitstream length: 96-bits == 12 bytes - for (i=0; i < 96; i++) - c.d.asBytes[i] = (BS[i/8] & (1<<(7-(i%8))))?1:0; - SendCommand(&c); - return 0; + fcode=(fc & 0x000000FF); + cnum=(cn & 0x0000FFFF); + if (fc!=fcode) + PrintAndLog("Facility-Code (%u) truncated to 8-bits: %u",fc,fcode); + if (cn!=cnum) + PrintAndLog("Card number (%u) truncated to 16-bits: %u",cn,cnum); + PrintAndLog("Emulating AWID26 -- FC: %u; CN: %u\n",fcode,cnum); + PrintAndLog("Press pm3-button to abort simulation or run another command"); + // AWID uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 0 + if (getAWIDBits(fc, cn, BS)) { + PrintAndLog("Running 'lf simfsk c 50 H 10 L 8 d %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x'", + BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6], + BS[7],BS[8],BS[9],BS[10],BS[11]); + } else + PrintAndLog("Error with tag bitstream generation."); + UsbCommand c; + c.cmd = CMD_FSK_SIM_TAG; + c.arg[0] = arg1; // fcHigh<<8 + fcLow + c.arg[1] = arg2; // Inversion and clk setting + c.arg[2] = 96; // Bitstream length: 96-bits == 12 bytes + for (i=0; i < 96; i++) + c.d.asBytes[i] = (BS[i/8] & (1<<(7-(i%8))))?1:0; + SendCommand(&c); + return 0; } int CmdAWIDClone(const char *Cmd) { - uint32_t fc=0,cn=0,blocks[4] = {0x00107060, 0, 0, 0x11111111}, i=0; - uint8_t BitStream[12]; - uint8_t *BS=BitStream; - UsbCommand c; - + uint32_t fc=0,cn=0,blocks[4] = {0x00107060, 0, 0, 0x11111111}, i=0; + uint8_t BitStream[12]; + uint8_t *BS=BitStream; + UsbCommand c; + - if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { - return usage_lf_awid_clone(); - } + if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { + return usage_lf_awid_clone(); + } - if ((fc & 0xFF) != fc) { - fc &= 0xFF; - PrintAndLog("Facility-Code Truncated to 8-bits (AWID26): %u", fc); - } - if ((cn & 0xFFFF) != cn) { - cn &= 0xFFFF; - PrintAndLog("Card Number Truncated to 16-bits (AWID26): %u", cn); - } - if (getAWIDBits(fc,cn,BS)) { - PrintAndLog("Preparing to clone AWID26 to T55x7 with FC: %u, CN: %u (Raw: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x)", - fc,cn, BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6],BS[7],BS[8],BS[9],BS[10],BS[11]); - blocks[1] = (BS[0]<<24) + (BS[1]<<16) + (BS[2]<<8) + (BS[3]); - blocks[2] = (BS[4]<<24) + (BS[5]<<16) + (BS[6]<<8) + (BS[7]); - PrintAndLog("Block 0: 0x%08x", blocks[0]); - PrintAndLog("Block 1: 0x%08x", blocks[1]); - PrintAndLog("Block 2: 0x%08x", blocks[2]); - PrintAndLog("Block 3: 0x%08x", blocks[3]); - for (i=0; i<4; i++) { - c.cmd = CMD_T55XX_WRITE_BLOCK; - c.arg[0] = blocks[i]; - c.arg[1] = i; - c.arg[2] = 0; - SendCommand(&c); - } - } - return 0; + if ((fc & 0xFF) != fc) { + fc &= 0xFF; + PrintAndLog("Facility-Code Truncated to 8-bits (AWID26): %u", fc); + } + if ((cn & 0xFFFF) != cn) { + cn &= 0xFFFF; + PrintAndLog("Card Number Truncated to 16-bits (AWID26): %u", cn); + } + if (getAWIDBits(fc,cn,BS)) { + PrintAndLog("Preparing to clone AWID26 to T55x7 with FC: %u, CN: %u (Raw: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x)", + fc,cn, BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6],BS[7],BS[8],BS[9],BS[10],BS[11]); + blocks[1] = (BS[0]<<24) + (BS[1]<<16) + (BS[2]<<8) + (BS[3]); + blocks[2] = (BS[4]<<24) + (BS[5]<<16) + (BS[6]<<8) + (BS[7]); + PrintAndLog("Block 0: 0x%08x", blocks[0]); + PrintAndLog("Block 1: 0x%08x", blocks[1]); + PrintAndLog("Block 2: 0x%08x", blocks[2]); + PrintAndLog("Block 3: 0x%08x", blocks[3]); + for (i=0; i<4; i++) { + c.cmd = CMD_T55XX_WRITE_BLOCK; + c.arg[0] = blocks[i]; + c.arg[1] = i; + c.arg[2] = 0; + SendCommand(&c); + } + } + return 0; } static command_t CommandTable[] = { - {"help", CmdHelp, 1, "This help"}, - {"fskdemod", CmdAWIDDemodFSK, 0, "['1'] Realtime AWID FSK demodulator (option '1' for one tag only)"}, - {"sim", CmdAWIDSim, 0, " -- AWID tag simulator"}, - {"clone", CmdAWIDClone, 0, " -- Clone AWID to T55x7 (tag must be in range of antenna)"}, - {NULL, NULL, 0, NULL} + {"help", CmdHelp, 1, "This help"}, + {"fskdemod", CmdAWIDDemodFSK, 0, "['1'] Realtime AWID FSK demodulator (option '1' for one tag only)"}, + {"sim", CmdAWIDSim, 0, " -- AWID tag simulator"}, + {"clone", CmdAWIDClone, 0, " -- Clone AWID to T55x7 (tag must be in range of antenna)"}, + {NULL, NULL, 0, NULL} }; int CmdLFAWID(const char *Cmd) { - CmdsParse(CommandTable, Cmd); - return 0; + CmdsParse(CommandTable, Cmd); + return 0; } int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); - return 0; + CmdsHelp(CommandTable); + return 0; } From 976627d5ba2939ffcdf34b68d620b566ba1afa93 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Thu, 16 Jul 2015 23:50:41 +0200 Subject: [PATCH 040/145] Fixed (?) issues from PR #129 --- armsrc/appmain.c | 1 + client/cmdlfawid.c | 10 +++++++--- client/cmdlft55xx.c | 5 +++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 37899f57..e5d448da 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -667,6 +667,7 @@ void UsbPacketReceived(uint8_t *packet, int len) break; case CMD_T55XX_WRITE_BLOCK: T55xxWriteBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes[0]); + cmd_send(CMD_ACK,0,0,0,0,0); break; case CMD_T55XX_READ_TRACE: T55xxReadTrace(); diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c index 17837a11..06397e70 100644 --- a/client/cmdlfawid.c +++ b/client/cmdlfawid.c @@ -16,7 +16,7 @@ #include "cmdparser.h" // CmdsParse, CmdsHelp #include "cmdlfawid.h" // AWID function declarations #include "lfdemod.h" // parityTest - +#include "cmdmain.h" static int CmdHelp(const char *Cmd); @@ -176,8 +176,7 @@ int CmdAWIDClone(const char *Cmd) uint32_t fc=0,cn=0,blocks[4] = {0x00107060, 0, 0, 0x11111111}, i=0; uint8_t BitStream[12]; uint8_t *BS=BitStream; - UsbCommand c; - + UsbCommand c, resp; if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) { return usage_lf_awid_clone(); @@ -206,6 +205,11 @@ int CmdAWIDClone(const char *Cmd) c.arg[1] = i; c.arg[2] = 0; SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){ + PrintAndLog("Error occurred, device did not respond during write operation."); + return -1; + } + } } return 0; diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index b357e71c..0007f175 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -670,6 +670,7 @@ int CmdT55xxWriteBlock(const char *Cmd) } UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {data, block, 0}}; + UsbCommand resp; c.d.asBytes[0] = 0x0; PrintAndLog("Writing to block: %d data : 0x%08X", block, data); @@ -681,6 +682,10 @@ int CmdT55xxWriteBlock(const char *Cmd) PrintAndLog("pwd : 0x%08X", password); } SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){ + PrintAndLog("Error occurred, device did not ACK write operation. (May be due to old firmware)"); + return -1; + } return 0; } From 83f3f8ac40b47e220954e620a5ecbe41f54f4dc7 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Fri, 17 Jul 2015 00:01:58 +0200 Subject: [PATCH 041/145] Potential fix for 0-length usb packets seen on OSX --- armsrc/lfops.c | 6 +----- common/usb_cdc.c | 16 ++++++++++++++++ common/usb_cdc.h | 1 + 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/armsrc/lfops.c b/armsrc/lfops.c index 188d7280..733bc953 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -399,14 +399,10 @@ void SimulateTagLowFrequency(int period, int gap, int ledcontrol) #define OPEN_COIL() HIGH(GPIO_SSC_DOUT) i = 0; - byte_t rx[sizeof(UsbCommand)]; // Storage for usb_read call in loop for(;;) { //wait until SSC_CLK goes HIGH while(!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)) { - // Craig Young - Adding a usb_read() here to avoid abort on empty UsbCommand - // My OS X client does this preventing simulation. - // Performance hit should be non-existent since the read is only performed if usb_poll is true - if(BUTTON_PRESS() || (usb_poll() && usb_read(rx,sizeof(UsbCommand)))) { + if(BUTTON_PRESS() || (usb_poll_validate_length() )) { DbpString("Stopped"); return; } diff --git a/common/usb_cdc.c b/common/usb_cdc.c index ccbb3c50..3c6e9282 100644 --- a/common/usb_cdc.c +++ b/common/usb_cdc.c @@ -293,6 +293,22 @@ bool usb_poll() return (pUdp->UDP_CSR[AT91C_EP_OUT] & btReceiveBank); } +/** + In github PR #129, some users appears to get a false positive from + usb_poll, which returns true, but the usb_read operation + still returns 0. + This check is basically the same as above, but also checks + that the length available to read is non-zero, thus hopefully fixes the + bug. +**/ +bool usb_poll_validate_length() +{ + + if (!usb_check()) return false; + if (!(pUdp->UDP_CSR[AT91C_EP_OUT] & btReceiveBank)) return false; + return (pUdp->UDP_CSR[AT91C_EP_OUT] >> 16) > 0; +} + //*---------------------------------------------------------------------------- //* \fn usb_read //* \brief Read available data from Endpoint OUT diff --git a/common/usb_cdc.h b/common/usb_cdc.h index 59e73a47..c42da8db 100644 --- a/common/usb_cdc.h +++ b/common/usb_cdc.h @@ -41,6 +41,7 @@ void usb_disable(); void usb_enable(); bool usb_check(); bool usb_poll(); +bool usb_poll_validate_length(); uint32_t usb_read(byte_t* data, size_t len); uint32_t usb_write(const byte_t* data, const size_t len); From 40c5f34265d56fe84d290aab15a1093cb9a03951 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Fri, 17 Jul 2015 21:49:27 +0200 Subject: [PATCH 042/145] Clear command buffer --- client/cmdlft55xx.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index 0007f175..2291735c 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -242,6 +242,7 @@ int CmdT55xxReadBlock(const char *Cmd) { c.d.asBytes[0] = 0x1; } + clearCommandBuffer(); SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK,NULL,2500) ) { PrintAndLog("command execution time out"); @@ -681,6 +682,7 @@ int CmdT55xxWriteBlock(const char *Cmd) c.d.asBytes[0] = 0x1; PrintAndLog("pwd : 0x%08X", password); } + clearCommandBuffer(); SendCommand(&c); if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){ PrintAndLog("Error occurred, device did not ACK write operation. (May be due to old firmware)"); @@ -883,6 +885,7 @@ int AquireData( uint8_t block ){ // c.d.asBytes[0] = 0x1; // } + clearCommandBuffer(); SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK,NULL,2500) ) { PrintAndLog("command execution time out"); From aa53efc340d9f2dc382e4bb98d49bede5a18e920 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 20 Jul 2015 13:41:40 -0400 Subject: [PATCH 043/145] iclass additions multiple contributors - thanks! --- armsrc/appmain.c | 19 +- armsrc/apps.h | 9 +- armsrc/iclass.c | 285 +++--- client/cmdhf.c | 10 +- client/cmdhficlass.c | 1590 ++++++++++++++++++++++++++++------ client/cmdhficlass.h | 6 + client/cmdlf.c | 2 +- client/hid-flasher/usb_cmd.h | 7 + client/loclass/cipher.c | 21 + client/loclass/cipher.h | 2 + client/lualibs/commands.lua | 9 +- common/protocols.c | 28 +- include/usb_cmd.h | 7 +- 13 files changed, 1580 insertions(+), 415 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 0cbfa249..906379a7 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -860,11 +860,26 @@ void UsbPacketReceived(uint8_t *packet, int len) ReaderIClass(c->arg[0]); break; case CMD_READER_ICLASS_REPLAY: - ReaderIClass_Replay(c->arg[0], c->d.asBytes); + ReaderIClass_Replay(c->arg[0], c->d.asBytes); break; - case CMD_ICLASS_EML_MEMSET: + case CMD_ICLASS_EML_MEMSET: emlSet(c->d.asBytes,c->arg[0], c->arg[1]); break; + case CMD_ICLASS_WRITEBLOCK: + iClass_WriteBlock(c->arg[0], c->arg[1], c->d.asBytes); + break; + case CMD_ICLASS_READBLOCK: + iClass_ReadBlk(c->arg[0], c->arg[1]); + break; + case CMD_ICLASS_AUTHENTICATION: + iClass_Authentication(c->d.asBytes); + break; + case CMD_ICLASS_DUMP: + iClass_Dump(c->arg[0], c->arg[1], c->arg[2]); + break; + case CMD_ICLASS_CLONE: + iClass_Clone(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + break; #endif case CMD_BUFF_CLEAR: diff --git a/armsrc/apps.h b/armsrc/apps.h index 42efd118..e8b43e9b 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -149,9 +149,6 @@ void OnSuccess(); void OnError(uint8_t reason); - - - /// iso15693.h void RecordRawAdcSamplesIso15693(void); void AcquireRawAdcSamplesIso15693(void); @@ -167,6 +164,12 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain void ReaderIClass(uint8_t arg0); void ReaderIClass_Replay(uint8_t arg0,uint8_t *MAC); void IClass_iso14443A_GetPublic(uint8_t arg0); +void iClass_Authentication(uint8_t *MAC); +void iClass_WriteBlock(uint8_t blockNo, uint8_t keyType, uint8_t *data); +void iClass_ReadBlk(uint8_t blockNo, uint8_t keyType); +bool iClass_ReadBlock(uint8_t blockNo, uint8_t keyType, uint8_t *readdata); +void iClass_Dump(uint8_t blockno, uint8_t numblks, uint8_t keyType); +void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t keyType, uint8_t *data); // hitag2.h void SnoopHitag(uint32_t type); diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 97c62bb6..a27fb970 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1601,16 +1601,16 @@ void setupIclassReader() } -size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries) +bool sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries) { while(retries-- > 0) { ReaderTransmitIClass(command, cmdsize); if(expected_size == ReaderReceiveIClass(resp)){ - return 0; + return true; } } - return 1;//Error + return false;//Error } /** @@ -1620,14 +1620,17 @@ size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* * 1 = Got CSN * 2 = Got CSN and CC */ -uint8_t handshakeIclassTag(uint8_t *card_data) +uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) { static uint8_t act_all[] = { 0x0a }; - static uint8_t identify[] = { 0x0c }; + //static uint8_t identify[] = { 0x0c }; + static uint8_t identify[] = { 0x0c, 0x00, 0x73, 0x33 }; static uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - - - static uint8_t readcheck_cc[]= { 0x88, 0x02,}; + static uint8_t readcheck_cc[]= { 0x88, 0x02 }; + if (use_credit_key) + readcheck_cc[0] = 0x18; + else + readcheck_cc[0] = 0x88; uint8_t resp[ICLASS_BUFFER_SIZE]; @@ -1668,6 +1671,9 @@ uint8_t handshakeIclassTag(uint8_t *card_data) return read_status; } +uint8_t handshakeIclassTag(uint8_t *card_data){ + return handshakeIclassTag_ext(card_data, false); +} // Reader iClass Anticollission @@ -1687,6 +1693,9 @@ void ReaderIClass(uint8_t arg0) { uint8_t result_status = 0; bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE; bool try_once = arg0 & FLAG_ICLASS_READER_ONE_TRY; + bool use_credit_key = false; + if (arg0 & FLAG_ICLASS_READER_CEDITKEY) + use_credit_key = true; set_tracing(TRUE); setupIclassReader(); @@ -1701,7 +1710,7 @@ void ReaderIClass(uint8_t arg0) { } WDT_HIT(); - read_status = handshakeIclassTag(card_data); + read_status = handshakeIclassTag_ext(card_data, use_credit_key); if(read_status == 0) continue; if(read_status == 1) result_status = FLAG_ICLASS_READER_CSN; @@ -1715,11 +1724,10 @@ void ReaderIClass(uint8_t arg0) { if(arg0 & FLAG_ICLASS_READER_CONF) { if(sendCmdGetResponseWithRetries(readConf, sizeof(readConf),card_data+8, 10, 10)) - { - Dbprintf("Failed to dump config block"); - }else { result_status |= FLAG_ICLASS_READER_CONF; + } else { + Dbprintf("Failed to dump config block"); } } @@ -1727,10 +1735,9 @@ void ReaderIClass(uint8_t arg0) { if(arg0 & FLAG_ICLASS_READER_AA){ if(sendCmdGetResponseWithRetries(readAA, sizeof(readAA),card_data+(8*4), 10, 10)) { -// Dbprintf("Failed to dump AA block"); - }else - { result_status |= FLAG_ICLASS_READER_AA; + } else { + //Dbprintf("Failed to dump AA block"); } } @@ -1814,7 +1821,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { //for now replay captured auth (as cc not updated) memcpy(check+5,MAC,4); - if(sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5)) + if(!sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5)) { Dbprintf("Error: Authentication Fail!"); continue; @@ -1826,7 +1833,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { read[2] = crc >> 8; read[3] = crc & 0xff; - if(sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10)) + if(!sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10)) { Dbprintf("Dump config (block 1) failed"); continue; @@ -1853,7 +1860,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { read[2] = crc >> 8; read[3] = crc & 0xff; - if(!sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10)) + if(sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10)) { Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x", block, resp[0], resp[1], resp[2], @@ -1904,130 +1911,130 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { LED_A_OFF(); } -//2. Create Read method (cut-down from above) based off responses from 1. -// Since we have the MAC could continue to use replay function. -//3. Create Write method -/* -void IClass_iso14443A_write(uint8_t arg0, uint8_t blockNo, uint8_t *data, uint8_t *MAC) { - uint8_t act_all[] = { 0x0a }; - uint8_t identify[] = { 0x0c }; - uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - uint8_t readcheck_cc[]= { 0x88, 0x02 }; - uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 }; - uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - - uint16_t crc = 0; - - uint8_t* resp = (((uint8_t *)BigBuf) + 3560); +void iClass_Authentication(uint8_t *MAC) { + uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t resp[ICLASS_BUFFER_SIZE]; + memcpy(check+5,MAC,4); + bool isOK; + isOK = sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5); + cmd_send(CMD_ACK,isOK,0,0,0,0); + //Dbprintf("isOK %d, Tag response : %02x%02x%02x%02x",isOK,resp[0],resp[1],resp[2],resp[3]); +} +bool iClass_ReadBlock(uint8_t blockNo, uint8_t keyType, uint8_t *readdata) { + uint8_t readcmd[] = {keyType, blockNo}; //0x88, 0x00 + uint8_t resp[8]; + size_t isOK = 1; - // Reset trace buffer - memset(trace, 0x44, RECV_CMD_OFFSET); - traceLen = 0; + readcmd[1] = blockNo; + isOK = sendCmdGetResponseWithRetries(readcmd, sizeof(readcmd),resp, 8, 5); + memcpy(readdata,resp,sizeof(resp)); - // Setup SSC - FpgaSetupSsc(); - // Start from off (no field generated) - // Signal field is off with the appropriate LED - LED_D_OFF(); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); + return isOK; +} - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); +void iClass_ReadBlk(uint8_t blockno, uint8_t keyType) { + uint8_t readblockdata[8]; + bool isOK = false; + isOK = iClass_ReadBlock(blockno, keyType, readblockdata); + //Dbprintf("read block [%02x] [%02x%02x%02x%02x%02x%02x%02x%02x]",blockNo,readblockdata[0],readblockdata[1],readblockdata[2],readblockdata[3],readblockdata[4],readblockdata[5],readblockdata[6],readblockdata[7]); + cmd_send(CMD_ACK,isOK,0,0,readblockdata,8); +} - // Now give it time to spin up. - // Signal field is on with the appropriate LED - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD); - SpinDelay(200); +void iClass_Dump(uint8_t blockno, uint8_t numblks, uint8_t keyType) { + uint8_t readblockdata[8]; + bool isOK = false; + uint8_t blkCnt = 0; - LED_A_ON(); - - for(int i=0;i<1;i++) { - - if(traceLen > TRACE_SIZE) { - DbpString("Trace full"); - break; - } - - if (BUTTON_PRESS()) break; - - // Send act_all - ReaderTransmitIClass(act_all, 1); - // Card present? - if(ReaderReceiveIClass(resp)) { - ReaderTransmitIClass(identify, 1); - if(ReaderReceiveIClass(resp) == 10) { - // Select card - memcpy(&select[1],resp,8); - ReaderTransmitIClass(select, sizeof(select)); - - if(ReaderReceiveIClass(resp) == 10) { - Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x", - resp[0], resp[1], resp[2], - resp[3], resp[4], resp[5], - resp[6], resp[7]); - } - // Card selected - Dbprintf("Readcheck on Sector 2"); - ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc)); - if(ReaderReceiveIClass(resp) == 8) { - Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x", - resp[0], resp[1], resp[2], - resp[3], resp[4], resp[5], - resp[6], resp[7]); - }else return; - Dbprintf("Authenticate"); - //for now replay captured auth (as cc not updated) - memcpy(check+5,MAC,4); - Dbprintf(" AA: %02x %02x %02x %02x", - check[5], check[6], check[7],check[8]); - ReaderTransmitIClass(check, sizeof(check)); - if(ReaderReceiveIClass(resp) == 4) { - Dbprintf(" AR: %02x %02x %02x %02x", - resp[0], resp[1], resp[2],resp[3]); - }else { - Dbprintf("Error: Authentication Fail!"); - return; - } - Dbprintf("Write Block"); - - //read configuration for max block number - read_success=false; - read[1]=1; - uint8_t *blockno=&read[1]; - crc = iclass_crc16((char *)blockno,1); - read[2] = crc >> 8; - read[3] = crc & 0xff; - while(!read_success){ - ReaderTransmitIClass(read, sizeof(read)); - if(ReaderReceiveIClass(resp) == 10) { - read_success=true; - mem=resp[5]; - memory.k16= (mem & 0x80); - memory.book= (mem & 0x20); - memory.k2= (mem & 0x8); - memory.lockauth= (mem & 0x2); - memory.keyaccess= (mem & 0x1); - - } - } - if (memory.k16){ - cardsize=255; - }else cardsize=32; - //check card_size - - memcpy(write+1,blockNo,1); - memcpy(write+2,data,8); - memcpy(write+10,mac,4); - while(!send_success){ - ReaderTransmitIClass(write, sizeof(write)); - if(ReaderReceiveIClass(resp) == 10) { - write_success=true; - } - }// - } - WDT_HIT(); + BigBuf_free(); + uint8_t *dataout = BigBuf_malloc(255*8); + memset(dataout,0xFF,255*8); + if (dataout == NULL){ + Dbprintf("out of memory"); + OnError(1); + return; } - - LED_A_OFF(); -}*/ + + for (;blkCnt < numblks; blkCnt++) { + isOK = iClass_ReadBlock(blockno+blkCnt, keyType, readblockdata); + if (!isOK || (readblockdata[0] == 0xBB || readblockdata[7] == 0x33 || readblockdata[2] == 0xBB)) { //try again + isOK = iClass_ReadBlock(blockno+blkCnt, keyType, readblockdata); + if (!isOK) { + Dbprintf("Block %02X failed to read", blkCnt+blockno); + break; + } + } + memcpy(dataout+(blkCnt*8),readblockdata,8); + /*Dbprintf("| %02x | %02x%02x%02x%02x%02x%02x%02x%02x |", + blockno+blkCnt, readblockdata[0], readblockdata[1], readblockdata[2], + readblockdata[3], readblockdata[4], readblockdata[5], + readblockdata[6], readblockdata[7]); + */ + } + //return pointer to dump memory in arg3 + cmd_send(CMD_ACK,isOK,blkCnt,BigBuf_max_traceLen(),0,0); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); + BigBuf_free(); +} + +bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t keyType, uint8_t *data) { + uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t readblockdata[8]; + write[1] = blockNo; + memcpy(write+2, data, 12); // data + mac + uint8_t resp[10]; + bool isOK; + isOK = sendCmdGetResponseWithRetries(write,sizeof(write),resp,sizeof(resp),5); + //Dbprintf("reply [%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x]",resp[0],resp[1],resp[2],resp[3],resp[4],resp[5],resp[6],resp[7],resp[8],resp[9]); + if (isOK) { + isOK = iClass_ReadBlock(blockNo, keyType, readblockdata); + //try again + if (!isOK || (readblockdata[0] == 0xBB || readblockdata[7] == 0xBB || readblockdata[2] == 0xBB)) + isOK = iClass_ReadBlock(blockNo, keyType, readblockdata); + } + if (isOK) { + //Dbprintf("read block [%02x] [%02x%02x%02x%02x%02x%02x%02x%02x]",blockNo,readblockdata[0],readblockdata[1],readblockdata[2],readblockdata[3],readblockdata[4],readblockdata[5],readblockdata[6],readblockdata[7]); + if (memcmp(write+2,readblockdata,sizeof(readblockdata)) != 0){ + isOK=false; + } + } + return isOK; +} + +void iClass_WriteBlock(uint8_t blockNo, uint8_t keyType, uint8_t *data) { + bool isOK = iClass_WriteBlock_ext(blockNo, keyType, data); + if (isOK){ + Dbprintf("Write block [%02x] successful",blockNo); + } else { + Dbprintf("Write block [%02x] failed",blockNo); + } + cmd_send(CMD_ACK,isOK,0,0,0,0); +} + +void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t keyType, uint8_t *data) { + int i; + int written = 0; + int total_block = (endblock - startblock) + 1; + for (i = 0; i < total_block;i++){ + // block number + if (iClass_WriteBlock_ext(i+startblock, keyType, data+(i*12))){ + Dbprintf("Write block [%02x] successful",i + startblock); + written++; + } else { + if (iClass_WriteBlock_ext(i+startblock, keyType, data+(i*12))){ + Dbprintf("Write block [%02x] successful",i + startblock); + written++; + } else { + Dbprintf("Write block [%02x] failed",i + startblock); + } + } + } + if (written == total_block) + Dbprintf("Clone complete"); + else + Dbprintf("Clone incomplete"); + + cmd_send(CMD_ACK,1,0,0,0,0); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); +} diff --git a/client/cmdhf.c b/client/cmdhf.c index f8daff7e..8406fe76 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -557,16 +557,16 @@ int CmdHFSearch(const char *Cmd){ PrintAndLog("\nValid ISO14443A Tag Found - Quiting Search\n"); return ans; } - ans = HF14BInfo(false); - if (ans) { - PrintAndLog("\nValid ISO14443B Tag Found - Quiting Search\n"); - return ans; - } ans = HFiClassReader("", false, false); if (ans) { PrintAndLog("\nValid iClass Tag (or PicoPass Tag) Found - Quiting Search\n"); return ans; } + ans = HF14BInfo(false); + if (ans) { + PrintAndLog("\nValid ISO14443B Tag Found - Quiting Search\n"); + return ans; + } ans = HF15Reader("", false); if (ans) { PrintAndLog("\nValid ISO15693 Tag Found - Quiting Search\n"); diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index 824aaa36..db3de205 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -31,9 +31,28 @@ #include "loclass/fileutils.h" #include "protocols.h" #include "usb_cmd.h" +#include "cmdhfmfu.h" + +#define llX PRIx64 static int CmdHelp(const char *Cmd); +#define ICLASS_KEYS_MAX 8 +static uint8_t iClass_Key_Table[ICLASS_KEYS_MAX][8] = { + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 } +}; + +typedef struct iclass_block { + uint8_t d[8]; +} iclass_block_t; + int xorbits_8(uint8_t val) { uint8_t res = val ^ (val >> 1); //1st pass @@ -170,10 +189,11 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) bool tagFound = false; UsbCommand c = {CMD_READER_ICLASS, {FLAG_ICLASS_READER_CSN| FLAG_ICLASS_READER_CONF|FLAG_ICLASS_READER_AA}}; - if (!loop) c.arg[0] |= FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_ONE_TRY; - SendCommand(&c); + // loop in client not device - else on windows have a communication error + c.arg[0] |= FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_ONE_TRY; UsbCommand resp; while(!ukbhit()){ + SendCommand(&c); if (WaitForResponseTimeout(CMD_ACK,&resp, 4500)) { uint8_t readStatus = resp.arg[0] & 0xff; uint8_t *data = resp.d.asBytes; @@ -200,7 +220,6 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) if (!loop) break; } return 0; - } int CmdHFiClassReader(const char *Cmd) @@ -231,6 +250,601 @@ int CmdHFiClassReader_Replay(const char *Cmd) return 0; } +int hf_iclass_eload_usage() +{ + PrintAndLog("Loads iclass tag-dump into emulator memory on device"); + PrintAndLog("Usage: hf iclass eload f "); + PrintAndLog(""); + PrintAndLog("Example: hf iclass eload f iclass_tagdump-aa162d30f8ff12f1.bin"); + return 0; +} + +int iclassEmlSetMem(uint8_t *data, int blockNum, int blocksCount) { + UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}}; + memcpy(c.d.asBytes, data, blocksCount * 16); + SendCommand(&c); + return 0; +} +int CmdHFiClassELoad(const char *Cmd) +{ + + char opt = param_getchar(Cmd, 0); + if (strlen(Cmd)<1 || opt == 'h') + return hf_iclass_eload_usage(); + + //File handling and reading + FILE *f; + char filename[FILE_PATH_SIZE]; + if(opt == 'f' && param_getstr(Cmd, 1, filename) > 0) + { + f = fopen(filename, "rb"); + }else{ + return hf_iclass_eload_usage(); + } + + if(!f) { + PrintAndLog("Failed to read from file '%s'", filename); + return 1; + } + + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); + + uint8_t *dump = malloc(fsize); + + + size_t bytes_read = fread(dump, 1, fsize, f); + fclose(f); + + printIclassDumpInfo(dump); + //Validate + + if (bytes_read < fsize) + { + prnlog("Error, could only read %d bytes (should be %d)",bytes_read, fsize ); + free(dump); + return 1; + } + //Send to device + uint32_t bytes_sent = 0; + uint32_t bytes_remaining = bytes_read; + + while(bytes_remaining > 0){ + uint32_t bytes_in_packet = MIN(USB_CMD_DATA_SIZE, bytes_remaining); + UsbCommand c = {CMD_ICLASS_EML_MEMSET, {bytes_sent,bytes_in_packet,0}}; + memcpy(c.d.asBytes, dump, bytes_in_packet); + SendCommand(&c); + bytes_remaining -= bytes_in_packet; + bytes_sent += bytes_in_packet; + } + free(dump); + PrintAndLog("Sent %d bytes of data to device emulator memory", bytes_sent); + return 0; +} + +int readKeyfile(const char *filename, size_t len, uint8_t* buffer) +{ + FILE *f = fopen(filename, "rb"); + if(!f) { + PrintAndLog("Failed to read from file '%s'", filename); + return 1; + } + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); + size_t bytes_read = fread(buffer, 1, len, f); + fclose(f); + if(fsize != len) + { + PrintAndLog("Warning, file size is %d, expected %d", fsize, len); + return 1; + } + if(bytes_read != len) + { + PrintAndLog("Warning, could only read %d bytes, expected %d" ,bytes_read, len); + return 1; + } + return 0; +} + +int usage_hf_iclass_decrypt() +{ + PrintAndLog("Usage: hf iclass decrypt f o "); + PrintAndLog(""); + PrintAndLog("OBS! In order to use this function, the file 'iclass_decryptionkey.bin' must reside"); + PrintAndLog("in the working directory. The file should be 16 bytes binary data"); + PrintAndLog(""); + PrintAndLog("example: hf iclass decrypt f tagdump_12312342343.bin"); + PrintAndLog(""); + PrintAndLog("OBS! This is pretty stupid implementation, it tries to decrypt every block after block 6. "); + PrintAndLog("Correct behaviour would be to decrypt only the application areas where the key is valid,"); + PrintAndLog("which is defined by the configuration block."); + return 1; +} + +int CmdHFiClassDecrypt(const char *Cmd) +{ + uint8_t key[16] = { 0 }; + if(readKeyfile("iclass_decryptionkey.bin", 16, key)) + { + usage_hf_iclass_decrypt(); + return 1; + } + PrintAndLog("Decryption file found... "); + char opt = param_getchar(Cmd, 0); + if (strlen(Cmd)<1 || opt == 'h') + return usage_hf_iclass_decrypt(); + + //Open the tagdump-file + FILE *f; + char filename[FILE_PATH_SIZE]; + if(opt == 'f' && param_getstr(Cmd, 1, filename) > 0) + { + f = fopen(filename, "rb"); + }else{ + return usage_hf_iclass_decrypt(); + } + + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); + uint8_t enc_dump[8] = {0}; + uint8_t *decrypted = malloc(fsize); + des3_context ctx = { DES_DECRYPT ,{ 0 } }; + des3_set2key_dec( &ctx, key); + size_t bytes_read = fread(enc_dump, 1, 8, f); + + //Use the first block (CSN) for filename + char outfilename[FILE_PATH_SIZE] = { 0 }; + snprintf(outfilename,FILE_PATH_SIZE,"iclass_tagdump-%02x%02x%02x%02x%02x%02x%02x%02x-decrypted", + enc_dump[0],enc_dump[1],enc_dump[2],enc_dump[3], + enc_dump[4],enc_dump[5],enc_dump[6],enc_dump[7]); + + size_t blocknum =0; + while(bytes_read == 8) + { + if(blocknum < 7) + { + memcpy(decrypted+(blocknum*8), enc_dump, 8); + }else{ + des3_crypt_ecb(&ctx, enc_dump,decrypted +(blocknum*8) ); + } + printvar("decrypted block", decrypted +(blocknum*8), 8); + bytes_read = fread(enc_dump, 1, 8, f); + blocknum++; + } + fclose(f); + + saveFile(outfilename,"bin", decrypted, blocknum*8); + + return 0; +} + +int usage_hf_iclass_encrypt(){ + PrintAndLog("Usage: hf iclass encrypt "); + PrintAndLog(""); + PrintAndLog("OBS! In order to use this function, the file 'iclass_decryptionkey.bin' must reside"); + PrintAndLog("in the working directory. The file should be 16 bytes binary data"); + PrintAndLog(""); + PrintAndLog("example: hf iclass encrypt 0102030405060708"); + PrintAndLog(""); + return 0; +} + +int iClassEncryptBlkData(uint8_t *blkData) +{ + uint8_t key[16] = { 0 }; + if(readKeyfile("iclass_decryptionkey.bin", 16, key)) + { + usage_hf_iclass_encrypt(); + return 1; + } + PrintAndLog("Decryption file found... "); + + uint8_t decryptedData[16]; + uint8_t *decrypted = decryptedData; + des3_context ctx = { DES_DECRYPT ,{ 0 } }; + des3_set2key_enc( &ctx, key); + + des3_crypt_ecb(&ctx, blkData,decrypted); + //printvar("decrypted block", decrypted, 8); + memcpy(blkData,decrypted,8); + + return 1; +} + +int CmdHFiClassEncryptBlk(const char *Cmd) +{ + uint8_t blkData[8] = {0}; + char opt = param_getchar(Cmd, 0); + if (strlen(Cmd)<1 || opt == 'h') + return usage_hf_iclass_encrypt(); + + //get the bytes to encrypt + if (param_gethex(Cmd, 0, blkData, 16)) + { + PrintAndLog("BlockData must include 16 HEX symbols"); + return 0; + } + if (!iClassEncryptBlkData(blkData)) return 0; + + printvar("encrypted block", blkData, 8); + return 1; +} + +void Calc_wb_mac(uint8_t blockno,uint8_t *data,uint8_t *div_key,uint8_t MAC[4]){ + uint8_t WB[9]; + WB[0] = blockno; + memcpy(WB + 1,data,8); + doMAC_N(WB,sizeof(WB),div_key,MAC); + //printf("Cal wb mac block [%02x][%02x%02x%02x%02x%02x%02x%02x%02x] : MAC [%02x%02x%02x%02x]",WB[0],WB[1],WB[2],WB[3],WB[4],WB[5],WB[6],WB[7],WB[8],MAC[0],MAC[1],MAC[2],MAC[3]); +} + +static bool select_only(uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool verbose){ + UsbCommand resp; + + UsbCommand c = {CMD_READER_ICLASS, {0}}; + c.arg[0] = FLAG_ICLASS_READER_ONLY_ONCE| FLAG_ICLASS_READER_CC; + if (use_credit_key) + c.arg[0] |= FLAG_ICLASS_READER_CEDITKEY; + + clearCommandBuffer(); + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + { + PrintAndLog("Command execute timeout"); + return false; + } + + uint8_t isOK = resp.arg[0] & 0xff; + uint8_t *data = resp.d.asBytes; + + memcpy(CSN,data,8); + if (CCNR!=NULL)memcpy(CCNR,data+16,8); + //PrintAndLog("isOk:%02x", isOK); + if(isOK > 0) + { + if (verbose) PrintAndLog("CSN: %s",sprint_hex(CSN,8)); + } + if(isOK <= 1){ + PrintAndLog("Failed to obtain CC! Aborting"); + return false; + } + return true; +} + +static bool select_and_auth(uint8_t *KEY, uint8_t *MAC, uint8_t *div_key, bool use_credit_key, bool elite, bool verbose) { + uint8_t CSN[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t CCNR[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keytable[128] = {0}; + uint8_t *used_key; + uint8_t key_sel[8] = {0}; + uint8_t key_sel_p[8] = { 0 }; + + if (!select_only(CSN, CCNR, use_credit_key, verbose)) + return false; + + if(elite) { + hash2(KEY, keytable); + //Get the key index (hash1) + uint8_t key_index[8] = {0}; + hash1(CSN, key_index); + //printvar("hash1", key_index,8); + for(uint8_t i = 0; i < 8 ; i++) + key_sel[i] = keytable[key_index[i]] & 0xFF; + //PrintAndLog("Pre-fortified 'permuted' HS key that would be needed by an iclass reader to talk to above CSN:"); + //printvar("k_sel", key_sel,8); + //Permute from iclass format to standard format + permutekey_rev(key_sel, key_sel_p); + used_key = key_sel_p; + } else { + used_key = KEY; + } + //PrintAndLog("Pre-fortified key that would be needed by the OmniKey reader to talk to above CSN:"); + //printvar("Used key",KEY,8); + diversifyKey(CSN, used_key, div_key); + //PrintAndLog("Hash0, a.k.a diversified key, that is computed using Ksel and stored in the card (Block 3):"); + //printvar("Div key", div_key, 8); + //printvar("CC_NR:",CCNR,8); + doMAC(CCNR, div_key, MAC); + //printvar("MAC", MAC, 4); + UsbCommand resp; + UsbCommand d = {CMD_ICLASS_AUTHENTICATION, {0}}; + memcpy(d.d.asBytes, MAC, 4); + clearCommandBuffer(); + SendCommand(&d); + if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + { + PrintAndLog("Auth Command execute timeout"); + return false; + } + uint8_t isOK = resp.arg[0] & 0xff; + if (!isOK) { + PrintAndLog("Authentication error"); + return false; + } + return true; +} + +int usage_hf_iclass_dump(){ + PrintAndLog("Usage: hf iclass dump f k c e\n"); + PrintAndLog("Options:"); + PrintAndLog(" f : specify a filename to save dump to"); + PrintAndLog(" k : *Access Key as 16 hex symbols or 1 hex to select key from memory"); + PrintAndLog(" c : Credit Key as 16 hex symbols or 1 hex to select key from memory"); + PrintAndLog(" e : If 'e' is specified, the key is interpreted as the 16 byte"); + PrintAndLog(" Custom Key (KCus), which can be obtained via reader-attack"); + PrintAndLog(" See 'hf iclass sim 2'. This key should be on iclass-format"); + PrintAndLog(" NOTE: * = required"); + PrintAndLog("Samples:"); + PrintAndLog(" hf iclass dump k 001122334455667B"); + PrintAndLog(" hf iclass dump k AAAAAAAAAAAAAAAA c 001122334455667B"); + PrintAndLog(" hf iclass dump k AAAAAAAAAAAAAAAA e"); + return 0; +} + +int CmdHFiClassReader_Dump(const char *Cmd){ + + uint8_t MAC[4] = {0x00,0x00,0x00,0x00}; + uint8_t div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t c_div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t blockno = 0; + uint8_t numblks = 0; + uint8_t maxBlk = 32; + uint8_t KEY[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t CreditKEY[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keyNbr = 0; + uint8_t dataLen = 0; + uint8_t fileNameLen = 0; + char filename[FILE_PATH_SIZE]={0}; + char tempStr[50] = {0}; + bool have_credit_key = false; + bool elite = false; + bool errors = false; + uint8_t cmdp = 0; + + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_iclass_dump(); + case 'c': + case 'C': + have_credit_key = true; + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 16) { + errors = param_gethex(tempStr, 0, CreditKEY, dataLen); + } else if (dataLen == 1) { + keyNbr = param_get8(Cmd, cmdp+1); + if (keyNbr <= ICLASS_KEYS_MAX) { + memcpy(CreditKEY, iClass_Key_Table[keyNbr], 8); + } else { + PrintAndLog("\nERROR: Credit KeyNbr is invalid\n"); + errors = true; + } + } else { + PrintAndLog("\nERROR: Credit Key is incorrect length\n"); + errors = true; + } + cmdp += 2; + break; + case 'e': + case 'E': + elite = true; + cmdp++; + break; + case 'f': + case 'F': + fileNameLen = param_getstr(Cmd, cmdp+1, filename); + if (fileNameLen < 1) { + PrintAndLog("No filename found after f"); + errors = true; + } + cmdp += 2; + break; + case 'k': + case 'K': + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 16) { + errors = param_gethex(tempStr, 0, KEY, dataLen); + } else if (dataLen == 1) { + keyNbr = param_get8(Cmd, cmdp+1); + if (keyNbr <= ICLASS_KEYS_MAX) { + memcpy(KEY, iClass_Key_Table[keyNbr], 8); + } else { + PrintAndLog("\nERROR: Credit KeyNbr is invalid\n"); + errors = true; + } + } else { + PrintAndLog("\nERROR: Credit Key is incorrect length\n"); + errors = true; + } + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) return usage_hf_iclass_dump(); + } + + if (cmdp < 2) return usage_hf_iclass_dump(); + + //get config and first 3 blocks + UsbCommand c = {CMD_READER_ICLASS, {FLAG_ICLASS_READER_CSN | + FLAG_ICLASS_READER_CONF | FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_ONE_TRY}}; + UsbCommand resp; + uint8_t tag_data[255*8]; + clearCommandBuffer(); + SendCommand(&c); + if (WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { + uint8_t readStatus = resp.arg[0] & 0xff; + uint8_t *data = resp.d.asBytes; + + if( readStatus == 0){ + //Aborted + PrintAndLog("No tag found..."); + return 0; + } + if( readStatus & (FLAG_ICLASS_READER_CSN|FLAG_ICLASS_READER_CONF|FLAG_ICLASS_READER_CC)){ + memcpy(tag_data, data, 8*3); + /*for (; blockno < 3; blockno++) { + PrintAndLog(" | %02X | %02X%02X%02X%02X%02X%02X%02X%02X |", blockno, + data[(blockno*8)+0],data[(blockno*8)+1],data[(blockno*8)+2],data[(blockno*8)+3], + data[(blockno*8)+4],data[(blockno*8)+5],data[(blockno*8)+6],data[(blockno*8)+7]); + }*/ + blockno+=2; + numblks = data[8]; + + if (data[13] & 0x80) { + // large memory - not able to dump pages currently + maxBlk = 255; + } else { + maxBlk = 32; + } + //PrintAndLog("maxBlk: %02X",maxBlk); + } + } else { + PrintAndLog("Command execute timeout"); + return 0; + } + + if (!select_and_auth(KEY, MAC, div_key, false, elite, false)){ + //try twice - for some reason it sometimes fails the first time... + if (!select_and_auth(KEY, MAC, div_key, false, elite, false)){ + ul_switch_off_field(); + return 0; + } + } + //print debit div_key + //PrintAndLog(" | 03 | %02X%02X%02X%02X%02X%02X%02X%02X |", + // div_key[0],div_key[1],div_key[2],div_key[3], + // div_key[4],div_key[5],div_key[6],div_key[7]); + + if (have_credit_key){ + //turn off hf field + //PrintAndLog("attempt 1 to auth with credit key"); + ul_switch_off_field(); + memset(c_div_key,0,8); + memset(MAC,0,4); + if (!select_and_auth(CreditKEY, MAC, c_div_key, true, false, false)){ + //try twice - for some reason it sometimes fails the first time... + memset(c_div_key,0,8); + memset(MAC,0,4); + if (!select_and_auth(CreditKEY, MAC, c_div_key, true, false, false)){ + ul_switch_off_field(); + return 0; + } + } + //print credit div_key + //PrintAndLog(" | 04 | %02X%02X%02X%02X%02X%02X%02X%02X |", + // div_key[0],div_key[1],div_key[2],div_key[3], + // div_key[4],div_key[5],div_key[6],div_key[7]); + + //turn off hf field + //PrintAndLog("attempt 2 to auth with debit key"); + ul_switch_off_field(); + memset(div_key,0,8); + memset(MAC,0,4); + if (!select_and_auth(KEY, MAC, div_key, false, elite, false)){ + //try twice - for some reason it sometimes fails the first time... + if (!select_and_auth(KEY, MAC, div_key, false, elite, false)){ + ul_switch_off_field(); + return 0; + } + } + } + //PrintAndLog("have %d blocks",blockno); + + UsbCommand w = {CMD_ICLASS_DUMP, {blockno, numblks-blockno+1, 0x88}}; + clearCommandBuffer(); + SendCommand(&w); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { + PrintAndLog("Command execute time-out 1"); + return 1; + } + uint32_t blocksRead = resp.arg[1]; + uint8_t isOK = resp.arg[0] & 0xff; + if (!isOK && !blocksRead) { + PrintAndLog("Read Block Failed"); + return 0; + } + uint32_t startindex = resp.arg[2]; + if (blocksRead*8 > sizeof(tag_data)-(blockno*8)) { + PrintAndLog("Data exceeded Buffer size!"); + blocksRead = (sizeof(tag_data)/8) - blockno; + } + //PrintAndLog("blocksread: %d, blockno: %d, startindex: %x",blocksRead,blockno,startindex); + GetFromBigBuf(tag_data+(blockno*8), blocksRead*8, startindex); + WaitForResponse(CMD_ACK,NULL); + uint32_t gotBytes = blocksRead*8 + blockno*8; + + //PrintAndLog("have %d blocks",gotBytes/8); + + if (have_credit_key && maxBlk > blockno+numblks+1) { + //turn off hf field + ul_switch_off_field(); + //PrintAndLog("attempt 2 to auth with credit key"); + memset(c_div_key,0,8); + memset(MAC,0,4); + if (!select_and_auth(CreditKEY, MAC, c_div_key, true, false, false)){ + //try twice - for some reason it sometimes fails the first time... + if (!select_and_auth(CreditKEY, MAC, c_div_key, true, false, false)){ + ul_switch_off_field(); + return 0; + } + } + w.arg[0] = blockno + blocksRead; + w.arg[1] = maxBlk - (blockno + blocksRead); + w.arg[2] = 0x18; + clearCommandBuffer(); + SendCommand(&w); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { + PrintAndLog("Command execute timeout 2"); + return 0; + } + uint8_t isOK = resp.arg[0] & 0xff; + blocksRead = resp.arg[1]; + if (!isOK && !blocksRead) { + PrintAndLog("Read Block Failed 2"); + return 0; + } + + startindex = resp.arg[2]; + if (blocksRead*8 > sizeof(tag_data)-gotBytes) { + PrintAndLog("Data exceeded Buffer size!"); + blocksRead = (sizeof(tag_data) - gotBytes)/8; + } + GetFromBigBuf(tag_data+gotBytes, blocksRead*8, startindex); + WaitForResponse(CMD_ACK,NULL); + + gotBytes += blocksRead*8; + //PrintAndLog("have %d blocks",gotBytes/8); + } + + memcpy(tag_data+(3*8),div_key,8); + memcpy(tag_data+(4*8),c_div_key,8); + + for (blockno = 0; blockno < gotBytes/8; blockno++){ + PrintAndLog(" | %02X | %02X%02X%02X%02X%02X%02X%02X%02X |", blockno, + tag_data[(blockno*8)+0],tag_data[(blockno*8)+1],tag_data[(blockno*8)+2],tag_data[(blockno*8)+3], + tag_data[(blockno*8)+4],tag_data[(blockno*8)+5],tag_data[(blockno*8)+6],tag_data[(blockno*8)+7]); + } + if (filename[0] == 0){ + snprintf(filename, FILE_PATH_SIZE,"iclass_tagdump-%02x%02x%02x%02x%02x%02x%02x%02x", + tag_data[0],tag_data[1],tag_data[2],tag_data[3], + tag_data[4],tag_data[5],tag_data[6],tag_data[7]); + } + saveFile(filename,"bin",tag_data, gotBytes ); + PrintAndLog("Saving dump file - %d blocks read", gotBytes/8); + return 1; +} + +/* int CmdHFiClassReader_Dump(const char *Cmd) { uint8_t readerType = 0; @@ -238,23 +852,15 @@ int CmdHFiClassReader_Dump(const char *Cmd) uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t CSN[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t CCNR[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - //uint8_t CC_temp[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t keytable[128] = {0}; - int elite = 0; + bool elite = false; + bool use_credit_key = false; uint8_t *used_key; int i; - if (strlen(Cmd)<1) + if (strlen(Cmd) < 1) { - PrintAndLog("Usage: hf iclass dump [e]"); - PrintAndLog(" Key - A 16 byte master key"); - PrintAndLog(" e - If 'e' is specified, the key is interpreted as the 16 byte"); - PrintAndLog(" Custom Key (KCus), which can be obtained via reader-attack"); - PrintAndLog(" See 'hf iclass sim 2'. This key should be on iclass-format"); - PrintAndLog(" sample: hf iclass dump 0011223344556677"); - - - return 0; + return usage_hf_iclass_dump(); } if (param_gethex(Cmd, 0, KEY, 16)) @@ -266,12 +872,16 @@ int CmdHFiClassReader_Dump(const char *Cmd) if (param_getchar(Cmd, 1) == 'e') { PrintAndLog("Elite switch on"); - elite = 1; + elite = true; //calc h2 hash2(KEY, keytable); printarr_human_readable("keytable", keytable, 128); + if (param_getchar(Cmd, 2) == 'c') + use_credit_key = true; + } else if (param_getchar(Cmd, 1) == 'c'){ + use_credit_key = true; } UsbCommand resp; @@ -280,10 +890,11 @@ int CmdHFiClassReader_Dump(const char *Cmd) UsbCommand c = {CMD_READER_ICLASS, {0}}; c.arg[0] = FLAG_ICLASS_READER_ONLY_ONCE| FLAG_ICLASS_READER_CC; + if (use_credit_key) + c.arg[0] |= FLAG_ICLASS_READER_CEDITKEY; + clearCommandBuffer(); SendCommand(&c); - - if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) { PrintAndLog("Command execute timeout"); @@ -383,260 +994,406 @@ int CmdHFiClassReader_Dump(const char *Cmd) } } } - - return 0; } +*/ -int hf_iclass_eload_usage() -{ - PrintAndLog("Loads iclass tag-dump into emulator memory on device"); - PrintAndLog("Usage: hf iclass eload f "); - PrintAndLog(""); - PrintAndLog("Example: hf iclass eload f iclass_tagdump-aa162d30f8ff12f1.bin"); - return 0; +int WriteBlock(uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_credit_key, bool elite, bool verbose){ + uint8_t MAC[4]={0x00,0x00,0x00,0x00}; + uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keyType = (use_credit_key) ? 0x18 : 0x88; + if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, verbose)) + return 0; -} + UsbCommand resp; -int iclassEmlSetMem(uint8_t *data, int blockNum, int blocksCount) { - UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, 0}}; - memcpy(c.d.asBytes, data, blocksCount * 16); - SendCommand(&c); - return 0; -} -int CmdHFiClassELoad(const char *Cmd) -{ - - char opt = param_getchar(Cmd, 0); - if (strlen(Cmd)<1 || opt == 'h') - return hf_iclass_eload_usage(); - - //File handling and reading - FILE *f; - char filename[FILE_PATH_SIZE]; - if(opt == 'f' && param_getstr(Cmd, 1, filename) > 0) + Calc_wb_mac(blockno,bldata,div_key,MAC); + UsbCommand w = {CMD_ICLASS_WRITEBLOCK, {blockno, keyType}}; + memcpy(w.d.asBytes, bldata, 8); + memcpy(w.d.asBytes + 8,MAC, 4); + + clearCommandBuffer(); + SendCommand(&w); + if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) { - f = fopen(filename, "rb"); - }else{ - return hf_iclass_eload_usage(); + PrintAndLog("Write Command execute timeout"); + return 0; } - - if(!f) { - PrintAndLog("Failed to read from file '%s'", filename); - return 1; + uint8_t isOK = resp.arg[0] & 0xff; + if (!isOK) { + PrintAndLog("Write Block Failed"); + return 0; } + PrintAndLog("Write Block Successful"); - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - fseek(f, 0, SEEK_SET); - - uint8_t *dump = malloc(fsize); - - - size_t bytes_read = fread(dump, 1, fsize, f); - fclose(f); - - printIclassDumpInfo(dump); - //Validate - - if (bytes_read < fsize) - { - prnlog("Error, could only read %d bytes (should be %d)",bytes_read, fsize ); - free(dump); - return 1; - } - //Send to device - uint32_t bytes_sent = 0; - uint32_t bytes_remaining = bytes_read; - - while(bytes_remaining > 0){ - uint32_t bytes_in_packet = MIN(USB_CMD_DATA_SIZE, bytes_remaining); - UsbCommand c = {CMD_ICLASS_EML_MEMSET, {bytes_sent,bytes_in_packet,0}}; - memcpy(c.d.asBytes, dump, bytes_in_packet); - SendCommand(&c); - bytes_remaining -= bytes_in_packet; - bytes_sent += bytes_in_packet; - } - free(dump); - PrintAndLog("Sent %d bytes of data to device emulator memory", bytes_sent); - return 0; -} - -int usage_hf_iclass_decrypt() -{ - PrintAndLog("Usage: hf iclass decrypt f o "); - PrintAndLog(""); - PrintAndLog("OBS! In order to use this function, the file 'iclass_decryptionkey.bin' must reside"); - PrintAndLog("in the working directory. The file should be 16 bytes binary data"); - PrintAndLog(""); - PrintAndLog("example: hf iclass decrypt f tagdump_12312342343.bin"); - PrintAndLog(""); - PrintAndLog("OBS! This is pretty stupid implementation, it tries to decrypt every block after block 6. "); - PrintAndLog("Correct behaviour would be to decrypt only the application areas where the key is valid,"); - PrintAndLog("which is defined by the configuration block."); return 1; } -int readKeyfile(const char *filename, size_t len, uint8_t* buffer) -{ - FILE *f = fopen(filename, "rb"); +int usage_hf_iclass_writeblock() { + PrintAndLog("Options:"); + PrintAndLog(" b : The block number as 2 hex symbols"); + PrintAndLog(" d : Set the Data to write as 16 hex symbols"); + PrintAndLog(" k : Access Key as 16 hex symbols or 1 hex to select key from memory"); + PrintAndLog(" c : If 'c' is specified, the key set is assumed to be the credit key\n"); + PrintAndLog(" e : If 'e' is specified, elite computations applied to key"); + PrintAndLog("Samples:"); + PrintAndLog(" hf iclass writeblk b 0A d AAAAAAAAAAAAAAAA k 001122334455667B"); + PrintAndLog(" hf iclass writeblk b 1B d AAAAAAAAAAAAAAAA k 001122334455667B c"); + PrintAndLog(" hf iclass writeblk b 0A d AAAAAAAAAAAAAAAA n 0"); + return 0; +} + +int CmdHFiClass_WriteBlock(const char *Cmd) { + uint8_t blockno=0; + uint8_t bldata[8]={0}; + uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keyNbr = 0; + uint8_t dataLen = 0; + char tempStr[50] = {0}; + bool use_credit_key = false; + bool elite = false; + bool errors = false; + uint8_t cmdp = 0; + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_iclass_writeblock(); + case 'b': + case 'B': + if (param_gethex(Cmd, cmdp+1, &blockno, 2)) { + PrintAndLog("Block No must include 2 HEX symbols\n"); + errors = true; + } + cmdp += 2; + break; + case 'c': + case 'C': + use_credit_key = true; + cmdp++; + break; + case 'd': + case 'D': + if (param_gethex(Cmd, cmdp+1, bldata, 16)) + { + PrintAndLog("KEY must include 16 HEX symbols\n"); + errors = true; + } + cmdp += 2; + break; + case 'e': + case 'E': + elite = true; + cmdp++; + break; + case 'k': + case 'K': + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 16) { + errors = param_gethex(tempStr, 0, KEY, dataLen); + } else if (dataLen == 1) { + keyNbr = param_get8(Cmd, cmdp+1); + if (keyNbr <= ICLASS_KEYS_MAX) { + memcpy(KEY, iClass_Key_Table[keyNbr], 8); + } else { + PrintAndLog("\nERROR: Credit KeyNbr is invalid\n"); + errors = true; + } + } else { + PrintAndLog("\nERROR: Credit Key is incorrect length\n"); + errors = true; + } + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) return usage_hf_iclass_writeblock(); + } + + if (cmdp < 6) return usage_hf_iclass_writeblock(); + + return WriteBlock(blockno, bldata, KEY, use_credit_key, elite, true); +} + +int usage_hf_iclass_clone() { + PrintAndLog("Usage: hf iclass clone f b l k e c"); + PrintAndLog("Options:"); + PrintAndLog(" f : specify a filename to clone from"); + PrintAndLog(" b : The first block to clone as 2 hex symbols"); + PrintAndLog(" l : Set the Data to write as 16 hex symbols"); + PrintAndLog(" k : Access Key as 16 hex symbols or 1 hex to select key from memory"); + PrintAndLog(" c : If 'c' is specified, the key set is assumed to be the credit key\n"); + PrintAndLog(" e : If 'e' is specified, elite computations applied to key"); + PrintAndLog("Samples:"); + PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 06 l 1A k 1122334455667788 e"); + PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 05 l 19 k 0"); + PrintAndLog(" hf iclass clone f iclass_tagdump-121345.bin b 06 l 19 k 0 e"); + return -1; +} + +int CmdHFiClassCloneTag(const char *Cmd) { + char filename[FILE_PATH_SIZE]; + char tempStr[50]={0}; + uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keyNbr = 0; + uint8_t fileNameLen = 0; + uint8_t startblock = 0; + uint8_t endblock = 0; + uint8_t dataLen = 0; + bool use_credit_key = false; + bool elite = false; + bool errors = false; + uint8_t cmdp = 0; + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_iclass_clone(); + case 'b': + case 'B': + if (param_gethex(Cmd, cmdp+1, &startblock, 2)) { + PrintAndLog("Start Block No must include 2 HEX symbols\n"); + errors = true; + } + cmdp += 2; + break; + case 'c': + case 'C': + use_credit_key = true; + cmdp++; + break; + case 'e': + case 'E': + elite = true; + cmdp++; + break; + case 'f': + case 'F': + fileNameLen = param_getstr(Cmd, cmdp+1, filename); + if (fileNameLen < 1) { + PrintAndLog("No filename found after f"); + errors = true; + } + cmdp += 2; + break; + case 'k': + case 'K': + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 16) { + errors = param_gethex(tempStr, 0, KEY, dataLen); + } else if (dataLen == 1) { + keyNbr = param_get8(Cmd, cmdp+1); + if (keyNbr <= ICLASS_KEYS_MAX) { + memcpy(KEY, iClass_Key_Table[keyNbr], 8); + } else { + PrintAndLog("\nERROR: Credit KeyNbr is invalid\n"); + errors = true; + } + } else { + PrintAndLog("\nERROR: Credit Key is incorrect length\n"); + errors = true; + } + cmdp += 2; + break; + case 'l': + case 'L': + if (param_gethex(Cmd, cmdp+1, &endblock, 2)) { + PrintAndLog("Start Block No must include 2 HEX symbols\n"); + errors = true; + } + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) return usage_hf_iclass_clone(); + } + + if (cmdp < 8) return usage_hf_iclass_clone(); + + FILE *f; + + iclass_block_t tag_data[USB_CMD_DATA_SIZE/12]; + + if ((endblock-startblock+1)*12 > USB_CMD_DATA_SIZE) { + PrintAndLog("Trying to write too many blocks at once. Max: %d", USB_CMD_DATA_SIZE/8); + } + // file handling and reading + f = fopen(filename,"rb"); if(!f) { PrintAndLog("Failed to read from file '%s'", filename); return 1; } - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - fseek(f, 0, SEEK_SET); - size_t bytes_read = fread(buffer, 1, len, f); - fclose(f); - if(fsize != len) - { - PrintAndLog("Warning, file size is %d, expected %d", fsize, len); - return 1; - } - if(bytes_read != len) - { - PrintAndLog("Warning, could only read %d bytes, expected %d" ,bytes_read, len); - return 1; - } - return 0; -} -int CmdHFiClassDecrypt(const char *Cmd) -{ - uint8_t key[16] = { 0 }; - if(readKeyfile("iclass_decryptionkey.bin", 16, key)) - { - usage_hf_iclass_decrypt(); - return 1; - } - PrintAndLog("Decryption file found... "); - char opt = param_getchar(Cmd, 0); - if (strlen(Cmd)<1 || opt == 'h') - return usage_hf_iclass_decrypt(); - - //Open the tagdump-file - FILE *f; - char filename[FILE_PATH_SIZE]; - if(opt == 'f' && param_getstr(Cmd, 1, filename) > 0) - { - f = fopen(filename, "rb"); - }else{ - return usage_hf_iclass_decrypt(); - } - - fseek(f, 0, SEEK_END); - long fsize = ftell(f); - fseek(f, 0, SEEK_SET); - uint8_t enc_dump[8] = {0}; - uint8_t *decrypted = malloc(fsize); - des3_context ctx = { DES_DECRYPT ,{ 0 } }; - des3_set2key_dec( &ctx, key); - size_t bytes_read = fread(enc_dump, 1, 8, f); - - //Use the first block (CSN) for filename - char outfilename[FILE_PATH_SIZE] = { 0 }; - snprintf(outfilename,FILE_PATH_SIZE,"iclass_tagdump-%02x%02x%02x%02x%02x%02x%02x%02x-decrypted", - enc_dump[0],enc_dump[1],enc_dump[2],enc_dump[3], - enc_dump[4],enc_dump[5],enc_dump[6],enc_dump[7]); - - size_t blocknum =0; - while(bytes_read == 8) - { - if(blocknum < 7) - { - memcpy(decrypted+(blocknum*8), enc_dump, 8); - }else{ - des3_crypt_ecb(&ctx, enc_dump,decrypted +(blocknum*8) ); - } - printvar("decrypted block", decrypted +(blocknum*8), 8); - bytes_read = fread(enc_dump, 1, 8, f); - blocknum++; - } - fclose(f); - - saveFile(outfilename,"bin", decrypted, blocknum*8); - - return 0; -} - -int CmdHFiClass_iso14443A_write(const char *Cmd) -{ - uint8_t readerType = 0; - uint8_t MAC[4]={0x00,0x00,0x00,0x00}; - uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - uint8_t CSN[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - uint8_t CCNR[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - - uint8_t blockNo=0; - uint8_t bldata[8]={0}; - - if (strlen(Cmd)<3) - { - PrintAndLog("Usage: hf iclass write "); - PrintAndLog(" sample: hf iclass write 0011223344556677 10 AAAAAAAAAAAAAAAA"); + if (startblock<5) { + PrintAndLog("You cannot write key blocks this way. yet... make your start block > 4"); return 0; } + // now read data from the file from block 6 --- 19 + // ok we will use this struct [data 8 bytes][MAC 4 bytes] for each block calculate all mac number for each data + // then copy to usbcommand->asbytes; the max is 32 - 6 = 24 block 12 bytes each block 288 bytes then we can only accept to clone 21 blocks at the time, + // else we have to create a share memory + int i; + fseek(f,startblock*8,SEEK_SET); + fread(tag_data,sizeof(iclass_block_t),endblock - startblock + 1,f); + /* + for (i = 0; i < endblock - startblock+1; i++){ + printf("block [%02x] [%02x%02x%02x%02x%02x%02x%02x%02x]\n",i + startblock,tag_data[i].d[0],tag_data[i].d[1],tag_data[i].d[2],tag_data[i].d[3],tag_data[i].d[4],tag_data[i].d[5],tag_data[i].d[6],tag_data[i].d[7]); + }*/ - if (param_gethex(Cmd, 0, KEY, 16)) - { - PrintAndLog("KEY must include 16 HEX symbols"); - return 1; - } + uint8_t MAC[4]={0x00,0x00,0x00,0x00}; + uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - blockNo = param_get8(Cmd, 1); - if (blockNo>32) - { - PrintAndLog("Error: Maximum number of blocks is 32 for iClass 2K Cards!"); - return 1; - } - if (param_gethex(Cmd, 2, bldata, 8)) - { - PrintAndLog("Block data must include 8 HEX symbols"); - return 1; - } + if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, true)) + return 0; - UsbCommand c = {CMD_ICLASS_ISO14443A_WRITE, {0}}; - SendCommand(&c); + UsbCommand w = {CMD_ICLASS_CLONE,{startblock,endblock,((use_credit_key) ? 0x18 : 0x88)}}; + uint8_t *ptr; + // calculate all mac for every the block we will write + for (i = startblock; i <= endblock; i++){ + Calc_wb_mac(i,tag_data[i - startblock].d,div_key,MAC); + // usb command d start pointer = d + (i - 6) * 12 + // memcpy(pointer,tag_data[i - 6],8) 8 bytes + // memcpy(pointer + 8,mac,sizoof(mac) 4 bytes; + // next one + ptr = w.d.asBytes + (i - startblock) * 12; + memcpy(ptr, &(tag_data[i - startblock].d[0]), 8); + memcpy(ptr + 8,MAC, 4); + } + uint8_t p[12]; + for (i = 0; i <= endblock - startblock;i++){ + memcpy(p,w.d.asBytes + (i * 12),12); + printf("block [%02x]",i + startblock); + printf(" [%02x%02x%02x%02x%02x%02x%02x%02x]",p[0],p[1],p[2],p[3],p[4],p[5],p[6],p[7]); + printf(" MAC [%02x%02x%02x%02x]\n",p[8],p[9],p[10],p[11]); + } UsbCommand resp; - - if (WaitForResponseTimeout(CMD_ACK,&resp,4500)) { - uint8_t isOK = resp.arg[0] & 0xff; - uint8_t * data = resp.d.asBytes; - - memcpy(CSN,data,8); - memcpy(CCNR,data+8,8); - PrintAndLog("DEBUG: %s",sprint_hex(CSN,8)); - PrintAndLog("DEBUG: %s",sprint_hex(CCNR,8)); - PrintAndLog("isOk:%02x", isOK); - } else { + SendCommand(&w); + if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + { PrintAndLog("Command execute timeout"); + return 0; } + return 1; +} - diversifyKey(CSN,KEY, div_key); +int ReadBlock(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, bool verbose){ + uint8_t MAC[4]={0x00,0x00,0x00,0x00}; + uint8_t div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - PrintAndLog("Div Key: %s",sprint_hex(div_key,8)); - doMAC(CCNR, div_key, MAC); + if (!select_and_auth(KEY, MAC, div_key, (keyType==0x18), elite, verbose)) + return 0; - UsbCommand c2 = {CMD_ICLASS_ISO14443A_WRITE, {readerType,blockNo}}; - memcpy(c2.d.asBytes, bldata, 8); - memcpy(c2.d.asBytes+8, MAC, 4); - SendCommand(&c2); - - 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, 4)); - else - PrintAndLog("isOk:%02x", isOK); - } else { + UsbCommand resp; + UsbCommand w = {CMD_ICLASS_READBLOCK, {blockno, keyType}}; + clearCommandBuffer(); + SendCommand(&w); + if (!WaitForResponseTimeout(CMD_ACK,&resp,4500)) + { PrintAndLog("Command execute timeout"); + return 0; } + uint8_t isOK = resp.arg[0] & 0xff; + if (!isOK) { + PrintAndLog("Read Block Failed"); + return 0; + } + //data read is stored in: resp.d.asBytes[0-15] + if (verbose) PrintAndLog("Block %02X: %s\n",blockno, sprint_hex(resp.d.asBytes,8)); + return 1; +} + +int usage_hf_iclass_readblock(){ + PrintAndLog("Usage: hf iclass readblk b k c e\n"); + PrintAndLog("Options:"); + PrintAndLog(" b : The block number as 2 hex symbols"); + PrintAndLog(" k : Access Key as 16 hex symbols or 1 hex to select key from memory"); + PrintAndLog(" c : If 'c' is specified, the key set is assumed to be the credit key\n"); + PrintAndLog(" e : If 'e' is specified, elite computations applied to key"); + PrintAndLog("Samples:"); + PrintAndLog(" hf iclass readblk b 06 k 0011223344556677"); + PrintAndLog(" hf iclass readblk b 1B k 0011223344556677 c"); + PrintAndLog(" hf iclass readblk b 0A k 0"); return 0; } + +int CmdHFiClass_ReadBlock(const char *Cmd) +{ + uint8_t blockno=0; + uint8_t keyType = 0x88; //debit key + uint8_t KEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keyNbr = 0; + uint8_t dataLen = 0; + char tempStr[50] = {0}; + bool elite = false; + bool errors = false; + uint8_t cmdp = 0; + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_iclass_readblock(); + case 'b': + case 'B': + if (param_gethex(Cmd, cmdp+1, &blockno, 2)) { + PrintAndLog("Block No must include 2 HEX symbols\n"); + errors = true; + } + cmdp += 2; + break; + case 'c': + case 'C': + keyType = 0x18; + cmdp++; + break; + case 'e': + case 'E': + elite = true; + cmdp++; + break; + case 'k': + case 'K': + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 16) { + errors = param_gethex(tempStr, 0, KEY, dataLen); + } else if (dataLen == 1) { + keyNbr = param_get8(Cmd, cmdp+1); + if (keyNbr <= ICLASS_KEYS_MAX) { + memcpy(KEY, iClass_Key_Table[keyNbr], 8); + } else { + PrintAndLog("\nERROR: Credit KeyNbr is invalid\n"); + errors = true; + } + } else { + PrintAndLog("\nERROR: Credit Key is incorrect length\n"); + errors = true; + } + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) return usage_hf_iclass_readblock(); + } + + if (cmdp < 4) return usage_hf_iclass_readblock(); + + return ReadBlock(KEY, blockno, keyType, elite, true); +} + int CmdHFiClass_loclass(const char *Cmd) { char opt = param_getchar(Cmd, 0); @@ -683,19 +1440,350 @@ int CmdHFiClass_loclass(const char *Cmd) return 0; } +int usage_hf_iclass_readtagfile(){ + PrintAndLog("Usage: hf iclass readtagfile "); + return 1; +} + +void printIclassDumpContents(uint8_t *iclass_dump, uint8_t startblock, uint8_t endblock, size_t filesize){ + uint8_t blockdata[8]; + uint8_t mem_config; + memcpy(&mem_config, iclass_dump + 13,1); + uint8_t maxmemcount; + uint8_t filemaxblock = filesize / 8; + if (mem_config == 0x80) + maxmemcount = 255; + else + maxmemcount = 32; + + if (startblock == 0) + startblock = 6; + if ((endblock > maxmemcount) || (endblock == 0)) + endblock = maxmemcount; + if (endblock > filemaxblock) + endblock = filemaxblock; + int i = startblock; + int j; + while (i < endblock){ + printf("block[%02X]: ",i); + memcpy(blockdata,iclass_dump + (i * 8),8); + for (j = 0;j < 8;j++) + printf("%02X ",blockdata[j]); + printf("\n"); + i++; + } + if ((i < filemaxblock) && (i < maxmemcount)){ + printf("block[%02X]: ",i); + memcpy(blockdata,iclass_dump + (i * 8),8); + for (j = 0;j < 8;j++) + printf("%02X",blockdata[j]); + printf("\n"); + } +} + +int CmdHFiClassReadTagFile(const char *Cmd) +{ + int startblock = 0; + int endblock = 0; + char tempnum[5]; + FILE *f; + char filename[FILE_PATH_SIZE]; + if (param_getstr(Cmd, 0, filename) < 1) + return usage_hf_iclass_readtagfile(); + if (param_getstr(Cmd,1,(char *)&tempnum) < 1) + startblock = 0; + else + sscanf(tempnum,"%d",&startblock); + + if (param_getstr(Cmd,2,(char *)&tempnum) < 1) + endblock = 0; + else + sscanf(tempnum,"%d",&endblock); + // file handling and reading + f = fopen(filename,"rb"); + if(!f) { + PrintAndLog("Failed to read from file '%s'", filename); + return 1; + } + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); + + uint8_t *dump = malloc(fsize); + + + size_t bytes_read = fread(dump, 1, fsize, f); + fclose(f); + uint8_t *csn = dump; + printf("CSN : %02X %02X %02X %02X %02X %02X %02X %02X\n",csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]); + // printIclassDumpInfo(dump); + printIclassDumpContents(dump,startblock,endblock,bytes_read); + free(dump); + return 0; +} + +uint64_t xorcheck(uint64_t sdiv,uint64_t hdiv){ + uint64_t new_div = 0x00; + new_div ^= sdiv; + new_div ^= hdiv; + return new_div; +} + +uint64_t hexarray_to_uint64(uint8_t *key){ + char temp[17]; + uint64_t uint_key; + for (int i = 0;i < 8;i++) + sprintf(&temp[(i *2)],"%02X",key[i]); + temp[16] = '\0'; + if (sscanf(temp,"%016"llX,&uint_key) < 1) + return 0; + return uint_key; +} + +int usage_hf_iclass_calc_ekey(){ + PrintAndLog("Usage: hf iclass calc_ekey [c]"); + return 1; +} + +int CmdHFiClassCalcEKey(const char *Cmd){ + uint8_t STDKEY[8]; + uint8_t ELITEKEY[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t CSN[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t CCNR[12]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t std_div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t elite_div_key[8]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; + uint8_t keytable[128] = {0}; + uint8_t key_index[8] = {0}; + uint64_t new_div_key; + uint64_t i_elite_div_key; + uint64_t i_std_div_key; + bool use_credit_key = false; + //memcpy(STDKEY,GLOBAL_KEY,sizeof(STDKEY)); + int i; + if (strlen(Cmd) < 2) + return usage_hf_iclass_calc_ekey(); + + if (param_gethex(Cmd, 0, STDKEY, 16)) + return usage_hf_iclass_calc_ekey(); + + if (param_gethex(Cmd, 1, ELITEKEY, 16) != 0) + return usage_hf_iclass_calc_ekey(); + + if (param_getchar(Cmd, 2)=='c') + use_credit_key = true; + + hash2(ELITEKEY, keytable); + + uint8_t key_sel[8] = { 0 }; + uint8_t key_sel_p[8] = { 0 }; + + if (!select_only(CSN, CCNR, use_credit_key, true)) + return 0; + + diversifyKey(CSN, STDKEY, std_div_key); + + // printvar("(S)Div key", std_div_key, 8); + hash1(CSN, key_index); + for(i = 0; i < 8 ; i++) + key_sel[i] = keytable[key_index[i]] & 0xFF; + + //Permute from iclass format to standard format + permutekey_rev(key_sel, key_sel_p); + diversifyKey(CSN, key_sel_p, elite_div_key); + // printvar("(E)Div key", elite_div_key, 8); + i_elite_div_key = hexarray_to_uint64(elite_div_key); + i_std_div_key = hexarray_to_uint64(std_div_key); + new_div_key = xorcheck(i_std_div_key, i_elite_div_key); + printf("New Div Key : %016"llX"\n",new_div_key); + return 0; +} + +int loadKeys(char *filename){ + FILE *f; + f = fopen(filename,"rb"); + if(!f) { + PrintAndLog("Failed to read from file '%s'", filename); + return 0; + } + fseek(f, 0, SEEK_END); + long fsize = ftell(f); + fseek(f, 0, SEEK_SET); + + uint8_t *dump = malloc(fsize); + + size_t bytes_read = fread(dump, 1, fsize, f); + fclose(f); + if (bytes_read > ICLASS_KEYS_MAX * 8){ + PrintAndLog("File is too long to load - bytes: %u", bytes_read); + free(dump); + return 0; + } + uint8_t i = 0; + for (; i < bytes_read/8; i++){ + memcpy(iClass_Key_Table[i],dump+(i*8),8); + } + free(dump); + PrintAndLog("%u keys loaded", i); + return 1; +} + +int saveKeys(char *filename){ + FILE *f; + f = fopen(filename,"wb"); + if (f == NULL) { + printf("error opening file %s\n",filename); + return 0; + } + for (uint8_t i = 0; i < ICLASS_KEYS_MAX; i++){ + if (fwrite(iClass_Key_Table[i],8,1,f) != 1){ + PrintAndLog("save key failed to write to file: %s", filename); + break; + } + } + fclose(f); + return 0; +} + +int printKeys(){ + PrintAndLog(""); + for (uint8_t i = 0; i < ICLASS_KEYS_MAX; i++){ + PrintAndLog("%u: %s",i,sprint_hex(iClass_Key_Table[i],8)); + } + PrintAndLog(""); + return 0; +} + +int usage_hf_iclass_managekeys(){ + PrintAndLog("HELP : Manage iClass Keys in client memory:\n"); + PrintAndLog("Usage: hf iclass managekeys n [keynbr] k [key] f [filename] s l p\n"); + PrintAndLog(" Options:"); + PrintAndLog(" n : specify the keyNbr to set in memory"); + PrintAndLog(" k : set a key in memory"); + PrintAndLog(" f : specify a filename to use with load or save operations"); + PrintAndLog(" s : save keys in memory to file specified by filename"); + PrintAndLog(" l : load keys to memory from file specified by filename"); + PrintAndLog(" p : print keys loaded into memory\n"); + PrintAndLog("Samples:"); + PrintAndLog(" set key : hf iclass managekeys n 0 k 1122334455667788"); + PrintAndLog(" save key file: hf iclass managekeys f mykeys.bin s"); + PrintAndLog(" load key file: hf iclass managekeys f mykeys.bin l"); + PrintAndLog(" print keys : hf iclass managekeys p\n"); + return 0; +} + +int CmdManageKeys(const char *Cmd){ + uint8_t keyNbr = 0; + uint8_t dataLen = 0; + uint8_t KEY[8] = {0}; + char filename[FILE_PATH_SIZE]; + uint8_t fileNameLen = 0; + bool errors = false; + uint8_t operation = 0; + char tempStr[20]; + uint8_t cmdp = 0; + + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_iclass_managekeys(); + case 'f': + case 'F': + fileNameLen = param_getstr(Cmd, cmdp+1, filename); + if (fileNameLen < 1) { + PrintAndLog("No filename found after f"); + errors = true; + } + cmdp += 2; + break; + case 'n': + case 'N': + keyNbr = param_get8(Cmd, cmdp+1); + if (keyNbr < 0) { + PrintAndLog("Wrong block number"); + errors = true; + } + cmdp += 2; + break; + case 'k': + case 'K': + operation += 3; //set key + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 16) { //ul-c or ev1/ntag key length + errors = param_gethex(tempStr, 0, KEY, dataLen); + } else { + PrintAndLog("\nERROR: Key is incorrect length\n"); + errors = true; + } + cmdp += 2; + break; + case 'p': + case 'P': + operation += 4; //print keys in memory + cmdp++; + break; + case 'l': + case 'L': + operation += 5; //load keys from file + cmdp++; + break; + case 's': + case 'S': + operation += 6; //save keys to file + cmdp++; + break; + default: + PrintAndLog("Unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) return usage_hf_iclass_managekeys(); + } + if (operation == 0){ + PrintAndLog("no operation specified (load, save, or print)\n"); + return usage_hf_iclass_managekeys(); + } + if (operation > 6){ + PrintAndLog("Too many operations specified\n"); + return usage_hf_iclass_managekeys(); + } + if (operation > 4 && fileNameLen == 0){ + PrintAndLog("You must enter a filename when loading or saving\n"); + return usage_hf_iclass_managekeys(); + } + + switch (operation){ + case 3: memcpy(iClass_Key_Table[keyNbr], KEY, 8); return 1; + case 4: return printKeys(); + case 5: return loadKeys(filename); + case 6: return saveKeys(filename); + break; + } + return 0; +} + static command_t CommandTable[] = { - {"help", CmdHelp, 1, "This help"}, - {"list", CmdHFiClassList, 0, "[Deprecated] List iClass history"}, - {"snoop", CmdHFiClassSnoop, 0, "Eavesdrop iClass communication"}, - {"sim", CmdHFiClassSim, 0, "Simulate iClass tag"}, - {"reader",CmdHFiClassReader, 0, "Read an iClass tag"}, - {"replay",CmdHFiClassReader_Replay, 0, "Read an iClass tag via Reply Attack"}, - {"dump", CmdHFiClassReader_Dump, 0, "Authenticate and Dump iClass tag"}, -// {"write", CmdHFiClass_iso14443A_write, 0, "Authenticate and Write iClass block"}, - {"loclass", CmdHFiClass_loclass, 1, "Use loclass to perform bruteforce of reader attack dump"}, - {"eload", CmdHFiClassELoad, 0, "[experimental] Load data into iclass emulator memory"}, - {"decrypt", CmdHFiClassDecrypt, 1, "Decrypt tagdump" }, + {"help", CmdHelp, 1, "This help"}, + {"calc_ekey", CmdHFiClassCalcEKey, 0, "Get Elite Diversified key (block 3) to write to convert std to elite"}, + {"clone", CmdHFiClassCloneTag, 0, "Authenticate and Clone from iClass bin file"}, + {"decrypt", CmdHFiClassDecrypt, 1, "Decrypt tagdump" }, + {"dump", CmdHFiClassReader_Dump, 0, "Authenticate and Dump iClass tag's AA1"}, + {"eload", CmdHFiClassELoad, 0, "[experimental] Load data into iClass emulator memory"}, + {"encryptblk", CmdHFiClassEncryptBlk, 1, "[blockData] Encrypt given block data"}, + {"list", CmdHFiClassList, 0, "[Deprecated] List iClass history"}, + //{"load", CmdHFiClass_load, 0, "Load from tagfile to iClass card"}, + {"loclass", CmdHFiClass_loclass, 1, "Use loclass to perform bruteforce of reader attack dump"}, + {"managekeys", CmdManageKeys, 1, "Manage the keys to use with iClass"}, + {"readblk", CmdHFiClass_ReadBlock, 0, "Authenticate and Read iClass block"}, + {"reader", CmdHFiClassReader, 0, "Read an iClass tag"}, + {"readtagfile", CmdHFiClassReadTagFile, 1, "Display Content from tagfile"}, + {"replay", CmdHFiClassReader_Replay, 0, "Read an iClass tag via Reply Attack"}, + {"sim", CmdHFiClassSim, 0, "Simulate iClass tag"}, + {"snoop", CmdHFiClassSnoop, 0, "Eavesdrop iClass communication"}, + {"writeblk", CmdHFiClass_WriteBlock, 0, "Authenticate and Write iClass block"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdhficlass.h b/client/cmdhficlass.h index 30c6a8a7..88e61434 100644 --- a/client/cmdhficlass.h +++ b/client/cmdhficlass.h @@ -20,5 +20,11 @@ int CmdHFiClassList(const char *Cmd); int HFiClassReader(const char *Cmd, bool loop, bool verbose); int CmdHFiClassReader(const char *Cmd); int CmdHFiClassReader_Replay(const char *Cmd); +int CmdHFiClassReadKeyFile(const char *filename); +int CmdHFiClassWriteKeyFile(const char *Cmd); +int CmdHFiClass_ReadBlock(const char *Cmd); +int CmdHFiClass_WriteBlock(const char *Cmd); +int CmdHFiClassCalcEKey(const char *Cmd); +int CmdHFiClass_TestMac(const char *Cmd); #endif diff --git a/client/cmdlf.c b/client/cmdlf.c index 1acee39b..21b19b09 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -1136,7 +1136,7 @@ static command_t CommandTable[] = {"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"}, + {"simask", CmdLFaskSim, 0, "[clock] [invert <1|0>] [biphase/manchester/raw <'b'|'m'|'r'>] [msg separator 's'] [d ] -- Simulate LF ASK tag from demodbuffer or input"}, {"simfsk", CmdLFfskSim, 0, "[c ] [i] [H ] [L ] [d ] -- Simulate LF FSK tag from demodbuffer or input"}, {"simpsk", CmdLFpskSim, 0, "[1|2|3] [c ] [i] [r ] [d ] -- Simulate LF PSK tag from demodbuffer or input"}, {"simbidir", CmdLFSimBidir, 0, "Simulate LF tag (with bidirectional data transmission between reader and tag)"}, diff --git a/client/hid-flasher/usb_cmd.h b/client/hid-flasher/usb_cmd.h index b3a7f4ec..cc415352 100644 --- a/client/hid-flasher/usb_cmd.h +++ b/client/hid-flasher/usb_cmd.h @@ -114,9 +114,16 @@ typedef struct { #define CMD_WRITER_LEGIC_RF 0x0389 #define CMD_EPA_PACE_COLLECT_NONCE 0x038A +#define CMD_ICLASS_CLONE 0x0390 +#define CMD_ICLASS_DUMP 0x0391 #define CMD_SNOOP_ICLASS 0x0392 #define CMD_SIMULATE_TAG_ICLASS 0x0393 #define CMD_READER_ICLASS 0x0394 +#define CMD_READER_ICLASS_REPLAY 0x0395 +#define CMD_ICLASS_READBLOCK 0x0396 +#define CMD_ICLASS_WRITEBLOCK 0x0397 +#define CMD_ICLASS_EML_MEMSET 0x0398 +#define CMD_ICLASS_AUTHENTICATION 0x0399 // For measurements of the antenna tuning #define CMD_MEASURE_ANTENNA_TUNING 0x0400 diff --git a/client/loclass/cipher.c b/client/loclass/cipher.c index 7c9cc873..2aae093d 100644 --- a/client/loclass/cipher.c +++ b/client/loclass/cipher.c @@ -241,6 +241,27 @@ void doMAC(uint8_t *cc_nr_p, uint8_t *div_key_p, uint8_t mac[4]) //free(cc_nr); return; } +void doMAC_N(uint8_t *cc_nr_p,uint8_t cc_nr_size, uint8_t *div_key_p, uint8_t mac[4]) +{ + uint8_t *cc_nr; + uint8_t div_key[8]; + cc_nr = (uint8_t*) malloc(cc_nr_size); + + memcpy(cc_nr,cc_nr_p,cc_nr_size); + memcpy(div_key,div_key_p,8); + + reverse_arraybytes(cc_nr,cc_nr_size); + BitstreamIn bitstream = {cc_nr,cc_nr_size * 8,0}; + uint8_t dest []= {0,0,0,0,0,0,0,0}; + BitstreamOut out = { dest, sizeof(dest)*8, 0 }; + MAC(div_key,bitstream, out); + //The output MAC must also be reversed + reverse_arraybytes(dest, sizeof(dest)); + memcpy(mac, dest, 4); + free(cc_nr); + return; +} + #ifndef ON_DEVICE int testMAC() { diff --git a/client/loclass/cipher.h b/client/loclass/cipher.h index bdea9432..24e86851 100644 --- a/client/loclass/cipher.h +++ b/client/loclass/cipher.h @@ -42,6 +42,8 @@ #include void doMAC(uint8_t *cc_nr_p, uint8_t *div_key_p, uint8_t mac[4]); +void doMAC_N(uint8_t *cc_nr_p,uint8_t cc_nr_size, uint8_t *div_key_p, uint8_t mac[4]); + #ifndef ON_DEVICE int testMAC(); #endif diff --git a/client/lualibs/commands.lua b/client/lualibs/commands.lua index 4c7bc638..97f0b70a 100644 --- a/client/lualibs/commands.lua +++ b/client/lualibs/commands.lua @@ -86,11 +86,16 @@ local _commands = { CMD_EPA_PACE_COLLECT_NONCE = 0x038A, --//CMD_EPA_ = 0x038B, + CMD_ICLASS_CLONE = 0x0390, + CMD_ICLASS_DUMP = 0x0391, CMD_SNOOP_ICLASS = 0x0392, CMD_SIMULATE_TAG_ICLASS = 0x0393, CMD_READER_ICLASS = 0x0394, - CMD_READER_ICLASS_REPLAY = 0x0395, - CMD_ICLASS_ISO14443A_WRITE = 0x0397, + CMD_READER_ICLASS_REPLAY = 0x0395, + CMD_ICLASS_READBLOCK = 0x0396, + CMD_ICLASS_WRITEBLOCK = 0x0397, + CMD_ICLASS_EML_MEMSET = 0x0398, + CMD_ICLASS_AUTHENTICATION = 0x0399, --// For measurements of the antenna tuning CMD_MEASURE_ANTENNA_TUNING = 0x0400, diff --git a/common/protocols.c b/common/protocols.c index aa80491b..56a6924f 100644 --- a/common/protocols.c +++ b/common/protocols.c @@ -74,24 +74,30 @@ void fuse_config(const picopass_hdr *hdr) if( isset( fuses, FUSE_RA)) prnt(" RA: Read access enabled"); else prnt(" RA: Read access not enabled"); } -void mem_config(const picopass_hdr *hdr) +void mem_app_config(const picopass_hdr *hdr) { uint8_t mem = hdr->conf.mem_config; - if( isset (mem, 0x80)) prnt(" Mem: 16KBits (255 * 8 bytes)"); - else prnt(" Mem: 2 KBits ( 32 * 8 bytes)"); - -} -void applimit_config(const picopass_hdr *hdr) -{ uint8_t applimit = hdr->conf.app_limit; - prnt(" AA1: blocks 6-%d", applimit); - prnt(" AA2: blocks %d-", (applimit+1)); + if (applimit < 6) applimit = 26; + uint8_t kb=2; + uint8_t maxBlk = 32; + if( isset(mem, 0x10) && notset(mem, 0x80)){ + // 2kb default + } else if( isset(mem, 0x80) && notset(mem, 0x10)){ + kb = 16; + maxBlk = 255; //16kb + } else { + kb = 32; + maxBlk = 255; + } + prnt(" Mem: %u KBits ( %u * 8 bytes) [%02X]", kb, maxBlk, mem); + prnt(" AA1: blocks 06-%02X", applimit); + prnt(" AA2: blocks %02X-%02X", (applimit+1), (hdr->conf.mem_config)); } void print_picopass_info(const picopass_hdr *hdr) { fuse_config(hdr); - mem_config(hdr); - applimit_config(hdr); + mem_app_config(hdr); } void printIclassDumpInfo(uint8_t* iclass_dump) { diff --git a/include/usb_cmd.h b/include/usb_cmd.h index 524554e9..2618476a 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -128,12 +128,16 @@ typedef struct{ #define CMD_EPA_PACE_COLLECT_NONCE 0x038A #define CMD_EPA_PACE_REPLAY 0x038B +#define CMD_ICLASS_CLONE 0x0390 +#define CMD_ICLASS_DUMP 0x0391 #define CMD_SNOOP_ICLASS 0x0392 #define CMD_SIMULATE_TAG_ICLASS 0x0393 #define CMD_READER_ICLASS 0x0394 #define CMD_READER_ICLASS_REPLAY 0x0395 -#define CMD_ICLASS_ISO14443A_WRITE 0x0397 +#define CMD_ICLASS_READBLOCK 0x0396 +#define CMD_ICLASS_WRITEBLOCK 0x0397 #define CMD_ICLASS_EML_MEMSET 0x0398 +#define CMD_ICLASS_AUTHENTICATION 0x0399 // For measurements of the antenna tuning #define CMD_MEASURE_ANTENNA_TUNING 0x0400 @@ -204,6 +208,7 @@ typedef struct{ #define FLAG_ICLASS_READER_CONF 0x08 #define FLAG_ICLASS_READER_AA 0x10 #define FLAG_ICLASS_READER_ONE_TRY 0x20 +#define FLAG_ICLASS_READER_CEDITKEY 0x40 From db2dc28d34943676c0890ac0bc3fb8026a8c2808 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Mon, 20 Jul 2015 23:17:55 +0200 Subject: [PATCH 044/145] Reverted previous change to , I made it no longer cache previous results --- client/cmdhw.c | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) diff --git a/client/cmdhw.c b/client/cmdhw.c index 05ad0c9f..7218f3e9 100644 --- a/client/cmdhw.c +++ b/client/cmdhw.c @@ -406,21 +406,15 @@ int CmdVersion(const char *Cmd) { UsbCommand c = {CMD_VERSION}; - static UsbCommand resp = {0, {0, 0, 0}}; - - if (resp.arg[0] == 0 && resp.arg[1] == 0) { // no cached information available - SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && Cmd != NULL) { - PrintAndLog("Prox/RFID mark3 RFID instrument"); - PrintAndLog((char*)resp.d.asBytes); - lookupChipID(resp.arg[0], resp.arg[1]); - } - } else if (Cmd != NULL) { + UsbCommand resp = {0, {0, 0, 0}}; + + SendCommand(&c); + if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && Cmd != NULL) { PrintAndLog("Prox/RFID mark3 RFID instrument"); PrintAndLog((char*)resp.d.asBytes); lookupChipID(resp.arg[0], resp.arg[1]); } - + return 0; } From d2deaf7bcff57422c1467becfeebdd4fa7492295 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Mon, 20 Jul 2015 23:18:46 +0200 Subject: [PATCH 045/145] Fixed some indentation --- common/usb_cdc.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/common/usb_cdc.c b/common/usb_cdc.c index 3c6e9282..e13ddbe2 100644 --- a/common/usb_cdc.c +++ b/common/usb_cdc.c @@ -314,26 +314,26 @@ bool usb_poll_validate_length() //* \brief Read available data from Endpoint OUT //*---------------------------------------------------------------------------- uint32_t usb_read(byte_t* data, size_t len) { - byte_t bank = btReceiveBank; + byte_t bank = btReceiveBank; uint32_t packetSize, nbBytesRcv = 0; - uint32_t time_out = 0; + uint32_t time_out = 0; while (len) { if (!usb_check()) break; if ( pUdp->UDP_CSR[AT91C_EP_OUT] & bank ) { packetSize = MIN(pUdp->UDP_CSR[AT91C_EP_OUT] >> 16, len); - len -= packetSize; + len -= packetSize; while(packetSize--) data[nbBytesRcv++] = pUdp->UDP_FDR[AT91C_EP_OUT]; pUdp->UDP_CSR[AT91C_EP_OUT] &= ~(bank); if (bank == AT91C_UDP_RX_DATA_BK0) { bank = AT91C_UDP_RX_DATA_BK1; - } else { + } else { bank = AT91C_UDP_RX_DATA_BK0; - } + } } - if (time_out++ == 0x1fff) break; + if (time_out++ == 0x1fff) break; } btReceiveBank = bank; From 23931c11d54647e29eedb774bb58ec47512bb5cc Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Mon, 20 Jul 2015 23:22:33 +0200 Subject: [PATCH 046/145] Minor fix with previous cache-removal --- client/cmdhw.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhw.c b/client/cmdhw.c index 7218f3e9..2b6f9518 100644 --- a/client/cmdhw.c +++ b/client/cmdhw.c @@ -409,7 +409,7 @@ int CmdVersion(const char *Cmd) UsbCommand resp = {0, {0, 0, 0}}; SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && Cmd != NULL) { + if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { PrintAndLog("Prox/RFID mark3 RFID instrument"); PrintAndLog((char*)resp.d.asBytes); lookupChipID(resp.arg[0], resp.arg[1]); From 86a83668b571d34deec1643eeda3b871cee56b75 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Tue, 21 Jul 2015 00:13:06 +0200 Subject: [PATCH 047/145] Minor changes in iso1443-standalone mode --- armsrc/appmain.c | 438 +++++++++++++++++++++++------------------------ 1 file changed, 215 insertions(+), 223 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index ddfe001c..7aa353b2 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -298,19 +298,13 @@ void SendVersion(void) cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), text_and_rodata_section_size + compressed_data_section_size, 0, VersionString, strlen(VersionString)); } -#ifdef WITH_LF -#ifndef WITH_ISO14443a_StandAlone -// samy's sniff and repeat routine -void SamyRun() -{ - DbpString("Stand-alone mode! No PC necessary."); - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); +#if defined(WITH_ISO14443a_StandAlone) || defined(WITH_LF) - // 3 possible options? no just 2 for now #define OPTS 2 - int high[OPTS], low[OPTS]; - +void StandAloneMode() +{ + DbpString("Stand-alone mode! No PC necessary."); // Oooh pretty -- notify user we're in elite samy mode now LED(LED_RED, 200); LED(LED_ORANGE, 200); @@ -322,6 +316,216 @@ void SamyRun() LED(LED_ORANGE, 200); LED(LED_RED, 200); +} + +#endif + + + +#ifdef WITH_ISO14443a_StandAlone +void StandAloneMode14a() +{ + StandAloneMode(); + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + + int selected = 0; + int playing = 0; + int cardRead[OPTS] = {0}; + uint8_t readUID[10] = {0}; + uint32_t uid_1st[OPTS]={0}; + uint32_t uid_2nd[OPTS]={0}; + + LED(selected + 1, 0); + + for (;;) + { + usb_poll(); + WDT_HIT(); + + // Was our button held down or pressed? + int button_pressed = BUTTON_HELD(1000); + SpinDelay(300); + + // Button was held for a second, begin recording + if (button_pressed > 0 && cardRead[selected] == 0) + { + LEDsoff(); + LED(selected + 1, 0); + LED(LED_RED2, 0); + + // record + Dbprintf("Enabling iso14443a reader mode for [Bank: %u]...", selected); + + // wait for button to be released + while(BUTTON_PRESS()) + WDT_HIT(); + /* need this delay to prevent catching some weird data */ + SpinDelay(500); + /* Code for reading from 14a tag */ + uint8_t uid[10] ={0}; + uint32_t cuid; + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + + for ( ; ; ) + { + WDT_HIT(); + if (!iso14443a_select_card(uid, NULL, &cuid)) + continue; + else + { + Dbprintf("Read UID:"); Dbhexdump(10,uid,0); + memcpy(readUID,uid,10*sizeof(uint8_t)); + uint8_t *dst = (uint8_t *)&uid_1st[selected]; + // Set UID byte order + for (int i=0; i<4; i++) + dst[i] = uid[3-i]; + dst = (uint8_t *)&uid_2nd[selected]; + for (int i=0; i<4; i++) + dst[i] = uid[7-i]; + break; + } + } + LEDsoff(); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + + LEDsoff(); + LED(selected + 1, 0); + // Finished recording + + // If we were previously playing, set playing off + // so next button push begins playing what we recorded + playing = 0; + + cardRead[selected] = 1; + + } + /* MF UID clone */ + else if (button_pressed > 0 && cardRead[selected] == 1) + { + LEDsoff(); + LED(selected + 1, 0); + LED(LED_ORANGE, 250); + + + // record + Dbprintf("Preparing to Clone card [Bank: %x]; uid: %08x", selected, uid_1st[selected]); + + // wait for button to be released + while(BUTTON_PRESS()) + { + // Delay cloning until card is in place + WDT_HIT(); + } + Dbprintf("Starting clone. [Bank: %u]", selected); + // need this delay to prevent catching some weird data + SpinDelay(500); + // Begin clone function here: + /* Example from client/mifarehost.c for commanding a block write for "magic Chinese" cards: + UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}}; + memcpy(c.d.asBytes, data, 16); + SendCommand(&c); + + Block read is similar: + UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}}; + We need to imitate that call with blockNo 0 to set a uid. + + The get and set commands are handled in this file: + // Work with "magic Chinese" card + case CMD_MIFARE_CSETBLOCK: + MifareCSetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + break; + case CMD_MIFARE_CGETBLOCK: + MifareCGetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + // + break; + + mfCSetUID provides example logic for UID set workflow: + -Read block0 from card in field with MifareCGetBlock() + -Configure new values without replacing reserved bytes + memcpy(block0, uid, 4); // Copy UID bytes from byte array + // Mifare UID BCC + block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 + Bytes 5-7 are reserved SAK and ATQA for mifare classic + -Use mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER) to write it + */ + uint8_t oldBlock0[16] = {0}, newBlock0[16] = {0}, testBlock0[16] = {0}; + // arg0 = Flags == CSETBLOCK_SINGLE_OPER=0x1F, arg1=returnSlot, arg2=blockNo + MifareCGetBlock(0x1F, 1, 0, oldBlock0); + Dbprintf("UID from target tag: %02X%02X%02X%02X", oldBlock0[0],oldBlock0[1],oldBlock0[2],oldBlock0[3]); + memcpy(newBlock0,oldBlock0,16); + // Copy uid_1st for bank (2nd is for longer UIDs not supported if classic) + + newBlock0[0] = uid_1st[selected]>>24; + newBlock0[1] = 0xFF & (uid_1st[selected]>>16); + newBlock0[2] = 0xFF & (uid_1st[selected]>>8); + newBlock0[3] = 0xFF & (uid_1st[selected]); + newBlock0[4] = newBlock0[0]^newBlock0[1]^newBlock0[2]^newBlock0[3]; + // arg0 = needWipe, arg1 = workFlags, arg2 = blockNo, datain + MifareCSetBlock(0, 0xFF,0, newBlock0); + MifareCGetBlock(0x1F, 1, 0, testBlock0); + if (memcmp(testBlock0,newBlock0,16)==0) + { + DbpString("Cloned successfull!"); + cardRead[selected] = 0; // Only if the card was cloned successfully should we clear it + } + LEDsoff(); + LED(selected + 1, 0); + // Finished recording + + // If we were previously playing, set playing off + // so next button push begins playing what we recorded + playing = 0; + + } + // Change where to record (or begin playing) + else if (button_pressed && cardRead[selected]) + { + // Next option if we were previously playing + if (playing) + selected = (selected + 1) % OPTS; + playing = !playing; + + LEDsoff(); + LED(selected + 1, 0); + + // Begin transmitting + if (playing) + { + LED(LED_GREEN, 0); + DbpString("Playing"); + while (!BUTTON_HELD(500)) { // Loop simulating tag until the button is held a half-sec + Dbprintf("Simulating ISO14443a tag with uid[0]: %08x, uid[1]: %08x [Bank: %u]", uid_1st[selected],uid_2nd[selected],selected); + SimulateIso14443aTag(1,uid_1st[selected],uid_2nd[selected],NULL); + } + //cardRead[selected] = 1; + Dbprintf("Done playing [Bank: %u]",selected); + + /* We pressed a button so ignore it here with a delay */ + SpinDelay(300); + + // when done, we're done playing, move to next option + selected = (selected + 1) % OPTS; + playing = !playing; + LEDsoff(); + LED(selected + 1, 0); + } + else + while(BUTTON_PRESS()) + WDT_HIT(); + } + } +} +#elif WITH_LF +// samy's sniff and repeat routine +void SamyRun() +{ + StandAloneMode(); + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + int high[OPTS], low[OPTS]; int selected = 0; int playing = 0; int cardRead = 0; @@ -332,7 +536,7 @@ void SamyRun() for (;;) { usb_poll(); - WDT_HIT(); + WDT_HIT(); // Was our button held down or pressed? int button_pressed = BUTTON_HELD(1000); @@ -445,219 +649,7 @@ void SamyRun() } } } -#endif -#endif -#ifdef WITH_ISO14443a -#ifdef WITH_ISO14443a_StandAlone -void StandAloneMode14a() -{ - DbpString("Stand-alone mode! No PC necessary."); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - // 3 possible options? no just 1 for now -#undef OPTS -#define OPTS 2 - // Oooh pretty -- notify user we're in elite samy mode now - LED(LED_RED, 200); - LED(LED_ORANGE, 200); - LED(LED_GREEN, 200); - LED(LED_ORANGE, 200); - LED(LED_RED, 200); - LED(LED_ORANGE, 200); - LED(LED_GREEN, 200); - LED(LED_ORANGE, 200); - LED(LED_RED, 200); - - int selected = 0; - int playing = 0; - int cardRead[OPTS] = {0}; - uint8_t readUID[10] = {0}; - int uid_1st[OPTS]={0}; - int uid_2nd[OPTS]={0}; - - LED(selected + 1, 0); - - for (;;) - { - usb_poll(); - WDT_HIT(); - - // Was our button held down or pressed? - int button_pressed = BUTTON_HELD(1000); - - SpinDelay(300); - - // Button was held for a second, begin recording - if (button_pressed > 0 && cardRead[selected] == 0) - { - LEDsoff(); - LED(selected + 1, 0); - LED(LED_RED2, 0); - - // record - Dbprintf("Enabling iso14443a reader mode for [Bank: %u]...", selected); - - // wait for button to be released - while(BUTTON_PRESS()) - WDT_HIT(); - /* need this delay to prevent catching some weird data */ - SpinDelay(500); - /* Code for reading from 14a tag */ - uint8_t uid[10] ={0}; - uint32_t cuid; - iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - - for ( ; ; ) - { - if (!iso14443a_select_card(uid, NULL, &cuid)) - continue; - else - { - Dbprintf("Read UID:"); Dbhexdump(10,uid,0); - memcpy(readUID,uid,10*sizeof(uint8_t)); - uint8_t *dst = (uint8_t *)&uid_1st[selected]; - // Set UID byte order - for (int i=0; i<4; i++) - dst[i] = uid[3-i]; - dst = (uint8_t *)&uid_2nd[selected]; - for (int i=0; i<4; i++) - dst[i] = uid[7-i]; - break; - } - } - LEDsoff(); - LED(LED_GREEN, 200); - LED(LED_ORANGE, 200); - LED(LED_GREEN, 200); - LED(LED_ORANGE, 200); - - LEDsoff(); - LED(selected + 1, 0); - // Finished recording - - // If we were previously playing, set playing off - // so next button push begins playing what we recorded - playing = 0; - - cardRead[selected] = 1; - - } -/* MF UID clone */ - else if (button_pressed > 0 && cardRead[selected] == 1) - { - LEDsoff(); - LED(selected + 1, 0); - LED(LED_ORANGE, 250); - - - // record - Dbprintf("Preparing to Clone card [Bank: %x]; uid: %08x", selected, uid_1st[selected]); - - // wait for button to be released - while(BUTTON_PRESS()) - { - // Delay cloning until card is in place - WDT_HIT(); - } - Dbprintf("Starting clone. [Bank: %u]", selected); - // need this delay to prevent catching some weird data - SpinDelay(500); - // Begin clone function here: - /* Example from client/mifarehost.c for commanding a block write for "magic Chinese" cards: - UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}}; - memcpy(c.d.asBytes, data, 16); - SendCommand(&c); - - Block read is similar: - UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}}; - We need to imitate that call with blockNo 0 to set a uid. - - The get and set commands are handled in this file: - // Work with "magic Chinese" card - case CMD_MIFARE_CSETBLOCK: - MifareCSetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); - break; - case CMD_MIFARE_CGETBLOCK: - MifareCGetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); - // - break; - - mfCSetUID provides example logic for UID set workflow: - -Read block0 from card in field with MifareCGetBlock() - -Configure new values without replacing reserved bytes - memcpy(block0, uid, 4); // Copy UID bytes from byte array - // Mifare UID BCC - block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 - Bytes 5-7 are reserved SAK and ATQA for mifare classic - -Use mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER) to write it - */ - uint8_t oldBlock0[16] = {0}, newBlock0[16] = {0}, testBlock0[16] = {0}; - // arg0 = Flags == CSETBLOCK_SINGLE_OPER=0x1F, arg1=returnSlot, arg2=blockNo - MifareCGetBlock(0x1F, 1, 0, oldBlock0); - Dbprintf("UID from target tag: %02X%02X%02X%02X", oldBlock0[0],oldBlock0[1],oldBlock0[2],oldBlock0[3]); - memcpy(newBlock0,oldBlock0,16); - // Copy uid_1st for bank (2nd is for longer UIDs not supported if classic) - newBlock0[0] = uid_1st[selected]>>24; - newBlock0[1] = 0xFF & (uid_1st[selected]>>16); - newBlock0[2] = 0xFF & (uid_1st[selected]>>8); - newBlock0[3] = 0xFF & (uid_1st[selected]); - newBlock0[4] = newBlock0[0]^newBlock0[1]^newBlock0[2]^newBlock0[3]; - // arg0 = needWipe, arg1 = workFlags, arg2 = blockNo, datain - MifareCSetBlock(0, 0xFF,0, newBlock0); - MifareCGetBlock(0x1F, 1, 0, testBlock0); - if (memcmp(testBlock0,newBlock0,16)==0) - { - DbpString("Cloned successfull!"); - cardRead[selected] = 0; // Only if the card was cloned successfully should we clear it - } - LEDsoff(); - LED(selected + 1, 0); - // Finished recording - - // If we were previously playing, set playing off - // so next button push begins playing what we recorded - playing = 0; - - } - // Change where to record (or begin playing) - else if (button_pressed && cardRead[selected]) - { - // Next option if we were previously playing - if (playing) - selected = (selected + 1) % OPTS; - playing = !playing; - - LEDsoff(); - LED(selected + 1, 0); - - // Begin transmitting - if (playing) - { - LED(LED_GREEN, 0); - DbpString("Playing"); - while (!BUTTON_HELD(500)) { // Loop simulating tag until the button is held a half-sec - Dbprintf("Simulating ISO14443a tag with uid[0]: %08x, uid[1]: %08x [Bank: %u]", uid_1st[selected],uid_2nd[selected],selected); - SimulateIso14443aTag(1,uid_1st[selected],uid_2nd[selected],NULL); - } - //cardRead[selected] = 1; - Dbprintf("Done playing [Bank: %u]",selected); - - /* We pressed a button so ignore it here with a delay */ - SpinDelay(300); - - // when done, we're done playing, move to next option - selected = (selected + 1) % OPTS; - playing = !playing; - LEDsoff(); - LED(selected + 1, 0); - } - else - while(BUTTON_PRESS()) - WDT_HIT(); - } - } -} -#endif #endif /* OBJECTIVE From 4d68ec02b281add4d6a7f6cbf5406a691f0b5f5d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 21 Jul 2015 14:26:46 -0400 Subject: [PATCH 048/145] iclass refactor/cleanup --- armsrc/iclass.c | 9 - client/cmdhficlass.c | 754 +++++++++++++++++-------------------------- client/cmdhficlass.h | 21 +- 3 files changed, 319 insertions(+), 465 deletions(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index a27fb970..9a70c06b 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1918,7 +1918,6 @@ void iClass_Authentication(uint8_t *MAC) { bool isOK; isOK = sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5); cmd_send(CMD_ACK,isOK,0,0,0,0); - //Dbprintf("isOK %d, Tag response : %02x%02x%02x%02x",isOK,resp[0],resp[1],resp[2],resp[3]); } bool iClass_ReadBlock(uint8_t blockNo, uint8_t keyType, uint8_t *readdata) { uint8_t readcmd[] = {keyType, blockNo}; //0x88, 0x00 @@ -1936,7 +1935,6 @@ void iClass_ReadBlk(uint8_t blockno, uint8_t keyType) { uint8_t readblockdata[8]; bool isOK = false; isOK = iClass_ReadBlock(blockno, keyType, readblockdata); - //Dbprintf("read block [%02x] [%02x%02x%02x%02x%02x%02x%02x%02x]",blockNo,readblockdata[0],readblockdata[1],readblockdata[2],readblockdata[3],readblockdata[4],readblockdata[5],readblockdata[6],readblockdata[7]); cmd_send(CMD_ACK,isOK,0,0,readblockdata,8); } @@ -1964,11 +1962,6 @@ void iClass_Dump(uint8_t blockno, uint8_t numblks, uint8_t keyType) { } } memcpy(dataout+(blkCnt*8),readblockdata,8); - /*Dbprintf("| %02x | %02x%02x%02x%02x%02x%02x%02x%02x |", - blockno+blkCnt, readblockdata[0], readblockdata[1], readblockdata[2], - readblockdata[3], readblockdata[4], readblockdata[5], - readblockdata[6], readblockdata[7]); - */ } //return pointer to dump memory in arg3 cmd_send(CMD_ACK,isOK,blkCnt,BigBuf_max_traceLen(),0,0); @@ -1985,7 +1978,6 @@ bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t keyType, uint8_t *data) { uint8_t resp[10]; bool isOK; isOK = sendCmdGetResponseWithRetries(write,sizeof(write),resp,sizeof(resp),5); - //Dbprintf("reply [%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x]",resp[0],resp[1],resp[2],resp[3],resp[4],resp[5],resp[6],resp[7],resp[8],resp[9]); if (isOK) { isOK = iClass_ReadBlock(blockNo, keyType, readblockdata); //try again @@ -1993,7 +1985,6 @@ bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t keyType, uint8_t *data) { isOK = iClass_ReadBlock(blockNo, keyType, readblockdata); } if (isOK) { - //Dbprintf("read block [%02x] [%02x%02x%02x%02x%02x%02x%02x%02x]",blockNo,readblockdata[0],readblockdata[1],readblockdata[2],readblockdata[3],readblockdata[4],readblockdata[5],readblockdata[6],readblockdata[7]); if (memcmp(write+2,readblockdata,sizeof(readblockdata)) != 0){ isOK=false; } diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index db3de205..605793a5 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -53,8 +53,7 @@ typedef struct iclass_block { uint8_t d[8]; } iclass_block_t; -int xorbits_8(uint8_t val) -{ +int xorbits_8(uint8_t val) { uint8_t res = val ^ (val >> 1); //1st pass res = res ^ (res >> 1); // 2nd pass res = res ^ (res >> 2); // 3rd pass @@ -62,20 +61,18 @@ int xorbits_8(uint8_t val) return res & 1; } -int CmdHFiClassList(const char *Cmd) -{ +int CmdHFiClassList(const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list iclass' instead"); return 0; } -int CmdHFiClassSnoop(const char *Cmd) -{ +int CmdHFiClassSnoop(const char *Cmd) { UsbCommand c = {CMD_SNOOP_ICLASS}; SendCommand(&c); return 0; } -int usage_hf_iclass_sim() -{ + +int usage_hf_iclass_sim(void) { PrintAndLog("Usage: hf iclass sim