static uint8_t *emulator_memory = NULL;
// trace related variables
-static uint16_t traceLen = 0;
+static uint16_t traceLen;
int tracing = 1; //Last global one.. todo static?
// get the address of BigBuf
if( AesCtxIni(&ctx, iv, key, KEY128, CBC) < 0)
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");
// initialize context and decrypt cipher at other end
if( AesCtxIni(&ctx, iv, key, KEY128, CBC) < 0)
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("%s\n", databuf);
ToSendBit = 8;
}
-void ToSendStuffBit(int b)
-{
+void ToSendStuffBit(int b) {
if(ToSendBit >= 8) {
- ToSendMax++;
+ ++ToSendMax;
ToSend[ToSendMax] = 0;
ToSendBit = 0;
}
- if(b) {
+ if(b)
ToSend[ToSendMax] |= (1 << (7 - ToSendBit));
- }
- ToSendBit++;
+ ++ToSendBit;
if(ToSendMax >= sizeof(ToSend)) {
ToSendBit = 0;
// 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);
cmd_send(CMD_DEBUG_PRINT_STRING,len,0,0,(byte_t*)str,len);
}
#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);
}
#endif
void Dbprintf(const char *fmt, ...) {
-// should probably limit size here; oh well, let's just use a big buffer
- char output_string[128];
+ // should probably limit size here; oh well, let's just use a big buffer
+ char output_string[128] = {0x00};
va_list ap;
va_start(ap, fmt);
// prints HEX & ASCII
void Dbhexdump(int len, uint8_t *d, bool bAsci) {
- int l=0,i;
+ int l=0, i;
char ascii[9];
while (len>0) {
- if (len>8) l=8;
- else l=len;
+
+ l = (len>8) ? 8 : len;
memcpy(ascii,d,l);
ascii[l]=0;
// 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 (bAsci) {
+ if (bAsci)
Dbprintf("%-8s %*D",ascii,l,d," ");
- } else {
+ else
Dbprintf("%*D",l,d," ");
- }
- len-=8;
- d+=8;
+ len -= 8;
+ d += 8;
}
}
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];
-
return d;
}
int i;
int a = 0;
- for(i = 0; i < 32; i++) {
+ for(i = 0; i < 32; ++i)
a += ReadAdc(ch);
- }
return (a + 15) >> 5;
}
-void MeasureAntennaTuning(void)
-{
+void MeasureAntennaTuning(void) {
uint8_t LF_Results[256];
int i, adcval = 0, peak = 0, peakv = 0, peakf = 0; //ptr = 0
int vLf125 = 0, vLf134 = 0, vHf = 0; // in mV
FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
+
for (i=255; i>=19; i--) {
- WDT_HIT();
+ WDT_HIT();
FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i);
SpinDelay(20);
adcval = ((MAX_ADC_LF_VOLTAGE * AvgAdc(ADC_CHAN_LF)) >> 10);
cmd_send(CMD_MEASURED_ANTENNA_TUNING, vLf125 | (vLf134<<16), vHf, peakf | (peakv<<16), LF_Results, 256);
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
- LED_A_OFF();
- LED_B_OFF();
- return;
+
+ LEDsoff();
}
-void MeasureAntennaTuningHf(void)
-{
+void MeasureAntennaTuningHf(void) {
int vHf = 0; // in mV
DbpString("Measuring HF antenna, press button to exit");
Dbprintf("%d mV",vHf);
if (BUTTON_PRESS()) break;
}
+
DbpString("cancelled");
-
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
-
}
-void ReadMem(int addr)
-{
+void ReadMem(int addr) {
const uint8_t *data = ((uint8_t *)addr);
Dbprintf("%x: %02x %02x %02x %02x %02x %02x %02x %02x",
* pointer, then use it.
*/
char *bootrom_version = *(char**)&_bootphase1_version_pointer;
+
if( bootrom_version < &_flash_start || bootrom_version >= &_flash_end ) {
strcat(VersionString, "bootrom version information appears invalid\n");
} else {
FpgaGatherVersion(FPGA_BITSTREAM_LF, temp, sizeof(temp));
strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1);
+
FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp));
strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1);
/**
* Prints runtime information about the PM3.
**/
-void SendStatus(void)
-{
+void SendStatus(void) {
BigBuf_print_status();
Fpga_print_status();
printConfig(); //LF Sampling config
};
static const int LIGHT_LEN = sizeof(LIGHT_SCHEME)/sizeof(LIGHT_SCHEME[0]);
-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;
-
+void ListenReaderField(int limit) {
#define LF_ONLY 1
#define HF_ONLY 2
#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
FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
for(;;) {
if (usb_poll()) {
rx_len = usb_read(rx,sizeof(UsbCommand));
- if (rx_len) {
+ if (rx_len)
UsbPacketReceived(rx,rx_len);
- }
}
WDT_HIT();
static uint8_t filterlut[1 << 20];\r
static void __attribute__((constructor)) fill_lut()\r
{\r
- uint32_t i;\r
- for(i = 0; i < 1 << 20; ++i)\r
- filterlut[i] = filter(i);\r
+ uint32_t i;\r
+ for(i = 0; i < 1 << 20; ++i)\r
+ filterlut[i] = filter(i);\r
}\r
#define filter(x) (filterlut[(x) & 0xfffff])\r
#endif\r
* It returns a zero terminated list of possible cipher states after the\r
* tag nonce was fed in\r
*/\r
-\r
struct Crypto1State* lfsr_common_prefix(uint32_t pfx, uint32_t rr, uint8_t ks[8], uint8_t par[8][8])\r
{\r
struct Crypto1State *statelist, *s;\r
#include "crapto1.h"
#include <stdlib.h>
-
void crypto1_create(struct Crypto1State *s, uint64_t key)
{
// struct Crypto1State *s = malloc(sizeof(*s));
- s->odd = s->even = 0;
int i;
for(i = 47;s && i > 0; i -= 2) {
s->odd = s->odd << 1 | BIT(key, (i - 1) ^ 7);
s->even = s->even << 1 | BIT(key, i ^ 7);
}
- return;
}
void crypto1_destroy(struct Crypto1State *state)
{
cmac (key, DESFIRE (tag)->ivect, res, *nbytes, DESFIRE (tag)->cmac);
if (append_mac) {
- maced_data_length (key, *nbytes);
-
+ size_t len = maced_data_length (key, *nbytes);
+ ++len;
memcpy (res, data, *nbytes);
memcpy (res + *nbytes, DESFIRE (tag)->cmac, CMAC_LENGTH);
*nbytes += CMAC_LENGTH;
static uint8_t apdu_lengths_replay[5];
// 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
//-----------------------------------------------------------------------------
static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait)
{
- int c;
- FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
- AT91C_BASE_SSC->SSC_THR = 0x00;
- FpgaSetupSsc();
-
- if (wait)
- {
- if(*wait < 10) *wait = 10;
-
- for(c = 0; c < *wait;) {
- if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
- AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
- c++;
- }
- if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
- volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
- (void)r;
- }
- WDT_HIT();
- }
+ int c;
+ FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
+ AT91C_BASE_SSC->SSC_THR = 0x00;
+ FpgaSetupSsc();
- }
+ if (wait) {
+ if(*wait < 10) *wait = 10;
+
+ for(c = 0; c < *wait;) {
+ if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
+ AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
+ c++;
+ }
+ if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
+ volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
+ (void)r;
+ }
+ WDT_HIT();
+ }
+ }
- uint8_t sendbyte;
- bool firstpart = TRUE;
- c = 0;
+ uint8_t sendbyte;
+ bool firstpart = TRUE;
+ c = 0;
for(;;) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
}
WDT_HIT();
}
- if (samples) *samples = (c + *wait) << 3;
+ if (samples && wait) *samples = (c + *wait) << 3;
}
static uint32_t LastTimeProxToAirStart;
static uint32_t LastProxToAirDuration;
-
-
// CARD TO READER - manchester
// Sequence D: 11110000 modulation with subcarrier during first half
// Sequence E: 00001111 modulation with subcarrier during second half
trigger = enable;
}
-
void iso14a_set_timeout(uint32_t timeout) {
iso14a_timeout = timeout;
if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443A Timeout set to %ld (%dms)", iso14a_timeout, iso14a_timeout / 106);
}
-
void iso14a_set_ATS_timeout(uint8_t *ats) {
uint8_t tb1;
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] & 0x10) == 0x10) { // there is an interface byte TA(1) preceding TB(1)
+
+ if ((ats[1] & 0x10) == 0x10) // there is an interface byte TA(1) preceding TB(1)
tb1 = ats[3];
- } else {
+ 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 = 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/(8*16));
+ iso14a_set_timeout(fwt/128);
}
}
}
-
//-----------------------------------------------------------------------------
// Generate the parity value for a byte sequence
//
{ .response = response3a, .response_n = sizeof(response3a) }, // Acknowledge select - cascade 2
{ .response = response5, .response_n = sizeof(response5) }, // Authentication answer (random nonce)
{ .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 = 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
// Such a response is less time critical, so we can prepare them on the fly
LED_A_ON();
for(;;) {
+
+ WDT_HIT();
+
// Clean receive command buffer
if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
DbpString("Button press");
for (uint16_t i = 0; i < delay; i++) {
bitmask |= (0x01 << i);
}
- ToSend[ToSendMax++] = 0x00;
+ ToSend[++ToSendMax] = 0x00;
for (uint16_t i = 0; i < ToSendMax; i++) {
bits_to_shift = ToSend[i] & bitmask;
ToSend[i] = ToSend[i] >> delay;
PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
}
if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
+
while(GetCountSspClk() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
LastTimeProxToAirStart = *timing;
} else {
for(;;) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
AT91C_BASE_SSC->SSC_THR = cmd[c];
- c++;
+ ++c;
if(c >= len)
break;
}
uint8_t sel_all[] = { 0x93,0x20 };
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 resp[MAX_FRAME_SIZE]; // theoretically. A usual RATS will be much smaller
- uint8_t resp_par[MAX_PARITY_SIZE];
- byte_t uid_resp[4];
- size_t uid_resp_len;
+ uint8_t resp[MAX_FRAME_SIZE] = {0}; // theoretically. A usual RATS will be much smaller
+ uint8_t resp_par[MAX_PARITY_SIZE] = {0};
+ byte_t uid_resp[4] = {0};
+ size_t uid_resp_len = 0;
uint8_t sak = 0x04; // cascade uid
int cascade_level = 0;
}
if (anticollision) {
- // clear uid
- if (uid_ptr) {
- memset(uid_ptr,0,10);
- }
+ // clear uid
+ if (uid_ptr)
+ memset(uid_ptr,0,10);
}
// check for proprietary anticollision:
- if ((resp[0] & 0x1F) == 0) {
- return 3;
- }
+ if ((resp[0] & 0x1F) == 0) return 3;
// OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
// which case we need to make a cascade 2 request and select - this is a long UID
if (anticollision) {
// SELECT_ALL
- ReaderTransmit(sel_all, sizeof(sel_all), NULL);
- if (!ReaderReceive(resp, resp_par)) return 0;
-
- if (Demod.collisionPos) { // we had a collision and need to construct the UID bit by bit
- memset(uid_resp, 0, 4);
- uint16_t uid_resp_bits = 0;
- uint16_t collision_answer_offset = 0;
- // anti-collision-loop:
- while (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
- uint16_t UIDbit = (resp[i/8] >> (i % 8)) & 0x01;
- uid_resp[uid_resp_bits / 8] |= UIDbit << (uid_resp_bits % 8);
+ ReaderTransmit(sel_all, sizeof(sel_all), NULL);
+ if (!ReaderReceive(resp, resp_par)) return 0;
+
+ if (Demod.collisionPos) { // we had a collision and need to construct the UID bit by bit
+ memset(uid_resp, 0, 4);
+ uint16_t uid_resp_bits = 0;
+ uint16_t collision_answer_offset = 0;
+ // anti-collision-loop:
+ while (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
+ 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] |= 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
- 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];
+ // 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);
}
- 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;
- }
- // 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 { // no collision, use the response to SELECT_ALL as current uid
+ memcpy(uid_resp, resp, 4);
+ }
+
} else {
if (cascade_level < num_cascades - 1) {
uid_resp[0] = 0x88;
uid_resp_len = 4;
// calculate crypto UID. Always use last 4 Bytes.
- if(cuid_ptr) {
+ if(cuid_ptr)
*cuid_ptr = bytes_to_num(uid_resp, 4);
- }
// 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)
// Receive the SAK
if (!ReaderReceive(resp, resp_par)) return 0;
+
sak = resp[0];
// Test if more parts of the uid are coming
uid_resp_len = 3;
}
- if(uid_ptr && anticollision) {
+ if(uid_ptr && anticollision)
memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len);
- }
if(p_hi14a_card) {
memcpy(p_hi14a_card->uid + (cascade_level*3), uid_resp, uid_resp_len);
ReaderTransmit(rats, sizeof(rats), NULL);
if (!(len = ReaderReceive(resp, resp_par))) return 0;
-
if(p_hi14a_card) {
memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats));
//uint8_t mf_auth[] = { 0x60,0x05, 0x58, 0x2c };
uint8_t mf_auth[] = { 0x60,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;
AppendCrc14443a(mf_auth, 2);
uint8_t receivedAnswer[MAX_MIFARE_FRAME_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;
uint8_t par[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
static byte_t par_low = 0;
byte_t par_list[8] = {0x00};
byte_t ks_list[8] = {0x00};
- #define PRNG_SEQUENCE_LENGTH (1 << 16);
static uint32_t sync_time = 0;
static int32_t sync_cycles = 0;
int catch_up_cycles = 0;
int last_catch_up = 0;
- uint16_t elapsed_prng_sequences = 0;
+ uint16_t elapsed_prng_sequences = 1;
uint16_t consecutive_resyncs = 0;
int isOK = 0;
- if (first_try) {
- mf_nr_ar3 = 0;
- 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).
- nt_attacked = 0;
- par[0] = 0;
- }
- else {
- // we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same)
- mf_nr_ar3++;
- mf_nr_ar[3] = mf_nr_ar3;
- par[0] = par_low;
- }
-
- LED_A_ON();
- LED_B_OFF();
- LED_C_OFF();
-
-
+ #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][NUM_DEBUG_INFOS];
+ int32_t debug_info[MAX_STRATEGY+1][NUM_DEBUG_INFOS];
uint32_t select_time = 0;
uint32_t halt_time = 0;
-
- for(uint16_t i = 0; TRUE; ++i) {
+ //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) {
+ 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).
+ mf_nr_ar3 = 0;
+ nt_attacked = 0;
+ par[0] = 0;
+ } else {
+ // we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same)
+ mf_nr_ar3++;
+ mf_nr_ar[3] = mf_nr_ar3;
+ par[0] = par_low;
+ }
- LED_C_ON();
+ LED_C_ON();
+ for(uint16_t i = 0; TRUE; ++i) {
+
WDT_HIT();
// Test if the action was cancelled
}
if (strategy == 2) {
- // test with additional hlt command
+ // test with additional halt command
halt_time = 0;
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) {
SpinDelay(200);
iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
SpinDelay(100);
+ sync_time = GetCountSspClk() & 0xfffffff8;
WDT_HIT();
}
- if(!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {
- if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card");
+ if (!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {
+ if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card\n");
continue;
}
- select_time = GetCountSspClk();
+ select_time = GetCountSspClk() & 0xfffffff8;
elapsed_prng_sequences = 1;
+
if (debug_info_nr == -1) {
+
sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles;
catch_up_cycles = 0;
-
+
// if we missed the sync time already, advance to the next nonce repeat
+ WDT_HIT();
while(GetCountSspClk() > sync_time) {
- elapsed_prng_sequences++;
+ ++elapsed_prng_sequences;
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)
- 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 {
// collect some information on tag nonces for debugging:
}
// Receive the (4 Byte) "random" nonce
- if (!ReaderReceive(receivedAnswer, receivedAnswerPar)) {
- if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Couldn't receive tag nonce");
+ if (!ReaderReceive(receivedAnswer, receivedAnswerPar))
continue;
- }
previous_nt = nt;
nt = bytes_to_num(receivedAnswer, 4);
continue; // continue trying...
}
}
+
if (++sync_tries > MAX_SYNC_TRIES) {
if (strategy > MAX_STRATEGY || MF_DBGLEVEL < 3) {
isOK = -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
} else { // continue for a while, just to collect some debug info
++debug_info_nr;
debug_info[strategy][debug_info_nr] = nt_distance;
- if (debug_info_nr == NUM_DEBUG_INFOS) {
+ if (debug_info_nr == NUM_DEBUG_INFOS-1) {
++strategy;
debug_info_nr = 0;
}
continue;
}
}
+
sync_cycles = (sync_cycles - nt_distance/elapsed_prng_sequences);
- if (sync_cycles <= 0) {
+ if (sync_cycles <= 0)
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);
- }
+
continue;
}
}
if ((nt != nt_attacked) && nt_attacked) { // we somehow lost sync. Try to catch up again...
+
catch_up_cycles = -dist_nt(nt_attacked, nt);
if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one.
catch_up_cycles = 0;
continue;
}
+
+ // average?
catch_up_cycles /= elapsed_prng_sequences;
+
if (catch_up_cycles == last_catch_up) {
++consecutive_resyncs;
- }
- else {
+ } else {
last_catch_up = catch_up_cycles;
consecutive_resyncs = 0;
}
+ sync_cycles += catch_up_cycles;
+
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);
- }
- else {
- sync_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. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, -catch_up_cycles, consecutive_resyncs);
+ } else {
+ 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);
+
last_catch_up = 0;
catch_up_cycles = 0;
consecutive_resyncs = 0;
mf_nr_ar[3] &= 0x1F;
WDT_HIT();
-
+
if (isOK == -4) {
- if (MF_DBGLEVEL >= 3) {
- for (uint16_t i = 0; i <= MAX_STRATEGY; ++i) {
- for(uint16_t j = 0; j < NUM_DEBUG_INFOS; ++j) {
- Dbprintf("collected debug info[%d][%d] = %d", i, j, debug_info[i][j]);
- }
- }
- }
+ for (uint16_t i = 0; i < MAX_STRATEGY+1; ++i)
+ for(uint16_t j = 0; j < NUM_DEBUG_INFOS; ++j)
+ Dbprintf("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};
cmd_send(CMD_ACK,isOK,0,0,buf,28);
- // Thats it...
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff();
-
set_tracing(FALSE);
}
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 */
- f->data |= (bit<<f->bits);
+ f->data |= (bit << f->bits);
f->bits++;
}
frame_receive_rwd(¤t_frame, 12, 1);
byte = current_frame.data & 0xff;
+
if( LegicCRC(byte_index, byte, cmd_sz) != (current_frame.data >> 8) ) {
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;
}
*/
int legic_write_byte(int byte, int addr, int addr_sz) {
//do not write UID, CRC, DCF
- if(addr <= 0x06) {
+ if(addr <= 0x06)
return 0;
- }
//== send write command ==============================
crc_clear(&legic_crc);
\r
set_tracing(TRUE);\r
\r
- for (i = 0; i < keyCount; i++) {\r
- if(mifare_classic_halt(pcs, cuid)) {\r
+ for (i = 0; i < keyCount; ++i) {\r
+ if (mifare_classic_halt(pcs, cuid))\r
if (MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Halt error");\r
- }\r
\r
- if(!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {\r
+ if (!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {\r
if (OLD_MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Can't select card");\r
break;\r
- };\r
+ }\r
\r
ui64Key = bytes_to_num(datain + i * 6, 6);\r
- if(mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST)) {\r
+ if (mifare_classic_auth(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST))\r
continue;\r
- };\r
\r
isOK = 1;\r
break;\r
}\r
- \r
- // ----------------------------- crypto1 destroy\r
crypto1_destroy(pcs);\r
\r
LED_B_ON();\r
cmd_send(CMD_ACK,isOK,0,0,datain + i * 6,6);\r
- LED_B_OFF();\r
-\r
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);\r
LEDsoff();\r
set_tracing(FALSE);\r
\r
static int sniffState = SNF_INIT;\r
static uint8_t sniffUIDType;\r
-static uint8_t sniffUID[8] = {0x00};\r
-static uint8_t sniffATQA[2] = {0x00};\r
+static uint8_t sniffUID[8];\r
+static uint8_t sniffATQA[2];\r
static uint8_t sniffSAK;\r
-static uint8_t sniffBuf[16] = {0x00};\r
-static uint32_t timerData = 0;\r
+static uint8_t sniffBuf[16];\r
+static uint32_t timerData;\r
\r
\r
bool MfSniffInit(void){\r
uint32_t nt, ntpp; // Supplied tag nonce\r
\r
uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };\r
- uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
- uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
+ uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};\r
+ uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};\r
\r
// Transmit MIFARE_CLASSIC_AUTH\r
len = mifare_sendcmd_short(pcs, isNested, 0x60 + (keyType & 0x01), blockNo, receivedAnswer, receivedAnswerPar, timing);\r
\r
// Generate (encrypted) nr+parity by loading it into the cipher (Nr)\r
par[0] = 0;\r
- for (pos = 0; pos < 4; pos++)\r
- {\r
+ for (pos = 0; pos < 4; pos++) {\r
mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos];\r
par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos));\r
} \r
nt = prng_successor(nt,32);\r
\r
// ar+parity\r
- for (pos = 4; pos < 8; pos++)\r
- {\r
+ for (pos = 4; pos < 8; pos++) {\r
nt = prng_successor(nt,8);\r
mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff);\r
par[0] |= (((filter(pcs->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7-pos));\r
\r
// Receive 4 byte tag answer\r
len = ReaderReceive(receivedAnswer, receivedAnswerPar);\r
- if (!len)\r
- {\r
+ if (!len) {\r
if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout.");\r
return 2;\r
}\r
if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Error card response.");\r
return 3;\r
}\r
-\r
return 0;\r
}\r
\r
int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData)\r
{\r
uint16_t len;\r
- uint8_t bt[2];\r
+ uint8_t bt[2] = {0x00};\r
uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00};\r
uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00};\r
\r
int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) \r
{\r
// variables\r
- uint16_t len, i; \r
+ uint16_t len; \r
uint32_t pos = 0;\r
uint8_t par[3] = {0x00}; // enough for 18 Bytes to send\r
byte_t res = 0;\r
AppendCrc14443a(d_block, 16);\r
\r
// crypto\r
- for (pos = 0; pos < 18; pos++)\r
- {\r
+ for (pos = 0; pos < 18; pos++) {\r
d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos];\r
par[pos>>3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos&0x0007)));\r
} \r
len = ReaderReceive(receivedAnswer, receivedAnswerPar); \r
\r
res = 0;\r
- for (i = 0; i < 4; i++)\r
- res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], i)) << i;\r
+ res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 0)) << 0;\r
+ res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 1)) << 1;\r
+ res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 2)) << 2;\r
+ res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 3)) << 3;\r
\r
if ((len != 1) || (res != 0x0A)) {\r
if (MF_DBGLEVEL >= 1) Dbprintf("Cmd send data2 Error: %02x", res); \r
memset(emCARD, 0, CARD_MEMORY_SIZE);\r
\r
// fill sectors trailer data\r
- for(b = 3; b < 256; b<127?(b+=4):(b+=16)) {\r
+ for(b = 3; b < 256; b<127?(b+=4):(b+=16))\r
emlSetMem((uint8_t *)trailer, b , 1);\r
- } \r
\r
// uid\r
emlSetMem((uint8_t *)uid, 0, 1);\r
}\r
\r
UsbCommand resp;\r
- if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) {\r
+ if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) {\r
isOK = resp.arg[0];\r
uid = (uint32_t)bytes_to_num(resp.d.asBytes + 0, 4);\r
nt = (uint32_t)bytes_to_num(resp.d.asBytes + 4, 4);\r
c.arg[0] = false;\r
goto start;\r
} else {\r
- isOK = 0;\r
- printf("------------------------------------------------------------------\n");\r
PrintAndLog("Found valid key: %012"llx" \n", r_key);\r
}\r
+ \r
t1 = clock() - t1;\r
- if ( t1 > 0 ){\r
+ if ( t1 > 0 )\r
PrintAndLog("Time in darkside: %.0f ticks - %4.2f sec\n", (float)t1, ((float)t1)/CLOCKS_PER_SEC);\r
- }\r
return 0;\r
}\r
\r
uint8_t trgKeyType = 0;\r
uint8_t SectorsCnt = 0;\r
uint8_t key[6] = {0, 0, 0, 0, 0, 0};\r
- uint8_t keyBlock[14*6];\r
+ uint8_t keyBlock[6*6];\r
uint64_t key64 = 0;\r
bool transferToEml = false;\r
\r
transferToEml |= (ctmp == 'd' || ctmp == 'D');\r
\r
if (cmdp == 'o') {\r
- PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A');\r
int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true);\r
- if (isOK) {\r
- switch (isOK) {\r
- case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;\r
- case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;\r
- case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;\r
- default : PrintAndLog("Unknown Error.\n");\r
- }\r
- return 2;\r
- }\r
- key64 = bytes_to_num(keyBlock, 6);\r
- if (key64) {\r
- PrintAndLog("Found valid key:%012"llx, key64);\r
-\r
- // transfer key to the emulator\r
- if (transferToEml) {\r
- uint8_t sectortrailer;\r
- if (trgBlockNo < 32*4) { // 4 block sector\r
- sectortrailer = (trgBlockNo & 0x03) + 3;\r
- } else { // 16 block sector\r
- sectortrailer = (trgBlockNo & 0x0f) + 15;\r
+ switch (isOK) {\r
+ case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;\r
+ case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;\r
+ case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;\r
+ case -4 : PrintAndLog("No valid key found"); break;\r
+ case -5 : \r
+ key64 = bytes_to_num(keyBlock, 6);\r
+\r
+ // transfer key to the emulator\r
+ if (transferToEml) {\r
+ uint8_t sectortrailer;\r
+ if (trgBlockNo < 32*4) { // 4 block sector\r
+ sectortrailer = (trgBlockNo & 0x03) + 3;\r
+ } else { // 16 block sector\r
+ sectortrailer = (trgBlockNo & 0x0f) + 15;\r
+ }\r
+ mfEmlGetMem(keyBlock, sectortrailer, 1);\r
+ \r
+ if (!trgKeyType)\r
+ num_to_bytes(key64, 6, keyBlock);\r
+ else\r
+ num_to_bytes(key64, 6, &keyBlock[10]);\r
+ mfEmlSetMem(keyBlock, sectortrailer, 1); \r
}\r
- mfEmlGetMem(keyBlock, sectortrailer, 1);\r
- \r
- if (!trgKeyType)\r
- num_to_bytes(key64, 6, keyBlock);\r
- else\r
- num_to_bytes(key64, 6, &keyBlock[10]);\r
- mfEmlSetMem(keyBlock, sectortrailer, 1); \r
- }\r
- } else {\r
- PrintAndLog("No valid key found");\r
+ return 0;\r
+ default : PrintAndLog("Unknown Error.\n");\r
}\r
+ return 2;\r
}\r
else { // ------------------------------------ multiple sectors working\r
clock_t t1 = clock();\r
num_to_bytes(0xa0a1a2a3a4a5, 6, (uint8_t*)(keyBlock + 3 * 6));\r
num_to_bytes(0xb0b1b2b3b4b5, 6, (uint8_t*)(keyBlock + 4 * 6));\r
num_to_bytes(0xaabbccddeeff, 6, (uint8_t*)(keyBlock + 5 * 6));\r
- num_to_bytes(0x4d3a99c351dd, 6, (uint8_t*)(keyBlock + 6 * 6));\r
- num_to_bytes(0x1a982c7e459a, 6, (uint8_t*)(keyBlock + 7 * 6));\r
- num_to_bytes(0xd3f7d3f7d3f7, 6, (uint8_t*)(keyBlock + 8 * 6));\r
- num_to_bytes(0x714c5c886e97, 6, (uint8_t*)(keyBlock + 9 * 6));\r
- num_to_bytes(0x587ee5f9350f, 6, (uint8_t*)(keyBlock + 10 * 6));\r
- num_to_bytes(0xa0478cc39091, 6, (uint8_t*)(keyBlock + 11 * 6));\r
- num_to_bytes(0x533cb6c723f6, 6, (uint8_t*)(keyBlock + 12 * 6));\r
- num_to_bytes(0x8fd0a4f256e9, 6, (uint8_t*)(keyBlock + 13 * 6));\r
\r
PrintAndLog("Testing known keys. Sector count=%d", SectorsCnt);\r
for (i = 0; i < SectorsCnt; i++) {\r
}\r
}\r
}\r
+ clock_t t2 = clock() - t1;\r
+ if ( t2 > 0 )\r
+ PrintAndLog("Time to check 6 known keys: %.0f ticks %4.2f sec", (float)t2, ((float)t2)/CLOCKS_PER_SEC);\r
+ \r
\r
// nested sectors\r
iterations = 0;\r
- PrintAndLog("nested...");\r
+ PrintAndLog("enter nested...");\r
bool calibrate = true;\r
for (i = 0; i < NESTED_SECTOR_RETRY; i++) {\r
- for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; sectorNo++) {\r
- for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) { \r
+ for (uint8_t sectorNo = 0; sectorNo < SectorsCnt; ++sectorNo) {\r
+ for (trgKeyType = 0; trgKeyType < 2; ++trgKeyType) { \r
+\r
if (e_sector[sectorNo].foundKey[trgKeyType]) continue;\r
- PrintAndLog("-----------------------------------------------");\r
- int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate);\r
- if(isOK) {\r
- switch (isOK) {\r
- case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;\r
- case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;\r
- case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;\r
- default : PrintAndLog("Unknown Error.\n");\r
- }\r
- free(e_sector);\r
- return 2;\r
- } else {\r
- calibrate = false;\r
- }\r
\r
- iterations++;\r
-\r
- key64 = bytes_to_num(keyBlock, 6);\r
- if (key64) {\r
- PrintAndLog("Found valid key:%012"llx, key64);\r
- e_sector[sectorNo].foundKey[trgKeyType] = 1;\r
- e_sector[sectorNo].Key[trgKeyType] = key64;\r
+ int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate);\r
+ switch (isOK) {\r
+ case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break;\r
+ case -2 : PrintAndLog("Button pressed. Aborted.\n"); break;\r
+ case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break;\r
+ case -4 : //key not found\r
+ calibrate = false;\r
+ iterations++;\r
+ continue; \r
+ case -5 :\r
+ calibrate = false;\r
+ iterations++;\r
+ e_sector[sectorNo].foundKey[trgKeyType] = 1;\r
+ e_sector[sectorNo].Key[trgKeyType] = bytes_to_num(keyBlock, 6);\r
+ continue;\r
+ \r
+ default : PrintAndLog("Unknown Error.\n");\r
}\r
+ free(e_sector);\r
+ return 2;\r
}\r
}\r
}\r
\r
// 20160116 If Sector A is found, but not Sector B, try just reading it of the tag?\r
- PrintAndLog("testing to read B...");\r
+ PrintAndLog("trying to read key B...");\r
for (i = 0; i < SectorsCnt; i++) {\r
// KEY A but not KEY B\r
if ( e_sector[i].foundKey[0] && !e_sector[i].foundKey[1] ) {\r
keyBlock = calloc(stKeyBlock, 6);\r
if (keyBlock == NULL) return 1;\r
\r
- uint64_t defaultKeys[] =\r
- {\r
+ uint64_t defaultKeys[] = {\r
0xffffffffffff, // Default key (first key used by program if no user defined key)\r
0x000000000000, // Blank key\r
0xa0a1a2a3a4a5, // NFCForum MAD key\r
int defaultKeysSize = sizeof(defaultKeys) / sizeof(uint64_t);\r
\r
for (int defaultKeyCounter = 0; defaultKeyCounter < defaultKeysSize; defaultKeyCounter++)\r
- {\r
num_to_bytes(defaultKeys[defaultKeyCounter], 6, (uint8_t*)(keyBlock + defaultKeyCounter * 6));\r
- }\r
+\r
\r
if (param_getchar(Cmd, 0)=='*') {\r
blockNo = 3;\r
case '4': SectorsCnt = 40; break;\r
default: SectorsCnt = 16;\r
}\r
- }\r
- else\r
+ } else {\r
blockNo = param_get8(Cmd, 0);\r
+ }\r
\r
ctmp = param_getchar(Cmd, 1);\r
switch (ctmp) { \r
}\r
keyBlock = p;\r
}\r
- PrintAndLog("chk key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,\r
+ PrintAndLog("check key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,\r
(keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2],\r
(keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);\r
keycnt++;\r
}\r
memset(keyBlock + 6 * keycnt, 0, 6);\r
num_to_bytes(strtoll(buf, NULL, 16), 6, keyBlock + 6*keycnt);\r
- PrintAndLog("chk custom key[%2d] %012"llx, keycnt, bytes_to_num(keyBlock + 6*keycnt, 6));\r
+ PrintAndLog("check custom key[%2d] %012"llx, keycnt, bytes_to_num(keyBlock + 6*keycnt, 6));\r
keycnt++;\r
memset(buf, 0, sizeof(buf));\r
}\r
if (keycnt == 0) {\r
PrintAndLog("No key specified, trying default keys");\r
for (;keycnt < defaultKeysSize; keycnt++)\r
- PrintAndLog("chk default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,\r
+ PrintAndLog("check default key[%2d] %02x%02x%02x%02x%02x%02x", keycnt,\r
(keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2],\r
(keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6);\r
}\r
// skip already found keys.\r
if (e_sector[i].foundKey[trgKeyType]) continue;\r
\r
- PrintAndLog("--sector:%2d, block:%3d, key type:%C, key count:%2d ", i, b, trgKeyType ? 'B':'A', keycnt);\r
- \r
uint32_t max_keys = keycnt > (USB_CMD_DATA_SIZE/6) ? (USB_CMD_DATA_SIZE/6) : keycnt;\r
\r
for (uint32_t c = 0; c < keycnt; c += max_keys) {\r
\r
res = mfCheckKeys(b, trgKeyType, true, size, &keyBlock[6*c], &key64);\r
if (!res) {\r
- PrintAndLog("Found valid key:[%012"llx"]",key64); \r
+ PrintAndLog("Sector:%3d Block:%3d, key type: %C -- Found key [%012"llx"]", i, b, trgKeyType ? 'B':'A', key64);\r
+ \r
e_sector[i].Key[trgKeyType] = key64;\r
e_sector[i].foundKey[trgKeyType] = TRUE;\r
break;\r
- } else {\r
+ } else { \r
e_sector[i].Key[trgKeyType] = 0xffffffffffff;\r
e_sector[i].foundKey[trgKeyType] = FALSE;\r
}\r
#include <pthread.h>\r
#include "mifarehost.h"\r
#include "proxmark3.h"\r
+#include "radixsort.h"\r
\r
// MIFARE\r
int compar_int(const void * a, const void * b) {\r
//return (*(uint64_t*)b - *(uint64_t*)a);\r
\r
// better:\r
- if (*(uint64_t*)b == *(uint64_t*)a) return 0;\r
- else if (*(uint64_t*)b > *(uint64_t*)a) return 1;\r
- else return -1;\r
+ // if (*(uint64_t*)b > *(uint64_t*)a) return 1;\r
+ // if (*(uint64_t*)b < *(uint64_t*)a) return -1;\r
+ // return 0;\r
+\r
+ return (*(uint64_t*)b > *(uint64_t*)a) - (*(uint64_t*)b < *(uint64_t*)a);\r
+ //return (*(int64_t*)b > *(int64_t*)a) - (*(int64_t*)b < *(int64_t*)a);\r
}\r
\r
// Compare 16 Bits out of cryptostate\r
int Compare16Bits(const void * a, const void * b) {\r
- if ((*(uint64_t*)b & 0x00ff000000ff0000) == (*(uint64_t*)a & 0x00ff000000ff0000)) return 0;\r
- else if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1;\r
- else return -1;\r
+\r
+ // if ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000)) return 1; \r
+ // if ((*(uint64_t*)b & 0x00ff000000ff0000) < (*(uint64_t*)a & 0x00ff000000ff0000)) return -1; \r
+ // return 0;\r
+\r
+ return \r
+ ((*(uint64_t*)b & 0x00ff000000ff0000) > (*(uint64_t*)a & 0x00ff000000ff0000))\r
+ -\r
+ ((*(uint64_t*)b & 0x00ff000000ff0000) < (*(uint64_t*)a & 0x00ff000000ff0000))\r
+ ;\r
+ // return \r
+ // ((*(int64_t*)b & 0x00ff000000ff0000) > (*(int64_t*)a & 0x00ff000000ff0000))\r
+ // -\r
+ // ((*(int64_t*)b & 0x00ff000000ff0000) < (*(int64_t*)a & 0x00ff000000ff0000))\r
+ // ;\r
}\r
\r
typedef \r
StateList_t *statelist = arg;\r
\r
statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid);\r
- for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++);\r
+ \r
+ for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; ++p1);\r
+ \r
statelist->len = p1 - statelist->head.slhead;\r
statelist->tail.sltail = --p1;\r
qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits);\r
uint16_t i;\r
uint32_t uid;\r
UsbCommand resp;\r
-\r
StateList_t statelists[2];\r
struct Crypto1State *p1, *p2, *p3, *p4;\r
\r
- // flush queue\r
- \r
UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}};\r
memcpy(c.d.asBytes, key, 6);\r
clearCommandBuffer();\r
SendCommand(&c);\r
-\r
if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1;\r
\r
// error during nested\r
if (resp.arg[0]) return resp.arg[0];\r
\r
memcpy(&uid, resp.d.asBytes, 4);\r
- PrintAndLog("UID: %08x Block:%d Key: %c", uid, (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8) ?'A':'B' );\r
\r
- for (i = 0; i < 2; i++) {\r
+ for (i = 0; i < 2; ++i) {\r
statelists[i].blockNo = resp.arg[2] & 0xff;\r
statelists[i].keyType = (resp.arg[2] >> 8) & 0xff;\r
statelists[i].uid = uid;\r
memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4);\r
}\r
\r
- // calc keys\r
- \r
+ // calc keys \r
pthread_t thread_id[2];\r
\r
// create and run worker threads\r
- for (i = 0; i < 2; i++) {\r
+ for (i = 0; i < 2; i++)\r
pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]);\r
- }\r
\r
// wait for threads to terminate:\r
- for (i = 0; i < 2; i++) {\r
+ for (i = 0; i < 2; i++)\r
pthread_join(thread_id[i], (void*)&statelists[i].head.slhead);\r
- }\r
\r
\r
// the first 16 Bits of the cryptostate already contain part of our key.\r
while (Compare16Bits(p1, p2) == 1) p2++;\r
}\r
}\r
+ \r
p3->even = 0; p3->odd = 0;\r
p4->even = 0; p4->odd = 0;\r
statelists[0].len = p3 - statelists[0].head.slhead;\r
qsort(statelists[0].head.keyhead, statelists[0].len, sizeof(uint64_t), compar_int);\r
qsort(statelists[1].head.keyhead, statelists[1].len, sizeof(uint64_t), compar_int);\r
\r
+ // clock_t t1 = clock();\r
+ //radixSort(statelists[0].head.keyhead, statelists[0].len);\r
+ //radixSort(statelists[1].head.keyhead, statelists[1].len);\r
+ // t1 = clock() - t1; \r
+ // PrintAndLog("radixsort, ticks %.0f", (float)t1);\r
+\r
uint64_t *p5, *p6, *p7;\r
p5 = p7 = statelists[0].head.keyhead; \r
p6 = statelists[1].head.keyhead;\r
}\r
}\r
statelists[0].len = p7 - statelists[0].head.keyhead;\r
- statelists[0].tail.keytail=--p7;\r
+ statelists[0].tail.keytail = --p7;\r
\r
memset(resultKey, 0, 6);\r
+ uint64_t key64 = 0;\r
+\r
// The list may still contain several key candidates. Test each of them with mfCheckKeys\r
for (i = 0; i < statelists[0].len; i++) {\r
- uint8_t keyBlock[6];\r
- uint64_t key64;\r
+\r
crypto1_get_lfsr(statelists[0].head.slhead + i, &key64);\r
- num_to_bytes(key64, 6, keyBlock);\r
- key64 = 0;\r
- if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, keyBlock, &key64)) {\r
- num_to_bytes(key64, 6, resultKey);\r
- break;\r
+ num_to_bytes(key64, 6, resultKey);\r
+\r
+ if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, 1, resultKey, &key64)) {\r
+ free(statelists[0].head.slhead);\r
+ free(statelists[1].head.slhead);\r
+ 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);\r
+ return -5;\r
}\r
}\r
- \r
+ PrintAndLog("UID: %08x target block:%3u key type: %c", uid, (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8)?'B':'A'); \r
free(statelists[0].head.slhead);\r
- free(statelists[1].head.slhead); \r
- return 0;\r
+ free(statelists[1].head.slhead);\r
+ return -4;\r
}\r
\r
int mfCheckKeys (uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){\r
\r
*key = 0;\r
-\r
- UsbCommand c = {CMD_MIFARE_CHKKEYS, {((blockNo & 0xff) | ((keyType&0xff)<<8)), clear_trace, keycnt}};\r
+ UsbCommand c = {CMD_MIFARE_CHKKEYS, { (blockNo | (keyType<<8)), clear_trace, keycnt}};\r
memcpy(c.d.asBytes, keyBlock, 6 * keycnt);\r
- \r
clearCommandBuffer();\r
SendCommand(&c);\r
UsbCommand resp;\r
- if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) return 1;\r
+ if (!WaitForResponseTimeout(CMD_ACK,&resp, 3000)) return 1;\r
if ((resp.arg[0] & 0xff) != 0x01) return 2;\r
*key = bytes_to_num(resp.d.asBytes, 6);\r
return 0;\r
uint8_t params = MAGIC_SINGLE;\r
uint8_t block0[16];\r
memset(block0, 0x00, sizeof(block0));\r
- \r
\r
int old = mfCGetBlock(0, block0, params);\r
- if (old == 0) {\r
+ if (old == 0)\r
PrintAndLog("old block 0: %s", sprint_hex(block0, sizeof(block0)));\r
- } else {\r
- PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0.");\r
- }\r
+ else \r
+ PrintAndLog("Couldn't get old data. Will write over the last bytes of Block 0."); \r
\r
// fill in the new values\r
// UID\r
}\r
\r
int isBlockTrailer(int blockN) {\r
- return ((blockN & 0x03) == 0x03);\r
+ return ((blockN & 0x03) == 0x03);\r
}\r
\r
int loadTraceCard(uint8_t *tuid) {\r
for (i = 0; i < len; i++)\r
data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i];\r
} else {\r
- bt = 0;\r
- for (i = 0; i < 4; i++)\r
- bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], i)) << i;\r
- \r
+ bt = 0; \r
+ bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 0)) << 0;\r
+ bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 1)) << 1;\r
+ bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 2)) << 2;\r
+ bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 3)) << 3; \r
data[0] = bt;\r
}\r
return;\r
}\r
\r
-\r
int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) {\r
+ \r
uint8_t data[64];\r
\r
if (traceState == TRACE_ERROR) return 1;\r
+ \r
if (len > 64) {\r
traceState = TRACE_ERROR;\r
return 1;\r
uint32_t ar_enc; // encrypted reader response\r
uint32_t at_enc; // encrypted tag response\r
*/\r
-\r
struct Crypto1State *pcs = NULL;\r
\r
ks2 = ar_enc ^ prng_successor(nt, 64);\r
struct Crypto1State * crypto1_create(uint64_t key)
{
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) {
+ //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->even = s->even << 1 | BIT(key, i ^ 7);
}
#include "ui.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) {
struct Crypto1State *state;
if (ret == 99)
break;
}
- free(cmd);
} else {
printf("\n");
break;
}
write_history(".history");
-
+
+ free(cmd);
+
if (arg->usb_present == 1) {
rarg.run = 0;
pthread_join(reader_thread, NULL);