fix hf mf sim

* use DMA to receive reader command
* switch earlier from send to listen mode
* move ADC initializer to iso14443_setup
* remove remainders of incomplete Mifare 10Byte UID simulation
* show 'short' bytes (7Bits or 8Bits without parity) in 'hf list mf' and 'hf list 14a'
* whitespace
This commit is contained in:
pwpiwi 2019-04-18 17:22:00 +02:00
commit 8578ea82cc
7 changed files with 618 additions and 597 deletions

View file

@ -278,8 +278,6 @@ static void UartReset()
Uart.parityLen = 0; // number of decoded parity bytes Uart.parityLen = 0; // number of decoded parity bytes
Uart.shiftReg = 0; // shiftreg to hold decoded data bits Uart.shiftReg = 0; // shiftreg to hold decoded data bits
Uart.parityBits = 0; // holds 8 parity bits Uart.parityBits = 0; // holds 8 parity bits
Uart.startTime = 0;
Uart.endTime = 0;
} }
static void UartInit(uint8_t *data, uint8_t *parity) static void UartInit(uint8_t *data, uint8_t *parity)
@ -287,6 +285,8 @@ static void UartInit(uint8_t *data, uint8_t *parity)
Uart.output = data; Uart.output = data;
Uart.parity = parity; Uart.parity = parity;
Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits
Uart.startTime = 0;
Uart.endTime = 0;
UartReset(); UartReset();
} }
@ -627,9 +627,9 @@ void RAMFUNC SnoopIso14443a(uint8_t param) {
bool triggered = !(param & 0x03); bool triggered = !(param & 0x03);
// And now we loop, receiving samples. // And now we loop, receiving samples.
for(uint32_t rsamples = 0; true; ) { for (uint32_t rsamples = 0; true; ) {
if(BUTTON_PRESS()) { if (BUTTON_PRESS()) {
DbpString("cancelled by button"); DbpString("cancelled by button");
break; break;
} }
@ -747,11 +747,11 @@ static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par
ToSend[++ToSendMax] = SEC_D; ToSend[++ToSendMax] = SEC_D;
LastProxToAirDuration = 8 * ToSendMax - 4; LastProxToAirDuration = 8 * ToSendMax - 4;
for(uint16_t i = 0; i < len; i++) { for (uint16_t i = 0; i < len; i++) {
uint8_t b = cmd[i]; uint8_t b = cmd[i];
// Data bits // Data bits
for(uint16_t j = 0; j < 8; j++) { for (uint16_t j = 0; j < 8; j++) {
if(b & 1) { if(b & 1) {
ToSend[++ToSendMax] = SEC_D; ToSend[++ToSendMax] = SEC_D;
} else { } else {
@ -798,7 +798,7 @@ static void Code4bitAnswerAsTag(uint8_t cmd)
ToSend[++ToSendMax] = SEC_D; ToSend[++ToSendMax] = SEC_D;
uint8_t b = cmd; uint8_t b = cmd;
for(i = 0; i < 4; i++) { for (i = 0; i < 4; i++) {
if(b & 1) { if(b & 1) {
ToSend[++ToSendMax] = SEC_D; ToSend[++ToSendMax] = SEC_D;
LastProxToAirDuration = 8 * ToSendMax - 4; LastProxToAirDuration = 8 * ToSendMax - 4;
@ -867,7 +867,7 @@ static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int
// clear RXRDY: // clear RXRDY:
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
for(;;) { for (;;) {
WDT_HIT(); WDT_HIT();
if(BUTTON_PRESS()) return false; if(BUTTON_PRESS()) return false;
@ -886,7 +886,7 @@ static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int
int EmSend4bit(uint8_t resp); int EmSend4bit(uint8_t resp);
static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par); static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
int EmSendCmdEx(uint8_t *resp, uint16_t respLen); int EmSendCmd(uint8_t *resp, uint16_t respLen);
int EmSendPrecompiledCmd(tag_response_info_t *response_info); int EmSendPrecompiledCmd(tag_response_info_t *response_info);
@ -1097,7 +1097,7 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data)
tag_response_info_t* p_response; tag_response_info_t* p_response;
LED_A_ON(); LED_A_ON();
for(;;) { for (;;) {
// Clean receive command buffer // Clean receive command buffer
if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) { if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
DbpString("Button press"); DbpString("Button press");
@ -1121,7 +1121,7 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data)
} else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2) } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2)
p_response = &responses[4]; order = 30; p_response = &responses[4]; order = 30;
} else if(receivedCmd[0] == 0x30) { // Received a (plain) READ } else if(receivedCmd[0] == 0x30) { // Received a (plain) READ
EmSendCmdEx(data+(4*receivedCmd[1]),16); EmSendCmd(data+(4*receivedCmd[1]),16);
// Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]); // Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
// We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
p_response = NULL; p_response = NULL;
@ -1276,11 +1276,11 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks) PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
} }
if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing"); if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
while(GetCountSspClk() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks) while (GetCountSspClk() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
LastTimeProxToAirStart = *timing; LastTimeProxToAirStart = *timing;
} else { } else {
ThisTransferTime = ((MAX(NextTransferTime, GetCountSspClk()) & 0xfffffff8) + 8); ThisTransferTime = ((MAX(NextTransferTime, GetCountSspClk()) & 0xfffffff8) + 8);
while(GetCountSspClk() < ThisTransferTime); while (GetCountSspClk() < ThisTransferTime);
LastTimeProxToAirStart = ThisTransferTime; LastTimeProxToAirStart = ThisTransferTime;
} }
@ -1288,7 +1288,7 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
AT91C_BASE_SSC->SSC_THR = SEC_Y; AT91C_BASE_SSC->SSC_THR = SEC_Y;
uint16_t c = 0; uint16_t c = 0;
for(;;) { for (;;) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
AT91C_BASE_SSC->SSC_THR = cmd[c]; AT91C_BASE_SSC->SSC_THR = cmd[c];
c++; c++;
@ -1392,69 +1392,86 @@ static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, cons
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity)
{ {
uint32_t field_off_time = -1;
uint32_t samples = 0;
int ret = 0;
uint8_t b = 0;;
uint8_t dmaBuf[DMA_BUFFER_SIZE];
uint8_t *upTo = dmaBuf;
*len = 0; *len = 0;
uint32_t timer = 0, vtime = 0;
int analogCnt = 0;
int analogAVG = 0;
// Set ADC to read field strength
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
AT91C_BASE_ADC->ADC_MR =
ADC_MODE_PRESCALE(63) |
ADC_MODE_STARTUP_TIME(1) |
ADC_MODE_SAMPLE_HOLD_TIME(15);
AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF_LOW);
// start ADC
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
// Run a 'software UART' on the stream of incoming samples. // Run a 'software UART' on the stream of incoming samples.
UartInit(received, parity); UartInit(received, parity);
// start ADC
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
// Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN
while (GetCountSspClk() < LastTimeProxToAirStart + LastProxToAirDuration + (FpgaSendQueueDelay>>3)) /* wait */ ; while (GetCountSspClk() < LastTimeProxToAirStart + LastProxToAirDuration + (FpgaSendQueueDelay>>3) - 8 - 3) /* wait */ ;
// Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
// only, since we are receiving, not transmitting). // only, since we are receiving, not transmitting).
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
// Clear RXRDY // clear receive register, measure time of next transfer
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; (void)b; uint32_t temp = AT91C_BASE_SSC->SSC_RHR; (void) temp;
while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) ;
uint32_t start_time = GetCountSspClk() & 0xfffffff8;
// Setup and start DMA.
FpgaSetupSscDma(dmaBuf, DMA_BUFFER_SIZE);
for(;;) { for(;;) {
WDT_HIT(); uint16_t behindBy = ((uint8_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE-1);
if (BUTTON_PRESS()) return 1; if (behindBy == 0) continue;
// test if the field exists b = *upTo++;
if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
upTo = dmaBuf; // start reading the circular buffer from the beginning
if(behindBy > (9*DMA_BUFFER_SIZE/10)) {
Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy);
ret = 1;
break;
}
}
if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; // DMA Next Counter registers
}
if (BUTTON_PRESS()) {
ret = 1;
break;
}
// check reader's HF field
if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF_LOW)) { if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF_LOW)) {
analogCnt++; if ((MAX_ADC_HF_VOLTAGE_LOW * AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF_LOW]) >> 10 < MF_MINFIELDV) {
analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF_LOW]; if (GetTickCount() - field_off_time > 50) {
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START; ret = 2; // reader has switched off HF field for more than 50ms. Timeout
if (analogCnt >= 32) { break;
if ((MAX_ADC_HF_VOLTAGE_LOW * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
vtime = GetTickCount();
if (!timer) timer = vtime;
// 50ms no field --> card to idle state
if (vtime - timer > 50) return 2;
} else
if (timer) timer = 0;
analogCnt = 0;
analogAVG = 0;
} }
} else {
field_off_time = GetTickCount(); // HF field is still there. Reset timer
}
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START; // restart ADC
} }
// receive and test the miller decoding if (MillerDecoding(b, start_time + samples*8)) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if(MillerDecoding(b, 0)) {
*len = Uart.len; *len = Uart.len;
EmLogTraceReader(); EmLogTraceReader();
return 0; ret = 0;
} break;
} }
samples++;
} }
FpgaDisableSscDma();
return ret;
} }
@ -1481,7 +1498,7 @@ static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen)
correctionNeeded = Uart.parity[(Uart.len-1)/8] & (0x80 >> ((Uart.len-1) & 7)); correctionNeeded = Uart.parity[(Uart.len-1)/8] & (0x80 >> ((Uart.len-1) & 7));
} }
if(correctionNeeded) { if (correctionNeeded) {
// 1236, so correction bit needed // 1236, so correction bit needed
i = 0; i = 0;
} else { } else {
@ -1489,21 +1506,20 @@ static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen)
} }
// clear receiving shift register and holding register // clear receiving shift register and holding register
while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
b = AT91C_BASE_SSC->SSC_RHR; (void) b; b = AT91C_BASE_SSC->SSC_RHR; (void) b;
while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)); while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
b = AT91C_BASE_SSC->SSC_RHR; (void) b; b = AT91C_BASE_SSC->SSC_RHR; (void) b;
// wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line) // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
for (uint16_t j = 0; j < 5; j++) { // allow timeout - better late than never for (uint16_t j = 0; j < 5; j++) { // allow timeout - better late than never
while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)); while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
if (AT91C_BASE_SSC->SSC_RHR) break; if (AT91C_BASE_SSC->SSC_RHR) break;
} }
LastTimeProxToAirStart = (GetCountSspClk() & 0xfffffff8) + (correctionNeeded?8:0); LastTimeProxToAirStart = (GetCountSspClk() & 0xfffffff8) + (correctionNeeded?8:0);
// send cycle // send cycle
for(; i < respLen; ) { for (; i < respLen; ) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
AT91C_BASE_SSC->SSC_THR = resp[i++]; AT91C_BASE_SSC->SSC_THR = resp[i++];
FpgaSendQueueDelay = (uint8_t)AT91C_BASE_SSC->SSC_RHR; FpgaSendQueueDelay = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
@ -1522,7 +1538,7 @@ static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen)
int EmSend4bit(uint8_t resp){ int EmSend4bit(uint8_t resp){
Code4bitAnswerAsTag(resp); Code4bitAnswerAsTag(resp);
int res = EmSendCmd14443aRaw(ToSend, ToSendMax); int res = EmSendCmd14443aRaw(ToSend, ToSendMax);
// do the tracing for the previous reader request and this tag answer: // Log this tag answer and fix timing of previous reader command:
EmLogTraceTag(&resp, 1, NULL, LastProxToAirDuration); EmLogTraceTag(&resp, 1, NULL, LastProxToAirDuration);
return res; return res;
} }
@ -1531,19 +1547,12 @@ int EmSend4bit(uint8_t resp){
static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par){ static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par){
CodeIso14443aAsTagPar(resp, respLen, par); CodeIso14443aAsTagPar(resp, respLen, par);
int res = EmSendCmd14443aRaw(ToSend, ToSendMax); int res = EmSendCmd14443aRaw(ToSend, ToSendMax);
// do the tracing for the previous reader request and this tag answer: // Log this tag answer and fix timing of previous reader command:
EmLogTraceTag(resp, respLen, par, LastProxToAirDuration); EmLogTraceTag(resp, respLen, par, LastProxToAirDuration);
return res; return res;
} }
int EmSendCmdEx(uint8_t *resp, uint16_t respLen){
uint8_t par[MAX_PARITY_SIZE];
GetParity(resp, respLen, par);
return EmSendCmdExPar(resp, respLen, par);
}
int EmSendCmd(uint8_t *resp, uint16_t respLen){ int EmSendCmd(uint8_t *resp, uint16_t respLen){
uint8_t par[MAX_PARITY_SIZE]; uint8_t par[MAX_PARITY_SIZE];
GetParity(resp, respLen, par); GetParity(resp, respLen, par);
@ -1558,7 +1567,7 @@ int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par){
int EmSendPrecompiledCmd(tag_response_info_t *response_info) { int EmSendPrecompiledCmd(tag_response_info_t *response_info) {
int ret = EmSendCmd14443aRaw(response_info->modulation, response_info->modulation_n); int ret = EmSendCmd14443aRaw(response_info->modulation, response_info->modulation_n);
// do the tracing for the previous reader request and this tag answer: // Log this tag answer and fix timing of previous reader command:
EmLogTraceTag(response_info->response, response_info->response_n, &(response_info->par), response_info->ProxToAirDuration); EmLogTraceTag(response_info->response, response_info->response_n, &(response_info->par), response_info->ProxToAirDuration);
return ret; return ret;
} }
@ -1586,7 +1595,7 @@ static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receive
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
c = 0; c = 0;
for(;;) { for (;;) {
WDT_HIT(); WDT_HIT();
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
@ -1757,7 +1766,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
// OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in // 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 // which case we need to make a cascade 2 request and select - this is a long UID
// While the UID is not complete, the 3rd bit (from the right) is set in the SAK. // While the UID is not complete, the 3rd bit (from the right) is set in the SAK.
for(; sak & 0x04; cascade_level++) { for (; sak & 0x04; cascade_level++) {
// SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97) // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2; sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
@ -1897,11 +1906,22 @@ void iso14443a_setup(uint8_t fpga_minor_mode) {
} }
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | fpga_minor_mode); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | fpga_minor_mode);
// Set ADC to read field strength
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
AT91C_BASE_ADC->ADC_MR =
ADC_MODE_PRESCALE(63) |
ADC_MODE_STARTUP_TIME(1) |
ADC_MODE_SAMPLE_HOLD_TIME(15);
AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF_LOW);
// Start the timer // Start the timer
StartCountSspClk(); StartCountSspClk();
DemodReset(); DemodReset();
UartReset(); UartReset();
LastTimeProxToAirStart = 0;
FpgaSendQueueDelay = 0;
LastProxToAirDuration = 20; // arbitrary small value. Avoid lock in EmGetCmd()
NextTransferTime = 2*DELAY_ARM2AIR_AS_READER; NextTransferTime = 2*DELAY_ARM2AIR_AS_READER;
iso14a_set_timeout(1060); // 10ms default iso14a_set_timeout(1060); // 10ms default
} }
@ -1957,9 +1977,9 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u
if (!len) { if (!len) {
return 0; //DATA LINK ERROR return 0; //DATA LINK ERROR
} else{ } else {
// S-Block WTX // S-Block WTX
while(len && ((data_bytes[0] & 0xF2) == 0xF2)) { while (len && ((data_bytes[0] & 0xF2) == 0xF2)) {
uint32_t save_iso14a_timeout = iso14a_get_timeout(); uint32_t save_iso14a_timeout = iso14a_get_timeout();
// temporarily increase timeout // temporarily increase timeout
iso14a_set_timeout(MAX((data_bytes[1] & 0x3f) * save_iso14a_timeout, MAX_ISO14A_TIMEOUT)); iso14a_set_timeout(MAX((data_bytes[1] & 0x3f) * save_iso14a_timeout, MAX_ISO14A_TIMEOUT));
@ -2225,7 +2245,7 @@ void ReaderMifare(bool first_try)
uint32_t select_time; uint32_t select_time;
uint32_t halt_time; uint32_t halt_time;
for(uint16_t i = 0; true; i++) { for (uint16_t i = 0; true; i++) {
LED_C_ON(); LED_C_ON();
WDT_HIT(); WDT_HIT();
@ -2414,7 +2434,7 @@ void ReaderMifare(bool first_try)
if (isOK == -4) { if (isOK == -4) {
if (MF_DBGLEVEL >= 3) { if (MF_DBGLEVEL >= 3) {
for (uint16_t i = 0; i <= MAX_STRATEGY; i++) { for (uint16_t i = 0; i <= MAX_STRATEGY; i++) {
for(uint16_t j = 0; j < NUM_DEBUG_INFOS; j++) { for (uint16_t j = 0; j < NUM_DEBUG_INFOS; j++) {
Dbprintf("collected debug info[%d][%d] = %d", i, j, debug_info[i][j]); Dbprintf("collected debug info[%d][%d] = %d", i, j, debug_info[i][j]);
} }
} }
@ -2492,7 +2512,7 @@ void RAMFUNC SniffMifare(uint8_t param) {
MfSniffInit(); MfSniffInit();
// And now we loop, receiving samples. // And now we loop, receiving samples.
for(uint32_t sniffCounter = 0; true; ) { for (uint32_t sniffCounter = 0; true; ) {
if(BUTTON_PRESS()) { if(BUTTON_PRESS()) {
DbpString("Canceled by button."); DbpString("Canceled by button.");

View file

@ -41,7 +41,6 @@ extern void ReaderMifare(bool first_try);
extern int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity); extern int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity);
extern int EmSendCmd(uint8_t *resp, uint16_t respLen); extern int EmSendCmd(uint8_t *resp, uint16_t respLen);
extern int EmSendCmdEx(uint8_t *resp, uint16_t respLen);
extern int EmSend4bit(uint8_t resp); extern int EmSend4bit(uint8_t resp);
extern int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par); extern int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
extern int EmSendPrecompiledCmd(tag_response_info_t *response_info); extern int EmSendPrecompiledCmd(tag_response_info_t *response_info);

View file

@ -277,7 +277,7 @@ static void MifareSimInit(uint8_t flags, uint8_t *datain, tag_response_info_t **
}; };
// Prepare ("precompile") the responses of the anticollision phase. There will be not enough time to do this at the moment the reader sends its REQA or SELECT // Prepare ("precompile") the responses of the anticollision phase. There will be not enough time to do this at the moment the reader sends its REQA or SELECT
// There are 7 predefined responses with a total of 18 bytes data to transmit. Coded responses need one byte per bit to transfer (data, parity, start, stop, correction) // There are 5 predefined responses with a total of 18 bytes data to transmit. Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
// 18 * 8 data bits, 18 * 1 parity bits, 5 start bits, 5 stop bits, 5 correction bits -> need 177 bytes buffer // 18 * 8 data bits, 18 * 1 parity bits, 5 start bits, 5 stop bits, 5 correction bits -> need 177 bytes buffer
#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 177 // number of bytes required for precompiled responses #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 177 // number of bytes required for precompiled responses
@ -313,7 +313,6 @@ static bool HasValidCRC(uint8_t *receivedCmd, uint16_t receivedCmd_len) {
* FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
* FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that * FLAG_4B_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
* FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that * FLAG_7B_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
* FLAG_10B_UID_IN_DATA - use 10-byte UID in the data-section not finished
* FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
* FLAG_RANDOM_NONCE - means we should generate some pseudo-random nonce data (only allows moebius attack) * FLAG_RANDOM_NONCE - means we should generate some pseudo-random nonce data (only allows moebius attack)
*@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ... *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is infinite ...
@ -335,18 +334,15 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
uint32_t cardINTREG = 0; uint32_t cardINTREG = 0;
uint8_t cardINTBLOCK = 0; uint8_t cardINTBLOCK = 0;
struct Crypto1State mpcs = {0, 0}; struct Crypto1State mpcs = {0, 0};
struct Crypto1State *pcs; struct Crypto1State *pcs = &mpcs;
pcs = &mpcs; uint32_t numReads = 0; //Counts numer of times reader reads a block
uint32_t numReads = 0;//Counts numer of times reader reads a block
uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE];
uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE];
uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE]; uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE];
uint16_t receivedCmd_len; uint16_t receivedCmd_len;
uint8_t response[MAX_MIFARE_FRAME_SIZE]; uint8_t response[MAX_MIFARE_FRAME_SIZE];
uint8_t response_par[MAX_MIFARE_PARITY_SIZE]; uint8_t response_par[MAX_MIFARE_PARITY_SIZE];
uint8_t fixed_nonce[] = {0x01, 0x02, 0x03, 0x04};
uint8_t rAUTH_NT[] = {0x01, 0x02, 0x03, 0x04};
uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
int num_blocks = ParamCardSizeBlocks(cardsize); int num_blocks = ParamCardSizeBlocks(cardsize);
@ -371,7 +367,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
if (flags & FLAG_RANDOM_NONCE) { if (flags & FLAG_RANDOM_NONCE) {
nonce = prand(); nonce = prand();
} else { } else {
nonce = bytes_to_num(rAUTH_NT, 4); nonce = bytes_to_num(fixed_nonce, 4);
} }
// free eventually allocated BigBuf memory but keep Emulator Memory // free eventually allocated BigBuf memory but keep Emulator Memory
@ -394,8 +390,8 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
while (!button_pushed && !finished && !usb_poll_validate_length()) { while (!button_pushed && !finished && !usb_poll_validate_length()) {
WDT_HIT(); WDT_HIT();
// find reader field
if (cardSTATE == MFEMUL_NOFIELD) { if (cardSTATE == MFEMUL_NOFIELD) {
// wait for reader HF field
int vHf = (MAX_ADC_HF_VOLTAGE_LOW * AvgAdc(ADC_CHAN_HF_LOW)) >> 10; int vHf = (MAX_ADC_HF_VOLTAGE_LOW * AvgAdc(ADC_CHAN_HF_LOW)) >> 10;
if (vHf > MF_MINFIELDV) { if (vHf > MF_MINFIELDV) {
LED_D_ON(); LED_D_ON();
@ -409,7 +405,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
FpgaEnableTracing(); FpgaEnableTracing();
int res = EmGetCmd(receivedCmd, &receivedCmd_len, receivedCmd_par); int res = EmGetCmd(receivedCmd, &receivedCmd_len, receivedCmd_par);
if (res == 2) { //Field is off! if (res == 2) { // Reader has dropped the HF field. Power off.
FpgaDisableTracing(); FpgaDisableTracing();
LED_D_OFF(); LED_D_OFF();
cardSTATE = MFEMUL_NOFIELD; cardSTATE = MFEMUL_NOFIELD;
@ -522,8 +518,8 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY)); crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
if (!encrypted_data) { // first authentication if (!encrypted_data) { // first authentication
crypto1_word(pcs, cuid ^ nonce, 0); // Update crypto state crypto1_word(pcs, cuid ^ nonce, 0); // Update crypto state
num_to_bytes(nonce, 4, rAUTH_AT); // Send unencrypted nonce num_to_bytes(nonce, 4, response); // Send unencrypted nonce
EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT)); EmSendCmd(response, sizeof(nonce));
FpgaDisableTracing(); FpgaDisableTracing();
if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader authenticating for block %d (0x%02x) with key %d", receivedCmd_dec[1], receivedCmd_dec[1], cardAUTHKEY); if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Reader authenticating for block %d (0x%02x) with key %d", receivedCmd_dec[1], receivedCmd_dec[1], cardAUTHKEY);
} else { // nested authentication } else { // nested authentication
@ -645,8 +641,10 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
} }
// command not allowed // command not allowed
if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Received command not allowed, nacking");
EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
FpgaDisableTracing();
if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Received command not allowed, nacking");
cardSTATE = MFEMUL_IDLE;
break; break;
} }
@ -727,6 +725,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
// test if auth OK // test if auth OK
if (cardRr != prng_successor(nonce, 64)){ if (cardRr != prng_successor(nonce, 64)){
FpgaDisableTracing();
if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("AUTH FAILED for sector %d with key %c. cardRr=%08x, succ=%08x", if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("AUTH FAILED for sector %d with key %c. cardRr=%08x, succ=%08x",
cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B', cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B',
cardRr, prng_successor(nonce, 64)); cardRr, prng_successor(nonce, 64));
@ -787,8 +786,8 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
break; break;
} }
cardINTREG = cardINTREG + ans; cardINTREG = cardINTREG + ans;
}
cardSTATE = MFEMUL_WORK; cardSTATE = MFEMUL_WORK;
}
break; break;
} }
@ -800,9 +799,9 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
cardSTATE = MFEMUL_IDLE; cardSTATE = MFEMUL_IDLE;
break; break;
} }
}
cardINTREG = cardINTREG - ans; cardINTREG = cardINTREG - ans;
cardSTATE = MFEMUL_WORK; cardSTATE = MFEMUL_WORK;
}
break; break;
} }
@ -818,6 +817,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
} }
} // end of switch } // end of switch
FpgaDisableTracing(); FpgaDisableTracing();
button_pushed = BUTTON_PRESS(); button_pushed = BUTTON_PRESS();

View file

@ -937,7 +937,6 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
char line[16][110]; char line[16][110];
for (int j = 0; j < data_len && j/16 < 16; j++) { for (int j = 0; j < data_len && j/16 < 16; j++) {
uint8_t parityBits = parityBytes[j>>3]; uint8_t parityBits = parityBytes[j>>3];
if (protocol != ISO_14443B if (protocol != ISO_14443B
&& protocol != ISO_15693 && protocol != ISO_15693
@ -948,7 +947,6 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
} else { } else {
snprintf(line[j/16]+(( j % 16) * 4), 110, " %02x ", frame[j]); snprintf(line[j/16]+(( j % 16) * 4), 110, " %02x ", frame[j]);
} }
} }
if (markCRCBytes) { if (markCRCBytes) {
@ -961,6 +959,13 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
} }
} }
// mark short bytes (less than 8 Bit + Parity)
if (protocol == ISO_14443A || protocol == PROTO_MIFARE) {
if (duration < 128 * (9 * data_len)) {
line[(data_len-1)/16][((data_len-1)%16) * 4 + 3] = '\'';
}
}
if (data_len == 0) { if (data_len == 0) {
sprintf(line[0]," <empty trace - possible error>"); sprintf(line[0]," <empty trace - possible error>");
} }
@ -990,7 +995,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
int num_lines = MIN((data_len - 1)/16 + 1, 16); int num_lines = MIN((data_len - 1)/16 + 1, 16);
for (int j = 0; j < num_lines ; j++) { for (int j = 0; j < num_lines ; j++) {
if (j == 0) { if (j == 0) {
PrintAndLog(" %10d | %10d | %s |%-64s | %s| %s", PrintAndLog(" %10" PRIu32 " | %10" PRIu32 " | %s |%-64s | %s| %s",
(timestamp - first_timestamp), (timestamp - first_timestamp),
(EndOfTransmissionTimestamp - first_timestamp), (EndOfTransmissionTimestamp - first_timestamp),
(isResponse ? "Tag" : "Rdr"), (isResponse ? "Tag" : "Rdr"),
@ -1222,7 +1227,7 @@ int CmdHFList(const char *Cmd)
PrintAndLog("iso14443a - All times are in carrier periods (1/13.56Mhz)"); PrintAndLog("iso14443a - All times are in carrier periods (1/13.56Mhz)");
PrintAndLog("iClass - Timings are not as accurate"); PrintAndLog("iClass - Timings are not as accurate");
PrintAndLog(""); PrintAndLog("");
PrintAndLog(" Start | End | Src | Data (! denotes parity error) | CRC | Annotation |"); PrintAndLog(" Start | End | Src | Data (! denotes parity error, ' denotes short bytes) | CRC | Annotation |");
PrintAndLog("------------|------------|-----|-----------------------------------------------------------------|-----|--------------------|"); PrintAndLog("------------|------------|-----|-----------------------------------------------------------------|-----|--------------------|");
ClearAuthData(); ClearAuthData();

View file

@ -1445,7 +1445,7 @@ int usage_hf14_mfsim(void) {
int CmdHF14AMfSim(const char *Cmd) { int CmdHF14AMfSim(const char *Cmd) {
UsbCommand resp; UsbCommand resp;
uint8_t uid[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t uid[7] = {0};
uint8_t exitAfterNReads = 0; uint8_t exitAfterNReads = 0;
uint8_t flags = 0; uint8_t flags = 0;
int uidlen = 0; int uidlen = 0;
@ -1563,7 +1563,6 @@ int CmdHF14AMfSim(const char *Cmd) {
uidlen = strlen(buf)-1; uidlen = strlen(buf)-1;
switch(uidlen) { switch(uidlen) {
case 20: flags |= FLAG_10B_UID_IN_DATA; break; //not complete
case 14: flags |= FLAG_7B_UID_IN_DATA; break; case 14: flags |= FLAG_7B_UID_IN_DATA; break;
case 8: flags |= FLAG_4B_UID_IN_DATA; break; case 8: flags |= FLAG_4B_UID_IN_DATA; break;
default: default:
@ -1581,8 +1580,7 @@ int CmdHF14AMfSim(const char *Cmd) {
cardsize == '2' ? "2K" : cardsize == '2' ? "2K" :
cardsize == '4' ? "4K" : "1K", cardsize == '4' ? "4K" : "1K",
flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4): flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",
flags & FLAG_10B_UID_IN_DATA ? sprint_hex(uid,10): "N/A",
exitAfterNReads, exitAfterNReads,
flags, flags,
flags); flags);
@ -1592,7 +1590,7 @@ int CmdHF14AMfSim(const char *Cmd) {
clearCommandBuffer(); clearCommandBuffer();
SendCommand(&c); SendCommand(&c);
while(! WaitForResponseTimeout(CMD_ACK,&resp,1500)) { while (! WaitForResponseTimeout(CMD_ACK,&resp,1500)) {
//We're waiting only 1.5 s at a time, otherwise we get the //We're waiting only 1.5 s at a time, otherwise we get the
// annoying message about "Waiting for a response... " // annoying message about "Waiting for a response... "
} }
@ -1609,6 +1607,7 @@ int CmdHF14AMfSim(const char *Cmd) {
count++; count++;
} }
fclose(f); fclose(f);
} else { //not from file } else { //not from file
PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) ", PrintAndLog("mf sim cardsize: %s, uid: %s, numreads:%d, flags:%d (0x%02x) ",
@ -1616,8 +1615,7 @@ int CmdHF14AMfSim(const char *Cmd) {
cardsize == '2' ? "2K" : cardsize == '2' ? "2K" :
cardsize == '4' ? "4K" : "1K", cardsize == '4' ? "4K" : "1K",
flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4): flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",
flags & FLAG_10B_UID_IN_DATA ? sprint_hex(uid,10): "N/A",
exitAfterNReads, exitAfterNReads,
flags, flags,
flags); flags);

View file

@ -226,12 +226,11 @@ typedef struct{
//Mifare simulation flags //Mifare simulation flags
#define FLAG_INTERACTIVE 0x01 #define FLAG_INTERACTIVE (1<<0)
#define FLAG_4B_UID_IN_DATA 0x02 #define FLAG_4B_UID_IN_DATA (1<<1)
#define FLAG_7B_UID_IN_DATA 0x04 #define FLAG_7B_UID_IN_DATA (1<<2)
#define FLAG_10B_UID_IN_DATA 0x08 #define FLAG_NR_AR_ATTACK (1<<4)
#define FLAG_NR_AR_ATTACK 0x10 #define FLAG_RANDOM_NONCE (1<<5)
#define FLAG_RANDOM_NONCE 0x20
//Iclass reader flags //Iclass reader flags