This commit is contained in:
iceman 2016-01-16 21:50:55 +01:00
commit 6c38d4c96f
18 changed files with 386 additions and 397 deletions

View file

@ -27,7 +27,7 @@ static uint16_t BigBuf_hi = BIGBUF_SIZE;
static uint8_t *emulator_memory = NULL; static uint8_t *emulator_memory = NULL;
// trace related variables // trace related variables
static uint16_t traceLen = 0; static uint16_t traceLen;
int tracing = 1; //Last global one.. todo static? int tracing = 1; //Last global one.. todo static?
// get the address of BigBuf // get the address of BigBuf

View file

@ -1152,7 +1152,7 @@ int main()
if( AesCtxIni(&ctx, iv, key, KEY128, CBC) < 0) if( AesCtxIni(&ctx, iv, key, KEY128, CBC) < 0)
printf("init error\n"); printf("init error\n");
if (AesEncrypt(&ctx, databuf, databuf, sizeof databuf) < 0) if (AesEncrypt(&ctx, databuf, databuf, sizeof(databuf) ) < 0)
printf("error in encryption\n"); printf("error in encryption\n");
// initialize context and decrypt cipher at other end // initialize context and decrypt cipher at other end
@ -1160,7 +1160,7 @@ int main()
if( AesCtxIni(&ctx, iv, key, KEY128, CBC) < 0) if( AesCtxIni(&ctx, iv, key, KEY128, CBC) < 0)
printf("init error\n"); printf("init error\n");
if (AesDecrypt(&ctx, databuf, databuf, sizeof databuf) < 0) if (AesDecrypt(&ctx, databuf, databuf, sizeof(databuf) ) < 0)
printf("error in decryption\n"); printf("error in decryption\n");
printf("%s\n", databuf); printf("%s\n", databuf);

View file

@ -57,19 +57,17 @@ void ToSendReset(void)
ToSendBit = 8; ToSendBit = 8;
} }
void ToSendStuffBit(int b) void ToSendStuffBit(int b) {
{
if(ToSendBit >= 8) { if(ToSendBit >= 8) {
ToSendMax++; ++ToSendMax;
ToSend[ToSendMax] = 0; ToSend[ToSendMax] = 0;
ToSendBit = 0; ToSendBit = 0;
} }
if(b) { if(b)
ToSend[ToSendMax] |= (1 << (7 - ToSendBit)); ToSend[ToSendMax] |= (1 << (7 - ToSendBit));
}
ToSendBit++; ++ToSendBit;
if(ToSendMax >= sizeof(ToSend)) { if(ToSendMax >= sizeof(ToSend)) {
ToSendBit = 0; ToSendBit = 0;
@ -81,22 +79,20 @@ void ToSendStuffBit(int b)
// Debug print functions, to go out over USB, to the usual PC-side client. // Debug print functions, to go out over USB, to the usual PC-side client.
//============================================================================= //=============================================================================
void DbpString(char *str) void DbpString(char *str) {
{
byte_t len = strlen(str); byte_t len = strlen(str);
cmd_send(CMD_DEBUG_PRINT_STRING,len,0,0,(byte_t*)str,len); cmd_send(CMD_DEBUG_PRINT_STRING,len,0,0,(byte_t*)str,len);
} }
#if 0 #if 0
void DbpIntegers(int x1, int x2, int x3) void DbpIntegers(int x1, int x2, int x3) {
{
cmd_send(CMD_DEBUG_PRINT_INTEGERS,x1,x2,x3,0,0); cmd_send(CMD_DEBUG_PRINT_INTEGERS,x1,x2,x3,0,0);
} }
#endif #endif
void Dbprintf(const char *fmt, ...) { void Dbprintf(const char *fmt, ...) {
// should probably limit size here; oh well, let's just use a big buffer // should probably limit size here; oh well, let's just use a big buffer
char output_string[128]; char output_string[128] = {0x00};
va_list ap; va_list ap;
va_start(ap, fmt); va_start(ap, fmt);
@ -108,28 +104,27 @@ void Dbprintf(const char *fmt, ...) {
// prints HEX & ASCII // prints HEX & ASCII
void Dbhexdump(int len, uint8_t *d, bool bAsci) { void Dbhexdump(int len, uint8_t *d, bool bAsci) {
int l=0,i; int l=0, i;
char ascii[9]; char ascii[9];
while (len>0) { while (len>0) {
if (len>8) l=8;
else l=len; l = (len>8) ? 8 : len;
memcpy(ascii,d,l); memcpy(ascii,d,l);
ascii[l]=0; ascii[l]=0;
// filter safe ascii // filter safe ascii
for (i=0;i<l;i++) for (i=0; i<l; ++i)
if (ascii[i]<32 || ascii[i]>126) ascii[i]='.'; if (ascii[i]<32 || ascii[i]>126) ascii[i]='.';
if (bAsci) { if (bAsci)
Dbprintf("%-8s %*D",ascii,l,d," "); Dbprintf("%-8s %*D",ascii,l,d," ");
} else { else
Dbprintf("%*D",l,d," "); Dbprintf("%*D",l,d," ");
}
len-=8; len -= 8;
d+=8; d += 8;
} }
} }
@ -163,10 +158,9 @@ static int ReadAdc(int ch)
AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START; AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
while(!(AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ch))) while (!(AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ch))) ;
;
d = AT91C_BASE_ADC->ADC_CDR[ch];
d = AT91C_BASE_ADC->ADC_CDR[ch];
return d; return d;
} }
@ -175,15 +169,13 @@ int AvgAdc(int ch) // was static - merlok
int i; int i;
int a = 0; int a = 0;
for(i = 0; i < 32; i++) { for(i = 0; i < 32; ++i)
a += ReadAdc(ch); a += ReadAdc(ch);
}
return (a + 15) >> 5; return (a + 15) >> 5;
} }
void MeasureAntennaTuning(void) void MeasureAntennaTuning(void) {
{
uint8_t LF_Results[256]; uint8_t LF_Results[256];
int i, adcval = 0, peak = 0, peakv = 0, peakf = 0; //ptr = 0 int i, adcval = 0, peak = 0, peakv = 0, peakf = 0; //ptr = 0
int vLf125 = 0, vLf134 = 0, vHf = 0; // in mV int vLf125 = 0, vLf134 = 0, vHf = 0; // in mV
@ -201,8 +193,9 @@ void MeasureAntennaTuning(void)
FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
for (i=255; i>=19; i--) { for (i=255; i>=19; i--) {
WDT_HIT(); WDT_HIT();
FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i);
SpinDelay(20); SpinDelay(20);
adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10); adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10);
@ -229,13 +222,11 @@ void MeasureAntennaTuning(void)
cmd_send(CMD_MEASURED_ANTENNA_TUNING, vLf125 | (vLf134<<16), vHf, peakf | (peakv<<16), LF_Results, 256); cmd_send(CMD_MEASURED_ANTENNA_TUNING, vLf125 | (vLf134<<16), vHf, peakf | (peakv<<16), LF_Results, 256);
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LED_A_OFF();
LED_B_OFF(); LEDsoff();
return;
} }
void MeasureAntennaTuningHf(void) void MeasureAntennaTuningHf(void) {
{
int vHf = 0; // in mV int vHf = 0; // in mV
DbpString("Measuring HF antenna, press button to exit"); DbpString("Measuring HF antenna, press button to exit");
@ -251,15 +242,13 @@ void MeasureAntennaTuningHf(void)
Dbprintf("%d mV",vHf); Dbprintf("%d mV",vHf);
if (BUTTON_PRESS()) break; if (BUTTON_PRESS()) break;
} }
DbpString("cancelled"); DbpString("cancelled");
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
} }
void ReadMem(int addr) void ReadMem(int addr) {
{
const uint8_t *data = ((uint8_t *)addr); const uint8_t *data = ((uint8_t *)addr);
Dbprintf("%x: %02x %02x %02x %02x %02x %02x %02x %02x", Dbprintf("%x: %02x %02x %02x %02x %02x %02x %02x %02x",
@ -280,6 +269,7 @@ void SendVersion(void)
* pointer, then use it. * pointer, then use it.
*/ */
char *bootrom_version = *(char**)&_bootphase1_version_pointer; char *bootrom_version = *(char**)&_bootphase1_version_pointer;
if( bootrom_version < &_flash_start || bootrom_version >= &_flash_end ) { if( bootrom_version < &_flash_start || bootrom_version >= &_flash_end ) {
strcat(VersionString, "bootrom version information appears invalid\n"); strcat(VersionString, "bootrom version information appears invalid\n");
} else { } else {
@ -292,6 +282,7 @@ void SendVersion(void)
FpgaGatherVersion(FPGA_BITSTREAM_LF, temp, sizeof(temp)); FpgaGatherVersion(FPGA_BITSTREAM_LF, temp, sizeof(temp));
strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1);
FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp)); FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp));
strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1);
@ -333,8 +324,7 @@ void printUSBSpeed(void)
/** /**
* Prints runtime information about the PM3. * Prints runtime information about the PM3.
**/ **/
void SendStatus(void) void SendStatus(void) {
{
BigBuf_print_status(); BigBuf_print_status();
Fpga_print_status(); Fpga_print_status();
printConfig(); //LF Sampling config printConfig(); //LF Sampling config
@ -782,16 +772,14 @@ static const char LIGHT_SCHEME[] = {
}; };
static const int LIGHT_LEN = sizeof(LIGHT_SCHEME)/sizeof(LIGHT_SCHEME[0]); static const int LIGHT_LEN = sizeof(LIGHT_SCHEME)/sizeof(LIGHT_SCHEME[0]);
void ListenReaderField(int limit) void ListenReaderField(int limit) {
{
int lf_av, lf_av_new, lf_baseline= 0, lf_max;
int hf_av, hf_av_new, hf_baseline= 0, hf_max;
int mode=1, display_val, display_max, i;
#define LF_ONLY 1 #define LF_ONLY 1
#define HF_ONLY 2 #define HF_ONLY 2
#define REPORT_CHANGE 10 // report new values only if they have changed at least by REPORT_CHANGE #define REPORT_CHANGE 10 // report new values only if they have changed at least by REPORT_CHANGE
int lf_av, lf_av_new, lf_baseline= 0, lf_max;
int hf_av, hf_av_new, hf_baseline= 0, hf_max;
int mode=1, display_val, display_max, i;
// switch off FPGA - we don't want to measure our own signal // switch off FPGA - we don't want to measure our own signal
FpgaDownloadAndGo(FPGA_BITSTREAM_HF); FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
@ -1400,9 +1388,8 @@ void __attribute__((noreturn)) AppMain(void)
for(;;) { for(;;) {
if (usb_poll()) { if (usb_poll()) {
rx_len = usb_read(rx,sizeof(UsbCommand)); rx_len = usb_read(rx,sizeof(UsbCommand));
if (rx_len) { if (rx_len)
UsbPacketReceived(rx,rx_len); UsbPacketReceived(rx,rx_len);
}
} }
WDT_HIT(); WDT_HIT();

View file

@ -24,9 +24,9 @@
static uint8_t filterlut[1 << 20]; static uint8_t filterlut[1 << 20];
static void __attribute__((constructor)) fill_lut() static void __attribute__((constructor)) fill_lut()
{ {
uint32_t i; uint32_t i;
for(i = 0; i < 1 << 20; ++i) for(i = 0; i < 1 << 20; ++i)
filterlut[i] = filter(i); filterlut[i] = filter(i);
} }
#define filter(x) (filterlut[(x) & 0xfffff]) #define filter(x) (filterlut[(x) & 0xfffff])
#endif #endif
@ -509,7 +509,6 @@ static struct Crypto1State* check_pfx_parity(uint32_t prefix, uint32_t rresp, ui
* It returns a zero terminated list of possible cipher states after the * It returns a zero terminated list of possible cipher states after the
* tag nonce was fed in * tag nonce was fed in
*/ */
struct Crypto1State* lfsr_common_prefix(uint32_t pfx, uint32_t rr, uint8_t ks[8], uint8_t par[8][8]) struct Crypto1State* lfsr_common_prefix(uint32_t pfx, uint32_t rr, uint8_t ks[8], uint8_t par[8][8])
{ {
struct Crypto1State *statelist, *s; struct Crypto1State *statelist, *s;

View file

@ -20,18 +20,15 @@
#include "crapto1.h" #include "crapto1.h"
#include <stdlib.h> #include <stdlib.h>
void crypto1_create(struct Crypto1State *s, uint64_t key) void crypto1_create(struct Crypto1State *s, uint64_t key)
{ {
// struct Crypto1State *s = malloc(sizeof(*s)); // struct Crypto1State *s = malloc(sizeof(*s));
s->odd = s->even = 0;
int i; int i;
for(i = 47;s && i > 0; i -= 2) { for(i = 47;s && i > 0; i -= 2) {
s->odd = s->odd << 1 | BIT(key, (i - 1) ^ 7); s->odd = s->odd << 1 | BIT(key, (i - 1) ^ 7);
s->even = s->even << 1 | BIT(key, i ^ 7); s->even = s->even << 1 | BIT(key, i ^ 7);
} }
return;
} }
void crypto1_destroy(struct Crypto1State *state) void crypto1_destroy(struct Crypto1State *state)
{ {

View file

@ -226,8 +226,8 @@ void* mifare_cryto_preprocess_data (desfiretag_t tag, void *data, size_t *nbytes
cmac (key, DESFIRE (tag)->ivect, res, *nbytes, DESFIRE (tag)->cmac); cmac (key, DESFIRE (tag)->ivect, res, *nbytes, DESFIRE (tag)->cmac);
if (append_mac) { if (append_mac) {
maced_data_length (key, *nbytes); size_t len = maced_data_length (key, *nbytes);
++len;
memcpy (res, data, *nbytes); memcpy (res, data, *nbytes);
memcpy (res + *nbytes, DESFIRE (tag)->cmac, CMAC_LENGTH); memcpy (res + *nbytes, DESFIRE (tag)->cmac, CMAC_LENGTH);
*nbytes += CMAC_LENGTH; *nbytes += CMAC_LENGTH;

View file

@ -102,7 +102,7 @@ static struct {
static uint8_t apdu_lengths_replay[5]; static uint8_t apdu_lengths_replay[5];
// type of card (ISO 14443 A or B) // type of card (ISO 14443 A or B)
static char iso_type = 0; static char iso_type;
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Wrapper for sending APDUs to type A and B cards // Wrapper for sending APDUs to type A and B cards

View file

@ -1383,33 +1383,31 @@ static int SendIClassAnswer(uint8_t *resp, int respLen, int delay)
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait) static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait)
{ {
int c; int c;
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
AT91C_BASE_SSC->SSC_THR = 0x00; AT91C_BASE_SSC->SSC_THR = 0x00;
FpgaSetupSsc(); FpgaSetupSsc();
if (wait) if (wait) {
{ if(*wait < 10) *wait = 10;
if(*wait < 10) *wait = 10;
for(c = 0; c < *wait;) { for(c = 0; c < *wait;) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing! AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
c++; c++;
} }
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
(void)r; (void)r;
} }
WDT_HIT(); WDT_HIT();
} }
}
}
uint8_t sendbyte; uint8_t sendbyte;
bool firstpart = TRUE; bool firstpart = TRUE;
c = 0; c = 0;
for(;;) { for(;;) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
@ -1437,7 +1435,7 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int
} }
WDT_HIT(); WDT_HIT();
} }
if (samples) *samples = (c + *wait) << 3; if (samples && wait) *samples = (c + *wait) << 3;
} }

View file

@ -106,8 +106,6 @@ static uint32_t NextTransferTime;
static uint32_t LastTimeProxToAirStart; static uint32_t LastTimeProxToAirStart;
static uint32_t LastProxToAirDuration; static uint32_t LastProxToAirDuration;
// CARD TO READER - manchester // CARD TO READER - manchester
// Sequence D: 11110000 modulation with subcarrier during first half // Sequence D: 11110000 modulation with subcarrier during first half
// Sequence E: 00001111 modulation with subcarrier during second half // Sequence E: 00001111 modulation with subcarrier during second half
@ -127,13 +125,11 @@ void iso14a_set_trigger(bool enable) {
trigger = enable; trigger = enable;
} }
void iso14a_set_timeout(uint32_t timeout) { void iso14a_set_timeout(uint32_t timeout) {
iso14a_timeout = timeout; iso14a_timeout = timeout;
if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443A Timeout set to %ld (%dms)", iso14a_timeout, iso14a_timeout / 106); if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443A Timeout set to %ld (%dms)", iso14a_timeout, iso14a_timeout / 106);
} }
void iso14a_set_ATS_timeout(uint8_t *ats) { void iso14a_set_ATS_timeout(uint8_t *ats) {
uint8_t tb1; uint8_t tb1;
@ -142,20 +138,22 @@ void iso14a_set_ATS_timeout(uint8_t *ats) {
if (ats[0] > 1) { // there is a format byte T0 if (ats[0] > 1) { // there is a format byte T0
if ((ats[1] & 0x20) == 0x20) { // there is an interface byte TB(1) if ((ats[1] & 0x20) == 0x20) { // there is an interface byte TB(1)
if ((ats[1] & 0x10) == 0x10) { // there is an interface byte TA(1) preceding TB(1)
tb1 = ats[3];
} else {
tb1 = ats[2];
}
fwi = (tb1 & 0xf0) >> 4; // frame waiting indicator (FWI)
fwt = 256 * 16 * (1 << fwi); // frame waiting time (FWT) in 1/fc
iso14a_set_timeout(fwt/(8*16)); if ((ats[1] & 0x10) == 0x10) // there is an interface byte TA(1) preceding TB(1)
tb1 = ats[3];
else
tb1 = ats[2];
fwi = (tb1 & 0xf0) >> 4; // frame waiting indicator (FWI)
//fwt = 256 * 16 * (1 << fwi); // frame waiting time (FWT) in 1/fc
fwt = 4096 * (1 << fwi);
//iso14a_set_timeout(fwt/(8*16));
iso14a_set_timeout(fwt/128);
} }
} }
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Generate the parity value for a byte sequence // Generate the parity value for a byte sequence
// //
@ -1059,10 +1057,12 @@ void SimulateIso14443aTag(int tagType, int flags, byte_t* data)
{ .response = response3a, .response_n = sizeof(response3a) }, // Acknowledge select - cascade 2 { .response = response3a, .response_n = sizeof(response3a) }, // Acknowledge select - cascade 2
{ .response = response5, .response_n = sizeof(response5) }, // Authentication answer (random nonce) { .response = response5, .response_n = sizeof(response5) }, // Authentication answer (random nonce)
{ .response = response6, .response_n = sizeof(response6) }, // dummy ATS (pseudo-ATR), answer to RATS { .response = response6, .response_n = sizeof(response6) }, // dummy ATS (pseudo-ATR), answer to RATS
//{ .response = response7_NTAG, .response_n = sizeof(response7_NTAG)}, // EV1/NTAG GET_VERSION response
{ .response = response8, .response_n = sizeof(response8) } // EV1/NTAG PACK response { .response = response8, .response_n = sizeof(response8) } // EV1/NTAG PACK response
//{ .response = response9, .response_n = sizeof(response9) } // EV1/NTAG CHK_TEAR response
}; };
//{ .response = response7_NTAG, .response_n = sizeof(response7_NTAG)}, // EV1/NTAG GET_VERSION response
//{ .response = response9, .response_n = sizeof(response9) } // EV1/NTAG CHK_TEAR response
// Allocate 512 bytes for the dynamic modulation, created when the reader queries for it // Allocate 512 bytes for the dynamic modulation, created when the reader queries for it
// Such a response is less time critical, so we can prepare them on the fly // Such a response is less time critical, so we can prepare them on the fly
@ -1112,6 +1112,9 @@ void SimulateIso14443aTag(int tagType, int flags, byte_t* data)
LED_A_ON(); LED_A_ON();
for(;;) { for(;;) {
WDT_HIT();
// Clean receive command buffer // Clean receive command buffer
if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) { if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
DbpString("Button press"); DbpString("Button press");
@ -1434,7 +1437,7 @@ void PrepareDelayedTransfer(uint16_t delay)
for (uint16_t i = 0; i < delay; i++) { for (uint16_t i = 0; i < delay; i++) {
bitmask |= (0x01 << i); bitmask |= (0x01 << i);
} }
ToSend[ToSendMax++] = 0x00; ToSend[++ToSendMax] = 0x00;
for (uint16_t i = 0; i < ToSendMax; i++) { for (uint16_t i = 0; i < ToSendMax; i++) {
bits_to_shift = ToSend[i] & bitmask; bits_to_shift = ToSend[i] & bitmask;
ToSend[i] = ToSend[i] >> delay; ToSend[i] = ToSend[i] >> delay;
@ -1466,6 +1469,7 @@ 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 {
@ -1481,7 +1485,7 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
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;
if(c >= len) if(c >= len)
break; break;
} }
@ -1886,10 +1890,10 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
uint8_t sel_all[] = { 0x93,0x20 }; uint8_t sel_all[] = { 0x93,0x20 };
uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
uint8_t resp[MAX_FRAME_SIZE]; // theoretically. A usual RATS will be much smaller uint8_t resp[MAX_FRAME_SIZE] = {0}; // theoretically. A usual RATS will be much smaller
uint8_t resp_par[MAX_PARITY_SIZE]; uint8_t resp_par[MAX_PARITY_SIZE] = {0};
byte_t uid_resp[4]; byte_t uid_resp[4] = {0};
size_t uid_resp_len; size_t uid_resp_len = 0;
uint8_t sak = 0x04; // cascade uid uint8_t sak = 0x04; // cascade uid
int cascade_level = 0; int cascade_level = 0;
@ -1908,16 +1912,13 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
} }
if (anticollision) { if (anticollision) {
// clear uid // clear uid
if (uid_ptr) { if (uid_ptr)
memset(uid_ptr,0,10); memset(uid_ptr,0,10);
}
} }
// check for proprietary anticollision: // check for proprietary anticollision:
if ((resp[0] & 0x1F) == 0) { if ((resp[0] & 0x1F) == 0) return 3;
return 3;
}
// 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
@ -1928,40 +1929,41 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
if (anticollision) { if (anticollision) {
// SELECT_ALL // SELECT_ALL
ReaderTransmit(sel_all, sizeof(sel_all), NULL); ReaderTransmit(sel_all, sizeof(sel_all), NULL);
if (!ReaderReceive(resp, resp_par)) return 0; if (!ReaderReceive(resp, resp_par)) return 0;
if (Demod.collisionPos) { // we had a collision and need to construct the UID bit by bit if (Demod.collisionPos) { // we had a collision and need to construct the UID bit by bit
memset(uid_resp, 0, 4); memset(uid_resp, 0, 4);
uint16_t uid_resp_bits = 0; uint16_t uid_resp_bits = 0;
uint16_t collision_answer_offset = 0; uint16_t collision_answer_offset = 0;
// anti-collision-loop: // anti-collision-loop:
while (Demod.collisionPos) { while (Demod.collisionPos) {
Dbprintf("Multiple tags detected. Collision after Bit %d", Demod.collisionPos); Dbprintf("Multiple tags detected. Collision after Bit %d", Demod.collisionPos);
for (uint16_t i = collision_answer_offset; i < Demod.collisionPos; i++, uid_resp_bits++) { // add valid UID bits before collision point for (uint16_t i = collision_answer_offset; i < Demod.collisionPos; i++, uid_resp_bits++) { // add valid UID bits before collision point
uint16_t UIDbit = (resp[i/8] >> (i % 8)) & 0x01; uint16_t UIDbit = (resp[i/8] >> (i % 8)) & 0x01;
uid_resp[uid_resp_bits / 8] |= UIDbit << (uid_resp_bits % 8); uid_resp[uid_resp_bits / 8] |= UIDbit << (uid_resp_bits % 8);
}
uid_resp[uid_resp_bits/8] |= 1 << (uid_resp_bits % 8); // next time select the card(s) with a 1 in the collision position
uid_resp_bits++;
// construct anticollosion command:
sel_uid[1] = ((2 + uid_resp_bits/8) << 4) | (uid_resp_bits & 0x07); // length of data in bytes and bits
for (uint16_t i = 0; i <= uid_resp_bits/8; i++) {
sel_uid[2+i] = uid_resp[i];
}
collision_answer_offset = uid_resp_bits%8;
ReaderTransmitBits(sel_uid, 16 + uid_resp_bits, NULL);
if (!ReaderReceiveOffset(resp, collision_answer_offset, resp_par)) return 0;
} }
uid_resp[uid_resp_bits/8] |= 1 << (uid_resp_bits % 8); // next time select the card(s) with a 1 in the collision position // finally, add the last bits and BCC of the UID
uid_resp_bits++; for (uint16_t i = collision_answer_offset; i < (Demod.len-1)*8; i++, uid_resp_bits++) {
// construct anticollosion command: uint16_t UIDbit = (resp[i/8] >> (i%8)) & 0x01;
sel_uid[1] = ((2 + uid_resp_bits/8) << 4) | (uid_resp_bits & 0x07); // length of data in bytes and bits uid_resp[uid_resp_bits/8] |= UIDbit << (uid_resp_bits % 8);
for (uint16_t i = 0; i <= uid_resp_bits/8; i++) {
sel_uid[2+i] = uid_resp[i];
} }
collision_answer_offset = uid_resp_bits%8;
ReaderTransmitBits(sel_uid, 16 + uid_resp_bits, NULL); } else { // no collision, use the response to SELECT_ALL as current uid
if (!ReaderReceiveOffset(resp, collision_answer_offset, resp_par)) return 0; memcpy(uid_resp, resp, 4);
}
// finally, add the last bits and BCC of the UID
for (uint16_t i = collision_answer_offset; i < (Demod.len-1)*8; i++, uid_resp_bits++) {
uint16_t UIDbit = (resp[i/8] >> (i%8)) & 0x01;
uid_resp[uid_resp_bits/8] |= UIDbit << (uid_resp_bits % 8);
} }
} else { // no collision, use the response to SELECT_ALL as current uid
memcpy(uid_resp, resp, 4);
}
} else { } else {
if (cascade_level < num_cascades - 1) { if (cascade_level < num_cascades - 1) {
uid_resp[0] = 0x88; uid_resp[0] = 0x88;
@ -1973,9 +1975,8 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
uid_resp_len = 4; uid_resp_len = 4;
// calculate crypto UID. Always use last 4 Bytes. // calculate crypto UID. Always use last 4 Bytes.
if(cuid_ptr) { if(cuid_ptr)
*cuid_ptr = bytes_to_num(uid_resp, 4); *cuid_ptr = bytes_to_num(uid_resp, 4);
}
// Construct SELECT UID command // Construct SELECT UID command
sel_uid[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC) sel_uid[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
@ -1986,6 +1987,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
// Receive the SAK // Receive the SAK
if (!ReaderReceive(resp, resp_par)) return 0; if (!ReaderReceive(resp, resp_par)) return 0;
sak = resp[0]; sak = resp[0];
// Test if more parts of the uid are coming // Test if more parts of the uid are coming
@ -1998,9 +2000,8 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
uid_resp_len = 3; uid_resp_len = 3;
} }
if(uid_ptr && anticollision) { if(uid_ptr && anticollision)
memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len); memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len);
}
if(p_hi14a_card) { if(p_hi14a_card) {
memcpy(p_hi14a_card->uid + (cascade_level*3), uid_resp, uid_resp_len); memcpy(p_hi14a_card->uid + (cascade_level*3), uid_resp, uid_resp_len);
@ -2022,7 +2023,6 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
if (!(len = ReaderReceive(resp, resp_par))) return 0; if (!(len = ReaderReceive(resp, resp_par))) return 0;
if(p_hi14a_card) { if(p_hi14a_card) {
memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats)); memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats));
p_hi14a_card->ats_len = len; p_hi14a_card->ats_len = len;
@ -2219,7 +2219,7 @@ void ReaderMifare(bool first_try, uint8_t block )
//uint8_t mf_auth[] = { 0x60,0x05, 0x58, 0x2c }; //uint8_t mf_auth[] = { 0x60,0x05, 0x58, 0x2c };
uint8_t mf_auth[] = { 0x60,0x00, 0x00, 0x00 }; uint8_t mf_auth[] = { 0x60,0x00, 0x00, 0x00 };
uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
static uint8_t mf_nr_ar3; static uint8_t mf_nr_ar3 = 0;
mf_auth[1] = block; mf_auth[1] = block;
AppendCrc14443a(mf_auth, 2); AppendCrc14443a(mf_auth, 2);
@ -2227,14 +2227,6 @@ void ReaderMifare(bool first_try, uint8_t block )
uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
if (first_try)
iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
// free eventually allocated BigBuf memory. We want all for tracing.
BigBuf_free();
clear_trace();
set_tracing(TRUE);
byte_t nt_diff = 0; byte_t nt_diff = 0;
uint8_t par[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough uint8_t par[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
static byte_t par_low = 0; static byte_t par_low = 0;
@ -2248,49 +2240,62 @@ void ReaderMifare(bool first_try, uint8_t block )
byte_t par_list[8] = {0x00}; byte_t par_list[8] = {0x00};
byte_t ks_list[8] = {0x00}; byte_t ks_list[8] = {0x00};
#define PRNG_SEQUENCE_LENGTH (1 << 16);
static uint32_t sync_time = 0; static uint32_t sync_time = 0;
static int32_t sync_cycles = 0; static int32_t sync_cycles = 0;
int catch_up_cycles = 0; int catch_up_cycles = 0;
int last_catch_up = 0; int last_catch_up = 0;
uint16_t elapsed_prng_sequences = 0; uint16_t elapsed_prng_sequences = 1;
uint16_t consecutive_resyncs = 0; uint16_t consecutive_resyncs = 0;
int isOK = 0; int isOK = 0;
#define PRNG_SEQUENCE_LENGTH (1 << 16);
#define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up.
#define MAX_SYNC_TRIES 32
#define NUM_DEBUG_INFOS 8 // per strategy
#define MAX_STRATEGY 3
uint16_t unexpected_random = 0;
uint16_t sync_tries = 0;
int16_t debug_info_nr = -1;
uint16_t strategy = 0;
int32_t debug_info[MAX_STRATEGY+1][NUM_DEBUG_INFOS];
uint32_t select_time = 0;
uint32_t halt_time = 0;
//uint8_t caller[7] = {0};
// init to zero.
for (uint16_t i = 0; i < MAX_STRATEGY+1; ++i)
for(uint16_t j = 0; j < NUM_DEBUG_INFOS; ++j)
debug_info[i][j] = 0;
LED_A_ON();
LED_B_OFF();
LED_C_OFF();
if (first_try)
iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
// free eventually allocated BigBuf memory. We want all for tracing.
BigBuf_free();
clear_trace();
set_tracing(TRUE);
if (first_try) { if (first_try) {
mf_nr_ar3 = 0;
sync_time = GetCountSspClk() & 0xfffffff8; sync_time = GetCountSspClk() & 0xfffffff8;
sync_cycles = PRNG_SEQUENCE_LENGTH; //65536; //0x10000 // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). sync_cycles = PRNG_SEQUENCE_LENGTH; //65536; //0x10000 // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
mf_nr_ar3 = 0;
nt_attacked = 0; nt_attacked = 0;
par[0] = 0; par[0] = 0;
} } else {
else {
// we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same) // we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same)
mf_nr_ar3++; mf_nr_ar3++;
mf_nr_ar[3] = mf_nr_ar3; mf_nr_ar[3] = mf_nr_ar3;
par[0] = par_low; par[0] = par_low;
} }
LED_A_ON(); LED_C_ON();
LED_B_OFF();
LED_C_OFF();
#define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up.
#define MAX_SYNC_TRIES 32
#define NUM_DEBUG_INFOS 8 // per strategy
#define MAX_STRATEGY 3
uint16_t unexpected_random = 0;
uint16_t sync_tries = 0;
int16_t debug_info_nr = -1;
uint16_t strategy = 0;
int32_t debug_info[MAX_STRATEGY][NUM_DEBUG_INFOS];
uint32_t select_time = 0;
uint32_t halt_time = 0;
for(uint16_t i = 0; TRUE; ++i) { for(uint16_t i = 0; TRUE; ++i) {
LED_C_ON();
WDT_HIT(); WDT_HIT();
// Test if the action was cancelled // Test if the action was cancelled
@ -2300,12 +2305,12 @@ void ReaderMifare(bool first_try, uint8_t block )
} }
if (strategy == 2) { if (strategy == 2) {
// test with additional hlt command // test with additional halt command
halt_time = 0; halt_time = 0;
int len = mifare_sendcmd_short(NULL, false, 0x50, 0x00, receivedAnswer, receivedAnswerPar, &halt_time); int len = mifare_sendcmd_short(NULL, false, 0x50, 0x00, receivedAnswer, receivedAnswerPar, &halt_time);
if (len && MF_DBGLEVEL >= 3) {
Dbprintf("Unexpected response of %d bytes to hlt command (additional debugging).", len); if (len && MF_DBGLEVEL >= 3)
} Dbprintf("Unexpected response of %d bytes to halt command (additional debugging).\n", len);
} }
if (strategy == 3) { if (strategy == 3) {
@ -2314,28 +2319,35 @@ void ReaderMifare(bool first_try, uint8_t block )
SpinDelay(200); SpinDelay(200);
iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
SpinDelay(100); SpinDelay(100);
sync_time = GetCountSspClk() & 0xfffffff8;
WDT_HIT(); WDT_HIT();
} }
if(!iso14443a_select_card(uid, NULL, &cuid, true, 0)) { if (!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {
if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card"); if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card\n");
continue; continue;
} }
select_time = GetCountSspClk();
select_time = GetCountSspClk() & 0xfffffff8;
elapsed_prng_sequences = 1; elapsed_prng_sequences = 1;
if (debug_info_nr == -1) { if (debug_info_nr == -1) {
sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles; sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles;
catch_up_cycles = 0; catch_up_cycles = 0;
// if we missed the sync time already, advance to the next nonce repeat // if we missed the sync time already, advance to the next nonce repeat
WDT_HIT();
while(GetCountSspClk() > sync_time) { while(GetCountSspClk() > sync_time) {
elapsed_prng_sequences++; ++elapsed_prng_sequences;
sync_time = (sync_time & 0xfffffff8) + sync_cycles; sync_time = (sync_time & 0xfffffff8) + sync_cycles;
//sync_time += sync_cycles;
//sync_time &= 0xfffffff8;
} }
WDT_HIT();
// Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked) // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time); ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time);
if (MF_DBGLEVEL == 2) Dbprintf("sync_time %d \n", sync_time);
} else { } else {
// collect some information on tag nonces for debugging: // collect some information on tag nonces for debugging:
@ -2357,10 +2369,8 @@ void ReaderMifare(bool first_try, uint8_t block )
} }
// Receive the (4 Byte) "random" nonce // Receive the (4 Byte) "random" nonce
if (!ReaderReceive(receivedAnswer, receivedAnswerPar)) { if (!ReaderReceive(receivedAnswer, receivedAnswerPar))
if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Couldn't receive tag nonce");
continue; continue;
}
previous_nt = nt; previous_nt = nt;
nt = bytes_to_num(receivedAnswer, 4); nt = bytes_to_num(receivedAnswer, 4);
@ -2382,6 +2392,7 @@ void ReaderMifare(bool first_try, uint8_t block )
continue; // continue trying... continue; // continue trying...
} }
} }
if (++sync_tries > MAX_SYNC_TRIES) { if (++sync_tries > MAX_SYNC_TRIES) {
if (strategy > MAX_STRATEGY || MF_DBGLEVEL < 3) { if (strategy > MAX_STRATEGY || MF_DBGLEVEL < 3) {
isOK = -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly isOK = -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
@ -2389,44 +2400,53 @@ void ReaderMifare(bool first_try, uint8_t block )
} else { // continue for a while, just to collect some debug info } else { // continue for a while, just to collect some debug info
++debug_info_nr; ++debug_info_nr;
debug_info[strategy][debug_info_nr] = nt_distance; debug_info[strategy][debug_info_nr] = nt_distance;
if (debug_info_nr == NUM_DEBUG_INFOS) { if (debug_info_nr == NUM_DEBUG_INFOS-1) {
++strategy; ++strategy;
debug_info_nr = 0; debug_info_nr = 0;
} }
continue; continue;
} }
} }
sync_cycles = (sync_cycles - nt_distance/elapsed_prng_sequences); sync_cycles = (sync_cycles - nt_distance/elapsed_prng_sequences);
if (sync_cycles <= 0) { if (sync_cycles <= 0)
sync_cycles += PRNG_SEQUENCE_LENGTH; sync_cycles += PRNG_SEQUENCE_LENGTH;
}
if (MF_DBGLEVEL >= 3) { if (MF_DBGLEVEL >= 2)
Dbprintf("calibrating in cycle %d. nt_distance=%d, elapsed_prng_sequences=%d, new sync_cycles: %d\n", i, nt_distance, elapsed_prng_sequences, sync_cycles); Dbprintf("calibrating in cycle %d. nt_distance=%d, elapsed_prng_sequences=%d, new sync_cycles: %d\n", i, nt_distance, elapsed_prng_sequences, sync_cycles);
}
continue; continue;
} }
} }
if ((nt != nt_attacked) && nt_attacked) { // we somehow lost sync. Try to catch up again... if ((nt != nt_attacked) && nt_attacked) { // we somehow lost sync. Try to catch up again...
catch_up_cycles = -dist_nt(nt_attacked, nt); catch_up_cycles = -dist_nt(nt_attacked, nt);
if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one. if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one.
catch_up_cycles = 0; catch_up_cycles = 0;
continue; continue;
} }
// average?
catch_up_cycles /= elapsed_prng_sequences; catch_up_cycles /= elapsed_prng_sequences;
if (catch_up_cycles == last_catch_up) { if (catch_up_cycles == last_catch_up) {
++consecutive_resyncs; ++consecutive_resyncs;
} } else {
else {
last_catch_up = catch_up_cycles; last_catch_up = catch_up_cycles;
consecutive_resyncs = 0; consecutive_resyncs = 0;
} }
sync_cycles += catch_up_cycles;
if (consecutive_resyncs < 3) { if (consecutive_resyncs < 3) {
if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, -catch_up_cycles, consecutive_resyncs); if (MF_DBGLEVEL >= 3)
} Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, -catch_up_cycles, consecutive_resyncs);
else { } else {
sync_cycles = sync_cycles + catch_up_cycles; sync_cycles += catch_up_cycles;
if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i, -catch_up_cycles, sync_cycles);
if (MF_DBGLEVEL >= 3)
Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i, -catch_up_cycles, sync_cycles);
last_catch_up = 0; last_catch_up = 0;
catch_up_cycles = 0; catch_up_cycles = 0;
consecutive_resyncs = 0; consecutive_resyncs = 0;
@ -2476,13 +2496,18 @@ void ReaderMifare(bool first_try, uint8_t block )
WDT_HIT(); WDT_HIT();
if (isOK == -4) { if (isOK == -4) {
if (MF_DBGLEVEL >= 3) { for (uint16_t i = 0; i < MAX_STRATEGY+1; ++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("info[%d][%d] = %d", i, j, debug_info[i][j]);
Dbprintf("collected debug info[%d][%d] = %d", i, j, debug_info[i][j]); }
}
} // reset sync_time.
} if ( isOK == 1) {
sync_time = 0;
sync_cycles = 0;
mf_nr_ar3 = 0;
nt_attacked = 0;
par[0] = 0;
} }
byte_t buf[28] = {0x00}; byte_t buf[28] = {0x00};
@ -2494,10 +2519,8 @@ void ReaderMifare(bool first_try, uint8_t block )
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); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff(); LEDsoff();
set_tracing(FALSE); set_tracing(FALSE);
} }

View file

@ -276,10 +276,10 @@ static void frame_receive_rwd(struct legic_frame * const f, int bits, int crypt)
static void frame_append_bit(struct legic_frame * const f, int bit) static void frame_append_bit(struct legic_frame * const f, int bit)
{ {
if(f->bits >= 31) if (f->bits >= 31)
return; /* Overflow, won't happen */ return; /* Overflow, won't happen */
f->data |= (bit<<f->bits); f->data |= (bit << f->bits);
f->bits++; f->bits++;
} }
@ -354,9 +354,11 @@ int legic_read_byte(int byte_index, int cmd_sz) {
frame_receive_rwd(&current_frame, 12, 1); frame_receive_rwd(&current_frame, 12, 1);
byte = current_frame.data & 0xff; byte = current_frame.data & 0xff;
if( LegicCRC(byte_index, byte, cmd_sz) != (current_frame.data >> 8) ) { if( LegicCRC(byte_index, byte, cmd_sz) != (current_frame.data >> 8) ) {
Dbprintf("!!! crc mismatch: expected %x but got %x !!!", Dbprintf("!!! crc mismatch: expected %x but got %x !!!",
LegicCRC(byte_index, current_frame.data & 0xff, cmd_sz), current_frame.data >> 8); LegicCRC(byte_index, current_frame.data & 0xff, cmd_sz),
current_frame.data >> 8);
return -1; return -1;
} }
@ -372,9 +374,8 @@ int legic_read_byte(int byte_index, int cmd_sz) {
*/ */
int legic_write_byte(int byte, int addr, int addr_sz) { int legic_write_byte(int byte, int addr, int addr_sz) {
//do not write UID, CRC, DCF //do not write UID, CRC, DCF
if(addr <= 0x06) { if(addr <= 0x06)
return 0; return 0;
}
//== send write command ============================== //== send write command ==============================
crc_clear(&legic_crc); crc_clear(&legic_crc);

View file

@ -996,32 +996,26 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
set_tracing(TRUE); set_tracing(TRUE);
for (i = 0; i < keyCount; i++) { for (i = 0; i < keyCount; ++i) {
if(mifare_classic_halt(pcs, cuid)) { if (mifare_classic_halt(pcs, cuid))
if (MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Halt error"); if (MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Halt error");
}
if(!iso14443a_select_card(uid, NULL, &cuid, true, 0)) { if (!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {
if (OLD_MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Can't select card"); if (OLD_MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Can't select card");
break; break;
}; }
ui64Key = bytes_to_num(datain + i * 6, 6); ui64Key = bytes_to_num(datain + i * 6, 6);
if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) { if (mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST))
continue; continue;
};
isOK = 1; isOK = 1;
break; break;
} }
// ----------------------------- crypto1 destroy
crypto1_destroy(pcs); crypto1_destroy(pcs);
LED_B_ON(); LED_B_ON();
cmd_send(CMD_ACK,isOK,0,0,datain + i * 6,6); cmd_send(CMD_ACK,isOK,0,0,datain + i * 6,6);
LED_B_OFF();
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff(); LEDsoff();
set_tracing(FALSE); set_tracing(FALSE);

View file

@ -13,11 +13,11 @@
static int sniffState = SNF_INIT; static int sniffState = SNF_INIT;
static uint8_t sniffUIDType; static uint8_t sniffUIDType;
static uint8_t sniffUID[8] = {0x00}; static uint8_t sniffUID[8];
static uint8_t sniffATQA[2] = {0x00}; static uint8_t sniffATQA[2];
static uint8_t sniffSAK; static uint8_t sniffSAK;
static uint8_t sniffBuf[16] = {0x00}; static uint8_t sniffBuf[16];
static uint32_t timerData = 0; static uint32_t timerData;
bool MfSniffInit(void){ bool MfSniffInit(void){

View file

@ -149,8 +149,8 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
uint32_t nt, ntpp; // Supplied tag nonce uint32_t nt, ntpp; // Supplied tag nonce
uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }; uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
// Transmit MIFARE_CLASSIC_AUTH // Transmit MIFARE_CLASSIC_AUTH
len = mifare_sendcmd_short(pcs, isNested, 0x60 + (keyType & 0x01), blockNo, receivedAnswer, receivedAnswerPar, timing); len = mifare_sendcmd_short(pcs, isNested, 0x60 + (keyType & 0x01), blockNo, receivedAnswer, receivedAnswerPar, timing);
@ -185,8 +185,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
// Generate (encrypted) nr+parity by loading it into the cipher (Nr) // Generate (encrypted) nr+parity by loading it into the cipher (Nr)
par[0] = 0; par[0] = 0;
for (pos = 0; pos < 4; pos++) for (pos = 0; pos < 4; pos++) {
{
mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos]; mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos];
par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos)); par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos));
} }
@ -195,8 +194,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
nt = prng_successor(nt,32); nt = prng_successor(nt,32);
// ar+parity // ar+parity
for (pos = 4; pos < 8; pos++) for (pos = 4; pos < 8; pos++) {
{
nt = prng_successor(nt,8); nt = prng_successor(nt,8);
mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff); mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff);
par[0] |= (((filter(pcs->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7-pos)); par[0] |= (((filter(pcs->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7-pos));
@ -207,8 +205,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
// Receive 4 byte tag answer // Receive 4 byte tag answer
len = ReaderReceive(receivedAnswer, receivedAnswerPar); len = ReaderReceive(receivedAnswer, receivedAnswerPar);
if (!len) if (!len) {
{
if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout."); if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout.");
return 2; return 2;
} }
@ -220,7 +217,6 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Error card response."); if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Error card response.");
return 3; return 3;
} }
return 0; return 0;
} }
@ -370,7 +366,7 @@ int mifare_ultra_auth(uint8_t *keybytes){
int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData)
{ {
uint16_t len; uint16_t len;
uint8_t bt[2]; uint8_t bt[2] = {0x00};
uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00}; uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00};
uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00};
@ -398,7 +394,7 @@ int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData)
int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData)
{ {
// variables // variables
uint16_t len, i; uint16_t len;
uint32_t pos = 0; uint32_t pos = 0;
uint8_t par[3] = {0x00}; // enough for 18 Bytes to send uint8_t par[3] = {0x00}; // enough for 18 Bytes to send
byte_t res = 0; byte_t res = 0;
@ -419,8 +415,7 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl
AppendCrc14443a(d_block, 16); AppendCrc14443a(d_block, 16);
// crypto // crypto
for (pos = 0; pos < 18; pos++) for (pos = 0; pos < 18; pos++) {
{
d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos]; d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos];
par[pos>>3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos&0x0007))); par[pos>>3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos&0x0007)));
} }
@ -431,8 +426,10 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl
len = ReaderReceive(receivedAnswer, receivedAnswerPar); len = ReaderReceive(receivedAnswer, receivedAnswerPar);
res = 0; res = 0;
for (i = 0; i < 4; i++) res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 0)) << 0;
res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], i)) << i; res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 1)) << 1;
res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 2)) << 2;
res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 3)) << 3;
if ((len != 1) || (res != 0x0A)) { if ((len != 1) || (res != 0x0A)) {
if (MF_DBGLEVEL >= 1) Dbprintf("Cmd send data2 Error: %02x", res); if (MF_DBGLEVEL >= 1) Dbprintf("Cmd send data2 Error: %02x", res);
@ -629,9 +626,8 @@ void emlClearMem(void) {
memset(emCARD, 0, CARD_MEMORY_SIZE); memset(emCARD, 0, CARD_MEMORY_SIZE);
// fill sectors trailer data // fill sectors trailer data
for(b = 3; b < 256; b<127?(b+=4):(b+=16)) { for(b = 3; b < 256; b<127?(b+=4):(b+=16))
emlSetMem((uint8_t *)trailer, b , 1); emlSetMem((uint8_t *)trailer, b , 1);
}
// uid // uid
emlSetMem((uint8_t *)uid, 0, 1); emlSetMem((uint8_t *)uid, 0, 1);

View file

@ -63,7 +63,7 @@ start:
} }
UsbCommand resp; UsbCommand resp;
if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {
isOK = resp.arg[0]; isOK = resp.arg[0];
uid = (uint32_t)bytes_to_num(resp.d.asBytes + 0, 4); uid = (uint32_t)bytes_to_num(resp.d.asBytes + 0, 4);
nt = (uint32_t)bytes_to_num(resp.d.asBytes + 4, 4); nt = (uint32_t)bytes_to_num(resp.d.asBytes + 4, 4);
@ -96,14 +96,12 @@ start:
c.arg[0] = false; c.arg[0] = false;
goto start; goto start;
} else { } else {
isOK = 0;
printf("------------------------------------------------------------------\n");
PrintAndLog("Found valid key: %012"llx" \n", r_key); PrintAndLog("Found valid key: %012"llx" \n", r_key);
} }
t1 = clock() - t1; t1 = clock() - t1;
if ( t1 > 0 ){ if ( t1 > 0 )
PrintAndLog("Time in darkside: %.0f ticks - %4.2f sec\n", (float)t1, ((float)t1)/CLOCKS_PER_SEC); PrintAndLog("Time in darkside: %.0f ticks - %4.2f sec\n", (float)t1, ((float)t1)/CLOCKS_PER_SEC);
}
return 0; return 0;
} }
@ -575,7 +573,7 @@ int CmdHF14AMfNested(const char *Cmd)
uint8_t trgKeyType = 0; uint8_t trgKeyType = 0;
uint8_t SectorsCnt = 0; uint8_t SectorsCnt = 0;
uint8_t key[6] = {0, 0, 0, 0, 0, 0}; uint8_t key[6] = {0, 0, 0, 0, 0, 0};
uint8_t keyBlock[14*6]; uint8_t keyBlock[6*6];
uint64_t key64 = 0; uint64_t key64 = 0;
bool transferToEml = false; bool transferToEml = false;
@ -649,40 +647,35 @@ int CmdHF14AMfNested(const char *Cmd)
transferToEml |= (ctmp == 'd' || ctmp == 'D'); transferToEml |= (ctmp == 'd' || ctmp == 'D');
if (cmdp == 'o') { if (cmdp == 'o') {
PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A');
int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true); int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true);
if (isOK) { switch (isOK) {
switch (isOK) { case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; case -2 : PrintAndLog("Button pressed. Aborted.\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;
case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break; case -4 : PrintAndLog("No valid key found"); break;
default : PrintAndLog("Unknown Error.\n"); case -5 :
} key64 = bytes_to_num(keyBlock, 6);
return 2;
}
key64 = bytes_to_num(keyBlock, 6);
if (key64) {
PrintAndLog("Found valid key:%012"llx, key64);
// transfer key to the emulator // transfer key to the emulator
if (transferToEml) { if (transferToEml) {
uint8_t sectortrailer; uint8_t sectortrailer;
if (trgBlockNo < 32*4) { // 4 block sector if (trgBlockNo < 32*4) { // 4 block sector
sectortrailer = (trgBlockNo & 0x03) + 3; sectortrailer = (trgBlockNo & 0x03) + 3;
} else { // 16 block sector } else { // 16 block sector
sectortrailer = (trgBlockNo & 0x0f) + 15; sectortrailer = (trgBlockNo & 0x0f) + 15;
}
mfEmlGetMem(keyBlock, sectortrailer, 1);
if (!trgKeyType)
num_to_bytes(key64, 6, keyBlock);
else
num_to_bytes(key64, 6, &keyBlock[10]);
mfEmlSetMem(keyBlock, sectortrailer, 1);
} }
mfEmlGetMem(keyBlock, sectortrailer, 1); return 0;
default : PrintAndLog("Unknown Error.\n");
if (!trgKeyType)
num_to_bytes(key64, 6, keyBlock);
else
num_to_bytes(key64, 6, &keyBlock[10]);
mfEmlSetMem(keyBlock, sectortrailer, 1);
}
} else {
PrintAndLog("No valid key found");
} }
return 2;
} }
else { // ------------------------------------ multiple sectors working else { // ------------------------------------ multiple sectors working
clock_t t1 = clock(); clock_t t1 = clock();
@ -697,14 +690,6 @@ int CmdHF14AMfNested(const char *Cmd)
num_to_bytes(0xa0a1a2a3a4a5, 6, (uint8_t*)(keyBlock + 3 * 6)); num_to_bytes(0xa0a1a2a3a4a5, 6, (uint8_t*)(keyBlock + 3 * 6));
num_to_bytes(0xb0b1b2b3b4b5, 6, (uint8_t*)(keyBlock + 4 * 6)); num_to_bytes(0xb0b1b2b3b4b5, 6, (uint8_t*)(keyBlock + 4 * 6));
num_to_bytes(0xaabbccddeeff, 6, (uint8_t*)(keyBlock + 5 * 6)); num_to_bytes(0xaabbccddeeff, 6, (uint8_t*)(keyBlock + 5 * 6));
num_to_bytes(0x4d3a99c351dd, 6, (uint8_t*)(keyBlock + 6 * 6));
num_to_bytes(0x1a982c7e459a, 6, (uint8_t*)(keyBlock + 7 * 6));
num_to_bytes(0xd3f7d3f7d3f7, 6, (uint8_t*)(keyBlock + 8 * 6));
num_to_bytes(0x714c5c886e97, 6, (uint8_t*)(keyBlock + 9 * 6));
num_to_bytes(0x587ee5f9350f, 6, (uint8_t*)(keyBlock + 10 * 6));
num_to_bytes(0xa0478cc39091, 6, (uint8_t*)(keyBlock + 11 * 6));
num_to_bytes(0x533cb6c723f6, 6, (uint8_t*)(keyBlock + 12 * 6));
num_to_bytes(0x8fd0a4f256e9, 6, (uint8_t*)(keyBlock + 13 * 6));
PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt); PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt);
for (i = 0; i < SectorsCnt; i++) { for (i = 0; i < SectorsCnt; i++) {
@ -719,44 +704,47 @@ int CmdHF14AMfNested(const char *Cmd)
} }
} }
} }
clock_t t2 = clock() - t1;
if ( t2 > 0 )
PrintAndLog("Time to check 6 known keys: %.0f ticks %4.2f sec", (float)t2, ((float)t2)/CLOCKS_PER_SEC);
// nested sectors // nested sectors
iterations = 0; iterations = 0;
PrintAndLog("nested..."); PrintAndLog("enter nested...");
bool calibrate = true; bool calibrate = true;
for (i = 0; i < NESTED_SECTOR_RETRY; i++) { for (i = 0; i < NESTED_SECTOR_RETRY; i++) {
for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) { for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; ++sectorNo) {
for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) { for (trgKeyType = 0; trgKeyType < 2; ++trgKeyType) {
if (e_sector[sectorNo].foundKey[trgKeyType]) continue; if (e_sector[sectorNo].foundKey[trgKeyType]) continue;
PrintAndLog("-----------------------------------------------");
int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate);
if(isOK) { switch (isOK) {
switch (isOK) { case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;
case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; case -2 : PrintAndLog("Button pressed. Aborted.\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;
case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break; case -4 : //key not found
default : PrintAndLog("Unknown Error.\n"); calibrate = false;
} iterations++;
free(e_sector); continue;
return 2; case -5 :
} else { calibrate = false;
calibrate = false; iterations++;
} e_sector[sectorNo].foundKey[trgKeyType] = 1;
e_sector[sectorNo].Key[trgKeyType] = bytes_to_num(keyBlock, 6);
continue;
iterations++; default : PrintAndLog("Unknown Error.\n");
key64 = bytes_to_num(keyBlock, 6);
if (key64) {
PrintAndLog("Found valid key:%012"llx, key64);
e_sector[sectorNo].foundKey[trgKeyType] = 1;
e_sector[sectorNo].Key[trgKeyType] = key64;
} }
free(e_sector);
return 2;
} }
} }
} }
// 20160116 If Sector A is found, but not Sector B, try just reading it of the tag? // 20160116 If Sector A is found, but not Sector B, try just reading it of the tag?
PrintAndLog("testing to read B..."); PrintAndLog("trying to read key B...");
for (i = 0; i < SectorsCnt; i++) { for (i = 0; i < SectorsCnt; i++) {
// KEY A but not KEY B // KEY A but not KEY B
if ( e_sector[i].foundKey[0] && !e_sector[i].foundKey[1] ) { if ( e_sector[i].foundKey[0] && !e_sector[i].foundKey[1] ) {
@ -993,8 +981,7 @@ int CmdHF14AMfChk(const char *Cmd)
keyBlock = calloc(stKeyBlock, 6); keyBlock = calloc(stKeyBlock, 6);
if (keyBlock == NULL) return 1; if (keyBlock == NULL) return 1;
uint64_t defaultKeys[] = uint64_t defaultKeys[] = {
{
0xffffffffffff, // Default key (first key used by program if no user defined key) 0xffffffffffff, // Default key (first key used by program if no user defined key)
0x000000000000, // Blank key 0x000000000000, // Blank key
0xa0a1a2a3a4a5, // NFCForum MAD key 0xa0a1a2a3a4a5, // NFCForum MAD key
@ -1012,9 +999,8 @@ int CmdHF14AMfChk(const char *Cmd)
int defaultKeysSize = sizeof(defaultKeys) / sizeof(uint64_t); int defaultKeysSize = sizeof(defaultKeys) / sizeof(uint64_t);
for (int defaultKeyCounter = 0; defaultKeyCounter < defaultKeysSize; defaultKeyCounter++) for (int defaultKeyCounter = 0; defaultKeyCounter < defaultKeysSize; defaultKeyCounter++)
{
num_to_bytes(defaultKeys[defaultKeyCounter], 6, (uint8_t*)(keyBlock + defaultKeyCounter * 6)); num_to_bytes(defaultKeys[defaultKeyCounter], 6, (uint8_t*)(keyBlock + defaultKeyCounter * 6));
}
if (param_getchar(Cmd, 0)=='*') { if (param_getchar(Cmd, 0)=='*') {
blockNo = 3; blockNo = 3;
@ -1025,9 +1011,9 @@ int CmdHF14AMfChk(const char *Cmd)
case '4': SectorsCnt = 40; break; case '4': SectorsCnt = 40; break;
default: SectorsCnt = 16; default: SectorsCnt = 16;
} }
} } else {
else
blockNo = param_get8(Cmd, 0); blockNo = param_get8(Cmd, 0);
}
ctmp = param_getchar(Cmd, 1); ctmp = param_getchar(Cmd, 1);
switch (ctmp) { switch (ctmp) {
@ -1061,7 +1047,7 @@ int CmdHF14AMfChk(const char *Cmd)
} }
keyBlock = p; keyBlock = p;
} }
PrintAndLog("chk key[%2d] %02x%02x%02x%02x%02x%02x", keycnt, PrintAndLog("check key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,
(keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2], (keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2],
(keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6); (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);
keycnt++; keycnt++;
@ -1101,7 +1087,7 @@ int CmdHF14AMfChk(const char *Cmd)
} }
memset(keyBlock + 6 * keycnt, 0, 6); memset(keyBlock + 6 * keycnt, 0, 6);
num_to_bytes(strtoll(buf, NULL, 16), 6, keyBlock + 6*keycnt); num_to_bytes(strtoll(buf, NULL, 16), 6, keyBlock + 6*keycnt);
PrintAndLog("chk custom key[%2d] %012"llx, keycnt, bytes_to_num(keyBlock + 6*keycnt, 6)); PrintAndLog("check custom key[%2d] %012"llx, keycnt, bytes_to_num(keyBlock + 6*keycnt, 6));
keycnt++; keycnt++;
memset(buf, 0, sizeof(buf)); memset(buf, 0, sizeof(buf));
} }
@ -1118,7 +1104,7 @@ int CmdHF14AMfChk(const char *Cmd)
if (keycnt == 0) { if (keycnt == 0) {
PrintAndLog("No key specified, trying default keys"); PrintAndLog("No key specified, trying default keys");
for (;keycnt < defaultKeysSize; keycnt++) for (;keycnt < defaultKeysSize; keycnt++)
PrintAndLog("chk default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt, PrintAndLog("check default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,
(keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2], (keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2],
(keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6); (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);
} }
@ -1143,8 +1129,6 @@ int CmdHF14AMfChk(const char *Cmd)
// skip already found keys. // skip already found keys.
if (e_sector[i].foundKey[trgKeyType]) continue; if (e_sector[i].foundKey[trgKeyType]) continue;
PrintAndLog("--sector:%2d, block:%3d, key type:%C, key count:%2d ", i, b, trgKeyType ? 'B':'A', keycnt);
uint32_t max_keys = keycnt > (USB_CMD_DATA_SIZE/6) ? (USB_CMD_DATA_SIZE/6) : keycnt; 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) { for (uint32_t c = 0; c < keycnt; c += max_keys) {
@ -1153,7 +1137,8 @@ int CmdHF14AMfChk(const char *Cmd)
res = mfCheckKeys(b, trgKeyType, true, size, &keyBlock[6*c], &key64); res = mfCheckKeys(b, trgKeyType, true, size, &keyBlock[6*c], &key64);
if (!res) { if (!res) {
PrintAndLog("Found valid key:[%012"llx"]",key64); PrintAndLog("Sector:%3d Block:%3d, key type: %C -- Found key [%012"llx"]", i, b, trgKeyType ? 'B':'A', key64);
e_sector[i].Key[trgKeyType] = key64; e_sector[i].Key[trgKeyType] = key64;
e_sector[i].foundKey[trgKeyType] = TRUE; e_sector[i].foundKey[trgKeyType] = TRUE;
break; break;

View file

@ -14,6 +14,7 @@
#include <pthread.h> #include <pthread.h>
#include "mifarehost.h" #include "mifarehost.h"
#include "proxmark3.h" #include "proxmark3.h"
#include "radixsort.h"
// MIFARE // MIFARE
int compar_int(const void * a, const void * b) { int compar_int(const void * a, const void * b) {
@ -21,16 +22,31 @@ int compar_int(const void * a, const void * b) {
//return (*(uint64_t*)b - *(uint64_t*)a); //return (*(uint64_t*)b - *(uint64_t*)a);
// better: // better:
if (*(uint64_t*)b == *(uint64_t*)a) return 0; // if (*(uint64_t*)b > *(uint64_t*)a) return 1;
else if (*(uint64_t*)b > *(uint64_t*)a) return 1; // if (*(uint64_t*)b < *(uint64_t*)a) return -1;
else return -1; // return 0;
return (*(uint64_t*)b > *(uint64_t*)a) - (*(uint64_t*)b < *(uint64_t*)a);
//return (*(int64_t*)b > *(int64_t*)a) - (*(int64_t*)b < *(int64_t*)a);
} }
// Compare 16 Bits out of cryptostate // Compare 16 Bits out of cryptostate
int Compare16Bits(const void * a, const void * b) { int Compare16Bits(const void * a, const void * b) {
if ((*(uint64_t*)b & 0x00ff000000ff0000) == (*(uint64_t*)a & 0x00ff000000ff0000)) return 0;
else if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1; // if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1;
else return -1; // if ((*(uint64_t*)b & 0x00ff000000ff0000) < (*(uint64_t*)a & 0x00ff000000ff0000)) return -1;
// return 0;
return
((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000))
-
((*(uint64_t*)b & 0x00ff000000ff0000) < (*(uint64_t*)a & 0x00ff000000ff0000))
;
// return
// ((*(int64_t*)b & 0x00ff000000ff0000) > (*(int64_t*)a & 0x00ff000000ff0000))
// -
// ((*(int64_t*)b & 0x00ff000000ff0000) < (*(int64_t*)a & 0x00ff000000ff0000))
// ;
} }
typedef typedef
@ -59,7 +75,9 @@ void* nested_worker_thread(void *arg)
StateList_t *statelist = arg; StateList_t *statelist = arg;
statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid); statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid);
for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++);
for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; ++p1);
statelist->len = p1 - statelist->head.slhead; statelist->len = p1 - statelist->head.slhead;
statelist->tail.sltail = --p1; statelist->tail.sltail = --p1;
qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits); qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits);
@ -72,26 +90,21 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
uint16_t i; uint16_t i;
uint32_t uid; uint32_t uid;
UsbCommand resp; UsbCommand resp;
StateList_t statelists[2]; StateList_t statelists[2];
struct Crypto1State *p1, *p2, *p3, *p4; struct Crypto1State *p1, *p2, *p3, *p4;
// flush queue
UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}}; UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};
memcpy(c.d.asBytes, key, 6); memcpy(c.d.asBytes, key, 6);
clearCommandBuffer(); clearCommandBuffer();
SendCommand(&c); SendCommand(&c);
if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1;
// error during nested // error during nested
if (resp.arg[0]) return resp.arg[0]; if (resp.arg[0]) return resp.arg[0];
memcpy(&uid, resp.d.asBytes, 4); memcpy(&uid, resp.d.asBytes, 4);
PrintAndLog("UID: %08x Block:%d Key: %c", uid, (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8) ?'A':'B' );
for (i = 0; i < 2; i++) { for (i = 0; i < 2; ++i) {
statelists[i].blockNo = resp.arg[2] & 0xff; statelists[i].blockNo = resp.arg[2] & 0xff;
statelists[i].keyType = (resp.arg[2] >> 8) & 0xff; statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;
statelists[i].uid = uid; statelists[i].uid = uid;
@ -100,18 +113,15 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
} }
// calc keys // calc keys
pthread_t thread_id[2]; pthread_t thread_id[2];
// create and run worker threads // create and run worker threads
for (i = 0; i < 2; i++) { for (i = 0; i < 2; i++)
pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]); pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);
}
// wait for threads to terminate: // wait for threads to terminate:
for (i = 0; i < 2; i++) { for (i = 0; i < 2; i++)
pthread_join(thread_id[i], (void*)&statelists[i].head.slhead); pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);
}
// the first 16 Bits of the cryptostate already contain part of our key. // the first 16 Bits of the cryptostate already contain part of our key.
@ -142,6 +152,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
while (Compare16Bits(p1, p2) == 1) p2++; while (Compare16Bits(p1, p2) == 1) p2++;
} }
} }
p3->even = 0; p3->odd = 0; p3->even = 0; p3->odd = 0;
p4->even = 0; p4->odd = 0; p4->even = 0; p4->odd = 0;
statelists[0].len = p3 - statelists[0].head.slhead; statelists[0].len = p3 - statelists[0].head.slhead;
@ -154,6 +165,12 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compar_int); qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compar_int);
qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compar_int); qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compar_int);
// clock_t t1 = clock();
//radixSort(statelists[0].head.keyhead, statelists[0].len);
//radixSort(statelists[1].head.keyhead, statelists[1].len);
// t1 = clock() - t1;
// PrintAndLog("radixsort, ticks %.0f", (float)t1);
uint64_t *p5, *p6, *p7; uint64_t *p5, *p6, *p7;
p5 = p7 = statelists[0].head.keyhead; p5 = p7 = statelists[0].head.keyhead;
p6 = statelists[1].head.keyhead; p6 = statelists[1].head.keyhead;
@ -168,38 +185,39 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
} }
} }
statelists[0].len = p7 - statelists[0].head.keyhead; statelists[0].len = p7 - statelists[0].head.keyhead;
statelists[0].tail.keytail=--p7; statelists[0].tail.keytail = --p7;
memset(resultKey, 0, 6); memset(resultKey, 0, 6);
uint64_t key64 = 0;
// The list may still contain several key candidates. Test each of them with mfCheckKeys // The list may still contain several key candidates. Test each of them with mfCheckKeys
for (i = 0; i < statelists[0].len; i++) { for (i = 0; i < statelists[0].len; i++) {
uint8_t keyBlock[6];
uint64_t key64;
crypto1_get_lfsr(statelists[0].head.slhead + i, &key64); crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);
num_to_bytes(key64, 6, keyBlock); num_to_bytes(key64, 6, resultKey);
key64 = 0;
if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) { if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, resultKey, &key64)) {
num_to_bytes(key64, 6, resultKey); free(statelists[0].head.slhead);
break; free(statelists[1].head.slhead);
PrintAndLog("UID: %08x target block:%3u key type: %c -- Found key [%012"llx"]", uid, (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8)?'B':'A', key64);
return -5;
} }
} }
PrintAndLog("UID: %08x target block:%3u key type: %c", uid, (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8)?'B':'A');
free(statelists[0].head.slhead); free(statelists[0].head.slhead);
free(statelists[1].head.slhead); free(statelists[1].head.slhead);
return 0; return -4;
} }
int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){
*key = 0; *key = 0;
UsbCommand c = {CMD_MIFARE_CHKKEYS, { (blockNo | (keyType<<8)), clear_trace, keycnt}};
UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType&0xff)<<8)), clear_trace, keycnt}};
memcpy(c.d.asBytes, keyBlock, 6 * keycnt); memcpy(c.d.asBytes, keyBlock, 6 * keycnt);
clearCommandBuffer(); clearCommandBuffer();
SendCommand(&c); SendCommand(&c);
UsbCommand resp; UsbCommand resp;
if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1; if (!WaitForResponseTimeout(CMD_ACK,&resp, 3000)) return 1;
if ((resp.arg[0] & 0xff) != 0x01) return 2; if ((resp.arg[0] & 0xff) != 0x01) return 2;
*key = bytes_to_num(resp.d.asBytes, 6); *key = bytes_to_num(resp.d.asBytes, 6);
return 0; return 0;
@ -238,13 +256,11 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_
uint8_t block0[16]; uint8_t block0[16];
memset(block0, 0x00, sizeof(block0)); memset(block0, 0x00, sizeof(block0));
int old = mfCGetBlock(0, block0, params); int old = mfCGetBlock(0, block0, params);
if (old == 0) { if (old == 0)
PrintAndLog("old block 0: %s", sprint_hex(block0, sizeof(block0))); PrintAndLog("old block 0: %s", sprint_hex(block0, sizeof(block0)));
} else { else
PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0."); PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0.");
}
// fill in the new values // fill in the new values
// UID // UID
@ -344,7 +360,7 @@ int isBlockEmpty(int blockN) {
} }
int isBlockTrailer(int blockN) { int isBlockTrailer(int blockN) {
return ((blockN & 0x03) == 0x03); return ((blockN & 0x03) == 0x03);
} }
int loadTraceCard(uint8_t *tuid) { int loadTraceCard(uint8_t *tuid) {
@ -440,19 +456,21 @@ void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool i
data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i]; data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];
} else { } else {
bt = 0; bt = 0;
for (i = 0; i < 4; i++) bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 0)) << 0;
bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i; bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 1)) << 1;
bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 2)) << 2;
bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 3)) << 3;
data[0] = bt; data[0] = bt;
} }
return; return;
} }
int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {
uint8_t data[64]; uint8_t data[64];
if (traceState == TRACE_ERROR) return 1; if (traceState == TRACE_ERROR) return 1;
if (len > 64) { if (len > 64) {
traceState = TRACE_ERROR; traceState = TRACE_ERROR;
return 1; return 1;
@ -637,7 +655,6 @@ int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data,
uint32_t ar_enc; // encrypted reader response uint32_t ar_enc; // encrypted reader response
uint32_t at_enc; // encrypted tag response uint32_t at_enc; // encrypted tag response
*/ */
struct Crypto1State *pcs = NULL; struct Crypto1State *pcs = NULL;
ks2 = ar_enc ^ prng_successor(nt, 64); ks2 = ar_enc ^ prng_successor(nt, 64);

View file

@ -23,10 +23,11 @@
struct Crypto1State * crypto1_create(uint64_t key) struct Crypto1State * crypto1_create(uint64_t key)
{ {
struct Crypto1State *s = malloc(sizeof(*s)); struct Crypto1State *s = malloc(sizeof(*s));
s->odd = s->even = 0; if ( !s ) return NULL;
int i;
for(i = 47;s && i > 0; i -= 2) { int i;
//for(i = 47;s && i > 0; i -= 2) {
for(i = 47; i > 0; i -= 2) {
s->odd = s->odd << 1 | BIT(key, (i - 1) ^ 7); s->odd = s->odd << 1 | BIT(key, (i - 1) ^ 7);
s->even = s->even << 1 | BIT(key, i ^ 7); s->even = s->even << 1 | BIT(key, i ^ 7);
} }

View file

@ -14,16 +14,6 @@
#include "ui.h" #include "ui.h"
#include "proxmark3.h" #include "proxmark3.h"
int compar_state(const void * a, const void * b) {
// didn't work: (the result is truncated to 32 bits)
//return (*(int64_t*)b - *(int64_t*)a);
// better:
if (*(int64_t*)b == *(int64_t*)a) return 0;
else if (*(int64_t*)b > *(int64_t*)a) return 1;
else return -1;
}
int nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint64_t par_info, uint64_t ks_info, uint64_t * key) { int nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint64_t par_info, uint64_t ks_info, uint64_t * key) {
struct Crypto1State *state; struct Crypto1State *state;

View file

@ -166,7 +166,6 @@ static void *main_loop(void *targ) {
if (ret == 99) if (ret == 99)
break; break;
} }
free(cmd);
} else { } else {
printf("\n"); printf("\n");
break; break;
@ -175,6 +174,8 @@ static void *main_loop(void *targ) {
write_history(".history"); write_history(".history");
free(cmd);
if (arg->usb_present == 1) { if (arg->usb_present == 1) {
rarg.run = 0; rarg.run = 0;
pthread_join(reader_thread, NULL); pthread_join(reader_thread, NULL);