]> git.zerfleddert.de Git - proxmark3-svn/commitdiff
Merge branch 'master' of https://github.com/iceman1001/proxmark3
authoriceman <iceman@iuse.se>
Sat, 16 Jan 2016 20:50:55 +0000 (21:50 +0100)
committericeman <iceman@iuse.se>
Sat, 16 Jan 2016 20:50:55 +0000 (21:50 +0100)
18 files changed:
armsrc/BigBuf.c
armsrc/aes.c
armsrc/appmain.c
armsrc/crapto1.c
armsrc/crypto1.c
armsrc/desfire_crypto.c
armsrc/epa.c
armsrc/iclass.c
armsrc/iso14443a.c
armsrc/legicrf.c
armsrc/mifarecmd.c
armsrc/mifaresniff.c
armsrc/mifareutil.c
client/cmdhfmf.c
client/mifarehost.c
client/nonce2key/crypto1.c
client/nonce2key/nonce2key.c
client/proxmark3.c

index da86e9d3ccdbd98c469ffa1b84acebbcdcd9413b..b3a9a1321ca0f9f4dfc492dcc4af01f55f7271bf 100644 (file)
@@ -27,7 +27,7 @@ static uint16_t BigBuf_hi = BIGBUF_SIZE;
 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
index a199d04b7dc8d48bacbf446de619406385320159..dc89a1cf0246ed9d5c78499b59d92caf394924d3 100644 (file)
@@ -1152,7 +1152,7 @@ int main()
     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
@@ -1160,7 +1160,7 @@ int main()
     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);
index 10db4a39f986d9b67eb904f3b3a15b60da19330b..3dfa526752b29a4c43a41d226f83a3d41b358b19 100644 (file)
@@ -57,19 +57,17 @@ void ToSendReset(void)
        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;
@@ -81,22 +79,20 @@ void ToSendStuffBit(int b)
 // 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);
@@ -108,28 +104,27 @@ void Dbprintf(const char *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;         
        }
 }
 
@@ -163,10 +158,9 @@ static int ReadAdc(int ch)
 
        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;
 }
 
@@ -175,15 +169,13 @@ int AvgAdc(int ch) // was static - merlok
        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
@@ -201,8 +193,9 @@ void MeasureAntennaTuning(void)
   
        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);
@@ -229,13 +222,11 @@ void MeasureAntennaTuning(void)
 
        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");
@@ -251,15 +242,13 @@ void MeasureAntennaTuningHf(void)
                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",
@@ -280,6 +269,7 @@ void SendVersion(void)
         * 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 {
@@ -292,6 +282,7 @@ void SendVersion(void)
 
        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);
 
@@ -333,8 +324,7 @@ void printUSBSpeed(void)
 /**
   * Prints runtime information about the PM3.
 **/
-void SendStatus(void)
-{
+void SendStatus(void) {
        BigBuf_print_status();
        Fpga_print_status();
        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]);
 
-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);
@@ -1400,9 +1388,8 @@ void  __attribute__((noreturn)) AppMain(void)
        for(;;) {
                if (usb_poll()) {
                        rx_len = usb_read(rx,sizeof(UsbCommand));
-                       if (rx_len) {
+                       if (rx_len)
                                UsbPacketReceived(rx,rx_len);
-                       }
                }
                WDT_HIT();
 
index 627cce4f4f0a7fbb13b4e59ad1cc66db96d22bc7..a6b6da4dbbfa31ccb4088099740da34b7118af2b 100644 (file)
@@ -24,9 +24,9 @@
 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
@@ -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\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
index a212ecc4cc79ce45de6da4337b4ecf6ec04f9f32..98d38b2bf2189ad4a65047e263669e6a67b53c84 100644 (file)
 #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)
 {
index 469a8ec46761a807978d376066269840a586a150..acce980f3b768e3fe48f4f24ef4fd1e416ccd44e 100644 (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);
 
             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;
index b89d495659d8171dc4b5a0c48497d1b5e9a049d2..3b4e341aa5d949f08b12b467e6ff2daee0bfed52 100644 (file)
@@ -102,7 +102,7 @@ static struct {
 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
index 101ca06088710b9182f69ddfa8c7cf92bdbb0074..dcb672e73515414d750155f215b2b866536b18e5 100644 (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)
 {
-  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)) {
 
@@ -1437,7 +1435,7 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int
     }
     WDT_HIT();
   }
-  if (samples) *samples = (c + *wait) << 3;
+  if (samples && wait) *samples = (c + *wait) << 3;
 }
 
 
index 1c4d0f05f35129c994deb0c178d1161ca887b4a3..8dbe9e81f714fb21c4cff3d43ca43086bfc0ce27 100644 (file)
@@ -106,8 +106,6 @@ static uint32_t NextTransferTime;
 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
@@ -127,13 +125,11 @@ void iso14a_set_trigger(bool enable) {
        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;
@@ -142,20 +138,22 @@ void iso14a_set_ATS_timeout(uint8_t *ats) {
        
        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
 //
@@ -1059,10 +1057,12 @@ void SimulateIso14443aTag(int tagType, int flags, byte_t* data)
                { .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
@@ -1112,6 +1112,9 @@ void SimulateIso14443aTag(int tagType, int flags, byte_t* data)
 
        LED_A_ON();
        for(;;) {
+               
+               WDT_HIT();
+               
                // Clean receive command buffer
                if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
                        DbpString("Button press");
@@ -1434,7 +1437,7 @@ void PrepareDelayedTransfer(uint16_t delay)
                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;
@@ -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)
                }
                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 {
@@ -1481,7 +1485,7 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
        for(;;) {
                if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
                        AT91C_BASE_SSC->SSC_THR = cmd[c];
-                       c++;
+                       ++c;
                        if(c >= len)
                                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_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;
@@ -1908,16 +1912,13 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
        }
 
        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
@@ -1928,40 +1929,41 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
 
                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;
@@ -1973,9 +1975,8 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
                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)
@@ -1986,6 +1987,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
 
                // Receive the SAK
                if (!ReaderReceive(resp, resp_par)) return 0;
+               
                sak = resp[0];
 
                // 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;
                }
 
-               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);
@@ -2021,7 +2022,6 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u
        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));
@@ -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,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);
@@ -2227,14 +2227,6 @@ void ReaderMifare(bool first_try, uint8_t block )
        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;
@@ -2248,49 +2240,62 @@ void ReaderMifare(bool first_try, uint8_t block )
        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
@@ -2300,12 +2305,12 @@ void ReaderMifare(bool first_try, uint8_t block )
                }
                
                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) {
@@ -2314,28 +2319,35 @@ void ReaderMifare(bool first_try, uint8_t block )
                        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:
@@ -2357,10 +2369,8 @@ void ReaderMifare(bool first_try, uint8_t block )
                }                       
 
                // 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);
@@ -2382,6 +2392,7 @@ void ReaderMifare(bool first_try, uint8_t block )
                                                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
@@ -2389,44 +2400,53 @@ void ReaderMifare(bool first_try, uint8_t block )
                                        } 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;
@@ -2474,15 +2494,20 @@ void ReaderMifare(bool first_try, uint8_t block )
        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};
@@ -2494,10 +2519,8 @@ void ReaderMifare(bool first_try, uint8_t block )
                
        cmd_send(CMD_ACK,isOK,0,0,buf,28);
 
-       // Thats it...
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
        LEDsoff();
-
        set_tracing(FALSE);
 }
 
index d9c94106e2f0fec21deede3e6d23fcd0e04455ad..5ad1fdf1f0c31895328f089847186405c2fec2cd 100644 (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)
 {
-   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++;
 }
 
@@ -354,9 +354,11 @@ int legic_read_byte(int byte_index, int cmd_sz) {
        frame_receive_rwd(&current_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;
        }
 
@@ -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) {
     //do not write UID, CRC, DCF
-    if(addr <= 0x06) { 
+    if(addr <= 0x06)
                return 0;
-       }
 
        //== send write command ==============================
        crc_clear(&legic_crc);
index a3ce6acf9595b6b7f9135503a8debb650f10f9b6..7fa3f525decc2960d933447563e5eea2e8a61e6e 100644 (file)
@@ -996,32 +996,26 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
        \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
index 3194f8d8c06a6510b4090db369b78a23c07a2ea2..fe57f42969ca3be8fa50d1fe9877077c8506e170 100644 (file)
 \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
index 1bc5454552aaf58d6bf5580426ce78520979be0a..20d4b68b7e99a9029ca31165797c77e9cca2be7a 100644 (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\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
@@ -185,8 +185,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
 \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
@@ -195,8 +194,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
        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
@@ -207,8 +205,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN
 \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
@@ -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.");\r
                return 3;\r
        }\r
-\r
        return 0;\r
 }\r
 \r
@@ -370,7 +366,7 @@ int mifare_ultra_auth(uint8_t *keybytes){
 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
@@ -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) \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
@@ -419,8 +415,7 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl
        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
@@ -431,8 +426,10 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl
        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
@@ -629,9 +626,8 @@ void emlClearMem(void) {
        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
index c5a86b5625f0d63a4c5e1173c7ee82eaf6ee5f54..d354952b10d8a2ab8d227c7f9b4ed92b4bb4dbe9 100644 (file)
@@ -63,7 +63,7 @@ start:
                }\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
@@ -96,14 +96,12 @@ start:
                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
@@ -575,7 +573,7 @@ int CmdHF14AMfNested(const char *Cmd)
        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
@@ -649,40 +647,35 @@ int CmdHF14AMfNested(const char *Cmd)
        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
@@ -697,14 +690,6 @@ int CmdHF14AMfNested(const char *Cmd)
                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
@@ -719,44 +704,47 @@ int CmdHF14AMfNested(const char *Cmd)
                                }\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
@@ -993,8 +981,7 @@ int CmdHF14AMfChk(const char *Cmd)
        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
@@ -1012,9 +999,8 @@ int CmdHF14AMfChk(const char *Cmd)
        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
@@ -1025,9 +1011,9 @@ int CmdHF14AMfChk(const char *Cmd)
                        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
@@ -1061,7 +1047,7 @@ int CmdHF14AMfChk(const char *Cmd)
                                }\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
@@ -1101,7 +1087,7 @@ int CmdHF14AMfChk(const char *Cmd)
                                        }\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
@@ -1118,7 +1104,7 @@ int CmdHF14AMfChk(const char *Cmd)
        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
@@ -1143,8 +1129,6 @@ int CmdHF14AMfChk(const char *Cmd)
                        // 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
@@ -1153,11 +1137,12 @@ int CmdHF14AMfChk(const char *Cmd)
                                \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
index 431db9dcd35c44f1a41e5fae84402a55d80be1bd..0987e1f2fa878bad6c41c3bc9f4f83b7ca99a829 100644 (file)
@@ -14,6 +14,7 @@
 #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
@@ -21,16 +22,31 @@ int compar_int(const void * a, const void * b) {
        //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
@@ -59,7 +75,9 @@ void* nested_worker_thread(void *arg)
        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
@@ -72,26 +90,21 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
        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
@@ -99,19 +112,16 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
                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
@@ -142,6 +152,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
                        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
@@ -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);\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
@@ -168,38 +185,39 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo
                }\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
@@ -237,14 +255,12 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_
        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
@@ -344,7 +360,7 @@ int isBlockEmpty(int blockN) {
 }\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
@@ -439,20 +455,22 @@ void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool i
                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
@@ -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\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
index e5a3fe73dc59ff2e8f53dee2d8a6273d2b8a6b96..ba297b8df262a7ff2510b73dd5e8e6b332a74296 100644 (file)
 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);
        }
index 99ede9e04426fadecdf9e47d1d83aa4a5164883d..2d0590df384bf27b7bcae53d36af315245472c69 100644 (file)
 #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;
index 83b582475da4bb2506b0e738580a9318f834d716..091f6d08a2f5b32b6c435cd4010aa62287f9d11a 100644 (file)
@@ -166,7 +166,6 @@ static void *main_loop(void *targ) {
                                if (ret == 99) 
                                        break;
                        }
-                       free(cmd);
                } else {
                        printf("\n");
                        break;
@@ -174,7 +173,9 @@ static void *main_loop(void *targ) {
        }
   
        write_history(".history");
-  
+
+       free(cmd);
+                       
        if (arg->usb_present == 1) {
                rarg.run = 0;
                pthread_join(reader_thread, NULL);
Impressum, Datenschutz