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.shiftReg = 0; // shiftreg to hold decoded data bits
Uart.parityBits = 0; // holds 8 parity bits
Uart.startTime = 0;
Uart.endTime = 0;
}
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.parity = parity;
Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits
Uart.startTime = 0;
Uart.endTime = 0;
UartReset();
}
@ -886,7 +886,7 @@ static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int
int EmSend4bit(uint8_t resp);
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);
@ -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)
p_response = &responses[4]; order = 30;
} 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]);
// We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
p_response = NULL;
@ -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)
{
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;
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.
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
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
// only, since we are receiving, not transmitting).
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
// Clear RXRDY
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; (void)b;
// clear receive register, measure time of next transfer
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(;;) {
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)) {
analogCnt++;
analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF_LOW];
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
if (analogCnt >= 32) {
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;
if ((MAX_ADC_HF_VOLTAGE_LOW * AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF_LOW]) >> 10 < MF_MINFIELDV) {
if (GetTickCount() - field_off_time > 50) {
ret = 2; // reader has switched off HF field for more than 50ms. Timeout
break;
}
} 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(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if(MillerDecoding(b, 0)) {
if (MillerDecoding(b, start_time + samples*8)) {
*len = Uart.len;
EmLogTraceReader();
return 0;
}
ret = 0;
break;
}
samples++;
}
FpgaDisableSscDma();
return ret;
}
@ -1489,7 +1506,6 @@ static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen)
}
// clear receiving shift register and holding register
while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
b = AT91C_BASE_SSC->SSC_RHR; (void) b;
while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
b = AT91C_BASE_SSC->SSC_RHR; (void) b;
@ -1522,7 +1538,7 @@ static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen)
int EmSend4bit(uint8_t resp){
Code4bitAnswerAsTag(resp);
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);
return res;
}
@ -1531,19 +1547,12 @@ int EmSend4bit(uint8_t resp){
static int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, uint8_t *par){
CodeIso14443aAsTagPar(resp, respLen, par);
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);
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){
uint8_t par[MAX_PARITY_SIZE];
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 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);
return ret;
}
@ -1897,11 +1906,22 @@ void iso14443a_setup(uint8_t 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
StartCountSspClk();
DemodReset();
UartReset();
LastTimeProxToAirStart = 0;
FpgaSendQueueDelay = 0;
LastProxToAirDuration = 20; // arbitrary small value. Avoid lock in EmGetCmd()
NextTransferTime = 2*DELAY_ARM2AIR_AS_READER;
iso14a_set_timeout(1060); // 10ms default
}

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 EmSendCmd(uint8_t *resp, uint16_t respLen);
extern int EmSendCmdEx(uint8_t *resp, uint16_t respLen);
extern int EmSend4bit(uint8_t resp);
extern int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
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
// 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
#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_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_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_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 ...
@ -335,8 +334,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
uint32_t cardINTREG = 0;
uint8_t cardINTBLOCK = 0;
struct Crypto1State mpcs = {0, 0};
struct Crypto1State *pcs;
pcs = &mpcs;
struct Crypto1State *pcs = &mpcs;
uint32_t numReads = 0; //Counts numer of times reader reads a block
uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE];
uint8_t receivedCmd_dec[MAX_MIFARE_FRAME_SIZE];
@ -344,9 +342,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
uint16_t receivedCmd_len;
uint8_t response[MAX_MIFARE_FRAME_SIZE];
uint8_t response_par[MAX_MIFARE_PARITY_SIZE];
uint8_t rAUTH_NT[] = {0x01, 0x02, 0x03, 0x04};
uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
uint8_t fixed_nonce[] = {0x01, 0x02, 0x03, 0x04};
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) {
nonce = prand();
} else {
nonce = bytes_to_num(rAUTH_NT, 4);
nonce = bytes_to_num(fixed_nonce, 4);
}
// 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()) {
WDT_HIT();
// find reader field
if (cardSTATE == MFEMUL_NOFIELD) {
// wait for reader HF field
int vHf = (MAX_ADC_HF_VOLTAGE_LOW * AvgAdc(ADC_CHAN_HF_LOW)) >> 10;
if (vHf > MF_MINFIELDV) {
LED_D_ON();
@ -409,7 +405,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
FpgaEnableTracing();
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();
LED_D_OFF();
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));
if (!encrypted_data) { // first authentication
crypto1_word(pcs, cuid ^ nonce, 0); // Update crypto state
num_to_bytes(nonce, 4, rAUTH_AT); // Send unencrypted nonce
EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
num_to_bytes(nonce, 4, response); // Send unencrypted nonce
EmSendCmd(response, sizeof(nonce));
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);
} else { // nested authentication
@ -645,8 +641,10 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
}
// command not allowed
if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Received command not allowed, nacking");
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;
}
@ -727,6 +725,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
// test if auth OK
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",
cardAUTHSC, cardAUTHKEY == AUTHKEYA ? 'A' : 'B',
cardRr, prng_successor(nonce, 64));
@ -787,8 +786,8 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
break;
}
cardINTREG = cardINTREG + ans;
}
cardSTATE = MFEMUL_WORK;
}
break;
}
@ -800,9 +799,9 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
cardSTATE = MFEMUL_IDLE;
break;
}
}
cardINTREG = cardINTREG - ans;
cardSTATE = MFEMUL_WORK;
}
break;
}
@ -818,6 +817,7 @@ void MifareSim(uint8_t flags, uint8_t exitAfterNReads, uint8_t cardsize, uint8_t
}
} // end of switch
FpgaDisableTracing();
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];
for (int j = 0; j < data_len && j/16 < 16; j++) {
uint8_t parityBits = parityBytes[j>>3];
if (protocol != ISO_14443B
&& protocol != ISO_15693
@ -948,7 +947,6 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui
} else {
snprintf(line[j/16]+(( j % 16) * 4), 110, " %02x ", frame[j]);
}
}
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) {
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);
for (int j = 0; j < num_lines ; j++) {
if (j == 0) {
PrintAndLog(" %10d | %10d | %s |%-64s | %s| %s",
PrintAndLog(" %10" PRIu32 " | %10" PRIu32 " | %s |%-64s | %s| %s",
(timestamp - first_timestamp),
(EndOfTransmissionTimestamp - first_timestamp),
(isResponse ? "Tag" : "Rdr"),
@ -1222,7 +1227,7 @@ 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(" Start | End | Src | Data (! denotes parity error, ' denotes short bytes) | CRC | Annotation |");
PrintAndLog("------------|------------|-----|-----------------------------------------------------------------|-----|--------------------|");
ClearAuthData();

View file

@ -1445,7 +1445,7 @@ int usage_hf14_mfsim(void) {
int CmdHF14AMfSim(const char *Cmd) {
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 flags = 0;
int uidlen = 0;
@ -1563,7 +1563,6 @@ int CmdHF14AMfSim(const char *Cmd) {
uidlen = strlen(buf)-1;
switch(uidlen) {
case 20: flags |= FLAG_10B_UID_IN_DATA; break; //not complete
case 14: flags |= FLAG_7B_UID_IN_DATA; break;
case 8: flags |= FLAG_4B_UID_IN_DATA; break;
default:
@ -1581,8 +1580,7 @@ int CmdHF14AMfSim(const char *Cmd) {
cardsize == '2' ? "2K" :
cardsize == '4' ? "4K" : "1K",
flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7):
flags & FLAG_10B_UID_IN_DATA ? sprint_hex(uid,10): "N/A",
flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",
exitAfterNReads,
flags,
flags);
@ -1609,6 +1607,7 @@ int CmdHF14AMfSim(const char *Cmd) {
count++;
}
fclose(f);
} else { //not from file
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 == '4' ? "4K" : "1K",
flags & FLAG_4B_UID_IN_DATA ? sprint_hex(uid,4):
flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7):
flags & FLAG_10B_UID_IN_DATA ? sprint_hex(uid,10): "N/A",
flags & FLAG_7B_UID_IN_DATA ? sprint_hex(uid,7): "N/A",
exitAfterNReads,
flags,
flags);

View file

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