diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index 7b49c0619..b6c9e544d 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -19,7 +19,7 @@ static uint32_t BigBuf[BIGBUF_SIZE/sizeof(uint32_t)]; Pointer to highest available memory: BigBuf_hi high BIGBUF_SIZE - reserved = BigBuf_malloc() subtracts amount from BigBuf_hi, + reserved = BigBuf_malloc() subtracts amount from BigBuf_hi, low 0x00 */ @@ -43,7 +43,7 @@ uint8_t *BigBuf_get_EM_addr(void) { // not yet allocated if (emulator_memory == NULL) emulator_memory = BigBuf_malloc(CARD_MEMORY_SIZE); - + return emulator_memory; } @@ -55,7 +55,7 @@ void BigBuf_Clear(void) { // clear ALL of BigBuf void BigBuf_Clear_ext(bool verbose) { memset(BigBuf, 0, BIGBUF_SIZE); - if (verbose) + if (verbose) Dbprintf("Buffer cleared (%i bytes)", BIGBUF_SIZE); } @@ -74,7 +74,7 @@ uint8_t *BigBuf_malloc(uint16_t chunksize) { return NULL; // no memory left chunksize = (chunksize + 3) & 0xfffc; // round to next multiple of 4 - BigBuf_hi -= chunksize; // aligned to 4 Byte boundary + BigBuf_hi -= chunksize; // aligned to 4 Byte boundary return (uint8_t *)BigBuf + BigBuf_hi; } @@ -91,7 +91,7 @@ void BigBuf_free_keep_EM(void) { BigBuf_hi = emulator_memory - (uint8_t *)BigBuf; else BigBuf_hi = BIGBUF_SIZE; - + // shouldn't this empty BigBuf also? } @@ -242,7 +242,7 @@ uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length){ if (offset + length < CARD_MEMORY_SIZE) { memcpy(mem+offset, data, length); return 0; - } + } Dbprintf("Error, trying to set memory outside of bounds! %d > %d", (offset + length), CARD_MEMORY_SIZE); return 1; } diff --git a/armsrc/BigBuf.h b/armsrc/BigBuf.h index 679eed676..9b7b33e47 100644 --- a/armsrc/BigBuf.h +++ b/armsrc/BigBuf.h @@ -22,7 +22,7 @@ #define MAX_PARITY_SIZE ((MAX_FRAME_SIZE + 7) / 8) #define MAX_MIFARE_FRAME_SIZE 18 // biggest Mifare frame is answer to a read (one block = 16 Bytes) + 2 Bytes CRC #define MAX_MIFARE_PARITY_SIZE 3 // need 18 parity bits for the 18 Byte above. 3 Bytes are enough to store these -#define CARD_MEMORY_SIZE 4096 +#define CARD_MEMORY_SIZE 4096 #define DMA_BUFFER_SIZE 256 //128 (how big is the dma?!? extern uint8_t *BigBuf_get_addr(void); diff --git a/armsrc/LCD.c b/armsrc/LCD.c index b40dba0f7..3e74c77fa 100644 --- a/armsrc/LCD.c +++ b/armsrc/LCD.c @@ -125,7 +125,7 @@ void LCDInit(void) LCDSend(PRAMWR); // Write to display i=LCD_XRES*LCD_YRES; while(i--) LCDSend(WHITE); - + // test text on different colored backgrounds LCDString(" The quick brown fox ", (char *)&FONT6x8,1,1+8*0,WHITE ,BLACK ); LCDString(" jumped over the ", (char *)&FONT6x8,1,1+8*1,BLACK ,WHITE ); @@ -135,7 +135,7 @@ void LCDInit(void) LCDString("UuVvWwXxYyZz0123456789", (char *)&FONT6x8,1,1+8*5,BLUE ,YELLOW); LCDString("`-=[]_;',./~!@#$%^&*()", (char *)&FONT6x8,1,1+8*6,BLACK ,CYAN ); LCDString(" _+{}|:\\\"<>? ",(char *)&FONT6x8,1,1+8*7,BLUE ,MAGENTA); - + // color bands LCDFill(0, 1+8* 8, 132, 8, BLACK); LCDFill(0, 1+8* 9, 132, 8, WHITE); diff --git a/armsrc/Standalone/hf_bog.c b/armsrc/Standalone/hf_bog.c index 65254bd5c..1f62e4c0c 100644 --- a/armsrc/Standalone/hf_bog.c +++ b/armsrc/Standalone/hf_bog.c @@ -8,20 +8,20 @@ /* This can actually be used in two separate ways. -It can either be used to just HF 14a sniff on the go and/or grab the +It can either be used to just HF 14a sniff on the go and/or grab the authentication attempts for ULC/NTAG/ULEV1 into the flash mem (RDV4). The retrieved sniffing session can be acquired by connecting the device to a client that supports the reconnect capability and issue 'hf 14a list'. In order to view the grabbed authentication attempts in the flash mem, -you can simply run 'script run read_pwd_mem' or just 'mem read l 256' +you can simply run 'script run read_pwd_mem' or just 'mem read l 256' from the client to view the stored quadlets. */ #include "hf_bog.h" -#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8) +#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8) #define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8) // Maximum number of auth attempts per standalone session @@ -31,7 +31,7 @@ uint8_t FindOffsetInFlash() { uint8_t mem[4] = { 0x00, 0x00, 0x00, 0x00 }; uint8_t eom[4] = { 0xFF, 0xFF, 0xFF, 0xFF }; uint8_t memcnt = 0; - + while (memcnt < 0xFF) { Flash_ReadData(memcnt, mem, 4); @@ -40,7 +40,7 @@ uint8_t FindOffsetInFlash() { } memcnt += 4; } - + return 0; // wrap-around } @@ -48,7 +48,7 @@ void EraseMemory() { if (!FlashInit()){ return; } - + Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(0,0); @@ -60,26 +60,26 @@ void EraseMemory() { // This is actually copied from SniffIso14443a void RAMFUNC SniffAndStore(uint8_t param) { - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - + // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(true); - + // Array to store the authpwds uint8_t *capturedPwds = BigBuf_malloc(4 * MAX_PWDS_PER_SESSION); - + // The command (reader -> tag) that we're receiving. uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); uint8_t *receivedCmdPar = BigBuf_malloc(MAX_PARITY_SIZE); - + // The response (tag -> reader) that we're receiving. uint8_t *receivedResp = BigBuf_malloc(MAX_FRAME_SIZE); uint8_t *receivedRespPar = BigBuf_malloc(MAX_PARITY_SIZE); - + // The DMA buffer, used to stream samples from the FPGA uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); uint8_t *data = dmaBuf; @@ -88,47 +88,47 @@ void RAMFUNC SniffAndStore(uint8_t param) { int dataLen = 0; bool TagIsActive = false; bool ReaderIsActive = false; - + // Set up the demodulator for tag -> reader responses. DemodInit(receivedResp, receivedRespPar); - + // Set up the demodulator for the reader -> tag commands UartInit(receivedCmd, receivedCmdPar); - + // Setup and start DMA. if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE) ){ - if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting"); + if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting"); return; } - + tUart* uart = GetUart(); tDemod* demod = GetDemod(); - + // We won't start recording the frames that we acquire until we trigger; // a good trigger condition to get started is probably when we see a // response from the tag. // triggered == false -- to wait first for card - bool triggered = !(param & 0x03); - + bool triggered = !(param & 0x03); + uint32_t rsamples = 0; - + // Current captured passwords counter uint8_t auth_attempts = 0; SpinDelay(50); - + // loop and listen while (!BUTTON_PRESS()) { WDT_HIT(); LED_A_ON(); - + int register readBufDataP = data - dmaBuf; int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR; if (readBufDataP <= dmaBufDataP) dataLen = dmaBufDataP - readBufDataP; else dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP; - + // test for length of buffer if (dataLen > DMA_BUFFER_SIZE) { // TODO: Check if this works properly Dbprintf("[!] blew circular buffer! | datalen %u", dataLen); @@ -149,7 +149,7 @@ void RAMFUNC SniffAndStore(uint8_t param) { } LED_A_OFF(); - + // Need two samples to feed Miller and Manchester-Decoder if (rsamples & 0x01) { @@ -164,17 +164,17 @@ void RAMFUNC SniffAndStore(uint8_t param) { if (triggered) { if ((receivedCmd) && ((receivedCmd[0] == MIFARE_ULEV1_AUTH) || (receivedCmd[0] == MIFARE_ULC_AUTH_1))) { if (MF_DBGLEVEL > 1) Dbprintf("PWD-AUTH KEY: 0x%02x%02x%02x%02x", receivedCmd[1], receivedCmd[2], receivedCmd[3], receivedCmd[4]); - + // temporarily save the captured pwd in our array memcpy(&capturedPwds[4 * auth_attempts], receivedCmd+1, 4); auth_attempts++; } - - if (!LogTrace(receivedCmd, - uart->len, + + if (!LogTrace(receivedCmd, + uart->len, uart->startTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, uart->endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, - uart->parity, + uart->parity, true)) break; } /* ready to receive another command. */ @@ -188,14 +188,14 @@ void RAMFUNC SniffAndStore(uint8_t param) { } // no need to try decoding tag data if the reader is sending - and we cannot afford the time - if (!ReaderIsActive) { + if (!ReaderIsActive) { uint8_t tagdata = (previous_data << 4) | (*data & 0x0F); if (ManchesterDecoding(tagdata, 0, (rsamples-1)*4)) { LED_B_ON(); - if (!LogTrace(receivedResp, - demod->len, - demod->startTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, + if (!LogTrace(receivedResp, + demod->len, + demod->startTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, demod->endTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, demod->parity, false)) break; @@ -208,7 +208,7 @@ void RAMFUNC SniffAndStore(uint8_t param) { UartReset(); //UartInit(receivedCmd, receivedCmdPar); LED_C_OFF(); - } + } TagIsActive = (demod->state != DEMOD_UNSYNCD); } } @@ -223,29 +223,29 @@ void RAMFUNC SniffAndStore(uint8_t param) { FpgaDisableSscDma(); set_tracing(false); - + Dbprintf("Stopped sniffing"); - + SpinDelay(200); - + // Write stuff to flash if (auth_attempts > 0) { if (MF_DBGLEVEL > 1) Dbprintf("[!] Authentication attempts = %u", auth_attempts); - + // Setting the SPI Baudrate to 48MHz to avoid the bit-flip issue (https://github.com/RfidResearchGroup/proxmark3/issues/34) FlashmemSetSpiBaudrate(48000000); - + // Find the offset in flash mem to continue writing the auth attempts uint8_t memoffset = FindOffsetInFlash(); if (MF_DBGLEVEL > 1) Dbprintf("[!] Memory offset = %u", memoffset); - + if ((memoffset + 4 * auth_attempts) > 0xFF) { // We opt to keep the new data only memoffset = 0; if (MF_DBGLEVEL > 1) Dbprintf("[!] Size of total data > 256 bytes. Discarding the old data."); } - + // Get previous data from flash mem uint8_t *previousdata = BigBuf_malloc(memoffset); if (memoffset > 0) @@ -253,49 +253,49 @@ void RAMFUNC SniffAndStore(uint8_t param) { uint16_t readlen = Flash_ReadData(0, previousdata, memoffset); if (MF_DBGLEVEL > 1) Dbprintf("[!] Read %u bytes from flash mem", readlen); } - + // create new bigbuf to hold all data size_t total_size = memoffset + 4 * auth_attempts; uint8_t *total_data = BigBuf_malloc(total_size); - + // Add the previousdata array into total_data array memcpy(total_data, previousdata, memoffset); - + // Copy bytes of capturedPwds immediately following bytes of previousdata memcpy(total_data + memoffset, capturedPwds, 4 * auth_attempts); - + // Erase first page of flash mem EraseMemory(); - + // Write total data to flash mem uint16_t writelen = Flash_WriteData(0, total_data, memoffset + 4 * auth_attempts); if (MF_DBGLEVEL > 1) Dbprintf("[!] Wrote %u bytes into flash mem", writelen); - + // If pwd saved successfully, blink led A three times if (writelen > 0) { SpinErr(0, 200, 5); // blink led A } - + SpinDelay(100); - + // Reset the SPI Baudrate to the default value (24MHz) FlashmemSetSpiBaudrate(24000000); } } void RunMod() { - + StandAloneMode(); - + Dbprintf(">> Bogiton 14a Sniff UL/UL-EV1/NTAG a.k.a BogitoRun Started <<"); Dbprintf("Starting to sniff"); - + // param: // bit 0 - trigger from first card answer - // bit 1 - trigger from first reader 7-bit request - SniffAndStore(0); - LEDsoff(); + // bit 1 - trigger from first reader 7-bit request + SniffAndStore(0); + LEDsoff(); SpinDelay(300); Dbprintf("- [ End ] -> You can take shell back ..."); - Dbprintf("- [ ! ] -> use 'script run read_pwd_mem' to print passwords"); + Dbprintf("- [ ! ] -> use 'script run read_pwd_mem' to print passwords"); } diff --git a/armsrc/Standalone/hf_colin.c b/armsrc/Standalone/hf_colin.c index 2eabd68d9..c1b8d65ab 100644 --- a/armsrc/Standalone/hf_colin.c +++ b/armsrc/Standalone/hf_colin.c @@ -161,7 +161,7 @@ void WriteTagToFlash(uint8_t index, size_t size) if (!FlashInit()){ return; } - + Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(0,0); @@ -212,7 +212,7 @@ void RunMod() { StandAloneMode(); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + currline = 20; curlline = 20; currfline = 24; @@ -328,7 +328,7 @@ ACCBITS : 796788[00]+VALUE foundKey[t][sectorNo][2] = 0xFF; foundKey[t][sectorNo][3] = 0xFF; foundKey[t][sectorNo][4] = 0xFF; - foundKey[t][sectorNo][5] = 0xFF; + foundKey[t][sectorNo][5] = 0xFF; } } diff --git a/armsrc/Standalone/hf_mattyrun.c b/armsrc/Standalone/hf_mattyrun.c index 78f197383..1f3d4b70c 100644 --- a/armsrc/Standalone/hf_mattyrun.c +++ b/armsrc/Standalone/hf_mattyrun.c @@ -13,7 +13,7 @@ I've personally recoded the image of the ARM in order to automate the attack and simulation on Mifare cards. I've moved some of the implementation on the client side to the ARM such as *chk*, *ecfill*, *sim* -and *clone* commands. +and *clone* commands. ### What it does now: It will check if the keys from the attacked tag are a subset from @@ -218,7 +218,7 @@ void RunMod() { StandAloneMode(); Dbprintf(">> Matty mifare chk/dump/sim a.k.a MattyRun Started <<"); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + /* It will check if the keys from the attacked tag are a subset from the hardcoded set of keys inside of the ARM. If this is the case @@ -232,9 +232,9 @@ void RunMod() { If you're using the proxmark connected to a device that has an OS, and you're not using the proxmark3 client to see the debug messages, you MUST uncomment usb_disable(). */ - + // Comment this line below if you want to see debug messages. - // usb_disable(); + // usb_disable(); /* Pseudo-configuration block. @@ -323,7 +323,7 @@ void RunMod() { bool err = 0; bool allKeysFound = true; uint32_t size = mfKeysCnt; - + for (int type = !keyType; type < 2 && !err; keyType == 2 ? (type++) : (type = 2)) { block = blockNo; for (int sec = 0; sec < sectorsCnt && !err; ++sec) { @@ -341,18 +341,18 @@ void RunMod() { num_to_bytes(key64, 6, foundKey[type][sec]); validKey[type][sec] = true; keyFound = true; - Dbprintf("\t✓ Found valid key: [%02x%02x%02x%02x%02x%02x]\n", + Dbprintf("\t✓ Found valid key: [%02x%02x%02x%02x%02x%02x]\n", (keyBlock + 6*key)[0], (keyBlock + 6*key)[1], (keyBlock + 6*key)[2], (keyBlock + 6*key)[3], (keyBlock + 6*key)[4], (keyBlock + 6*key)[5] ); } - + block < 127 ? (block += 4) : (block += 16); } } /* - TODO: + TODO: - Get UID from tag and set accordingly in emulator memory and call mifare1ksim with right flags (iceman) */ if (!allKeysFound && keyFound) { @@ -371,9 +371,9 @@ void RunMod() { If enabled, transfers found keys to memory and loads target content in emulator memory. Then it simulates to be the tag it has basically cloned. */ if ((transferToEml) && (allKeysFound)) { - + emlClearMem(); - + uint8_t mblock[16]; for (uint16_t sectorNo = 0; sectorNo < sectorsCnt; sectorNo++) { if (validKey[0][sectorNo] || validKey[1][sectorNo]) { @@ -388,25 +388,25 @@ void RunMod() { } Dbprintf("\t✓ Found keys have been transferred to the emulator memory."); if (ecfill) { - + Dbprintf("\tFilling in with key A."); - MifareECardLoad(sectorsCnt, 0, 0, &filled); + MifareECardLoad(sectorsCnt, 0, 0, &filled); if (filled != 1) { Dbprintf("\t✕ Failed filling with A."); } - + Dbprintf("\tFilling in with key B."); MifareECardLoad(sectorsCnt, 1, 0, &filled); if (filled != 1) { Dbprintf("\t✕ Failed filling with B."); } - + if ((filled == 1) && simulation) { Dbprintf("\t✓ Filled, simulation started."); - + // This will tell the fpga to emulate using previous keys and current target tag content. Dbprintf("\t Press button to abort simulation at anytime."); - + LED_B_ON(); // green // assuming arg0==0, use hardcoded uid 0xdeadbeaf Mifare1ksim( FLAG_4B_UID_IN_DATA | FLAG_UID_IN_EMUL, 0, 0, uid); @@ -454,5 +454,5 @@ void RunMod() { LED_C_ON(); } } - } + } } \ No newline at end of file diff --git a/armsrc/Standalone/hf_young.c b/armsrc/Standalone/hf_young.c index f4bc3db4f..3feb77a94 100644 --- a/armsrc/Standalone/hf_young.c +++ b/armsrc/Standalone/hf_young.c @@ -29,7 +29,7 @@ void RunMod() { card_clone_t uids[OPTS]; iso14a_card_select_t card[OPTS]; uint8_t params = (MAGIC_SINGLE | MAGIC_DATAIN); - + LED(selected + 1, 0); for (;;) { @@ -54,7 +54,7 @@ void RunMod() { for (;;) { // exit from Standalone Mode, send a usbcommand. if (usb_poll_validate_length()) return; - + if (BUTTON_PRESS()) { if (cardRead[selected]) { Dbprintf("Button press detected -- replaying card in bank[%d]", selected); @@ -68,21 +68,21 @@ void RunMod() { SpinDelay(300); } } - + if (!iso14443a_select_card(NULL, &card[selected], NULL, true, 0, true)) { continue; } else { - Dbprintf("Read UID:"); + Dbprintf("Read UID:"); Dbhexdump(card[selected].uidlen, card[selected].uid, 0); - + if (memcmp(uids[(selected+1)%OPTS].uid, card[selected].uid, card[selected].uidlen ) == 0 ) { Dbprintf("Card selected has same UID as what is stored in the other bank. Skipping."); - } else { + } else { uids[selected].sak = card[selected].sak; - uids[selected].uidlen = card[selected].uidlen; - memcpy(uids[selected].uid , card[selected].uid, uids[selected].uidlen); + uids[selected].uidlen = card[selected].uidlen; + memcpy(uids[selected].uid , card[selected].uid, uids[selected].uidlen); memcpy(uids[selected].atqa, card[selected].atqa, 2); - + if (uids[selected].uidlen > 4) Dbprintf("Bank[%d] received a 7-byte UID", selected); else @@ -91,7 +91,7 @@ void RunMod() { } } } - + Dbprintf("ATQA = %02X%02X", uids[selected].atqa[0], uids[selected].atqa[1]); Dbprintf("SAK = %02X", uids[selected].sak); LEDsoff(); @@ -108,7 +108,7 @@ void RunMod() { cardRead[selected] = 1; } - + /* MF Classic UID clone */ else if (iGotoClone==1) { iGotoClone=0; @@ -118,7 +118,7 @@ void RunMod() { // magiccards holds 4bytes uid. *usually* uint32_t tmpuid = bytes_to_num(uids[selected].uid, 4); - + // record Dbprintf("Preparing to Clone card [Bank: %d]; uid: %08x", selected, tmpuid); @@ -175,7 +175,7 @@ void RunMod() { // arg0 = workFlags, arg1 = blockNo, datain MifareCSetBlock(params, 0, newBlock0); MifareCGetBlock(params, 0, testBlock0); - + if (memcmp(testBlock0, newBlock0, 16)==0) { DbpString("Cloned successfull!"); cardRead[selected] = 0; // Only if the card was cloned successfully should we clear it @@ -190,9 +190,9 @@ void RunMod() { LEDsoff(); LED(selected + 1, 0); } - + // Change where to record (or begin playing) - // button_pressed == BUTTON_SINGLE_CLICK && cardRead[selected]) + // button_pressed == BUTTON_SINGLE_CLICK && cardRead[selected]) else if (playing==1) { LEDsoff(); LED(selected + 1, 0); @@ -203,7 +203,7 @@ void RunMod() { for ( ; ; ) { // exit from Standalone Mode, send a usbcommand. if (usb_poll_validate_length()) return; - + int button_action = BUTTON_HELD(1000); if ( button_action == 0) { // No button action, proceed with sim @@ -211,16 +211,16 @@ void RunMod() { uint8_t data[USB_CMD_DATA_SIZE] = {0}; // in case there is a read command received we shouldn't break memcpy(data, uids[selected].uid, uids[selected].uidlen); - + uint64_t tmpuid = bytes_to_num(uids[selected].uid, uids[selected].uidlen); - + if ( uids[selected].uidlen == 7 ) { flags = FLAG_7B_UID_IN_DATA; Dbprintf("Simulating ISO14443a tag with uid: %014" PRIx64 " [Bank: %d]", tmpuid, selected); } else { Dbprintf("Simulating ISO14443a tag with uid: %08" PRIx64 " [Bank: %d]", tmpuid, selected); } - + if (uids[selected].sak == 0x08 && uids[selected].atqa[0] == 0x04 && uids[selected].atqa[1] == 0) { DbpString("Mifare Classic 1k"); SimulateIso14443aTag(1, flags, data); @@ -240,7 +240,7 @@ void RunMod() { Dbprintf("Unrecognized tag type -- defaulting to Mifare Classic emulation"); SimulateIso14443aTag(1, flags, data); } - + } else if (button_action == BUTTON_SINGLE_CLICK) { selected = (selected + 1) % OPTS; Dbprintf("Done playing. Switching to record mode on bank %d", selected); diff --git a/armsrc/Standalone/hf_young.h b/armsrc/Standalone/hf_young.h index 3ccd08b72..46c0d1361 100644 --- a/armsrc/Standalone/hf_young.h +++ b/armsrc/Standalone/hf_young.h @@ -16,7 +16,7 @@ #include "standalone.h" // standalone definitions #include "iso14443a.h" #include "protocols.h" - + #define OPTS 2 #endif /* __HF_YOUNG_H */ \ No newline at end of file diff --git a/armsrc/Standalone/lf_hidbrute.c b/armsrc/Standalone/lf_hidbrute.c index 8c6b85f4f..f8b41771c 100644 --- a/armsrc/Standalone/lf_hidbrute.c +++ b/armsrc/Standalone/lf_hidbrute.c @@ -9,16 +9,16 @@ // the license. // // PROXMARK3 - HID CORPORATE 1000 BRUTEFORCER (STAND-ALONE MODE) -// +// // This version of Proxmark3 firmware adds one extra stand-alone mode to proxmark3 firmware. // The new stand-alone mode allows to execute a bruteforce on HID Corporate 1000 readers, by // reading a specific badge and bruteforcing the Card Number (incrementing and decrementing it), // mainteining the same Facility Code of the original badge. // -// Based on an idea of Brad Antoniewicz of McAfee® Foundstone® Professional Services (ProxBrute), +// Based on an idea of Brad Antoniewicz of McAfee® Foundstone® Professional Services (ProxBrute), // the stand-alone mode has been rewritten in order to overcome some limitations of ProxBrute firmware, // that does not consider parity bits. -// +// // https://github.com/federicodotta/proxmark3 // //----------------------------------------------------------------------------------- @@ -29,7 +29,7 @@ // samy's sniff and repeat routine for LF void RunMod() { StandAloneMode(); - Dbprintf(">> LF HID corporate bruteforce a.k.a CorporateBrute Started <<"); + Dbprintf(">> LF HID corporate bruteforce a.k.a CorporateBrute Started <<"); FpgaDownloadAndGo(FPGA_BITSTREAM_LF); uint32_t high[OPTS], low[OPTS]; @@ -40,9 +40,9 @@ void RunMod() { // Turn on selected LED LED(selected + 1, 0); - for (;;) { + for (;;) { WDT_HIT(); - + // exit from SamyRun, send a usbcommand. if (usb_poll_validate_length()) break; @@ -74,8 +74,8 @@ void RunMod() { // Finished recording // If we were previously playing, set playing off // so next button push begins playing what we recorded - playing = 0; - cardRead = 1; + playing = 0; + cardRead = 1; } else if (button_pressed > 0 && cardRead == 1) { LEDsoff(); @@ -101,8 +101,8 @@ void RunMod() { // If we were previously playing, set playing off // so next button push begins playing what we recorded - playing = 0; - cardRead = 0; + playing = 0; + cardRead = 0; } // Change where to record (or begin playing) @@ -110,7 +110,7 @@ void RunMod() { // Next option if we were previously playing if (playing) selected = (selected + 1) % OPTS; - + playing = !playing; LEDsoff(); @@ -121,15 +121,15 @@ void RunMod() { LED(LED_GREEN, 0); DbpString("[=] playing"); - + // wait for button to be released while (BUTTON_PRESS()) WDT_HIT(); - + Dbprintf("[=] %x %x %08x", selected, high[selected], low[selected]); - CmdHIDsimTAG(high[selected], low[selected], 0); + CmdHIDsimTAG(high[selected], low[selected], 0); DbpString("[=] done playing"); - + if (BUTTON_HELD(1000) > 0) goto out; @@ -144,9 +144,9 @@ void RunMod() { } else if (playing && selected == 2) { - // Now it work only with HID Corporate 1000 (35bit), but is easily extensible to others RFID. - // It is necessary only to calculate the correct parity. - + // Now it work only with HID Corporate 1000 (35bit), but is easily extensible to others RFID. + // It is necessary only to calculate the correct parity. + // Brute force code // Check if the badge is an HID Corporate 1000 if( (high[selected] & 0xFFFFFFF8) != 0x28 ) { @@ -159,7 +159,7 @@ void RunMod() { // wait for button to be released while (BUTTON_PRESS()) WDT_HIT(); - + // Calculate Facility Code and Card Number from high and low uint32_t cardnum = (low[selected] >> 1) & 0xFFFFF; uint32_t fc = ((high[selected] & 1 ) << 11 ) | (low[selected] >> 21); @@ -168,13 +168,13 @@ void RunMod() { Dbprintf("[=] Proxbrute - starting decrementing card number"); while (cardnum >= 0) { - + // Needed for exiting from proxbrute when button is pressed if (BUTTON_PRESS()) { if (BUTTON_HELD(1000) > 0) { - goto out; + goto out; } else { - while (BUTTON_PRESS()) { + while (BUTTON_PRESS()) { WDT_HIT(); } break; @@ -189,7 +189,7 @@ void RunMod() { // Print actual code to brute Dbprintf("[=] TAG ID: %x%08x (%d) - FC: %u - Card: %u", high[selected], low[selected], (low[selected] >> 1) & 0xFFFF, fc, cardnum); - + CmdHIDsimTAGEx(high[selected], low[selected], 1, 50000); } @@ -198,12 +198,12 @@ void RunMod() { Dbprintf("[=] Proxbrute - starting incrementing card number"); while (cardnum <= 0xFFFFF) { - + // Needed for exiting from proxbrute when button is pressed if (BUTTON_PRESS()) { if (BUTTON_HELD(1000) > 0) { goto out; - } else { + } else { while (BUTTON_PRESS()) { WDT_HIT(); } break; } @@ -233,32 +233,32 @@ void RunMod() { playing = !playing; LEDsoff(); LED(selected + 1, 0); - + } else { while(BUTTON_PRESS()) WDT_HIT(); } } } - -out: + +out: DbpString("[=] exiting"); - LEDsoff(); + LEDsoff(); } // Function that calculate next value for the brutforce of HID corporate 1000 void hid_corporate_1000_calculate_checksum_and_set( uint32_t *high, uint32_t *low, uint32_t cardnum, uint32_t fc) { uint32_t new_high = 0; - uint32_t new_low = 0; + uint32_t new_low = 0; // Calculate new high and low base value from card number and facility code, without parity - new_low = (fc << 21) | (cardnum << 1); + new_low = (fc << 21) | (cardnum << 1); new_high = 0x28 | ((fc >> 11) & 1); // 0x28 is 101000 int n_ones; uint32_t i; - + // Calculating and setting parity bit 34 // Select only bit used for parity bit 34 in low number (10110110110110110110110110110110) uint32_t parity_bit_34_low = new_low & 0xB6DB6DB6; @@ -271,7 +271,7 @@ void hid_corporate_1000_calculate_checksum_and_set( uint32_t *high, uint32_t *lo // Calculate number of ones in high number if (new_high & 1) n_ones++; - + // Set parity bit (Even parity) if (n_ones % 2) new_high = new_high | 0x2; @@ -289,14 +289,14 @@ void hid_corporate_1000_calculate_checksum_and_set( uint32_t *high, uint32_t *lo // Calculate number of ones in high number if ( new_high & 0x1) n_ones++; - + if ( new_high & 0x2) n_ones++; - + // Set parity bit (Odd parity) if (!(n_ones % 2)) new_low = new_low | 0x1; - + // Calculating and setting parity bit 35 n_ones = 0; // Calculate number of ones in low number (all bit of low, bitmask unnecessary) @@ -307,7 +307,7 @@ void hid_corporate_1000_calculate_checksum_and_set( uint32_t *high, uint32_t *lo // Calculate number of ones in high number if ( new_high & 0x1) n_ones++; - + if ( new_high & 0x2) n_ones++; diff --git a/armsrc/Standalone/lf_proxbrute.c b/armsrc/Standalone/lf_proxbrute.c index 69b5f5331..268a96eec 100644 --- a/armsrc/Standalone/lf_proxbrute.c +++ b/armsrc/Standalone/lf_proxbrute.c @@ -7,14 +7,14 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// main code for LF aka Proxbrute by Brad antoniewicz +// main code for LF aka Proxbrute by Brad antoniewicz //----------------------------------------------------------------------------- #include "lf_proxbrute.h" // samy's sniff and repeat routine for LF void RunMod() { StandAloneMode(); - Dbprintf(">> LF HID proxII bruteforce a.k.a ProxBrute Started (Brad Antoniewicz) <<"); + Dbprintf(">> LF HID proxII bruteforce a.k.a ProxBrute Started (Brad Antoniewicz) <<"); FpgaDownloadAndGo(FPGA_BITSTREAM_LF); uint32_t high[OPTS], low[OPTS]; @@ -25,9 +25,9 @@ void RunMod() { // Turn on selected LED LED(selected + 1, 0); - for (;;) { + for (;;) { WDT_HIT(); - + // exit from SamyRun, send a usbcommand. if (usb_poll_validate_length()) break; @@ -59,8 +59,8 @@ void RunMod() { // Finished recording // If we were previously playing, set playing off // so next button push begins playing what we recorded - playing = 0; - cardRead = 1; + playing = 0; + cardRead = 1; } else if (button_pressed > 0 && cardRead == 1) { LEDsoff(); @@ -86,8 +86,8 @@ void RunMod() { // If we were previously playing, set playing off // so next button push begins playing what we recorded - playing = 0; - cardRead = 0; + playing = 0; + cardRead = 0; } // Change where to record (or begin playing) @@ -107,7 +107,7 @@ void RunMod() { // wait for button to be released while (BUTTON_PRESS()) WDT_HIT(); - + /* START PROXBRUTE */ /* @@ -144,7 +144,7 @@ void RunMod() { /* END PROXBRUTE */ - + if (BUTTON_HELD(1000) > 0) goto out; @@ -163,7 +163,7 @@ void RunMod() { } } } -out: +out: DbpString("[=] exiting"); - LEDsoff(); + LEDsoff(); } \ No newline at end of file diff --git a/armsrc/Standalone/lf_samyrun.c b/armsrc/Standalone/lf_samyrun.c index c94d5fc42..c96a2ced6 100644 --- a/armsrc/Standalone/lf_samyrun.c +++ b/armsrc/Standalone/lf_samyrun.c @@ -6,14 +6,14 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// main code for LF aka SamyRun by Samy Kamkar +// main code for LF aka SamyRun by Samy Kamkar //----------------------------------------------------------------------------- #include "lf_samyrun.h" // samy's sniff and repeat routine for LF void RunMod() { StandAloneMode(); - Dbprintf(">> LF HID Read/Clone/Sim a.k.a SamyRun Started <<"); + Dbprintf(">> LF HID Read/Clone/Sim a.k.a SamyRun Started <<"); FpgaDownloadAndGo(FPGA_BITSTREAM_LF); uint32_t high[OPTS], low[OPTS]; @@ -24,15 +24,15 @@ void RunMod() { // Turn on selected LED LED(selected + 1, 0); - for (;;) { + for (;;) { WDT_HIT(); - + // exit from SamyRun, send a usbcommand. if (usb_poll_validate_length()) break; // Was our button held down or pressed? int button_pressed = BUTTON_HELD(1000); - + Dbprintf("button %d", button_pressed); SpinDelay(300); @@ -60,7 +60,7 @@ void RunMod() { // Finished recording // If we were previously playing, set playing off // so next button push begins playing what we recorded - playing = 0; + playing = 0; cardRead = 1; gotCard = true; @@ -89,8 +89,8 @@ void RunMod() { // If we were previously playing, set playing off // so next button push begins playing what we recorded - playing = 0; - cardRead = 0; + playing = 0; + cardRead = 0; } // Change where to record (or begin playing) @@ -98,7 +98,7 @@ void RunMod() { // Next option if we were previously playing if (playing) selected = (selected + 1) % OPTS; - + playing = !playing; LEDsoff(); @@ -106,18 +106,18 @@ void RunMod() { // Begin transmitting if (playing) { - + LED(LED_GREEN, 0); DbpString("[=] playing"); - + // wait for button to be released while (BUTTON_PRESS()) WDT_HIT(); - + Dbprintf("[=] %x %x %08x", selected, high[selected], low[selected]); - CmdHIDsimTAG(high[selected], low[selected], false); + CmdHIDsimTAG(high[selected], low[selected], false); DbpString("[=] done playing"); - + if (BUTTON_HELD(1000) > 0) goto out; @@ -137,7 +137,7 @@ void RunMod() { } } -out: +out: DbpString("[=] exiting"); LEDsoff(); } \ No newline at end of file diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 5002a7138..68b51913f 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -48,7 +48,7 @@ // is the order in which they go out on the wire. //============================================================================= -#define TOSEND_BUFFER_SIZE (9*MAX_FRAME_SIZE + 1 + 1 + 2) // 8 data bits and 1 parity bit per payload byte, 1 correction bit, 1 SOC bit, 2 EOC bits +#define TOSEND_BUFFER_SIZE (9*MAX_FRAME_SIZE + 1 + 1 + 2) // 8 data bits and 1 parity bit per payload byte, 1 correction bit, 1 SOC bit, 2 EOC bits uint8_t ToSend[TOSEND_BUFFER_SIZE]; int ToSendMax = -1; static int ToSendBit; @@ -114,13 +114,13 @@ void DbpStringEx(char *str, uint32_t cmd) { #if DEBUG uint8_t len = strlen(str); cmd_send(CMD_DEBUG_PRINT_STRING, len, cmd, 0, (uint8_t*)str, len); -#endif +#endif } void DbpString(char *str) { #if DEBUG DbpStringEx(str, 0); -#endif +#endif } #if 0 @@ -138,7 +138,7 @@ void DbprintfEx(uint32_t cmd, const char *fmt, ...) { va_end(ap); DbpStringEx(output_string, cmd); -#endif +#endif } void Dbprintf(const char *fmt, ...) { @@ -152,7 +152,7 @@ void Dbprintf(const char *fmt, ...) { va_end(ap); DbpString(output_string); -#endif +#endif } // prints HEX & ASCII @@ -160,30 +160,30 @@ void Dbhexdump(int len, uint8_t *d, bool bAsci) { #if DEBUG int l=0, i; char ascii[9]; - + while (len > 0) { l = (len > 8) ? 8 : len; - + memcpy(ascii, d, l); ascii[l] = 0; - + // filter safe ascii for (i=0; i 126) { ascii[i] = '.'; } } - + if (bAsci) Dbprintf("%-8s %*D", ascii, l, d, " "); else Dbprintf("%*D", l, d, " "); - + len -= 8; - d += 8; + d += 8; } -#endif +#endif } //----------------------------------------------------------------------------- @@ -193,17 +193,17 @@ void Dbhexdump(int len, uint8_t *d, bool bAsci) { //----------------------------------------------------------------------------- static uint16_t ReadAdc(int ch) { - // Note: ADC_MODE_PRESCALE and ADC_MODE_SAMPLE_HOLD_TIME are set to the maximum allowed value. + // Note: ADC_MODE_PRESCALE and ADC_MODE_SAMPLE_HOLD_TIME are set to the maximum allowed value. // AMPL_HI is are high impedance (10MOhm || 1MOhm) output, the input capacitance of the ADC is 12pF (typical). This results in a time constant - // of RC = (0.91MOhm) * 12pF = 10.9us. Even after the maximum configurable sample&hold time of 40us the input capacitor will not be fully charged. - // + // of RC = (0.91MOhm) * 12pF = 10.9us. Even after the maximum configurable sample&hold time of 40us the input capacitor will not be fully charged. + // // The maths are: // If there is a voltage v_in at the input, the voltage v_cap at the capacitor (this is what we are measuring) will be // // v_cap = v_in * (1 - exp(-SHTIM/RC)) = v_in * (1 - exp(-40us/10.9us)) = v_in * 0,97 (i.e. an error of 3%) AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST; - AT91C_BASE_ADC->ADC_MR = + AT91C_BASE_ADC->ADC_MR = ADC_MODE_PRESCALE(63) // ADC_CLK = MCK / ((63+1) * 2) = 48MHz / 128 = 375kHz | ADC_MODE_STARTUP_TIME(1) // Startup Time = (1+1) * 8 / ADC_CLK = 16 / 375kHz = 42,7us Note: must be > 20us | ADC_MODE_SAMPLE_HOLD_TIME(15); // Sample & Hold Time SHTIM = 15 / ADC_CLK = 15 / 375kHz = 40us @@ -216,7 +216,7 @@ static uint16_t ReadAdc(int ch) { return (AT91C_BASE_ADC->ADC_CDR[ch] & 0x3FF); } -// was static - merlok +// was static - merlok uint16_t AvgAdc(int ch) { uint16_t a = 0; for(uint8_t i = 0; i < 32; i++) @@ -243,11 +243,11 @@ void MeasureAntennaTuning(void) { * the resonating frequency of your LF antenna * ( hopefully around 95 if it is tuned to 125kHz!) */ - + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); SpinDelay(50); - + for (i = 255; i >= 19; i--) { WDT_HIT(); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, i); @@ -262,10 +262,10 @@ void MeasureAntennaTuning(void) { if(LF_Results[i] > peak) { peakv = adcval; peakf = i; - peak = LF_Results[i]; + peak = LF_Results[i]; } - } - + } + LED_A_ON(); // Let the FPGA drive the high-frequency antenna around 13.56 MHz. FpgaDownloadAndGo(FPGA_BITSTREAM_HF); @@ -277,15 +277,15 @@ void MeasureAntennaTuning(void) { if ( v_hf > MAX_ADC_HF_VOLTAGE-300 ) { v_hf = (MAX_ADC_HF_VOLTAGE_RDV40 * AvgAdc(ADC_CHAN_HF_RDV40)) >> 10; } - + uint64_t arg0 = v_lf134; arg0 <<= 32; arg0 |= v_lf125; - + uint64_t arg2 = peakv; arg2 <<= 32; arg2 |= peakf; - + cmd_send(CMD_MEASURED_ANTENNA_TUNING, arg0, v_hf, arg2, LF_Results, 256); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); @@ -299,7 +299,7 @@ void MeasureAntennaTuningHf(void) { SpinDelay(50); volt = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10; bool use_high = ( volt > MAX_ADC_HF_VOLTAGE-300 ); - + while( !BUTTON_PRESS() ){ SpinDelay(20); if ( !use_high ) { @@ -334,7 +334,7 @@ void SendVersion(void) { char *bootrom_version = *(char**)&_bootphase1_version_pointer; strncat(VersionString, " [ ARM ]\n", sizeof(VersionString) - strlen(VersionString) - 1); - + if( bootrom_version < &_flash_start || bootrom_version >= &_flash_end ) { strcat(VersionString, "bootrom version information appears invalid\n"); } else { @@ -346,7 +346,7 @@ void SendVersion(void) { strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); strncat(VersionString, "\n [ FPGA ]\n", sizeof(VersionString) - strlen(VersionString) - 1); - + for (int i = 0; i < fpga_bitstream_num; i++) { strncat(VersionString, fpga_version_information[i], sizeof(VersionString) - strlen(VersionString) - 1); if (i < fpga_bitstream_num - 1) { @@ -384,23 +384,23 @@ void printUSBSpeed(void) { Dbprintf(" Bytes transferred.......%d", bytes_transferred); Dbprintf(" USB Transfer Speed PM3 -> Client = %d Bytes/s", 1000 * bytes_transferred / (end_time - start_time)); } - + /** * Prints runtime information about the PM3. **/ void SendStatus(void) { BigBuf_print_status(); Fpga_print_status(); -#ifdef WITH_FLASH +#ifdef WITH_FLASH Flashmem_print_status(); #endif -#ifdef WITH_SMARTCARD +#ifdef WITH_SMARTCARD I2C_print_status(); -#endif +#endif #ifdef WITH_LF printConfig(); // LF Sampling config printT55xxConfig(); // LF T55XX Config -#endif +#endif printUSBSpeed(); Dbprintf("Various"); Dbprintf(" MF_DBGLEVEL.............%d", MF_DBGLEVEL); @@ -413,9 +413,9 @@ void SendStatus(void) { // Show some leds in a pattern to identify StandAlone mod is running void StandAloneMode(void) { - + DbpString("Stand-alone mode! No PC necessary."); - + SpinDown(50); SpinOff(50); SpinUp(50); @@ -428,7 +428,7 @@ void StandAloneMode(void) { void printStandAloneModes(void) { DbpString("Installed StandAlone Mode"); - + #if defined(WITH_LF_ICERUN) DbpString(" LF sniff/clone/simulation - aka IceRun (iceman)"); #endif @@ -440,13 +440,13 @@ void printStandAloneModes(void) { #endif #if defined(WITH_LF_PROXBRUTE) DbpString(" LF HID ProxII bruteforce - aka Proxbrute (Brad Antoniewicz)"); -#endif +#endif #if defined(WITH_LF_HIDBRUTE) DbpString(" LF HID corporate 1000 bruteforce - aka Corporatebrute (Federico dotta & Maurizio Agazzini)"); -#endif +#endif #if defined(WITH_HF_MATTYRUN) DbpString(" HF Mifare sniff/clone - aka MattyRun (Matías A. Ré Medina)"); -#endif +#endif #if defined(WITH_HF_COLIN) DbpString(" HF Mifare ultra fast sniff/sim/clone - aka VIGIKPWN (Colin Brigato)"); #endif @@ -454,16 +454,16 @@ void printStandAloneModes(void) { DbpString(" HF 14a sniff standalone with ULC/ULEV1/NTAG auth storing in flashmem - aka BogitoRun (Bogito)"); #endif - //DbpString("Running "); - //Dbprintf(" Is Device attached to USB| %s", USB_ATTACHED() ? "Yes" : "No"); - //Dbprintf(" Is Device attached to FPC| %s", 0 ? "Yes" : "No"); + //DbpString("Running "); + //Dbprintf(" Is Device attached to USB| %s", USB_ATTACHED() ? "Yes" : "No"); + //Dbprintf(" Is Device attached to FPC| %s", 0 ? "Yes" : "No"); //Dbprintf(" Is USB_reconnect value | %d", GetUSBreconnect() ); //Dbprintf(" Is USB_configured value | %d", GetUSBconfigured() ); - + //.. add your own standalone detection based on with compiler directive you are used. // don't "reuse" the already taken ones, this will make things easier when trying to detect the different modes // 2017-08-06 must adapt the makefile and have individual compilation flags for all mods - // + // } /* @@ -529,7 +529,7 @@ void ListenReaderField(int limit) { hf_av = hf_max = AvgAdc(ADC_CHAN_HF); // iceman, useless, since we are measuring readerfield, not our field. My tests shows a max of 20v from a reader. - // RDV40 will hit the roof, try other ADC channel used in that hardware revision. + // RDV40 will hit the roof, try other ADC channel used in that hardware revision. bool use_high = ( ((MAX_ADC_HF_VOLTAGE * hf_max) >> 10) > MAX_ADC_HF_VOLTAGE-300 ); if ( use_high ) { hf_av = hf_max = AvgAdc(ADC_CHAN_HF_RDV40); @@ -561,7 +561,7 @@ void ListenReaderField(int limit) { if (limit != HF_ONLY) { if(mode == 1) { - if (ABS(lf_av - lf_baseline) > REPORT_CHANGE) + if (ABS(lf_av - lf_baseline) > REPORT_CHANGE) LED_D_ON(); else LED_D_OFF(); @@ -579,7 +579,7 @@ void ListenReaderField(int limit) { if (limit != LF_ONLY) { if (mode == 1){ - if (ABS(hf_av - hf_baseline) > REPORT_CHANGE) + if (ABS(hf_av - hf_baseline) > REPORT_CHANGE) LED_B_ON(); else LED_B_OFF(); @@ -620,7 +620,7 @@ void ListenReaderField(int limit) { if (LIGHT_SCHEME[i] & 0x8) LED_D_ON(); else LED_D_OFF(); break; } - } + } } } } @@ -629,12 +629,12 @@ void UsbPacketReceived(uint8_t *packet, int len) { UsbCommand *c = (UsbCommand *)packet; //Dbprintf("received %d bytes, with command: 0x%04x and args: %d %d %d", len, c->cmd, c->arg[0], c->arg[1], c->arg[2]); - + switch(c->cmd) { #ifdef WITH_LF case CMD_SET_LF_T55XX_CONFIG: setT55xxConfig( c->arg[0], (t55xx_config *) c->d.asBytes); - break; + break; case CMD_SET_LF_SAMPLING_CONFIG: setSamplingConfig((sample_config *) c->d.asBytes); break; @@ -695,7 +695,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { WriteTItag(c->arg[0],c->arg[1],c->arg[2]); break; case CMD_SIMULATE_TAG_125K: - LED_A_ON(); + LED_A_ON(); SimulateTagLowFrequency(c->arg[0], c->arg[1], 1); LED_A_OFF(); break; @@ -703,7 +703,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { SimulateTagLowFrequencyBidir(c->arg[0], c->arg[1]); break; case CMD_INDALA_CLONE_TAG: - CopyIndala64toT55x7(c->arg[0], c->arg[1]); + CopyIndala64toT55x7(c->arg[0], c->arg[1]); break; case CMD_INDALA_CLONE_TAG_L: CopyIndala224toT55x7( @@ -711,11 +711,11 @@ void UsbPacketReceived(uint8_t *packet, int len) { c->d.asDwords[4], c->d.asDwords[5], c->d.asDwords[6] ); break; - case CMD_T55XX_READ_BLOCK: { + case CMD_T55XX_READ_BLOCK: { T55xxReadBlock(c->arg[0], c->arg[1], c->arg[2]); break; } - case CMD_T55XX_WRITE_BLOCK: + case CMD_T55XX_WRITE_BLOCK: T55xxWriteBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes[0]); break; case CMD_T55XX_WAKEUP: @@ -732,11 +732,11 @@ void UsbPacketReceived(uint8_t *packet, int len) { break; case CMD_PCF7931_WRITE: WritePCF7931( - c->d.asBytes[0], c->d.asBytes[1], c->d.asBytes[2], c->d.asBytes[3], + c->d.asBytes[0], c->d.asBytes[1], c->d.asBytes[2], c->d.asBytes[3], c->d.asBytes[4], c->d.asBytes[5], c->d.asBytes[6], c->d.asBytes[9], - c->d.asBytes[7] - 128, c->d.asBytes[8] - 128, - c->arg[0], - c->arg[1], + c->d.asBytes[7] - 128, c->d.asBytes[8] - 128, + c->arg[0], + c->arg[1], c->arg[2] ); break; @@ -800,7 +800,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { break; case CMD_ISO_15693_FIND_AFI: BruteforceIso15693Afi(c->arg[0]); - break; + break; case CMD_READER_ISO_15693: ReaderIso15693(c->arg[0]); break; @@ -818,7 +818,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { break; case CMD_READER_LEGIC_RF: LegicRfReader(c->arg[0], c->arg[1], c->arg[2]); - break; + break; case CMD_LEGIC_INFO: LegicRfInfo(); break; @@ -878,7 +878,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { break; case CMD_ANTIFUZZ_ISO_14443a: iso14443a_antifuzz(c->arg[0]); - break; + break; case CMD_EPA_PACE_COLLECT_NONCE: EPA_PACE_Collect_Nonce(c); break; @@ -900,7 +900,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { case CMD_MIFAREU_READCARD: MifareUReadCard(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; - case CMD_MIFAREUC_SETPWD: + case CMD_MIFAREUC_SETPWD: MifareUSetPwd(c->arg[0], c->d.asBytes); break; case CMD_MIFARE_READSC: @@ -935,7 +935,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { case CMD_SIMULATE_MIFARE_CARD: Mifare1ksim(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; - + // emulator case CMD_MIFARE_SET_DBGMODE: MifareSetDbgLvl(c->arg[0]); @@ -952,7 +952,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { case CMD_MIFARE_EML_CARDLOAD: MifareECardLoad(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; - + // Work with "magic Chinese" card case CMD_MIFARE_CSETBLOCK: MifareCSetBlock(c->arg[0], c->arg[1], c->d.asBytes); @@ -1071,35 +1071,35 @@ void UsbPacketReceived(uint8_t *packet, int len) { } case CMD_SMART_UPGRADE: { SmartCardUpgrade(c->arg[0]); - break; + break; } -#endif +#endif #ifdef WITH_FPC case CMD_FPC_SEND: { - + StartTicks(); DbpString("Mutual USB/FPC sending from device to client"); - + /* char at[11] = {'\0'}; static const char* s_at = "AT+BAUD8\0D\0A"; - strncat(at, s_at, sizeof(at) - strlen(at) - 1); + strncat(at, s_at, sizeof(at) - strlen(at) - 1); DbpString("Try AT baud rate setting"); usart_init(); int16_t res = usart_writebuffer((uint8_t*)&at, sizeof(at)); WaitMS(1); Dbprintf("SEND %d | %c%c%c%c%c%c%c%c%c%c%c", res, at[0], at[1], at[2], at[3], at[4], at[5], at[6], at[7], at[8], at[9], at[10]); - + uint8_t my_rx[20]; memset(my_rx, 0, sizeof(my_rx)); res = usart_readbuffer(my_rx, sizeof(my_rx)); WaitMS(1); Dbprintf("GOT %d | %c%c%c%c%c%c%c%c", res, my_rx[0], my_rx[1], my_rx[2], my_rx[3], my_rx[4], my_rx[5], my_rx[6], my_rx[7]); */ - - + + char dest[USB_CMD_DATA_SIZE] = { '\0' }; static const char* welcome = "Proxmark3 Serial interface via FPC ready\n"; strncat(dest, welcome, sizeof(dest) - strlen(dest) - 1); @@ -1109,27 +1109,27 @@ void UsbPacketReceived(uint8_t *packet, int len) { , c->d.asBytes[2] , c->d.asBytes[3] ); - + UsbCommand txcmd = { CMD_DEBUG_PRINT_STRING, { strlen(dest), 0, 0 } }; - memcpy(txcmd.d.asBytes, dest, sizeof(dest)); + memcpy(txcmd.d.asBytes, dest, sizeof(dest)); LED_A_ON(); - - usart_init(); + + usart_init(); usart_writebuffer((uint8_t*)&txcmd, sizeof(UsbCommand)); - + //usb cmd_send(CMD_DEBUG_PRINT_STRING, strlen(dest), 0, 0, dest, strlen(dest)); LED_A_OFF(); - - + + /* uint8_t my_rx[sizeof(UsbCommand)]; while (!BUTTON_PRESS() && !usb_poll_validate_length()) { LED_B_INV(); if (usart_readbuffer(my_rx, sizeof(UsbCommand)) ) { //UsbPacketReceived(my_rx, sizeof(my_rx)); - + UsbCommand *my = (UsbCommand *)my_rx; if (mc->cmd > 0 ) { Dbprintf("received command: 0x%04x and args: %d %d %d", my->cmd, my->arg[0], my->arg[1], my->arg[2]); @@ -1179,11 +1179,11 @@ void UsbPacketReceived(uint8_t *packet, int len) { // arg1 = length bytes to transfer // arg2 = BigBuf tracelen //Dbprintf("transfer to client parameters: %" PRIu32 " | %" PRIu32 " | %" PRIu32, startidx, numofbytes, c->arg[2]); - + for(size_t i = 0; i < numofbytes; i += USB_CMD_DATA_SIZE) { len = MIN( (numofbytes - i), USB_CMD_DATA_SIZE); isok = cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K, i, len, BigBuf_get_traceLen(), mem + startidx + i, len); - if (isok != 0) + if (isok != 0) Dbprintf("transfer to client failed :: | bytes between %d - %d (%d)", i, i+len, len); } // Trigger a finish downloading signal with an ACK frame @@ -1196,18 +1196,18 @@ void UsbPacketReceived(uint8_t *packet, int len) { LED_B_OFF(); break; } -#endif +#endif case CMD_UPLOAD_SIM_SAMPLES_125K: { // iceman; since changing fpga_bitstreams clears bigbuff, Its better to call it before. - // to be able to use this one for uploading data to device - // arg1 = 0 upload for LF usage + // to be able to use this one for uploading data to device + // arg1 = 0 upload for LF usage // 1 upload for HF usage #define FPGA_LF 1 if ( c->arg[1] == FPGA_LF ) FpgaDownloadAndGo(FPGA_BITSTREAM_LF); - else + else FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + uint8_t *mem = BigBuf_get_addr(); memcpy( mem + c->arg[0], c->d.asBytes, USB_CMD_DATA_SIZE); cmd_send(CMD_ACK,1,0,0,0,0); @@ -1216,7 +1216,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { case CMD_DOWNLOAD_EML_BIGBUF: { LED_B_ON(); uint8_t *mem = BigBuf_get_EM_addr(); - bool isok = false; + bool isok = false; size_t len = 0; uint32_t startidx = c->arg[0]; uint32_t numofbytes = c->arg[1]; @@ -1228,7 +1228,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { for (size_t i = 0; i < numofbytes; i += USB_CMD_DATA_SIZE) { len = MIN((numofbytes - i), USB_CMD_DATA_SIZE); isok = cmd_send(CMD_DOWNLOADED_EML_BIGBUF, i, len, 0, mem + startidx + i, len); - if (isok != 0) + if (isok != 0) Dbprintf("transfer to client failed :: | bytes between %d - %d (%d)", i, i+len, len); } // Trigger a finish downloading signal with an ACK frame @@ -1239,7 +1239,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { case CMD_READ_MEM: ReadMem(c->arg[0]); break; -#ifdef WITH_FLASH +#ifdef WITH_FLASH case CMD_FLASHMEM_SET_SPIBAUDRATE: FlashmemSetSpiBaudrate(c->arg[0]); break; @@ -1248,20 +1248,20 @@ void UsbPacketReceived(uint8_t *packet, int len) { uint16_t isok = 0; uint32_t startidx = c->arg[0]; uint16_t len = c->arg[1]; - + Dbprintf("FlashMem read | %d - %d | ", startidx, len); - + size_t size = MIN(USB_CMD_DATA_SIZE, len); - + if (!FlashInit()) { break; } uint8_t *mem = BigBuf_malloc(size); - + for(size_t i = 0; i < len; i += size) { len = MIN((len - i), size); - + Dbprintf("FlashMem reading | %d | %d | %d |", startidx + i, i, len); isok = Flash_ReadDataCont(startidx + i, mem, len); if ( isok == len ) { @@ -1283,16 +1283,16 @@ void UsbPacketReceived(uint8_t *packet, int len) { uint32_t startidx = c->arg[0]; uint16_t len = c->arg[1]; uint8_t* data = c->d.asBytes; - + uint32_t tmp = startidx + len; - + if (!FlashInit()) { break; } Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); - + if ( startidx == DEFAULT_T55XX_KEYS_OFFSET ) Flash_Erase4k(3, 0xC); else if (startidx == DEFAULT_MF_KEYS_OFFSET ) @@ -1301,33 +1301,33 @@ void UsbPacketReceived(uint8_t *packet, int len) { Flash_Erase4k(3, 0xA); Flash_CheckBusy(BUSY_TIMEOUT); - Flash_WriteEnable(); - + Flash_WriteEnable(); + // inside 256b page? - if ( (tmp & 0xFF) != 0) { - + if ( (tmp & 0xFF) != 0) { + // is offset+len larger than a page tmp = (startidx & 0xFF ) + len; if (tmp > 0xFF ) { - + // data spread over two pages. - - // offset xxxx10, + + // offset xxxx10, uint8_t first_len = (~startidx & 0xFF)+1; - - // first mem page + + // first mem page res = Flash_WriteDataCont(startidx, data, first_len); - + // second mem page res = Flash_WriteDataCont(startidx + first_len, data + first_len, len - first_len); - + isok = (res == (len - first_len)) ? 1 : 0; - + } else { res = Flash_WriteDataCont(startidx, data, len); isok = (res == len) ? 1 : 0; - } - } else { + } + } else { res = Flash_WriteDataCont(startidx, data, len); isok = (res == len) ? 1 : 0; } @@ -1350,7 +1350,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { } if ( page < 3) isok = Flash_WipeMemoryPage(page); - + cmd_send(CMD_ACK, isok, 0, 0, 0, 0); LED_B_OFF(); break; @@ -1359,14 +1359,14 @@ void UsbPacketReceived(uint8_t *packet, int len) { LED_B_ON(); uint8_t *mem = BigBuf_malloc(USB_CMD_DATA_SIZE); - bool isok = false; + bool isok = false; size_t len = 0; uint32_t startidx = c->arg[0]; uint32_t numofbytes = c->arg[1]; // arg0 = startindex // arg1 = length bytes to transfer // arg2 = RFU - + if (!FlashInit()) { break; } @@ -1383,7 +1383,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { Dbprintf("transfer to client failed :: | bytes between %d - %d", i, len); } FlashStop(); - + cmd_send(CMD_ACK, 1, 0, 0, 0, 0); LED_B_OFF(); break; @@ -1392,7 +1392,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { LED_B_ON(); rdv40_validation_t *info = (rdv40_validation_t*)BigBuf_malloc( sizeof(rdv40_validation_t) ); - + bool isok = Flash_ReadData(FLASH_MEM_SIGNATURE_OFFSET, info->signature, FLASH_MEM_SIGNATURE_LEN); if (FlashInit()) { @@ -1401,8 +1401,8 @@ void UsbPacketReceived(uint8_t *packet, int len) { } cmd_send(CMD_ACK, isok, 0, 0, info, sizeof(rdv40_validation_t)); BigBuf_free(); - - LED_B_OFF(); + + LED_B_OFF(); break; } #endif @@ -1445,7 +1445,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { usb_disable(); // (iceman) why this wait? - SpinDelay(1000); + SpinDelay(1000); AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST; // We're going to reset, and the bootrom will take control. for(;;) {} @@ -1458,7 +1458,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { usb_disable(); AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST; // We're going to flash, and the bootrom will take control. - for(;;) {} + for(;;) {} break; case CMD_DEVICE_INFO: { @@ -1466,7 +1466,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { if (common_area.flags.bootrom_present) { dev_info |= DEVICE_INFO_FLAG_BOOTROM_PRESENT; } - cmd_send(CMD_DEVICE_INFO,dev_info,0,0,0,0); + cmd_send(CMD_DEVICE_INFO,dev_info,0,0,0,0); break; } default: @@ -1479,7 +1479,7 @@ void __attribute__((noreturn)) AppMain(void) { SpinDelay(100); clear_trace(); - + if(common_area.magic != COMMON_AREA_MAGIC || common_area.version != 1) { /* Initialize common area */ memset(&common_area, 0, sizeof(common_area)); @@ -1489,7 +1489,7 @@ void __attribute__((noreturn)) AppMain(void) { common_area.flags.osimage_present = 1; LEDsoff(); - + // The FPGA gets its clock from us from PCK0 output, so set that up. AT91C_BASE_PIOA->PIO_BSR = GPIO_PCK0; AT91C_BASE_PIOA->PIO_PDR = GPIO_PCK0; @@ -1501,19 +1501,19 @@ void __attribute__((noreturn)) AppMain(void) { // Reset SPI AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST; AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SWRST; // errata says it needs twice to be correctly set. - + // Reset SSC AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST; // Configure MUX SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - + // Load the FPGA image, which we have stored in our flash. // (the HF version by default) FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + StartTickCount(); - + #ifdef WITH_LCD LCDInit(); #endif @@ -1524,22 +1524,22 @@ void __attribute__((noreturn)) AppMain(void) { #ifdef WITH_FPC usart_init(); -#endif +#endif #ifdef WITH_FLASH loadT55xxConfig(); #endif // This is made as late as possible to ensure enumeration without timeout - // against device such as http://www.hobbytronics.co.uk/usb-host-board-v2 + // against device such as http://www.hobbytronics.co.uk/usb-host-board-v2 usb_disable(); usb_enable(); uint8_t rx[sizeof(UsbCommand)]; - + for(;;) { WDT_HIT(); - + // Check if there is a usb packet available if (usb_poll_validate_length()) { if (usb_read(rx, sizeof(rx)) ) @@ -1554,19 +1554,19 @@ void __attribute__((noreturn)) AppMain(void) { */ #endif - + // Press button for one second to enter a possible standalone mode if (BUTTON_HELD(1000) > 0) { - + /* * So this is the trigger to execute a standalone mod. Generic entrypoint by following the standalone/standalone.h headerfile * All standalone mod "main loop" should be the RunMod() function. -* Since the standalone is either LF or HF, the somewhat bisarr defines below exists. -*/ +* Since the standalone is either LF or HF, the somewhat bisarr defines below exists. +*/ #if defined (WITH_LF) && ( defined (WITH_LF_SAMYRUN) || defined (WITH_LF_HIDBRUTE) || defined (WITH_LF_PROXBRUTE) ) RunMod(); #endif - + #if defined (WITH_ISO14443a) && ( defined (WITH_HF_YOUNG) || defined(WITH_HF_COLIN) || defined(WITH_HF_MATTYRUN) || defined(WITH_HF_BOG) ) RunMod(); #endif diff --git a/armsrc/apps.h b/armsrc/apps.h index d17d9ef4b..276331575 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -174,7 +174,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ); //desfire void Mifare_DES_Auth1(uint8_t arg0,uint8_t *datain); -void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain); +void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain); // mifaredesfire.h bool InitDesfireCard(); @@ -205,7 +205,7 @@ void AcquireRawAdcSamplesIso15693(void); void ReaderIso15693(uint32_t parameter); // Simulate an ISO15693 reader - greg void SimTagIso15693(uint32_t parameter, uint8_t *uid); // simulate an ISO15693 tag - greg void BruteforceIso15693Afi(uint32_t speed); // find an AFI of a tag - atrox -void DirectTag15693Command(uint32_t datalen,uint32_t speed, uint32_t recv, uint8_t *data); // send arbitrary commands from CLI - atrox +void DirectTag15693Command(uint32_t datalen,uint32_t speed, uint32_t recv, uint8_t *data); // send arbitrary commands from CLI - atrox void Iso15693InitReader(void); // iclass.h diff --git a/armsrc/buzzer.c b/armsrc/buzzer.c index 23e7e05d6..5f29c6472 100644 --- a/armsrc/buzzer.c +++ b/armsrc/buzzer.c @@ -1,6 +1,6 @@ #include "buzzer.h" -void Ring_BEE_ONCE(uint16_t music_note) { +void Ring_BEE_ONCE(uint16_t music_note) { BEE_ON(); SpinDelayUs(music_note); BEE_OFF(); @@ -12,7 +12,7 @@ void ring_2_7khz(uint16_t count) { } void Ring_BEE_TIME(uint16_t music_note,uint16_t count) { - for(uint16_t i=0 ; i < count; i++) + for(uint16_t i=0 ; i < count; i++) Ring_BEE_ONCE(music_note); SpinDelay(9); } @@ -28,15 +28,15 @@ void Ring_ALL(uint16_t count) { SpinDelay(10); } -void Ring_Little_Star(uint16_t count) { - Ring_BEE_TIME(note_1,count); - Ring_BEE_TIME(note_1,count); +void Ring_Little_Star(uint16_t count) { + Ring_BEE_TIME(note_1,count); + Ring_BEE_TIME(note_1,count); Ring_BEE_TIME(note_5,count); Ring_BEE_TIME(note_5,count); Ring_BEE_TIME(note_6,count); Ring_BEE_TIME(note_6,count); Ring_BEE_TIME(note_5,2*count); - LED_A_ON(); + LED_A_ON(); /* Ring_BEE_TIME(note_4,count); Ring_BEE_TIME(note_4,count); @@ -45,7 +45,7 @@ void Ring_Little_Star(uint16_t count) { Ring_BEE_TIME(note_2,count); Ring_BEE_TIME(note_2,count); Ring_BEE_TIME(note_1,2*count); - LED_A_OFF(); + LED_A_OFF(); Ring_BEE_TIME(note_5,count); Ring_BEE_TIME(note_5,count); @@ -54,7 +54,7 @@ void Ring_Little_Star(uint16_t count) { Ring_BEE_TIME(note_3,count); Ring_BEE_TIME(note_3,count); Ring_BEE_TIME(note_2,2*count); - LED_A_ON(); + LED_A_ON(); Ring_BEE_TIME(note_5,count); Ring_BEE_TIME(note_5,count); @@ -63,7 +63,7 @@ void Ring_Little_Star(uint16_t count) { Ring_BEE_TIME(note_3,count); Ring_BEE_TIME(note_3,count); Ring_BEE_TIME(note_2,2*count); - LED_A_OFF(); + LED_A_OFF(); Ring_BEE_TIME(note_1,count); Ring_BEE_TIME(note_1,count); @@ -72,7 +72,7 @@ void Ring_Little_Star(uint16_t count) { Ring_BEE_TIME(note_6,count); Ring_BEE_TIME(note_6,count); Ring_BEE_TIME(note_5,2*count); - LED_A_ON(); + LED_A_ON(); Ring_BEE_TIME(note_4,count); Ring_BEE_TIME(note_4,count); diff --git a/armsrc/des.c b/armsrc/des.c index 78ae87447..be5670e69 100644 --- a/armsrc/des.c +++ b/armsrc/des.c @@ -23,7 +23,7 @@ * \date 2007-06-16 * \brief DES and EDE-DES implementation * \license GPLv3 or later - * + * */ #include "des.h" @@ -145,25 +145,25 @@ const uint8_t pc2_permtab[] ={ const uint8_t splitin6bitword_permtab[] = { 8, 8, /* 64 bit -> 64 bit */ - 64, 64, 1, 6, 2, 3, 4, 5, - 64, 64, 7, 12, 8, 9, 10, 11, - 64, 64, 13, 18, 14, 15, 16, 17, - 64, 64, 19, 24, 20, 21, 22, 23, - 64, 64, 25, 30, 26, 27, 28, 29, - 64, 64, 31, 36, 32, 33, 34, 35, - 64, 64, 37, 42, 38, 39, 40, 41, - 64, 64, 43, 48, 44, 45, 46, 47 + 64, 64, 1, 6, 2, 3, 4, 5, + 64, 64, 7, 12, 8, 9, 10, 11, + 64, 64, 13, 18, 14, 15, 16, 17, + 64, 64, 19, 24, 20, 21, 22, 23, + 64, 64, 25, 30, 26, 27, 28, 29, + 64, 64, 31, 36, 32, 33, 34, 35, + 64, 64, 37, 42, 38, 39, 40, 41, + 64, 64, 43, 48, 44, 45, 46, 47 }; const uint8_t shiftkey_permtab[] = { 7, 7, /* 56 bit -> 56 bit */ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, - 18, 19, 20, 21, 22, 23, 24, 25, - 26, 27, 28, 1, - 30, 31, 32, 33, 34, 35, 36, 37, - 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53, + 18, 19, 20, 21, 22, 23, 24, 25, + 26, 27, 28, 1, + 30, 31, 32, 33, 34, 35, 36, 37, + 38, 39, 40, 41, 42, 43, 44, 45, + 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 29 }; @@ -173,9 +173,9 @@ const uint8_t shiftkeyinv_permtab[] = { 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, - 56, 29, 30, 31, 32, 33, 34, 35, - 36, 37, 38, 39, 40, 41, 42, 43, - 44, 45, 46, 47, 48, 49, 50, 51, + 56, 29, 30, 31, 32, 33, 34, 35, + 36, 37, 38, 39, 40, 41, 42, 43, + 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55 }; @@ -198,7 +198,7 @@ const uint8_t shiftkeyinv_permtab[] = { 2 1 1 0 */ -#define ROTTABLE 0x7EFC +#define ROTTABLE 0x7EFC #define ROTTABLE_INV 0x3F7E /******************************************************************************/ @@ -234,7 +234,7 @@ static inline void shiftkey(uint8_t *key){ uint8_t k[7]; memcpy(k, key, 7); - permute((uint8_t*)shiftkey_permtab, k, key); + permute((uint8_t*)shiftkey_permtab, k, key); } /******************************************************************************/ @@ -243,7 +243,7 @@ void shiftkey_inv(uint8_t *key){ uint8_t k[7]; memcpy(k, key, 7); permute((uint8_t*)shiftkeyinv_permtab, k, key); - + } /******************************************************************************/ @@ -251,7 +251,7 @@ static inline uint64_t splitin6bitwords(uint64_t a){ uint64_t ret=0; a &= 0x0000ffffffffffffLL; - permute((uint8_t*)splitin6bitword_permtab, (uint8_t*)&a, (uint8_t*)&ret); + permute((uint8_t*)splitin6bitword_permtab, (uint8_t*)&a, (uint8_t*)&ret); return ret; } @@ -259,11 +259,11 @@ uint64_t splitin6bitwords(uint64_t a){ static inline uint8_t substitute(uint8_t a, uint8_t * sbp){ - uint8_t x; + uint8_t x; x = sbp[a>>1]; x = (a&1)?x&0x0F:x>>4; return x; - + } /******************************************************************************/ @@ -272,11 +272,11 @@ uint32_t des_f(uint32_t r, uint8_t* kr){ uint8_t i; uint32_t t=0,ret; uint64_t data; - uint8_t *sbp; /* sboxpointer */ + uint8_t *sbp; /* sboxpointer */ permute((uint8_t*)e_permtab, (uint8_t*)&r, (uint8_t*)&data); for(i=0; i<6; ++i) ((uint8_t*)&data)[i] ^= kr[i]; - + /* Sbox substitution */ data = splitin6bitwords(data); sbp=(uint8_t*)sbox; @@ -288,7 +288,7 @@ uint32_t des_f(uint32_t r, uint8_t* kr){ sbp += 32; } changeendian32(&t); - + permute((uint8_t*)p_permtab,(uint8_t*)&t, (uint8_t*)&ret); return ret; @@ -310,7 +310,7 @@ void des_enc(void* out, const void* in, const void* key){ uint8_t kr[6], k[7]; uint8_t i; data_t data; - + permute((uint8_t*)ip_permtab, (uint8_t*)in, data.d.v8); permute((uint8_t*)pc1_permtab, (const uint8_t*)key, k); @@ -320,7 +320,7 @@ void des_enc(void* out, const void* in, const void* key){ shiftkey(k); permute((uint8_t*)pc2_permtab, k, kr); L ^= des_f(R, kr); - + shiftkey(k); if(ROTTABLE&((1<<((i<<1)+1))) ) shiftkey(k); @@ -332,7 +332,7 @@ void des_enc(void* out, const void* in, const void* key){ R ^= L; L ^= R; R ^= L; - + permute((uint8_t*)inv_ip_permtab, data.d.v8, (uint8_t*)out); } @@ -343,11 +343,11 @@ void des_dec(void* out, const void* in, const uint8_t* key){ uint8_t kr[6],k[7]; int8_t i; data_t data; - + permute((uint8_t*)ip_permtab, (uint8_t*)in, data.d.v8); permute((uint8_t*)pc1_permtab, (const uint8_t*)key, k); for(i=7; i>=0; --i){ - + permute((uint8_t*)pc2_permtab, k, kr); L ^= des_f(R, kr); shiftkey_inv(k); @@ -367,7 +367,7 @@ void des_dec(void* out, const void* in, const uint8_t* key){ R ^= L; L ^= R; R ^= L; - + permute((uint8_t*)inv_ip_permtab, data.d.v8, (uint8_t*)out); } @@ -389,51 +389,51 @@ void tdes_dec(void* out, void* in, const uint8_t* key){ void tdes_2key_enc(void* out, const void* in, size_t length, const void* key, unsigned char iv[8]){ - if( length % 8 ) return; + if( length % 8 ) return; uint8_t i; uint8_t* tin = (uint8_t*) in; uint8_t* tout = (uint8_t*) out; - + while( length > 0 ) { for( i = 0; i < 8; i++ ) tout[i] = (unsigned char)( tin[i] ^ iv[i] ); - + des_enc(tout, tin, (uint8_t*)key + 0); des_dec(tout, tout, (uint8_t*)key + 8); des_enc(tout, tout, (uint8_t*)key + 0); - + memcpy( iv, tout, 8 ); - + tin += 8; tout += 8; length -= 8; } } - + void tdes_2key_dec(void* out, const void* in, size_t length, const void* key, unsigned char iv[8]){ - - if( length % 8 ) return; + + if( length % 8 ) return; uint8_t i; unsigned char temp[8]; uint8_t* tin = (uint8_t*) in; uint8_t* tout = (uint8_t*) out; - + while( length > 0 ) { memcpy( temp, tin, 8 ); - + des_dec(tout, tin, (uint8_t*)key + 0); des_enc(tout, tout, (uint8_t*)key + 8); - des_dec(tout, tout, (uint8_t*)key + 0); + des_dec(tout, tout, (uint8_t*)key + 0); for( i = 0; i < 8; i++ ) tout[i] = (unsigned char)( tout[i] ^ iv[i] ); memcpy( iv, temp, 8 ); - + tin += 8; tout += 8; length -= 8; diff --git a/armsrc/des.h b/armsrc/des.h index 03b9f6469..22735f2f3 100644 --- a/armsrc/des.h +++ b/armsrc/des.h @@ -18,11 +18,11 @@ */ /** * \file des.h - * \author Daniel Otte + * \author Daniel Otte * \date 2007-06-16 * \brief des and tdes declarations * \license GPLv3 or later - * + * */ #ifndef __DES_H_ #define __DES_H_ @@ -46,12 +46,12 @@ /** \fn void des_enc(void* out, const void* in, const void* key) * \brief encrypt a block with DES - * + * * This function encrypts a block of 64 bits (8 bytes) with the DES algorithm. * Key expansion is done automatically. The key is 64 bits long, but note that * only 56 bits are used (the LSB of each byte is dropped). The input and output * blocks may overlap. - * + * * \param out pointer to the block (64 bit = 8 byte) where the ciphertext is written to * \param in pointer to the block (64 bit = 8 byte) where the plaintext is read from * \param key pointer to the key (64 bit = 8 byte) @@ -60,12 +60,12 @@ void des_enc(void* out, const void* in, const void* key); /** \fn void des_dec(void* out, const void* in, const void* key) * \brief decrypt a block with DES - * + * * This function decrypts a block of 64 bits (8 bytes) with the DES algorithm. * Key expansion is done automatically. The key is 64 bits long, but note that * only 56 bits are used (the LSB of each byte is dropped). The input and output * blocks may overlap. - * + * * \param out pointer to the block (64 bit = 8 byte) where the plaintext is written to * \param in pointer to the block (64 bit = 8 byte) where the ciphertext is read from * \param key pointer to the key (64 bit = 8 byte) @@ -75,12 +75,12 @@ void des_dec(void* out, const void* in, const uint8_t* key); /** \fn void tdes_enc(void* out, const void* in, const void* key) * \brief encrypt a block with Tripple-DES - * + * * This function encrypts a block of 64 bits (8 bytes) with the Tripple-DES (EDE) * algorithm. Key expansion is done automatically. The key is 192 bits long, but * note that only 178 bits are used (the LSB of each byte is dropped). The input * and output blocks may overlap. - * + * * \param out pointer to the block (64 bit = 8 byte) where the ciphertext is written to * \param in pointer to the block (64 bit = 8 byte) where the plaintext is read from * \param key pointer to the key (192 bit = 24 byte) @@ -90,19 +90,19 @@ void tdes_enc(void* out, void* in, const void* key); /** \fn void tdes_dec(void* out, const void* in, const void* key) * \brief decrypt a block with Tripple-DES - * + * * This function decrypts a block of 64 bits (8 bytes) with the Tripple-DES (EDE) * algorithm. Key expansion is done automatically. The key is 192 bits long, but * note that only 178 bits are used (the LSB of each byte is dropped). The input * and output blocks may overlap. - * + * * \param out pointer to the block (64 bit = 8 byte) where the plaintext is written to * \param in pointer to the block (64 bit = 8 byte) where the ciphertext is read from * \param key pointer to the key (192 bit = 24 byte) */ //void tdes_dec(void* out, const void* in, const void* key); void tdes_dec(void* out, void* in, const uint8_t* key); - + void tdes_2key_enc(void* out, const void* in, size_t length, const void* key, unsigned char iv[8]); void tdes_2key_dec(void* out, const void* in, size_t length, const void* key, unsigned char iv[8]); diff --git a/armsrc/desfire_crypto.c b/armsrc/desfire_crypto.c index 5cb36054c..d79ecc8e3 100644 --- a/armsrc/desfire_crypto.c +++ b/armsrc/desfire_crypto.c @@ -1,11 +1,11 @@ /*- * Copyright (C) 2010, Romain Tartiere. - * + * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for @@ -13,7 +13,7 @@ * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see - * + * * $Id$ */ @@ -447,10 +447,10 @@ void* mifare_cryto_postprocess_data (desfiretag_t tag, void *data, size_t *nbyte switch (DESFIRE (tag)->authentication_scheme) { case AS_LEGACY: AddCrc14A( (uint8_t*)res, end_crc_pos); - end_crc_pos = crc_pos + 2; - // - - + end_crc_pos = crc_pos + 2; + // + + crc = crc16; break; case AS_NEW: @@ -539,7 +539,7 @@ void mifare_cypher_single_block (desfirekey_t key, uint8_t *data, uint8_t *ivect break; case T_3DES: switch (operation) { - case MCO_ENCYPHER: + case MCO_ENCYPHER: // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT); // DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_DECRYPT); // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_ENCRYPT); @@ -562,7 +562,7 @@ void mifare_cypher_single_block (desfirekey_t key, uint8_t *data, uint8_t *ivect // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks3), DES_ENCRYPT); break; case MCO_DECYPHER: - tdes_dec(data, edata, key->data); + tdes_dec(data, edata, key->data); // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks3), DES_DECRYPT); // DES_ecb_encrypt ((DES_cblock *) edata, (DES_cblock *) data, &(key->ks2), DES_ENCRYPT); // DES_ecb_encrypt ((DES_cblock *) data, (DES_cblock *) edata, &(key->ks1), DES_DECRYPT); @@ -570,19 +570,19 @@ void mifare_cypher_single_block (desfirekey_t key, uint8_t *data, uint8_t *ivect } break; case T_AES: - switch (operation) + switch (operation) { case MCO_ENCYPHER: { AesCtx ctx; - AesCtxIni(&ctx, ivect, key->data, KEY128,CBC); + AesCtxIni(&ctx, ivect, key->data, KEY128,CBC); AesEncrypt(&ctx, data, edata, sizeof(edata) ); break; } case MCO_DECYPHER: { AesCtx ctx; - AesCtxIni(&ctx, ivect, key->data, KEY128,CBC); + AesCtxIni(&ctx, ivect, key->data, KEY128,CBC); AesDecrypt(&ctx, edata, data, sizeof(edata)); break; } diff --git a/armsrc/desfire_key.c b/armsrc/desfire_key.c index 800ff6da6..a4ed05f68 100644 --- a/armsrc/desfire_key.c +++ b/armsrc/desfire_key.c @@ -1,11 +1,11 @@ /*- * Copyright (C) 2010, Romain Tartiere. - * + * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. - * + * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for @@ -13,7 +13,7 @@ * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see - * + * * $Id$ */ diff --git a/armsrc/epa.c b/armsrc/epa.c index 71ecc29a3..80d51e553 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -289,7 +289,7 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) // set up communication func_return = EPA_Setup(); - if (func_return != 0) { + if (func_return != 0) { EPA_PACE_Collect_Nonce_Abort(1, func_return); return; } diff --git a/armsrc/felica.c b/armsrc/felica.c index d1e7bc344..6b2bb5bfb 100644 --- a/armsrc/felica.c +++ b/armsrc/felica.c @@ -16,7 +16,7 @@ # define FELICA_FRAME_DELAY_TIME (2672/16 + 1) #endif #ifndef DELAY_AIR2ARM_AS_READER -#define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16) +#define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16) #endif #ifndef DELAY_ARM2AIR_AS_READER #define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1) @@ -46,7 +46,7 @@ uint32_t iso18092_get_timeout(void) { #define FELICA_MAX_FRAME_SIZE 260 #endif -//structure to hold outgoing NFC frame +//structure to hold outgoing NFC frame static uint8_t frameSpace[FELICA_MAX_FRAME_SIZE+4]; //structure to hold incoming NFC frame, used for ISO/IEC 18092-compatible frames @@ -89,10 +89,10 @@ static void FelicaFrameinit(uint8_t *data) { } //shift byte into frame, reversing it at the same time -static void shiftInByte(uint8_t bt) { +static void shiftInByte(uint8_t bt) { uint8_t j; for(j=0; j < FelicaFrame.byte_offset; j++) { - FelicaFrame.framebytes[FelicaFrame.posCnt] = ( FelicaFrame.framebytes[FelicaFrame.posCnt]<<1 ) + (bt & 1); + FelicaFrame.framebytes[FelicaFrame.posCnt] = ( FelicaFrame.framebytes[FelicaFrame.posCnt]<<1 ) + (bt & 1); bt >>= 1; } FelicaFrame.posCnt++; @@ -120,7 +120,7 @@ static void Process18092Byte(uint8_t bt) { FelicaFrame.state = STATE_UNSYNCD; } else { for (uint8_t i=0; i<8; i++) { - + if (FelicaFrame.shiftReg == SYNC_16BIT) { //SYNC done! FelicaFrame.state = STATE_GET_LENGTH; @@ -132,7 +132,7 @@ static void Process18092Byte(uint8_t bt) { FelicaFrame.framebytes[2] = (FelicaFrame.framebytes[2] << 1) + (bt & 1); bt >>= 1; } - + FelicaFrame.posCnt = 2; if (i==0) break; @@ -146,7 +146,7 @@ static void Process18092Byte(uint8_t bt) { //Force SYNC on next byte FelicaFrame.state = STATE_GET_LENGTH; FelicaFrame.framebytes[0] = 0xb2; - FelicaFrame.framebytes[1] = 0x4d; + FelicaFrame.framebytes[1] = 0x4d; FelicaFrame.byte_offset = 0; FelicaFrame.posCnt = 1; } @@ -176,12 +176,12 @@ static void Process18092Byte(uint8_t bt) { FelicaFrame.crc_ok = check_crc(CRC_FELICA, FelicaFrame.framebytes+2, FelicaFrame.len-2); FelicaFrame.state = STATE_FULL; FelicaFrame.rem_len = 0; - if (MF_DBGLEVEL > 3) Dbprintf("[+] got 2 crc bytes [%s]", (FelicaFrame.crc_ok) ? "OK" : "No" ); + if (MF_DBGLEVEL > 3) Dbprintf("[+] got 2 crc bytes [%s]", (FelicaFrame.crc_ok) ? "OK" : "No" ); } break; } - case STATE_FULL: //ignore byte. Don't forget to clear frame to receive next one... - default: + case STATE_FULL: //ignore byte. Don't forget to clear frame to receive next one... + default: break; } } @@ -196,19 +196,19 @@ static uint8_t felica_select_card(felica_card_select_t *card) { // 0xB2 0x4B = sync code // 0x06 = len // 0x00 = rfu - // 0xff = system service + // 0xff = system service // 0xff = system service // 0x00 = // b7 = automatic switching of data rate // b6-b2 = reserved // b1 = fc/32 (414kbps) - // b0 = fc/64 (212kbps) + // b0 = fc/64 (212kbps) // 0x00 = timeslot // 0x09 0x21 = crc static uint8_t poll[10] = {0xb2,0x4d,0x06,FELICA_POLL_REQ,0xFF,0xFF,0x00,0x00,0x09,0x21}; - + int len = 20; - + // We try 20 times, or if answer was received. do { // end-of-reception response packet data, wait approx. 501μs @@ -219,23 +219,23 @@ static uint8_t felica_select_card(felica_card_select_t *card) { // polling card, break if success if (WaitForFelicaReply(512) && FelicaFrame.framebytes[3] == FELICA_POLL_ACK) break; - + WDT_HIT(); - + } while (--len); - + // timed-out if ( len == 0 ) return 1; - - // wrong answer + + // wrong answer if (FelicaFrame.framebytes[3] != FELICA_POLL_ACK) return 2; - + // VALIDATE CRC residue is 0, hence if crc is a value it failed. if (!check_crc(CRC_FELICA, FelicaFrame.framebytes+2, FelicaFrame.len-2)) return 3; - + // copy UID // idm 8 if (card) { @@ -246,9 +246,9 @@ static uint8_t felica_select_card(felica_card_select_t *card) { memcpy(card->uid, card->IDm + 2, 6); memcpy(card->iccode, card->PMm, 2); memcpy(card->mrt, card->PMm+2, 6); - + } - // more status bytes? + // more status bytes? return 0; } @@ -257,42 +257,42 @@ static uint8_t felica_select_card(felica_card_select_t *card) { // poll-1 (reply with available system codes - NFC Tag3 specs, IIRC): 0xb2,0x4d,0x06,0x00,0xff,0xff,0x01,0x00,0x3a,0x10 // resp: 0xb2,0x4d,0x14,0x01, 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX, 0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00, 0x88,0xb4,0x0c,0xe2, // page-req: 0xb2,0x4d,0x10,0x06, 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX, 0x01, 0x0b,0x00, 0x01, 0x80,0x00, 0x2e,0xb3, -// page-req: 0x06, IDm(8), ServiceNum(1),Slist(2*num) BLocknum (1) BLockids(2-3*num) +// page-req: 0x06, IDm(8), ServiceNum(1),Slist(2*num) BLocknum (1) BLockids(2-3*num) // page-resp: 0xb2,0x4d,0x1d,0x07, 0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX,0xXX, 0x00, 0x00, 0x01, 0x10,0x04,0x01,0x00,0x0d,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x23, 0xcb,0x6e, -// builds a readblock frame for felica lite(s). Using SERVICE: SERVICE_FELICA_LITE_READONLY -// Felica standard has a different file system, AFAIK, +// builds a readblock frame for felica lite(s). Using SERVICE: SERVICE_FELICA_LITE_READONLY +// Felica standard has a different file system, AFAIK, // 8-byte IDm, number of blocks, blocks numbers // number of blocks limited to 4 for FelicaLite(S) static void BuildFliteRdblk(uint8_t* idm, int blocknum, uint16_t *blocks ) { if (blocknum > 4 || blocknum <= 0) Dbprintf("Invalid number of blocks, %d != 4", blocknum); - + uint8_t c = 0, i = 0; - + frameSpace[c++] = 0xb2; frameSpace[c++] = 0x4d; - + c++; //set length later - + frameSpace[c++] = FELICA_RDBLK_REQ; //command number - + //card IDm, from poll frameSpace[c++] = idm[0]; frameSpace[c++] = idm[1]; frameSpace[c++] = idm[2]; frameSpace[c++] = idm[3]; frameSpace[c++] = idm[4]; - frameSpace[c++] = idm[5]; + frameSpace[c++] = idm[5]; frameSpace[c++] = idm[6]; frameSpace[c++] = idm[7]; - //number of services - frameSpace[c++] = 0x01; - + //number of services + frameSpace[c++] = 0x01; + //service code - frameSpace[c++] = (SERVICE_FELICA_LITE_READONLY >> 8); + frameSpace[c++] = (SERVICE_FELICA_LITE_READONLY >> 8); frameSpace[c++] = SERVICE_FELICA_LITE_READONLY & 0xFF; //number of blocks @@ -304,20 +304,20 @@ static void BuildFliteRdblk(uint8_t* idm, int blocknum, uint16_t *blocks ) { if (blocks[i] >= 256) { frameSpace[c++] = 0x00; frameSpace[c++] = (blocks[i] >> 8); //block number, little endian.... - frameSpace[c++] = (blocks[i] & 0xff); + frameSpace[c++] = (blocks[i] & 0xff); } else { frameSpace[c++] = 0x80; frameSpace[c++] = blocks[i]; } } - - //set length - frameSpace[2] = c-2; + + //set length + frameSpace[2] = c-2; AddCrc(frameSpace, c-2); } static void TransmitFor18092_AsReader(uint8_t * frame, int len, uint32_t *timing, uint8_t power, uint8_t highspeed) { - + uint8_t flags = FPGA_MAJOR_MODE_ISO18092; if ( power ) @@ -326,19 +326,19 @@ static void TransmitFor18092_AsReader(uint8_t * frame, int len, uint32_t *timing flags |= FPGA_HF_ISO18092_FLAG_424K; FpgaWriteConfWord(flags); - + uint32_t curr_transfer_time = ((MAX(felica_nexttransfertime, GetCountSspClk()) & 0xfffffff8) + 8); while (GetCountSspClk() < curr_transfer_time) {}; felica_lasttime_prox2air_start = curr_transfer_time; - + // preamble // sending 0x00 0x00 0x00 0x00 0x00 0x00 - uint16_t c = 0; + uint16_t c = 0; while (c < 6) { - // keep tx buffer in a defined state anyway. + // keep tx buffer in a defined state anyway. if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = 0x00; c++; @@ -350,16 +350,16 @@ static void TransmitFor18092_AsReader(uint8_t * frame, int len, uint32_t *timing c = 0; while (c < len) { - // Put byte into tx holding register as soon as it is ready + // Put byte into tx holding register as soon as it is ready if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = frame[c++]; } } -/**/ +/**/ while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) {}; AT91C_BASE_SSC->SSC_THR = 0x00; //minimum delay - + while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) {}; AT91C_BASE_SSC->SSC_THR = 0x00; //spin /**/ @@ -373,7 +373,7 @@ static void TransmitFor18092_AsReader(uint8_t * frame, int len, uint32_t *timing NULL, true ); - + felica_nexttransfertime = MAX(felica_nexttransfertime ,felica_lasttime_prox2air_start + FELICA_REQUEST_GUARD_TIME); } @@ -383,7 +383,7 @@ static void TransmitFor18092_AsReader(uint8_t * frame, int len, uint32_t *timing bool WaitForFelicaReply(uint16_t maxbytes) { uint32_t c = 0; - + // power, no modulation FpgaWriteConfWord(FPGA_MAJOR_MODE_ISO18092 | FPGA_HF_ISO18092_FLAG_READER | FPGA_HF_ISO18092_FLAG_NOMOD); @@ -391,22 +391,22 @@ bool WaitForFelicaReply(uint16_t maxbytes) { // clear RXRDY: uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - + uint32_t timeout = iso18092_get_timeout(); for(;;) { - WDT_HIT(); - + WDT_HIT(); + if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { - b = (uint8_t)(AT91C_BASE_SSC->SSC_RHR); - Process18092Byte(b); + b = (uint8_t)(AT91C_BASE_SSC->SSC_RHR); + Process18092Byte(b); if (FelicaFrame.state == STATE_FULL) { - felica_nexttransfertime = + felica_nexttransfertime = MAX( felica_nexttransfertime, (GetCountSspClk() & 0xfffffff8) - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER)/16 + FELICA_FRAME_DELAY_TIME ) - ; - + ; + LogTrace( FelicaFrame.framebytes, FelicaFrame.len, @@ -417,13 +417,13 @@ bool WaitForFelicaReply(uint16_t maxbytes) { ); return true; } else if (c++ > timeout && FelicaFrame.state == STATE_UNSYNCD) { - return false; + return false; } else if (FelicaFrame.state == STATE_GET_CRC) { Dbprintf(" Frame: "); Dbhexdump(16, FelicaFrame.framebytes, 0); //return false; } - } + } } return false; } @@ -437,34 +437,34 @@ static void iso18092_setup(uint8_t fpga_minor_mode) { // allocate command receive buffer BigBuf_free(); BigBuf_Clear_ext(false); - + // Initialize Demod and Uart structs //DemodInit(BigBuf_malloc(MAX_FRAME_SIZE)); FelicaFrameinit(BigBuf_malloc(FELICA_MAX_FRAME_SIZE)); felica_nexttransfertime = 2 * DELAY_ARM2AIR_AS_READER; iso18092_set_timeout(2120); // 106 * 20ms maximum start-up time of card - + init_table(CRC_FELICA); - + // connect Demodulated Signal to ADC: SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Set up the synchronous serial port FpgaSetupSsc(); - + // LSB transfer. Remember to set it back to MSB with AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); - + // Signal field is on with the appropriate LED FpgaWriteConfWord(FPGA_MAJOR_MODE_ISO18092 | fpga_minor_mode); - + //20.4 ms generate field, start sending polling command afterwars. SpinDelay(100); // Start the timer StartCountSspClk(); - + LED_D_ON(); } //----------------------------------------------------------------------------- @@ -472,7 +472,7 @@ static void iso18092_setup(uint8_t fpga_minor_mode) { //----------------------------------------------------------------------------- // arg0 FeliCa flags // arg1 len of commandbytes -// d.asBytes command bytes to send +// d.asBytes command bytes to send void felica_sendraw(UsbCommand *c) { if (MF_DBGLEVEL > 3) Dbprintf("FeliCa_sendraw Enter"); @@ -481,9 +481,9 @@ void felica_sendraw(UsbCommand *c) { size_t len = c->arg[1] & 0xffff; uint8_t *cmd = c->d.asBytes; uint32_t arg0 = 0; - + felica_card_select_t card; - + if ((param & FELICA_CONNECT)) clear_trace(); @@ -501,19 +501,19 @@ void felica_sendraw(UsbCommand *c) { goto OUT; } } - + if ((param & FELICA_RAW)) { - + // 2 sync, 1 len, 2crc == 5 uint8_t *buf = BigBuf_malloc(len+5); // add sync bits buf[0] = 0xb2; buf[1] = 0x4d; buf[2] = len; - + // copy command memcpy(buf+2, cmd, len); - + if ((param & FELICA_APPEND_CRC)) { // Don't append crc on empty bytearray... if ( len > 0 ) { @@ -530,24 +530,24 @@ void felica_sendraw(UsbCommand *c) { if ((param & FELICA_NO_DISCONNECT)) return; -OUT: +OUT: switch_off(); - - //Resetting Frame mode (First set in fpgaloader.c) + + //Resetting Frame mode (First set in fpgaloader.c) AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); - + if (MF_DBGLEVEL > 3) Dbprintf("FeliCa_sendraw Exit"); } void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip) { - + int remFrames = (samplesToSkip) ? samplesToSkip : 0; Dbprintf("Snoop FelicaLiteS: Getting first %d frames, Skipping %d triggers.\n", samplesToSkip, triggersToSkip); - + iso18092_setup( FPGA_HF_ISO18092_FLAG_NOMOD); - //the frame bits are slow enough. + //the frame bits are slow enough. int n = BigBuf_max_traceLen() / sizeof(uint8_t); // take all memory int numbts = 0; uint8_t *dest = (uint8_t *)BigBuf_get_addr(); @@ -558,14 +558,14 @@ void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip) { while (dest <= destend) { WDT_HIT(); if( BUTTON_PRESS()) break; - + if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { uint8_t dist = (uint8_t)(AT91C_BASE_SSC->SSC_RHR); Process18092Byte(dist); - + //to be sure we are in frame if (FelicaFrame.state == STATE_GET_LENGTH) { - //length is after 48 (PRE)+16 (SYNC) - 64 ticks +maybe offset? not 100% + //length is after 48 (PRE)+16 (SYNC) - 64 ticks +maybe offset? not 100% uint16_t distance = GetCountSspClk() - endframe - 64 + (FelicaFrame.byte_offset > 0 ? (8-FelicaFrame.byte_offset) : 0); *dest = distance >> 8; dest++; @@ -587,16 +587,16 @@ void felica_sniff(uint32_t samplesToSkip, uint32_t triggersToSkip) { remFrames--; if (remFrames <= 0) break; if (dest >= destend ) break; - + numbts += FelicaFrame.len; - + FelicaFrameReset(); } } } switch_off(); - + //reset framing AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); set_tracelen(numbts); @@ -622,13 +622,13 @@ void felica_sim_lite(uint64_t nfcid) { uint8_t resp_poll0[R_POLL0_LEN] = { 0xb2,0x4d,0x12,FELICA_POLL_ACK,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00,0xb3,0x7f}; uint8_t resp_poll1[R_POLL1_LEN] = { 0xb2,0x4d,0x14,FELICA_POLL_ACK,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00, 0x88,0xb4,0xb3,0x7f}; uint8_t resp_readblk[R_READBLK_LEN] = { 0xb2,0x4d,0x1d,FELICA_RDBLK_ACK,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x10,0x04,0x01,0x00,0x0d,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x23,0xcb,0x6e}; - + //NFC tag 3/ ISo technically. Many overlapping standards - DbpString("Felica Lite-S sim start"); + DbpString("Felica Lite-S sim start"); Dbprintf("NDEF2 UID: %02x %02x %02x %02x %02x %02x %02x %02x", ndef[0], ndef[1], ndef[2], ndef[3], ndef[4], ndef[5], ndef[6], ndef[7] ); - + //fill in blanks for( i=0; i<8; i++) { resp_poll0[i+4] = ndef[i]; @@ -656,11 +656,11 @@ void felica_sim_lite(uint64_t nfcid) { uint8_t dist = (uint8_t)(AT91C_BASE_SSC->SSC_RHR); //frtm = GetCountSspClk(); Process18092Byte(dist); - + if (FelicaFrame.state == STATE_FULL) { if (FelicaFrame.crc_ok) { - + if (FelicaFrame.framebytes[2] == 6 && FelicaFrame.framebytes[3] == 0) { //polling... there are two types of polling we answer to @@ -675,7 +675,7 @@ void felica_sim_lite(uint64_t nfcid) { listenmode = true; } } - + if (FelicaFrame.framebytes[2] > 5 && FelicaFrame.framebytes[3] == 0x06) { //we should rebuild it depending on page size, but... //Let's see first @@ -707,7 +707,7 @@ void felica_sim_lite(uint64_t nfcid) { curresp = NULL; } } - + switch_off(); //reset framing @@ -721,38 +721,38 @@ void felica_dump_lite_s() { uint8_t ndef[8]; uint8_t poll[10] = { 0xb2,0x4d,0x06,FELICA_POLL_REQ,0xff,0xff,0x00,0x00,0x09,0x21}; uint16_t liteblks[28] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x90,0x91,0x92,0xa0}; - + // setup device. iso18092_setup(FPGA_HF_ISO18092_FLAG_READER | FPGA_HF_ISO18092_FLAG_NOMOD); - + uint8_t blknum; bool isOK = false; uint16_t cnt = 0, cntfails = 0; uint8_t *dest = BigBuf_get_addr(); while (!BUTTON_PRESS() && !usb_poll_validate_length()) { - + WDT_HIT(); - - // polling? + + // polling? //TransmitFor18092_AsReader(poll, 10, GetCountSspClk()+512, 1, 0); TransmitFor18092_AsReader(poll, 10, NULL, 1, 0); - + if (WaitForFelicaReply(512) && FelicaFrame.framebytes[3] == FELICA_POLL_ACK) { - + // copy 8bytes to ndef. memcpy(ndef, FelicaFrame.framebytes + 4, 8); // for (c=0; c < 8; c++) // ndef[c] = FelicaFrame.framebytes[c+4]; - - for (blknum=0; blknum < sizeof(liteblks); ) { - // block to read. + for (blknum=0; blknum < sizeof(liteblks); ) { + + // block to read. BuildFliteRdblk(ndef, 1, &liteblks[blknum]); - + //TransmitFor18092_AsReader(frameSpace, frameSpace[2]+4, GetCountSspClk()+512, 1, 0); TransmitFor18092_AsReader(frameSpace, frameSpace[2]+4, NULL, 1, 0); - + // read block if (WaitForFelicaReply(1024) && FelicaFrame.framebytes[3] == FELICA_RDBLK_ACK) { @@ -766,10 +766,10 @@ void felica_dump_lite_s() { //cnt += 16; for(uint8_t j=0; j < 16; j++) dest[cnt++] = fb[15+j]; - + blknum++; cntfails = 0; - + // // print raw log. // Dbprintf("LEN %u | Dump bytes count %u ", FelicaFrame.len, cnt); Dbhexdump(FelicaFrame.len, FelicaFrame.framebytes+15, 0); @@ -782,15 +782,15 @@ void felica_dump_lite_s() { } } isOK = true; - break; - } + break; + } } - + switch_off(); - //Resetting Frame mode (First set in fpgaloader.c) + //Resetting Frame mode (First set in fpgaloader.c) AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); - + //setting tracelen - important! it was set by buffer overflow before set_tracelen(cnt); cmd_send(CMD_ACK, isOK, cnt, 0, 0, 0); diff --git a/armsrc/flashmem.c b/armsrc/flashmem.c index 92204baff..c3b7a6e82 100644 --- a/armsrc/flashmem.c +++ b/armsrc/flashmem.c @@ -4,9 +4,9 @@ #define SPI_CSR_NUM 2 #define SPI_PCS(npcs) ((~(1 << (npcs)) & 0xF) << 16) /// Calculates the value of the CSR SCBR field given the baudrate and MCK. -#define SPI_SCBR(baudrate, masterClock) ((uint32_t) ((masterClock) / (baudrate)) << 8) +#define SPI_SCBR(baudrate, masterClock) ((uint32_t) ((masterClock) / (baudrate)) << 8) /// Calculates the value of the CSR DLYBS field given the desired delay (in ns) -#define SPI_DLYBS(delay, masterClock) ((uint32_t) ((((masterClock) / 1000000) * (delay)) / 1000) << 16) +#define SPI_DLYBS(delay, masterClock) ((uint32_t) ((((masterClock) / 1000000) * (delay)) / 1000) << 16) /// Calculates the value of the CSR DLYBCT field given the desired delay (in ns) #define SPI_DLYBCT(delay, masterClock) ((uint32_t) ((((masterClock) / 1000000) * (delay)) / 32000) << 24) @@ -67,7 +67,7 @@ void FlashSetup(uint32_t baudrate){ // NPCS2 Mode 0 AT91C_BASE_SPI->SPI_MR = - (0 << 24) | // Delay between chip selects = DYLBCS/MCK BUT: + (0 << 24) | // Delay between chip selects = DYLBCS/MCK BUT: // If DLYBCS is less than or equal to six, six MCK periods // will be inserted by default. SPI_PCS(SPI_CSR_NUM) | // Peripheral Chip Select (selects SPI_NCS2 or PA10) @@ -88,10 +88,10 @@ void FlashSetup(uint32_t baudrate){ AT91C_BASE_SPI->SPI_CSR[2] = SPI_DLYBCT(dlybct,MCK) | // Delay between Consecutive Transfers (32 MCK periods) - SPI_DLYBS(0,MCK) | // Delay Beforce SPCK CLock + SPI_DLYBS(0,MCK) | // Delay Beforce SPCK CLock SPI_SCBR(baudrate,MCK) | // SPI Baudrate Selection AT91C_SPI_BITS_8 | // Bits per Transfer (8 bits) - //AT91C_SPI_CSAAT | // Chip Select inactive after transfer + //AT91C_SPI_CSAAT | // Chip Select inactive after transfer // 40.4.6.2 SPI: Bad tx_ready Behavior when CSAAT = 1 and SCBR = 1 // If the SPI is programmed with CSAAT = 1, SCBR(baudrate) = 1 and two transfers are performed consecutively on // the same slave with an IDLE state between them, the tx_ready signal does not rise after the second data has been @@ -140,17 +140,17 @@ void FlashStop(void) { // Disable all interrupts AT91C_BASE_SPI->SPI_IDR = 0xFFFFFFFF; - + // SPI disable AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIDIS; if ( MF_DBGLEVEL > 3 ) Dbprintf("FlashStop"); - + StopTicks(); } // send one byte over SPI -uint16_t FlashSendByte(uint32_t data) { +uint16_t FlashSendByte(uint32_t data) { // wait until SPI is ready for transfer //if you are checking for incoming data returned then the TXEMPTY flag is redundant @@ -176,7 +176,7 @@ uint16_t FlashSendLastByte(uint32_t data) { // read state register 1 uint8_t Flash_ReadStat1(void) { FlashSendByte(READSTAT1); - return FlashSendLastByte(0xFF); + return FlashSendLastByte(0xFF); } bool Flash_CheckBusy(uint32_t timeout) @@ -215,10 +215,10 @@ uint8_t Flash_ReadID(void) { FlashSendByte(0x00); uint8_t man_id = FlashSendByte(0xFF); - uint8_t dev_id = FlashSendLastByte(0xFF); + uint8_t dev_id = FlashSendLastByte(0xFF); if ( MF_DBGLEVEL > 3 ) Dbprintf("Flash ReadID | Man ID %02x | Device ID %02x", man_id, dev_id); - + if ( (man_id == WINBOND_MANID ) && (dev_id == WINBOND_DEVID) ) return dev_id; @@ -248,9 +248,9 @@ void Flash_UniqueID(uint8_t *uid) { } uint16_t Flash_ReadData(uint32_t address, uint8_t *out, uint16_t len) { - + if (!FlashInit()) return 0; - + // length should never be zero if (!len || Flash_CheckBusy(BUSY_TIMEOUT)) return 0; @@ -268,8 +268,8 @@ uint16_t Flash_ReadData(uint32_t address, uint8_t *out, uint16_t len) { out[i] = FlashSendByte(0xFF); out[i] = FlashSendLastByte(0xFF); - FlashStop(); - return len; + FlashStop(); + return len; } void Flash_TransferAdresse(uint32_t address){ @@ -280,10 +280,10 @@ void Flash_TransferAdresse(uint32_t address){ /* This ensure we can ReadData without having to cycle through initialization everytime */ uint16_t Flash_ReadDataCont(uint32_t address, uint8_t *out, uint16_t len) { - + // length should never be zero if (!len) return 0; - + uint8_t cmd = (FASTFLASH) ? FASTREAD : READDATA; FlashSendByte(cmd); @@ -292,31 +292,31 @@ uint16_t Flash_ReadDataCont(uint32_t address, uint8_t *out, uint16_t len) { if (FASTFLASH){ FlashSendByte(DUMMYBYTE); } - + uint16_t i = 0; for (; i < (len - 1); i++) out[i] = FlashSendByte(0xFF); out[i] = FlashSendLastByte(0xFF); - return len; + return len; } //////////////////////////////////////// -// Write data can only program one page. A page has 256 bytes. +// Write data can only program one page. A page has 256 bytes. // if len > 256, it might wrap around and overwrite pos 0. uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len) { // length should never be zero if (!len) return 0; - + // Max 256 bytes write if (((address & 0xFF) + len) > 256) { Dbprintf("Flash_WriteData 256 fail [ 0x%02x ] [ %u ]", (address & 0xFF)+len, len ); return 0; } - + // out-of-range if ( (( address >> 16 ) & 0xFF ) > MAX_BLOCKS) { Dbprintf("Flash_WriteData, block out-of-range"); @@ -327,11 +327,11 @@ uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len) { if ( MF_DBGLEVEL > 3 ) Dbprintf("Flash_WriteData init fail"); return 0; } - + Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); - + FlashSendByte(PAGEPROG); FlashSendByte((address >> 16) & 0xFF); FlashSendByte((address >> 8) & 0xFF); @@ -344,7 +344,7 @@ uint16_t Flash_WriteData(uint32_t address, uint8_t *in, uint16_t len) { FlashSendLastByte(in[i]); FlashStop(); - return len; + return len; } @@ -355,12 +355,12 @@ uint16_t Flash_WriteDataCont(uint32_t address, uint8_t *in, uint16_t len) { if (!len) return 0; - + if (((address & 0xFF) + len) > 256) { Dbprintf("Flash_WriteDataCont 256 fail [ 0x%02x ] [ %u ]", (address & 0xFF)+len, len ); return 0; } - + if ( (( address >> 16 ) & 0xFF ) > MAX_BLOCKS) { Dbprintf("Flash_WriteDataCont, block out-of-range"); return 0; @@ -376,7 +376,7 @@ uint16_t Flash_WriteDataCont(uint32_t address, uint8_t *in, uint16_t len) { FlashSendByte(in[i]); FlashSendLastByte(in[i]); - return len; + return len; } // assumes valid start 256 based 00 address @@ -418,12 +418,12 @@ bool Flash_WipeMemoryPage(uint8_t page) { return false; } Flash_ReadStat1(); - + // Each block is 64Kb. One block erase takes 1s ( 1000ms ) - Flash_WriteEnable(); Flash_Erase64k(page); Flash_CheckBusy(BUSY_TIMEOUT); + Flash_WriteEnable(); Flash_Erase64k(page); Flash_CheckBusy(BUSY_TIMEOUT); FlashStop(); - return true; + return true; } // Wipes flash memory completely, fills with 0xFF bool Flash_WipeMemory() { @@ -432,22 +432,22 @@ bool Flash_WipeMemory() { return false; } Flash_ReadStat1(); - + // Each block is 64Kb. Four blocks // one block erase takes 1s ( 1000ms ) - Flash_WriteEnable(); Flash_Erase64k(0); Flash_CheckBusy(BUSY_TIMEOUT); + Flash_WriteEnable(); Flash_Erase64k(0); Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase64k(1); Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase64k(2); Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase64k(3); Flash_CheckBusy(BUSY_TIMEOUT); - + FlashStop(); return true; } // enable the flash write void Flash_WriteEnable() { - FlashSendLastByte(WRITEENABLE); - if ( MF_DBGLEVEL > 3 ) Dbprintf("Flash Write enabled"); + FlashSendLastByte(WRITEENABLE); + if ( MF_DBGLEVEL > 3 ) Dbprintf("Flash Write enabled"); } // erase 4K at one time @@ -488,9 +488,9 @@ bool Flash_Erase32k(uint32_t address) { // 0x02 00 00 -- 0x 02 FF FF == block 2 // 0x03 00 00 -- 0x 03 FF FF == block 3 bool Flash_Erase64k(uint8_t block) { - + if (block > MAX_BLOCKS) return false; - + FlashSendByte(BLOCK64ERASE); FlashSendByte(block); FlashSendByte(0x00); @@ -512,7 +512,7 @@ void Flashmem_print_status(void) { return; } DbpString(" Init....................OK"); - + uint8_t dev_id = Flash_ReadID(); switch (dev_id) { case 0x11 : @@ -528,13 +528,13 @@ void Flashmem_print_status(void) { DbpString(" Device ID............... --> Unknown <--"); break; } - + uint8_t uid[8] = {0,0,0,0,0,0,0,0}; - Flash_UniqueID(uid); + Flash_UniqueID(uid); Dbprintf(" Unique ID...............0x%02x%02x%02x%02x%02x%02x%02x%02x", - uid[7], uid[6], uid[5], uid[4], + uid[7], uid[6], uid[5], uid[4], uid[3], uid[2], uid[1], uid[0] ); - + FlashStop(); } diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c index e4ab1ab0b..6f8489026 100644 --- a/armsrc/fpgaloader.c +++ b/armsrc/fpgaloader.c @@ -28,7 +28,7 @@ static uint32_t uncompressed_bytes_cnt; // Used to write the FPGA config word // May also be used to write to other SPI attached devices like an LCD //----------------------------------------------------------------------------- -static void DisableSpi(void) { +static void DisableSpi(void) { //* Reset all the Chip Select register AT91C_BASE_SPI->SPI_CSR[0] = 0; AT91C_BASE_SPI->SPI_CSR[1] = 0; @@ -40,7 +40,7 @@ static void DisableSpi(void) { // Disable all interrupts AT91C_BASE_SPI->SPI_IDR = 0xFFFFFFFF; - + // SPI disable AT91C_BASE_SPI->SPI_CR = AT91C_SPI_SPIDIS; } @@ -77,7 +77,7 @@ void SetupSpi(int mode) { ( 0 << 2) | // Chip selects connected directly to peripheral AT91C_SPI_PS_FIXED | // Fixed Peripheral Select AT91C_SPI_MSTR; // Master Mode - + AT91C_BASE_SPI->SPI_CSR[0] = ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods) ( 1 << 16) | // Delay Before SPCK (1 MCK period) @@ -97,7 +97,7 @@ void SetupSpi(int mode) { ( 0 << 2) | // Chip selects connected directly to peripheral ( 0 << 1) | // Fixed Peripheral Select ( 1 << 0); // Master Mode - + AT91C_BASE_SPI->SPI_CSR[2] = ( 1 << 24) | // Delay between Consecutive Transfers (32 MCK periods) ( 1 << 16) | // Delay Before SPCK (1 MCK period) @@ -107,9 +107,9 @@ void SetupSpi(int mode) { ( 1 << 1) | // Clock Phase data captured on leading edge, changes on following edge ( 0 << 0); // Clock Polarity inactive state is logic 0 break; -*/ +*/ default: - DisableSpi(); + DisableSpi(); break; } } @@ -134,7 +134,7 @@ void FpgaSetupSscExt(uint8_t clearPCER) { // Now set up the SSC proper, starting from a known state. AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST; - + // RX clock comes from TX clock, RX starts when TX starts, data changes // on RX clock rising edge, sampled on falling edge AT91C_BASE_SSC->SSC_RCMR = SSC_CLOCK_MODE_SELECT(1) | SSC_CLOCK_MODE_START(1); @@ -396,12 +396,12 @@ void FpgaDownloadAndGo(int bitstream_version) { // check whether or not the bitstream is already loaded if (downloaded_bitstream == bitstream_version) return; - + z_stream compressed_fpga_stream; uint8_t output_buffer[OUTPUT_BUFFER_LEN] = {0x00}; bool verbose = (MF_DBGLEVEL > 3); - + // make sure that we have enough memory to decompress BigBuf_free(); BigBuf_Clear_ext(verbose); @@ -418,7 +418,7 @@ void FpgaDownloadAndGo(int bitstream_version) { // turn off antenna FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - + // free eventually allocated BigBuf memory BigBuf_free(); BigBuf_Clear_ext(false); } @@ -466,7 +466,7 @@ void SetAdcMuxFor(uint32_t whichGpio) { #ifndef WITH_FPC LOW(GPIO_MUXSEL_HIRAW); LOW(GPIO_MUXSEL_LORAW); -#endif +#endif HIGH(whichGpio); } @@ -480,15 +480,15 @@ int FpgaGetCurrent(void) { return downloaded_bitstream; } -// Turns off the antenna, +// Turns off the antenna, // log message // if HF, Disable SSC DMA // turn off trace and leds off. -void switch_off(void) { +void switch_off(void) { if (MF_DBGLEVEL > 3) Dbprintf("switch_off"); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); if (downloaded_bitstream == FPGA_BITSTREAM_HF ) FpgaDisableSscDma(); set_tracing(false); - LEDsoff(); + LEDsoff(); } diff --git a/armsrc/fpgaloader.h b/armsrc/fpgaloader.h index a1e0d1ee0..852d66dfa 100644 --- a/armsrc/fpgaloader.h +++ b/armsrc/fpgaloader.h @@ -83,7 +83,7 @@ extern void switch_off(void); #define FPGA_HF_SIMULATOR_MODULATE_212K 0x2 // 0010 #define FPGA_HF_SIMULATOR_MODULATE_424K 0x4 // 0100 #define FPGA_HF_SIMULATOR_MODULATE_424K_8BIT 0x5 // 0101 -// no 848K +// no 848K // Options for ISO14443A #define FPGA_HF_ISO14443A_SNIFFER (0<<0) @@ -92,10 +92,10 @@ extern void switch_off(void); #define FPGA_HF_ISO14443A_READER_LISTEN (3<<0) #define FPGA_HF_ISO14443A_READER_MOD (4<<0) -//options for Felica. +//options for Felica. #define FPGA_MAJOR_MODE_ISO18092 (5<<5) // 01010 0000 #define FPGA_HF_ISO18092_FLAG_NOMOD (1<<0) // 0001 disable modulation module #define FPGA_HF_ISO18092_FLAG_424K (2<<0) // 0010 should enable 414k mode (untested). No autodetect #define FPGA_HF_ISO18092_FLAG_READER (4<<0) // 0100 enables antenna power, to act as a reader instead of tag - + #endif \ No newline at end of file diff --git a/armsrc/hfsnoop.c b/armsrc/hfsnoop.c index 06ec03ed6..cc72c7176 100644 --- a/armsrc/hfsnoop.c +++ b/armsrc/hfsnoop.c @@ -27,43 +27,43 @@ static void RAMFUNC optimizedSnoop(void) void HfSnoop(int samplesToSkip, int triggersToSkip) { BigBuf_free(); BigBuf_Clear(); - + Dbprintf("Skipping first %d sample pairs, Skipping %d triggers.\n", samplesToSkip, triggersToSkip); int trigger_cnt = 0; LED_D_ON(); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - + // Set up the synchronous serial port FpgaSetupSsc(); - // Setting Frame Mode For better performance on high speed data transfer. + // Setting Frame Mode For better performance on high speed data transfer. AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(16); - + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SNOOP); SpinDelay(100); - + uint16_t r = 0; while (!BUTTON_PRESS() && !usb_poll_validate_length() ) { WDT_HIT(); - + if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { r = (uint16_t)AT91C_BASE_SSC->SSC_RHR; - r = MAX(r & 0xff, r >> 8); + r = MAX(r & 0xff, r >> 8); if (r >= 180) { // 0xB4 ?? if (++trigger_cnt > triggersToSkip) break; - } + } } } if (!BUTTON_PRESS()) { int waitcount = samplesToSkip; // lets wait 40000 ticks of pck0 while(waitcount != 0) { - + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) waitcount--; } @@ -72,7 +72,7 @@ void HfSnoop(int samplesToSkip, int triggersToSkip) } //Resetting Frame mode (First set in fpgaloader.c) - AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); + AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); DbpString("HF Snoop end"); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index 6095d1639..32db10190 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -66,9 +66,9 @@ static enum { WRITE_STATE_PAGENUM_WRITTEN, WRITE_STATE_PROG } writestate; - -// ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces. + +// ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces. // Historically it used to be FREE_BUFFER_SIZE, which was 2744. #define AUTH_TABLE_LENGTH 2744 static uint8_t* auth_table; @@ -237,23 +237,23 @@ static int hitag2_cipher_transcrypt(uint64_t* cs, uint8_t *data, unsigned int by #define HITAG_T_TAG_ONE_HALF_PERIOD 10 #define HITAG_T_TAG_TWO_HALF_PERIOD 25 -#define HITAG_T_TAG_THREE_HALF_PERIOD 41 -#define HITAG_T_TAG_FOUR_HALF_PERIOD 57 +#define HITAG_T_TAG_THREE_HALF_PERIOD 41 +#define HITAG_T_TAG_FOUR_HALF_PERIOD 57 #define HITAG_T_TAG_HALF_PERIOD 16 #define HITAG_T_TAG_FULL_PERIOD 32 #define HITAG_T_TAG_CAPTURE_ONE_HALF 13 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25 -#define HITAG_T_TAG_CAPTURE_THREE_HALF 41 -#define HITAG_T_TAG_CAPTURE_FOUR_HALF 57 +#define HITAG_T_TAG_CAPTURE_THREE_HALF 41 +#define HITAG_T_TAG_CAPTURE_FOUR_HALF 57 static void hitag_send_bit(int bit) { LED_A_ON(); - // Reset clock for the next bit + // Reset clock for the next bit AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - + // Fixed modulation, earlier proxmark version used inverted signal if(bit == 0) { // Manchester: Unloaded, then loaded |__--| @@ -291,20 +291,20 @@ static void hitag_send_frame(const uint8_t* frame, size_t frame_len) static void hitag2_handle_reader_command(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* txlen) { uint8_t rx_air[HITAG_FRAME_LEN]; - + // Copy the (original) received frame how it is send over the air memcpy(rx_air,rx,nbytes(rxlen)); if(tag.crypto_active) { hitag2_cipher_transcrypt(&(tag.cs),rx,rxlen/8,rxlen%8); } - - // Reset the transmission frame length + + // Reset the transmission frame length *txlen = 0; - + // Try to find out which command was send by selecting on length (in bits) switch (rxlen) { - // Received 11000 from the reader, request for UID, send UID + // Received 11000 from the reader, request for UID, send UID case 05: { // Always send over the air in the clear plaintext mode if(rx_air[0] != 0xC0) { @@ -317,7 +317,7 @@ static void hitag2_handle_reader_command(uint8_t* rx, const size_t rxlen, uint8_ } break; - // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number + // Read/Write command: ..xx x..y yy with yyy == ~xxx, xxx is sector number case 10: { unsigned int sector = (~( ((rx[0]<<2)&0x04) | ((rx[1]>>6)&0x03) ) & 0x07); // Verify complement of sector index @@ -332,7 +332,7 @@ static void hitag2_handle_reader_command(uint8_t* rx, const size_t rxlen, uint8_ memcpy(tx,tag.sectors[sector],4); *txlen = 32; break; - + // Inverted Read command: 01xx x10y case 0x44: for (size_t i=0; i<4; i++) { @@ -349,7 +349,7 @@ static void hitag2_handle_reader_command(uint8_t* rx, const size_t rxlen, uint8_ tag.active_sector = sector; tag.state=TAG_STATE_WRITING; break; - + // Unknown command default: Dbprintf("Unknown command: %02x %02x",rx[0],rx[1]); @@ -409,7 +409,7 @@ static void hitag2_handle_reader_command(uint8_t* rx, const size_t rxlen, uint8_ // LogTraceHitag(rx,rxlen,0,0,false); // LogTraceHitag(tx,*txlen,0,0,true); - + if(tag.crypto_active) { hitag2_cipher_transcrypt(&(tag.cs), tx, *txlen/8, *txlen%8); } @@ -417,22 +417,22 @@ static void hitag2_handle_reader_command(uint8_t* rx, const size_t rxlen, uint8_ static void hitag_reader_send_bit(int bit) { LED_A_ON(); - // Reset clock for the next bit + // Reset clock for the next bit AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - + // Binary puls length modulation (BPLM) is used to encode the data stream // This means that a transmission of a one takes longer than that of a zero - + // Enable modulation, which means, drop the field HIGH(GPIO_SSC_DOUT); - + // Wait for 4-10 times the carrier period while(AT91C_BASE_TC0->TC_CV < T0*6); // SpinDelayUs(8*8); - + // Disable modulation, just activates the field again LOW(GPIO_SSC_DOUT); - + if(bit == 0) { // Zero bit: |_-| while (AT91C_BASE_TC0->TC_CV < T0*22) {}; @@ -451,7 +451,7 @@ static void hitag_reader_send_frame(const uint8_t* frame, size_t frame_len) for(size_t i=0; i> (7-(i%8)))&1); } - // Send EOF + // Send EOF AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; // Enable modulation, which means, drop the field HIGH(GPIO_SSC_DOUT); @@ -466,7 +466,7 @@ size_t blocknr; static bool hitag2_password(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* txlen) { // Reset the transmission frame length *txlen = 0; - + // Try to find out which command was send by selecting on length (in bits) switch (rxlen) { // No answer, try to resurrect @@ -479,7 +479,7 @@ static bool hitag2_password(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t *txlen = 5; memcpy(tx,"\xc0",nbytes(*txlen)); } break; - + // Received UID, tag password case 32: { if (!bPwd) { @@ -489,14 +489,14 @@ static bool hitag2_password(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t memcpy(tag.sectors[blocknr],rx,4); blocknr++; } else { - + if(blocknr == 1){ //store password in block1, the TAG answers with Block3, but we need the password in memory memcpy(tag.sectors[blocknr],tx,4); } else { memcpy(tag.sectors[blocknr],rx,4); } - + blocknr++; if (blocknr > 7) { DbpString("Read succesful!"); @@ -508,7 +508,7 @@ static bool hitag2_password(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t tx[1] = ((blocknr^7) << 6); } } break; - + // Unexpected response default: { Dbprintf("Uknown frame length: %d",rxlen); @@ -563,7 +563,7 @@ static bool hitag2_write_page(uint8_t* rx, const size_t rxlen, uint8_t* tx, size static bool hitag2_crypto(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* txlen, bool write) { // Reset the transmission frame length *txlen = 0; - + if(bCrypto) { hitag2_cipher_transcrypt(&cipher_state,rx,rxlen/8,rxlen%8); } @@ -647,7 +647,7 @@ static bool hitag2_crypto(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* } } } break; - + // Unexpected response default: { Dbprintf("Uknown frame length: %d",rxlen); @@ -655,7 +655,7 @@ static bool hitag2_crypto(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* } break; } } - + if(bCrypto) { // We have to return now to avoid double encryption if (!bAuthenticating) { @@ -668,9 +668,9 @@ static bool hitag2_crypto(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* static bool hitag2_authenticate(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* txlen) { - // Reset the transmission frame length + // Reset the transmission frame length *txlen = 0; - + // Try to find out which command was send by selecting on length (in bits) switch (rxlen) { // No answer, try to resurrect @@ -683,7 +683,7 @@ static bool hitag2_authenticate(uint8_t* rx, const size_t rxlen, uint8_t* tx, si *txlen = 5; memcpy(tx,"\xc0", nbytes(*txlen)); } break; - + // Received UID, crypto tag answer case 32: { if (!bCrypto) { @@ -695,23 +695,23 @@ static bool hitag2_authenticate(uint8_t* rx, const size_t rxlen, uint8_t* tx, si return true; } } break; - + // Unexpected response default: { Dbprintf("Uknown frame length: %d", rxlen); return false; } break; } - + return true; } static bool hitag2_test_auth_attempts(uint8_t* rx, const size_t rxlen, uint8_t* tx, size_t* txlen) { - // Reset the transmission frame length + // Reset the transmission frame length *txlen = 0; - + // Try to find out which command was send by selecting on length (in bits) switch (rxlen) { // No answer, try to resurrect @@ -736,7 +736,7 @@ static bool hitag2_test_auth_attempts(uint8_t* rx, const size_t rxlen, uint8_t* *txlen = 5; memcpy(tx,"\xc0",nbytes(*txlen)); } break; - + // Received UID, crypto tag answer, or read block response case 32: { if (!bCrypto) { @@ -753,13 +753,13 @@ static bool hitag2_test_auth_attempts(uint8_t* rx, const size_t rxlen, uint8_t* memcpy(NrAr,auth_table+auth_table_pos,8); } } break; - + default: { Dbprintf("Uknown frame length: %d",rxlen); return false; } break; } - + return true; } @@ -811,54 +811,54 @@ void SnoopHitag(uint32_t type) { int tag_sof; uint8_t rx[HITAG_FRAME_LEN]; size_t rxlen=0; - + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); - + // free eventually allocated BigBuf memory BigBuf_free(); BigBuf_Clear_ext(false); - + // Clean up trace and prepare it for storing frames clear_trace(); set_tracing(true); - + auth_table_len = 0; auth_table_pos = 0; auth_table = (uint8_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); memset(auth_table, 0x00, AUTH_TABLE_LENGTH); - + DbpString("Starting Hitag2 snoop"); LED_D_ON(); - + // Set up eavesdropping mode, frequency divisor which will drive the FPGA // and analog mux selection. FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); RELAY_OFF(); - + // Configure output pin that is connected to the FPGA (for modulating) AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; // Disable modulation, we are going to eavesdrop, not modulate ;) LOW(GPIO_SSC_DOUT); - + // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1); AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; - - // Disable timer during configuration + + // Disable timer during configuration AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; - + // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, // external trigger rising edge, load RA on rising edge of TIOA. uint32_t t1_channel_mode = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_BOTH | AT91C_TC_ABETRG | AT91C_TC_LDRA_BOTH; AT91C_BASE_TC1->TC_CMR = t1_channel_mode; - + // Enable and reset counter AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - + // Reset the received frame, frame count and timing info memset(rx, 0x00, sizeof(rx)); frame_count = 0; @@ -868,18 +868,18 @@ void SnoopHitag(uint32_t type) { lastbit = 1; bSkip = true; tag_sof = 4; - + while(!BUTTON_PRESS() && !usb_poll_validate_length()) { // Watchdog hit WDT_HIT(); - + // Receive frame, watch for at most T0*EOF periods while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) { // Check if rising edge in modulation is detected if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { - // Retrieve the new timing values + // Retrieve the new timing values int ra = (AT91C_BASE_TC1->TC_RA/T0); - + // Find out if we are dealing with a rising or falling edge rising_edge = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME) > 0; @@ -891,17 +891,17 @@ void SnoopHitag(uint32_t type) { memset(rx,0x00,sizeof(rx)); rxlen = 0; } - + // Only handle if reader frame and rising edge, or tag frame and falling edge if (reader_frame != rising_edge) { overflow += ra; continue; } - + // Add the buffered timing values of earlier captured edges which were skipped ra += overflow; overflow = 0; - + if (reader_frame) { LED_B_ON(); // Capture reader frame @@ -912,11 +912,11 @@ void SnoopHitag(uint32_t type) { // Capture the T0 periods that have passed since last communication or field drop (reset) response = (ra - HITAG_T_LOW); } else if(ra >= HITAG_T_1_MIN ) { - // '1' bit + // '1' bit rx[rxlen / 8] |= 1 << (7-(rxlen%8)); rxlen++; } else if(ra >= HITAG_T_0_MIN) { - // '0' bit + // '0' bit rx[rxlen / 8] |= 0 << (7-(rxlen%8)); rxlen++; } else { @@ -942,7 +942,7 @@ void SnoopHitag(uint32_t type) { // Manchester coding example |_-|...|_-|-_| (0...01) rx[rxlen / 8] |= 0 << (7-(rxlen%8)); rxlen++; - // We have to skip this half period at start and add the 'one' the second time + // We have to skip this half period at start and add the 'one' the second time if (!bSkip) { rx[rxlen / 8] |= 1 << (7-(rxlen%8)); rxlen++; @@ -965,7 +965,7 @@ void SnoopHitag(uint32_t type) { } } } - + // Check if frame was captured if(rxlen > 0) { frame_count++; @@ -982,7 +982,7 @@ void SnoopHitag(uint32_t type) { auth_table_len += 8; } } - + // Reset the received frame and response timing info memset(rx,0x00,sizeof(rx)); response = 0; @@ -991,7 +991,7 @@ void SnoopHitag(uint32_t type) { bSkip = true; tag_sof = 4; overflow = 0; - + LED_B_OFF(); LED_C_OFF(); } else { @@ -1027,7 +1027,7 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { size_t txlen=0; bool bQuitTraceFull = false; bQuiet = false; - + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); // free eventually allocated BigBuf memory @@ -1036,7 +1036,7 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { // Clean up trace and prepare it for storing frames clear_trace(); set_tracing(true); - + auth_table_len = 0; auth_table_pos = 0; uint8_t* auth_table; @@ -1047,7 +1047,7 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { DbpString("Starting Hitag2 simulation"); LED_D_ON(); hitag2_init(); - + if (tag_mem_supplied) { DbpString("Loading hitag2 memory..."); memcpy((uint8_t*)tag.sectors,data,48); @@ -1061,7 +1061,7 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { } Dbprintf("| %d | %08x |",i,block); } - + // Set up simulator mode, frequency divisor which will drive the FPGA // and analog mux selection. FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT); @@ -1076,21 +1076,21 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { // Disable modulation at default, which means release resistance LOW(GPIO_SSC_DOUT); - + // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0); - + // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the reader frames AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1); AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; - - // Disable timer during configuration + + // Disable timer during configuration AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, // external trigger rising edge, load RA on rising edge of TIOA. AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_RISING | AT91C_TC_ABETRG | AT91C_TC_LDRA_RISING; - + // Reset the received frame, frame count and timing info memset(rx,0x00,sizeof(rx)); frame_count = 0; @@ -1099,24 +1099,24 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { // Enable and reset counter AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - + while(!BUTTON_PRESS() && !usb_poll_validate_length()) { // Watchdog hit WDT_HIT(); - + // Receive frame, watch for at most T0*EOF periods while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_EOF) { // Check if rising edge in modulation is detected if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { - // Retrieve the new timing values + // Retrieve the new timing values int ra = (AT91C_BASE_TC1->TC_RA/T0) + overflow; overflow = 0; // Reset timer every frame, we have to capture the last edge for timing AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - + LED_B_ON(); - + // Capture reader frame if(ra >= HITAG_T_STOP) { if (rxlen != 0) { @@ -1125,11 +1125,11 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { // Capture the T0 periods that have passed since last communication or field drop (reset) response = (ra - HITAG_T_LOW); } else if(ra >= HITAG_T_1_MIN ) { - // '1' bit + // '1' bit rx[rxlen / 8] |= 1 << (7-(rxlen%8)); rxlen++; } else if(ra >= HITAG_T_0_MIN) { - // '0' bit + // '0' bit rx[rxlen / 8] |= 0 << (7-(rxlen%8)); rxlen++; } else { @@ -1137,7 +1137,7 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { } } } - + // Check if frame was captured if(rxlen > 4) { frame_count++; @@ -1151,17 +1151,17 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { } } } - + // Disable timer 1 with external trigger to avoid triggers during our own modulation AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; // Process the incoming frame (rx) and prepare the outgoing frame (tx) hitag2_handle_reader_command(rx,rxlen,tx,&txlen); - + // Wait for HITAG_T_WAIT_1 carrier periods after the last reader bit, // not that since the clock counts since the rising edge, but T_Wait1 is // with respect to the falling edge, we need to wait actually (T_Wait1 - T_Low) - // periods. The gap time T_Low varies (4..10). All timer values are in + // periods. The gap time T_Low varies (4..10). All timer values are in // terms of T0 units while(AT91C_BASE_TC0->TC_CV < T0*(HITAG_T_WAIT_1-HITAG_T_LOW)); @@ -1181,11 +1181,11 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { } } } - + // Reset the received frame and response timing info memset(rx,0x00,sizeof(rx)); response = 0; - + // Enable and reset external trigger in timer for capturing future frames AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; LED_B_OFF(); @@ -1202,7 +1202,7 @@ void SimulateHitagTag(bool tag_mem_supplied, uint8_t* data) { AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - + DbpString("Sim Stopped"); set_tracing(false); } @@ -1217,20 +1217,20 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { size_t txlen = 0; int lastbit = 1; bool bSkip; - int reset_sof; + int reset_sof; int tag_sof; int t_wait = HITAG_T_WAIT_MAX; bool bStop = false; bool bQuitTraceFull = false; - + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); // Reset the return status bSuccessful = false; - + // Clean up trace and prepare it for storing frames clear_trace(); set_tracing(true); - + //DbpString("Starting Hitag reader family"); // Check configuration @@ -1243,7 +1243,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { bQuiet = false; bPwd = false; } break; - + case RHT2F_AUTHENTICATE: { DbpString("Authenticating using nr,ar pair:"); memcpy(NrAr,htd->auth.NrAr, 8); @@ -1253,7 +1253,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { bAuthenticating = false; bQuitTraceFull = true; } break; - + case RHT2F_CRYPTO: { DbpString("Authenticating using key:"); memcpy(key,htd->crypto.key, 6); //HACK; 4 or 6?? I read both in the code. @@ -1286,18 +1286,18 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { return; } break; } - + LED_D_ON(); hitag2_init(); - + // Configure output and enable pin that is connected to the FPGA (for modulating) AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; - + // Set fpga in edge detect with reader field, we can modulate as reader now FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD); SpinDelay(20); - + // Set Frequency divisor which will drive the FPGA and analog mux selection FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); @@ -1308,21 +1308,21 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { // Give it a bit of time for the resonant antenna to settle. SpinDelay(30); - + // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0); // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1); AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; - - // Disable timer during configuration + + // Disable timer during configuration AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; - + // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, // external trigger rising edge, load RA on falling edge of TIOA. AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_FALLING | AT91C_TC_ABETRG | AT91C_TC_LDRA_FALLING; - + // Enable and reset counters AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; @@ -1345,7 +1345,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { // DbpString("Configured for hitag2 reader"); } else { Dbprintf("Error, unknown hitag reader type: %d",htf); - set_tracing(false); + set_tracing(false); LED_D_OFF(); return; } @@ -1353,7 +1353,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { while (!bStop && !BUTTON_PRESS()) { // Watchdog hit WDT_HIT(); - + // Check if frame was captured and store it if (rxlen > 0) { frame_count++; @@ -1367,7 +1367,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { } } } - + // By default reset the transmission buffer tx = txbuf; switch (htf) { @@ -1396,18 +1396,18 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { return; } break; } - + // Send and store the reader command // Disable timer 1 with external trigger to avoid triggers during our own modulation AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; - + // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, // Since the clock counts since the last falling edge, a 'one' means that the // falling edge occured halfway the period. with respect to this falling edge, // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. // All timer values are in terms of T0 units while (AT91C_BASE_TC0->TC_CV < T0 * (t_wait + (HITAG_T_TAG_HALF_PERIOD * lastbit))); - + // Transmit the reader frame hitag_reader_send_frame(tx, txlen); @@ -1428,7 +1428,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { } } } - + // Reset values for receiving frames memset(rx, 0x00, sizeof(rx)); rxlen = 0; @@ -1437,19 +1437,19 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { tag_sof = reset_sof; response = 0; uint32_t errorCount = 0; - + // Receive frame, watch for at most T0*EOF periods while (AT91C_BASE_TC1->TC_CV < T0 * HITAG_T_WAIT_MAX) { // Check if falling edge in tag modulation is detected if (AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { - // Retrieve the new timing values + // Retrieve the new timing values int ra = (AT91C_BASE_TC1->TC_RA/T0); - + // Reset timer every frame, we have to capture the last edge for timing AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - + LED_B_ON(); - + // Capture tag frame (manchester decoding using only falling edges) if (ra >= HITAG_T_EOF) { // Capture the T0 periods that have passed since last communication or field drop (reset) @@ -1465,7 +1465,7 @@ void ReaderHitag(hitag_function htf, hitag_data* htd) { // Manchester coding example |_-|...|_-|-_| (0...01) rx[rxlen / 8] |= 0 << (7-(rxlen%8)); rxlen++; - // We have to skip this half period at start and add the 'one' the second time + // We have to skip this half period at start and add the 'one' the second time if (!bSkip) { rx[rxlen / 8] |= 1 << (7-(rxlen%8)); rxlen++; @@ -1519,16 +1519,16 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { size_t txlen=0; int lastbit; bool bSkip; - int reset_sof; + int reset_sof; int tag_sof; int t_wait = HITAG_T_WAIT_MAX; bool bStop; bool bQuitTraceFull = false; - + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); // Reset the return status bSuccessful = false; - + // Clean up trace and prepare it for storing frames set_tracing(true); clear_trace(); @@ -1554,14 +1554,14 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { return; } break; } - + LED_D_ON(); hitag2_init(); - + // Configure output and enable pin that is connected to the FPGA (for modulating) AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; - + // Set fpga in edge detect with reader field, we can modulate as reader now FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD); @@ -1575,21 +1575,21 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { // Give it a bit of time for the resonant antenna to settle. SpinDelay(30); - + // Enable Peripheral Clock for TIMER_CLOCK0, used to measure exact timing before answering AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC0); // Enable Peripheral Clock for TIMER_CLOCK1, used to capture edges of the tag frames AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1); AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME; - - // Disable timer during configuration + + // Disable timer during configuration AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; - + // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, // external trigger rising edge, load RA on falling edge of TIOA. AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | AT91C_TC_ETRGEDG_FALLING | AT91C_TC_ABETRG | AT91C_TC_LDRA_FALLING; - + // Enable and reset counters AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; @@ -1623,7 +1623,7 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { while(!bStop && !BUTTON_PRESS()) { // Watchdog hit WDT_HIT(); - + // Check if frame was captured and store it if(rxlen > 0) { frame_count++; @@ -1638,7 +1638,7 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { } } } - + // By default reset the transmission buffer tx = txbuf; switch(htf) { @@ -1650,20 +1650,20 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { return; } break; } - + // Send and store the reader command // Disable timer 1 with external trigger to avoid triggers during our own modulation AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; - + // Wait for HITAG_T_WAIT_2 carrier periods after the last tag bit before transmitting, // Since the clock counts since the last falling edge, a 'one' means that the // falling edge occured halfway the period. with respect to this falling edge, // we need to wait (T_Wait2 + half_tag_period) when the last was a 'one'. // All timer values are in terms of T0 units while(AT91C_BASE_TC0->TC_CV < T0*(t_wait+(HITAG_T_TAG_HALF_PERIOD*lastbit))); - + // Dbprintf("DEBUG: Sending reader frame"); - + // Transmit the reader frame hitag_reader_send_frame(tx,txlen); @@ -1699,14 +1699,14 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { while (AT91C_BASE_TC1->TC_CV < T0*HITAG_T_WAIT_MAX) { // Check if falling edge in tag modulation is detected if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) { - // Retrieve the new timing values + // Retrieve the new timing values int ra = (AT91C_BASE_TC1->TC_RA/T0); - + // Reset timer every frame, we have to capture the last edge for timing AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - + LED_B_ON(); - + // Capture tag frame (manchester decoding using only falling edges) if(ra >= HITAG_T_EOF) { if (rxlen != 0) { @@ -1728,14 +1728,14 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { rxlen++; } else if(ra >= HITAG_T_TAG_CAPTURE_THREE_HALF) { // Manchester coding example |_-|...|_-|-_| (0...01) - + // need to test to verify we don't exceed memory... // if ( ((rxlen+2) / 8) > HITAG_FRAME_LEN) { // break; // } rx[rxlen / 8] |= 0 << (7-(rxlen%8)); rxlen++; - // We have to skip this half period at start and add the 'one' the second time + // We have to skip this half period at start and add the 'one' the second time if (!bSkip) { rx[rxlen / 8] |= 1 << (7-(rxlen%8)); rxlen++; @@ -1770,7 +1770,7 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { if (rxlen>0) break; } } - + // Wait some extra time for flash to be programmed if ((rxlen == 0) && (writestate == WRITE_STATE_PROG)) { @@ -1779,7 +1779,7 @@ void WriterHitag(hitag_function htf, hitag_data* htd, int page) { } } // Dbprintf("DEBUG: Done waiting for frame"); - + LED_B_OFF(); LED_D_OFF(); AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; diff --git a/armsrc/hitagS.c b/armsrc/hitagS.c index 59e2694e5..489cf9f7e 100644 --- a/armsrc/hitagS.c +++ b/armsrc/hitagS.c @@ -63,7 +63,7 @@ static const u32 ht2_f5c = 0x7907287B; // 0111 1001 0000 0111 0010 1000 0111 1 #define ht2bs_4a(a,b,c,d) (~(((a|b)&c)^(a|d)^b)) #define ht2bs_4b(a,b,c,d) (~(((d|c)&(a^b))^(d|a|b))) #define ht2bs_5c(a,b,c,d,e) (~((((((c^e)|d)&a)^b)&(c^b))^(((d^e)|a)&((d^b)|c)))) -#define uf20bs u32 +#define uf20bs u32 static u32 f20(const u64 x) { u32 i5; @@ -127,12 +127,12 @@ static u32 hitag2_byte(u64 *x) { #define HITAG_T_TAG_ONE_HALF_PERIOD 10 #define HITAG_T_TAG_TWO_HALF_PERIOD 25 -#define HITAG_T_TAG_THREE_HALF_PERIOD 41 +#define HITAG_T_TAG_THREE_HALF_PERIOD 41 #define HITAG_T_TAG_FOUR_HALF_PERIOD 57 - + #define HITAG_T_TAG_HALF_PERIOD 16 #define HITAG_T_TAG_FULL_PERIOD 32 - + #define HITAG_T_TAG_CAPTURE_ONE_HALF 13 #define HITAG_T_TAG_CAPTURE_TWO_HALF 25 #define HITAG_T_TAG_CAPTURE_THREE_HALF 41 @@ -168,24 +168,24 @@ static void hitag_send_bit(int bit) { // AC Coding --__ HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 32) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 64) {}; - + } else { // AC coding -_-_ HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 16) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 32) {}; - + HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 48) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 64) {}; - + } LED_A_OFF(); break; @@ -194,21 +194,21 @@ static void hitag_send_bit(int bit) { // AC Coding --__ HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_TAG_HALF_PERIOD) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * HITAG_T_TAG_FULL_PERIOD) {}; - + } else { // AC coding -_-_ HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 8) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 16) {}; - + HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 24) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 32) {}; } @@ -219,18 +219,18 @@ static void hitag_send_bit(int bit) { // Manchester: Unloaded, then loaded |__--| LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 16) {}; - + HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 32) {}; - + } else { // Manchester: Loaded, then unloaded |--__| HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 16) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 32) {}; - + } LED_A_OFF(); break; @@ -239,18 +239,18 @@ static void hitag_send_bit(int bit) { // Manchester: Unloaded, then loaded |__--| LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 8) {}; - + HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 16) {}; - + } else { // Manchester: Loaded, then unloaded |--__| HIGH(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 8) {}; - + LOW(GPIO_SSC_DOUT); while (AT91C_BASE_TC0->TC_CV < T0 * 16) {}; - + } LED_A_OFF(); break; @@ -288,7 +288,7 @@ static void hitag_reader_send_bit(int bit) { if (test == 1) { // Wait for 4-10 times the carrier period while (AT91C_BASE_TC0->TC_CV < T0 * 6) {}; - + // SpinDelayUs(8*8); // Disable modulation, just activates the field again @@ -297,18 +297,18 @@ static void hitag_reader_send_bit(int bit) { if (bit == 0) { // Zero bit: |_-| while (AT91C_BASE_TC0->TC_CV < T0 * 11) {}; - + // SpinDelayUs(16*8); } else { // One bit: |_--| while (AT91C_BASE_TC0->TC_CV < T0 * 14) {}; - + // SpinDelayUs(22*8); } } else { // Wait for 4-10 times the carrier period while (AT91C_BASE_TC0->TC_CV < T0 * 6) {}; - + // SpinDelayUs(8*8); // Disable modulation, just activates the field again @@ -317,12 +317,12 @@ static void hitag_reader_send_bit(int bit) { if (bit == 0) { // Zero bit: |_-| while (AT91C_BASE_TC0->TC_CV < T0 * 22) {}; - + // SpinDelayUs(16*8); } else { // One bit: |_--| while (AT91C_BASE_TC0->TC_CV < T0 * 28) {}; - + // SpinDelayUs(22*8); } } @@ -344,7 +344,7 @@ static void hitag_reader_send_frame(const byte_t* frame, size_t frame_len) { HIGH(GPIO_SSC_DOUT); // Wait for 4-10 times the carrier period while (AT91C_BASE_TC0->TC_CV < T0 * 6) {}; - + // Disable modulation, just activates the field again LOW(GPIO_SSC_DOUT); } @@ -891,7 +891,7 @@ static int hitagS_handle_tag_auth(hitag_function htf,uint64_t key, uint64_t NrAr } else if (tag.auth == 0) { tag.pstate = HT_SELECTED; } - + } else if (tag.pstate == HT_AUTHENTICATE && rxlen == 44) { //encrypted con2,password received. crc = CRC_PRESET; @@ -924,7 +924,7 @@ static int hitagS_handle_tag_auth(hitag_function htf,uint64_t key, uint64_t NrAr if (DEBUG) Dbprintf("pwdh0 %02X pwdl0 %02X pwdl1 %02X", pwdh0, pwdl0, pwdl1); - + //Dbprintf("%X %02X", rnd, ((rx[4] & 0x0f) * 16) + ((rx[5] & 0xf0) / 16)); //rnd += 1; @@ -932,7 +932,7 @@ static int hitagS_handle_tag_auth(hitag_function htf,uint64_t key, uint64_t NrAr tag.pstate = HT_SELECTED; //tag is now ready for read/write commands } return 0; - + } /* @@ -1185,7 +1185,7 @@ void ReadHitagS(hitag_function htf, hitag_data* htd) { unsigned char crc; unsigned char pageData[32]; page_to_be_written = 0; - + //read given key/challenge byte_t NrAr_[8]; uint64_t key = 0; @@ -1255,10 +1255,10 @@ void ReadHitagS(hitag_function htf, hitag_data* htd) { // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger, // external trigger rising edge, load RA on falling edge of TIOA. - AT91C_BASE_TC1->TC_CMR = + AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_TIMER_DIV1_CLOCK | - AT91C_TC_ETRGEDG_FALLING | - AT91C_TC_ABETRG | + AT91C_TC_ETRGEDG_FALLING | + AT91C_TC_ABETRG | AT91C_TC_LDRA_FALLING; // Enable and reset counters @@ -1497,7 +1497,7 @@ void ReadHitagS(hitag_function htf, hitag_data* htd) { AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - + cmd_send(CMD_ACK, bSuccessful, 0, 0, 0, 0); } @@ -1523,7 +1523,7 @@ void WritePageHitagS(hitag_function htf, hitag_data* htd,int page_) { int page = page_; unsigned char crc; byte_t data[4]= {0,0,0,0}; - + //read given key/challenge, the page and the data byte_t NrAr_[8]; uint64_t key=0; @@ -1541,7 +1541,7 @@ void WritePageHitagS(hitag_function htf, hitag_data* htd,int page_) { case 04: { //WHTS_KEY memcpy(data,htd->crypto.data,4); DbpString("Authenticating using key:"); - memcpy(key_,htd->crypto.key,6); + memcpy(key_,htd->crypto.key,6); Dbhexdump(6,key_,false); key=key_[5] | ((uint64_t)key_[4]) << 8 | ((uint64_t)key_[3]) << 16 | ((uint64_t)key_[2]) << 24 | ((uint64_t)key_[1]) << 32 | ((uint64_t)key_[0]) << 40; } break; @@ -1639,7 +1639,7 @@ void WritePageHitagS(hitag_function htf, hitag_data* htd,int page_) { //check for valid input if (page == 0) { Dbprintf( - "usage: lf hitag writer [03 | 04] [CHALLENGE | KEY] [page] [byte0] [byte1] [byte2] [byte3]"); + "usage: lf hitag writer [03 | 04] [CHALLENGE | KEY] [page] [byte0] [byte1] [byte2] [byte3]"); bStop = !false; } @@ -1863,7 +1863,7 @@ void check_challenges(bool file_given, byte_t* data) { // Set fpga in edge detect with reader field, we can modulate as reader now FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD); SpinDelay(50); - + // Set Frequency divisor which will drive the FPGA and analog mux selection FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 21cb9f299..af85c18fc 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -12,7 +12,7 @@ //----------------------------------------------------------------------------- // Based on ISO14443a implementation. Still in experimental phase. // Contribution made during a security research at Radboud University Nijmegen -// +// // Please feel free to contribute and extend iClass support!! //----------------------------------------------------------------------------- // @@ -21,7 +21,7 @@ // We still have sometimes a demodulation error when snooping iClass communication. // The resulting trace of a read-block-03 command may look something like this: // -// + 22279: : 0c 03 e8 01 +// + 22279: : 0c 03 e8 01 // // ...with an incorrect answer... // @@ -31,8 +31,8 @@ // // A correct trace should look like this: // -// + 21112: : 0c 03 e8 01 -// + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5 +// + 21112: : 0c 03 e8 01 +// + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5 // //----------------------------------------------------------------------------- @@ -60,7 +60,7 @@ int doIClassSimulation(int simulationMode, uint8_t *reader_mac_buf); // The length of a received command will in most cases be no more than 18 bytes. // 32 should be enough! -#ifndef ICLASS_BUFFER_SIZE +#ifndef ICLASS_BUFFER_SIZE #define ICLASS_BUFFER_SIZE 32 #endif @@ -172,7 +172,7 @@ static void uart_bit(uint8_t bit) { switch (buf) { case 0xbf: // 0 - 1011 1111 break; - case 0xef: // 1 - 1110 1111 + case 0xef: // 1 - 1110 1111 msg_byte |= (1<<6); break; case 0xfb: // 2 - 1111 1011 @@ -289,7 +289,7 @@ static RAMFUNC int OutOfNDecoding(int bit) { Uart.bitBuffer <<= 4; Uart.bitBuffer ^= bit; } - + // if (Uart.swapper) { // Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF; // Uart.byteCnt++; @@ -307,16 +307,16 @@ static RAMFUNC int OutOfNDecoding(int bit) { bit = 0; else bit = 1; - + if (((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) bitright = 0; else bitright = 1; - - if(bit != bitright) + + if(bit != bitright) bit = bitright; - + // So, now we only have to deal with *bit*, lets see... if (Uart.posCnt == 1) { // measurement first half bitperiod @@ -347,7 +347,7 @@ static RAMFUNC int OutOfNDecoding(int bit) { // measurement second half bitperiod // Count the bitslot we are in... (ISO 15693) Uart.nOutOfCnt++; - + if (!bit) { if (Uart.dropPosition) { if (Uart.state == STATE_START_OF_COMMUNICATION) { @@ -363,10 +363,10 @@ static RAMFUNC int OutOfNDecoding(int bit) { } } Uart.posCnt = 0; - + if (Uart.nOutOfCnt == Uart.OutOfCnt && Uart.OutOfCnt == 4) { Uart.nOutOfCnt = 0; - + if (Uart.state == STATE_START_OF_COMMUNICATION) { if (Uart.dropPosition == 4) { Uart.state = STATE_RECEIVING; @@ -390,12 +390,12 @@ static RAMFUNC int OutOfNDecoding(int bit) { //error = 9; } else { Uart.shiftReg >>= 2; - + // Swap bit order Uart.dropPosition--; //if(Uart.dropPosition == 1) { Uart.dropPosition = 2; } //else if(Uart.dropPosition == 2) { Uart.dropPosition = 1; } - + Uart.shiftReg ^= ((Uart.dropPosition & 0x03) << 6); Uart.bitCnt += 2; Uart.dropPosition = 0; @@ -459,13 +459,13 @@ static RAMFUNC int OutOfNDecoding(int bit) { Uart.posCnt = 1; // apparently we are busy with our first half bit period Uart.syncBit = bit & 8; Uart.samples = 3; - + if (!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; } else if (bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; } - + if (!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; } else if (bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; } - + if (!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0; if (Uart.syncBit && (Uart.bitBuffer & 8)) { Uart.syncBit = 8; @@ -519,7 +519,7 @@ static void DemodInit(uint8_t *data) { DemodReset(); } -// UART debug +// UART debug // it adds the debug values which will be put in the tracelog, // visible on client when running 'hf list iclass' /* @@ -562,11 +562,11 @@ static void uart_debug(int error, int bit) { /* * CARD TO READER -* in ISO15693-2 mode - Manchester +* in ISO15693-2 mode - Manchester * in ISO 14443b - BPSK coding * * Timings: -* ISO 15693-2 +* ISO 15693-2 * Tout = 330 µs, Tprog 1 = 4 to 15 ms, Tslot = 330 µs + (number of slots x 160 µs) * ISO 14443a * Tout = 100 µs, Tprog = 4 to 15 ms, Tslot = 100 µs+ (number of slots x 80 µs) @@ -645,7 +645,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { error = 0x88; uart_debug(error, bit); return false; - } + } } error = 0; } @@ -653,7 +653,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { } // state is DEMOD is in SYNC from here on. - + modulation = bit & Demod.syncBit; modulation |= ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit; Demod.samples += 4; @@ -667,13 +667,13 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { Demod.posCount = 0; if (modulation) { - + if (Demod.sub == SUB_FIRST_HALF) Demod.sub = SUB_BOTH; else Demod.sub = SUB_SECOND_HALF; } - + if (Demod.sub == SUB_NONE) { if (Demod.state == DEMOD_SOF_COMPLETE) { Demod.output[Demod.len] = 0x0f; @@ -687,7 +687,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { } switch (Demod.state) { - + case DEMOD_START_OF_COMMUNICATION: if (Demod.sub == SUB_BOTH) { @@ -700,7 +700,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { error = 0xd2; } break; - + case DEMOD_START_OF_COMMUNICATION2: if (Demod.sub == SUB_SECOND_HALF) { Demod.state = DEMOD_START_OF_COMMUNICATION3; @@ -710,7 +710,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { error = 0xd3; } break; - + case DEMOD_START_OF_COMMUNICATION3: if (Demod.sub == SUB_SECOND_HALF) { Demod.state = DEMOD_SOF_COMPLETE; @@ -720,7 +720,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { error = 0xd4; } break; - + case DEMOD_SOF_COMPLETE: case DEMOD_MANCHESTER_D: case DEMOD_MANCHESTER_E: @@ -782,7 +782,7 @@ static RAMFUNC int ManchesterDecoding_iclass( uint32_t v) { uart_debug(error, bit); return true; } - + return false; } @@ -796,7 +796,7 @@ static void iclass_setup_sniff(void){ LEDsoff(); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); // connect Demodulated Signal to ADC: @@ -805,7 +805,7 @@ static void iclass_setup_sniff(void){ // Set up the synchronous serial port FpgaSetupSsc(); - BigBuf_free(); BigBuf_Clear_ext(false); + BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(true); @@ -828,10 +828,10 @@ static void iclass_setup_sniff(void){ // put the FPGA in the appropriate mode FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER); SpinDelay(200); - + // Start the SSP timer StartCountSspClk(); - + LED_A_ON(); if (MF_DBGLEVEL > 3) Dbprintf("[+] iclass_setup_sniff Exit"); } @@ -844,15 +844,15 @@ static void iclass_setup_sniff(void){ // turn off afterwards void RAMFUNC SniffIClass(void) { - //int datalen = 0; - uint32_t previous_data = 0; + //int datalen = 0; + uint32_t previous_data = 0; uint32_t time_0 = 0, time_start = 0, time_stop = 0; uint32_t sniffCounter = 0; bool TagIsActive = false; bool ReaderIsActive = false; - + iclass_setup_sniff(); - + // The DMA buffer, used to stream samples from the FPGA // *dmaBuf is the start reference. uint8_t *dmaBuf = BigBuf_malloc(ICLASS_DMA_BUFFER_SIZE); @@ -861,7 +861,7 @@ void RAMFUNC SniffIClass(void) { // Setup and start DMA. if ( !FpgaSetupSscDma(dmaBuf, ICLASS_DMA_BUFFER_SIZE) ){ - if (MF_DBGLEVEL > 1) DbpString("[-] FpgaSetupSscDma failed. Exiting"); + if (MF_DBGLEVEL > 1) DbpString("[-] FpgaSetupSscDma failed. Exiting"); return; } @@ -881,8 +881,8 @@ void RAMFUNC SniffIClass(void) { previous_data <<= 8; previous_data |= *data; - - sniffCounter++; + + sniffCounter++; data++; if (data == dmaBuf + ICLASS_DMA_BUFFER_SIZE) { @@ -890,15 +890,15 @@ void RAMFUNC SniffIClass(void) { AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNCR = ICLASS_DMA_BUFFER_SIZE; } - - if ( *data & 0xF) { + + if ( *data & 0xF) { //tag_byte <<= 1; tag_byte ^= (1 << 4); foo ^= (1 << (3 - div)); Dbprintf(" %d|%x == %d|%x", tag_byte, tag_byte, foo, foo); } div++; - + // every odd sample if (sniffCounter & 0x01) { // no need to try decoding reader data if the tag is sending @@ -928,23 +928,23 @@ void RAMFUNC SniffIClass(void) { LED_C_INV(); // LOW nibble is always tag data. /* - - - uint32_t tag_byte = + + + uint32_t tag_byte = ((previous_data & 0x0F000000) >> 8 ) | ((previous_data & 0x000F0000) >> 4 ) | ((previous_data & 0x00000F00) ) | ((previous_data & 0x0000000F) << 4 ) | (*data & 0xF); */ - - + + //uint8_t tag_byte = ((previous_data & 0xF) << 4 ) | (*data & 0xF); if (ManchesterDecoding_iclass(foo)) { time_stop = GetCountSspClk() - time_0; LogTrace(Demod.output, Demod.len, time_start, time_stop, NULL, false); DemodReset(); - uart_reset(); + uart_reset(); } else { time_start = GetCountSspClk() - time_0; } @@ -956,16 +956,16 @@ void RAMFUNC SniffIClass(void) { } } // end main loop - if (MF_DBGLEVEL >= 1) { - DbpString("[+] Sniff statistics:"); + if (MF_DBGLEVEL >= 1) { + DbpString("[+] Sniff statistics:"); Dbhexdump(ICLASS_DMA_BUFFER_SIZE, data, false); } - - switch_off(); + + switch_off(); } void rotateCSN(uint8_t* originalCSN, uint8_t* rotatedCSN) { - int i; + int i; for(i = 0; i < 8; i++) rotatedCSN[i] = (originalCSN[i] >> 3) | (originalCSN[(i+1)%8] << 5); } @@ -976,13 +976,13 @@ void rotateCSN(uint8_t* originalCSN, uint8_t* rotatedCSN) { // Stop when button is pressed // Or return TRUE when command is captured //----------------------------------------------------------------------------- -static bool GetIClassCommandFromReader(uint8_t *received, int *len, int maxLen) { +static bool GetIClassCommandFromReader(uint8_t *received, int *len, int maxLen) { // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen // only, since we are receiving, not transmitting). // Signal field is off with the appropriate LED LED_D_OFF(); uart_init(received); - + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN); // clear RXRDY: uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; @@ -1069,7 +1069,7 @@ static void CodeIClassTagAnswer(const uint8_t *cmd, int len) { * - A 1-bit input to the FPGA becomes 8 pulses on 423.5kHz (fc/32) (18.88us). * - A 0-bit input to the FPGA becomes an unmodulated time of 18.88us * - * In this mode + * In this mode * SOF can be written as 00011101 = 0x1D * EOF can be written as 10111000 = 0xb8 * logic 1 be written as 01 = 0x1 @@ -1080,7 +1080,7 @@ static void CodeIClassTagAnswer(const uint8_t *cmd, int len) { // Send SOF ToSend[++ToSendMax] = 0x1D; - + int i; for(i = 0; i < len; i++) { uint8_t b = cmd[i]; @@ -1095,7 +1095,7 @@ static void CodeIClassTagAnswer(const uint8_t *cmd, int len) { ToSendMax++; } -// Only SOF +// Only SOF static void CodeIClassTagSOF() { //So far a dummy implementation, not used //int lastProxToAirDuration =0; @@ -1133,7 +1133,7 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain FpgaDownloadAndGo(FPGA_BITSTREAM_HF); FpgaSetupSsc(); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - + // Enable and clear the trace clear_trace(); set_tracing(true); @@ -1144,7 +1144,7 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain //Use the emulator memory for SIM uint8_t *emulator = BigBuf_get_EM_addr(); uint8_t mac_responses[USB_CMD_DATA_SIZE] = { 0 }; - + if (simType == 0) { // Use the CSN from commandline memcpy(emulator, datain, 8); @@ -1167,7 +1167,7 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain // The usb data is 512 bytes, fitting 65 8-byte CSNs in there. memcpy(emulator, datain + (i*8), 8); - + if (doIClassSimulation(MODE_EXIT_AFTER_MAC, mac_responses+i * EPURSE_MAC_SIZE)) { // Button pressed cmd_send(CMD_ACK, CMD_SIMULATE_TAG_ICLASS, i, 0, mac_responses, i * EPURSE_MAC_SIZE); @@ -1185,12 +1185,12 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain // This is the KEYROLL version of sim 2. // the collected data (mac_response) is doubled out since we are trying to collect both keys in the keyroll process. // Keyroll iceman 9 csns * 8 * 2 = 144 - // keyroll CARL55 15csns * 8 * 2 = 15 * 8 * 2 = 240 + // keyroll CARL55 15csns * 8 * 2 = 15 * 8 * 2 = 240 Dbprintf("[+] going into attack keyroll mode, %d CSNS sent", numberOfCSNS); // In this mode, a number of csns are within datain. We'll simulate each one, one at a time // in order to collect MAC's from the reader. This can later be used in an offlne-attack // in order to obtain the keys, as in the "dismantling iclass"-paper. - + // keyroll mode, reader swaps between old key and new key alternatively when fail a authentication. // attack below is same as SIM 2, but we run the CSN twice to collected the mac for both keys. int i = 0; @@ -1198,32 +1198,32 @@ void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain for (; i < numberOfCSNS && i * EPURSE_MAC_SIZE + 8 < USB_CMD_DATA_SIZE; i++) { memcpy(emulator, datain + (i*8), 8); - - // keyroll 1 + + // keyroll 1 if (doIClassSimulation(MODE_EXIT_AFTER_MAC, mac_responses + i * EPURSE_MAC_SIZE )) { cmd_send(CMD_ACK, CMD_SIMULATE_TAG_ICLASS, i*2, 0, mac_responses, i * EPURSE_MAC_SIZE * 2); // Button pressed - goto out; + goto out; } // keyroll 2 if (doIClassSimulation(MODE_EXIT_AFTER_MAC, mac_responses + (i + numberOfCSNS) * EPURSE_MAC_SIZE )) { cmd_send(CMD_ACK, CMD_SIMULATE_TAG_ICLASS, i*2, 0, mac_responses, i * EPURSE_MAC_SIZE* 2); // Button pressed - goto out; - } + goto out; + } } // double the amount of collected data. cmd_send(CMD_ACK, CMD_SIMULATE_TAG_ICLASS, i*2, 0, mac_responses, i * EPURSE_MAC_SIZE * 2 ); - + } else { // We may want a mode here where we hardcode the csns to use (from proxclone). // That will speed things up a little, but not required just yet. DbpString("[-] the mode is not implemented, reserved for future use"); } -out: - switch_off(); +out: + switch_off(); BigBuf_free_keep_EM(); } @@ -1236,13 +1236,13 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { // free eventually allocated BigBuf memory BigBuf_free_keep_EM(); - + State cipher_state; uint8_t *csn = BigBuf_get_EM_addr(); uint8_t *emulator = csn; uint8_t sof_data[] = { 0x0F} ; - + // CSN followed by two CRC bytes uint8_t anticoll_data[10] = { 0 }; uint8_t csn_data[10] = { 0 }; @@ -1254,7 +1254,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { // Compute CRC on both CSNs AddCrc(anticoll_data, 8); AddCrc(csn_data, 8); - + uint8_t diversified_key[8] = { 0 }; // e-Purse uint8_t card_challenge_data[8] = { 0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff }; @@ -1272,8 +1272,8 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { // set epurse of sim2,4 attack if (reader_mac_buf != NULL) { memcpy(reader_mac_buf, card_challenge_data, 8); - } - + } + int exitLoop = 0; // Reader 0a // Tag 0f @@ -1306,13 +1306,13 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { int resp_conf_len; uint8_t conf_data[10] = {0x12,0xFF,0xFF,0xFF,0x7F,0x1F,0xFF,0x3C,0x00,0x00}; AddCrc(conf_data, 8); - + // e-Purse // 18: Takes 2 bytes for SOF/EOF and 8 * 2 = 16 bytes (2 bytes/bit) uint8_t *resp_cc = BigBuf_malloc(28); int resp_cc_len; - // Application Issuer Area + // Application Issuer Area uint8_t *resp_aia = BigBuf_malloc(28); int resp_aia_len; uint8_t aia_data[10] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0x00,0x00}; @@ -1328,11 +1328,11 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { // First card answer: SOF CodeIClassTagSOF(); memcpy(resp_sof, ToSend, ToSendMax); resp_sof_Len = ToSendMax; - + // Anticollision CSN CodeIClassTagAnswer(anticoll_data, sizeof(anticoll_data)); memcpy(resp_anticoll, ToSend, ToSendMax); resp_anticoll_len = ToSendMax; - + // CSN CodeIClassTagAnswer(csn_data, sizeof(csn_data)); memcpy(resp_csn, ToSend, ToSendMax); resp_csn_len = ToSendMax; @@ -1340,7 +1340,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { // Configuration CodeIClassTagAnswer(conf_data, sizeof(conf_data)); memcpy(resp_conf, ToSend, ToSendMax); resp_conf_len = ToSendMax; - + // e-Purse CodeIClassTagAnswer(card_challenge_data, sizeof(card_challenge_data)); memcpy(resp_cc, ToSend, ToSendMax); resp_cc_len = ToSendMax; @@ -1374,7 +1374,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { //Signal tracer, can be used to get a trigger for an oscilloscope.. LED_B_OFF(); LED_C_OFF(); - + r2t_stime = (GetCountSspClk() - time_0) << 4; if (!GetIClassCommandFromReader(receivedCmd, &len, 0)) { buttonPressed = true; @@ -1382,7 +1382,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { continue; } r2t_etime = ((GetCountSspClk() - time_0) << 4 ) - r2t_stime; - + // 330us normal wait, adjusted for our execution LED_C_ON(); //Signal tracer @@ -1392,7 +1392,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { modulated_response = resp_sof; modulated_response_size = resp_sof_Len; //order = 1; trace_data = sof_data; trace_data_size = sizeof(sof_data); - // adjusted for 330 + (160*num of slot) + // adjusted for 330 + (160*num of slot) goto send; } else if (receivedCmd[0] == ICLASS_CMD_READ_OR_IDENTIFY) { // 0x0C if (len == 1) { @@ -1400,9 +1400,9 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { modulated_response = resp_anticoll; modulated_response_size = resp_anticoll_len; //order = 2; trace_data = anticoll_data; trace_data_size = sizeof(anticoll_data); - goto send; + goto send; } - if (len == 4){ + if (len == 4){ // block0,1,2,5 is always readable. switch (receivedCmd[1]){ case 0: // csn (0c 00) @@ -1415,7 +1415,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { trace_data = conf_data; trace_data_size = sizeof(conf_data); break; - case 2: // e-purse (0c 02) + case 2: // e-purse (0c 02) modulated_response = resp_cc; modulated_response_size = resp_cc_len; trace_data = card_challenge_data; trace_data_size = sizeof(card_challenge_data); @@ -1431,30 +1431,30 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { break; default: break; } - goto send; + goto send; } - + } else if (receivedCmd[0] == ICLASS_CMD_SELECT) { // 0x81 // Reader selects anticollission CSN. // Tag sends the corresponding real CSN modulated_response = resp_csn; modulated_response_size = resp_csn_len; //order = 3; trace_data = csn_data; trace_data_size = sizeof(csn_data); - goto send; + goto send; } else if (receivedCmd[0] == ICLASS_CMD_READCHECK_KD) { // 0x88 // Read e-purse (88 02) modulated_response = resp_cc; modulated_response_size = resp_cc_len; //order = 4; trace_data = card_challenge_data; trace_data_size = sizeof(card_challenge_data); LED_B_ON(); - goto send; + goto send; } else if (receivedCmd[0] == ICLASS_CMD_READCHECK_KC) { // 0x18 // Read e-purse (18 02) modulated_response = resp_cc; modulated_response_size = resp_cc_len; //order = 4; trace_data = card_challenge_data; trace_data_size = sizeof(card_challenge_data); LED_B_ON(); - goto send; + goto send; } else if (receivedCmd[0] == ICLASS_CMD_CHECK) { // 0x05 // Reader random and reader MAC!!! if (simulationMode == MODE_FULLSIM) { @@ -1473,9 +1473,9 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { modulated_response = resp_sof; modulated_response_size = 0; trace_data = NULL; trace_data_size = 0; - + if (simulationMode == MODE_EXIT_AFTER_MAC) { - + if ( MF_DBGLEVEL == MF_DBG_EXTENDED) { Dbprintf("[+] CSN: %02x %02x %02x %02x %02x %02x %02x %02x", csn[0], csn[1], csn[2], csn[3], csn[4], csn[5], csn[6], csn[7]); Dbprintf("[+] RDR: (len=%02d): %02x %02x %02x %02x %02x %02x %02x %02x %02x", len, @@ -1512,7 +1512,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { modulated_response_size = ToSendMax; goto send; } else if (simulationMode == MODE_FULLSIM && receivedCmd[0] == ICLASS_CMD_UPDATE) { - + //Probably the reader wants to update the nonce. Let's just ignore that for now. // OBS! If this is implemented, don't forget to regenerate the cipher_state //We're expected to respond with the data+crc, exactly what's already in the receivedcmd @@ -1524,10 +1524,10 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { trace_data = data_generic_trace; trace_data_size = 10; CodeIClassTagAnswer(trace_data, trace_data_size); - + memcpy(data_response, ToSend, ToSendMax); modulated_response = data_response; - modulated_response_size = ToSendMax; + modulated_response_size = ToSendMax; // response_delay = 4600 * 1.5; // tPROG 4-15ms goto send; // } else if(receivedCmd[0] == ICLASS_CMD_PAGESEL) { // 0x84 @@ -1542,7 +1542,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { // Never seen this command before if ( MF_DBGLEVEL == MF_DBG_EXTENDED) print_result("[-] Unhandled command received ", receivedCmd, len); - + // Do not respond modulated_response = resp_sof; modulated_response_size = 0; //order = 0; @@ -1550,7 +1550,7 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) { trace_data_size = 0; } -send: +send: /** A legit tag has about 330us delay between reader EOT and tag SOF. **/ @@ -1561,21 +1561,21 @@ send: } LogTrace(receivedCmd, len, r2t_stime, r2t_etime, NULL, true); - + if (trace_data != NULL) LogTrace(trace_data, trace_data_size, t2r_stime, t2r_etime, NULL, false); } LEDsoff(); - + if (buttonPressed) DbpString("[+] button pressed"); - + return buttonPressed; } /** - * @brief sends our simulated tag answer + * @brief sends our simulated tag answer * @param resp * @param respLen * @param delay @@ -1584,12 +1584,12 @@ static int SendIClassAnswer(uint8_t *resp, int respLen, uint16_t delay) { int i = 0; volatile uint8_t b = 0; - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K_8BIT); - + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K_8BIT); + AT91C_BASE_SSC->SSC_THR = 0x00; - + while (!BUTTON_PRESS()) { - + // Prevent rx holding register from overflowing if ( (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)){ b = AT91C_BASE_SSC->SSC_RHR; (void) b; @@ -1626,7 +1626,7 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD); AT91C_BASE_SSC->SSC_THR = 0x00; - + // make sure we timeout previous comms. if ( *wait ) SpinDelayUs(*wait); @@ -1640,7 +1640,7 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int // DOUBLE THE SAMPLES! if (firstpart) { - sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4); + sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4); } else { sendbyte = (cmd[c] & 0x0f) | (cmd[c] << 4); c++; @@ -1658,14 +1658,14 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int // Prevent rx holding register from overflowing if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { b = AT91C_BASE_SSC->SSC_RHR; (void)b; - } + } } if (samples) { if (wait) *samples = (c + *wait) << 3; else - *samples = c << 3; + *samples = c << 3; } } @@ -1684,7 +1684,7 @@ void CodeIClassCommand(const uint8_t* cmd, int len) { ToSend[++ToSendMax] = 0x0f; ToSend[++ToSendMax] = 0x00; - // Modulate the bytes + // Modulate the bytes for (i = 0; i < len; i++) { b = cmd[i]; for (j = 0; j < 4; j++) { @@ -1693,7 +1693,7 @@ void CodeIClassCommand(const uint8_t* cmd, int len) { if (k == (b & 3)) ToSend[++ToSendMax] = 0xf0; else - ToSend[++ToSendMax] = 0x00; + ToSend[++ToSendMax] = 0x00; } b >>= 2; } @@ -1720,9 +1720,9 @@ void ReaderTransmitIClass_ext(uint8_t* frame, int len, int wait) { TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait); if (trigger) LED_A_ON(); - + rsamples += samples; - + LogTrace(frame, len, rsamples, rsamples, NULL, true); } void ReaderTransmitIClass(uint8_t* frame, int len) { @@ -1741,7 +1741,7 @@ static int GetIClassAnswer(uint8_t* receivedResponse, int maxLen, int *samples, int c = 0; bool skip = false; - // Setup UART/DEMOD to receive + // Setup UART/DEMOD to receive DemodInit(receivedResponse); if (elapsed) *elapsed = 0; @@ -1759,7 +1759,7 @@ static int GetIClassAnswer(uint8_t* receivedResponse, int maxLen, int *samples, // keep tx buffer in a defined state anyway. if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0x00; + AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!! if (elapsed) (*elapsed)++; } @@ -1769,14 +1769,14 @@ static int GetIClassAnswer(uint8_t* receivedResponse, int maxLen, int *samples, if (c >= timeout) return false; c++; - + b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - - skip = !skip; + + skip = !skip; if (skip) continue; - + if (ManchesterDecoding_iclass(b & 0x0f)) { - if (samples) + if (samples) *samples = c << 3; return true; } @@ -1788,16 +1788,16 @@ static int GetIClassAnswer(uint8_t* receivedResponse, int maxLen, int *samples, int ReaderReceiveIClass(uint8_t* receivedAnswer) { int samples = 0; - if (!GetIClassAnswer(receivedAnswer, 0, &samples, NULL)) + if (!GetIClassAnswer(receivedAnswer, 0, &samples, NULL)) return false; rsamples += samples; LogTrace(receivedAnswer, Demod.len, rsamples, rsamples, NULL, false); - if (samples == 0) + if (samples == 0) return false; - + return Demod.len; } @@ -1808,9 +1808,9 @@ void setupIclassReader() { // Start from off (no field generated) // Signal field is off with the appropriate LED FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + FpgaSetupSsc(); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); @@ -1822,28 +1822,28 @@ void setupIclassReader() { // Signal field is on with the appropriate LED FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD); SpinDelay(300); - + StartCountSspClk(); - + LED_A_ON(); } bool sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries) { uint8_t got_n = 0; while (retries-- > 0) { - + ReaderTransmitIClass(command, cmdsize); - + //iceman - if received size is bigger than expected, we smash the stack here // since its called with fixed sized arrays got_n = ReaderReceiveIClass(resp); - + // 0xBB is the internal debug separator byte.. if ( expected_size != got_n|| (resp[0] == 0xBB || resp[7] == 0xBB || resp[2] == 0xBB)) { //try again continue; } - + if (got_n == expected_size) return true; } @@ -1865,7 +1865,7 @@ uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) { static uint8_t select[] = { ICLASS_CMD_SELECT, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; uint8_t readcheck_cc[] = { ICLASS_CMD_READCHECK_KD, 0x02 }; - if (use_credit_key) + if (use_credit_key) readcheck_cc[0] = ICLASS_CMD_READCHECK_KC; uint8_t resp[ICLASS_BUFFER_SIZE] = {0}; @@ -1873,7 +1873,7 @@ uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) { // Send act_all ReaderTransmitIClass_ext(act_all, 1, 330+160); - // Card present? + // Card present? if (!ReaderReceiveIClass(resp)) return read_status;//Fail //Send Identify @@ -1885,10 +1885,10 @@ uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) { //Copy the Anti-collision CSN to our select-packet memcpy(&select[1], resp, 8); - + //Select the card ReaderTransmitIClass(select, sizeof(select)); - + //We expect a 10-byte response here, 8 byte CSN and 2 byte CRC len = ReaderReceiveIClass(resp); if (len != 10) return read_status;//Fail @@ -1907,10 +1907,10 @@ uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) { // memcpy(card_data+8, resp, 8); // read_status++; // } - + bool isOK = sendCmdGetResponseWithRetries(readcheck_cc, sizeof(readcheck_cc), resp, 8, 3); if (!isOK) return read_status; - + //Save CC (e-purse) in response data memcpy(card_data+8, resp, 8); read_status++; @@ -1930,17 +1930,17 @@ void ReaderIClass(uint8_t arg0) { memset(card_data, 0xFF, sizeof(card_data)); memset(resp, 0xFF, sizeof(resp)); - + //Read conf block CRC(0x01) => 0xfa 0x22 uint8_t readConf[] = { ICLASS_CMD_READ_OR_IDENTIFY, 0x01, 0xfa, 0x22}; - + //Read App Issuer Area block CRC(0x05) => 0xde 0x64 uint8_t readAA[] = { ICLASS_CMD_READ_OR_IDENTIFY, 0x05, 0xde, 0x64}; int read_status = 0; uint16_t tryCnt = 0; uint8_t result_status = 0; - + bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE; // flag to read until one tag is found successfully bool try_once = arg0 & FLAG_ICLASS_READER_ONE_TRY; // flag to not to loop continuously, looking for tag bool use_credit_key = arg0 & FLAG_ICLASS_READER_CEDITKEY; // flag to use credit key @@ -1958,9 +1958,9 @@ void ReaderIClass(uint8_t arg0) { // if only looking for one card try 2 times if we missed it the first time if (try_once && tryCnt > 2) { if (MF_DBGLEVEL > 1) DbpString("Failed to find a tag"); - break; + break; } - + tryCnt++; result_status = 0; @@ -1998,7 +1998,7 @@ void ReaderIClass(uint8_t arg0) { // 0 : CSN // 1 : Configuration // 2 : e-purse - // 3 : kd / debit / aa2 (write-only) + // 3 : kd / debit / aa2 (write-only) // 4 : kc / credit / aa1 (write-only) // 5 : AIA, Application issuer area // @@ -2006,8 +2006,8 @@ void ReaderIClass(uint8_t arg0) { // with 0xFF:s in block 3 and 4. LED_B_ON(); - //Send back to client, but don't bother if we already sent this - - // only useful if looping in arm (not try_once && not abort_after_read) + //Send back to client, but don't bother if we already sent this - + // only useful if looping in arm (not try_once && not abort_after_read) if (memcmp(last_csn, card_data, 8) != 0) { // If caller requires that we get Conf, CC, AA, continue until we got it if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { @@ -2016,7 +2016,7 @@ void ReaderIClass(uint8_t arg0) { (result_status & FLAG_ICLASS_READER_CSN) ? 'Y':'N', (result_status & FLAG_ICLASS_READER_CONF)? 'Y':'N', (result_status & FLAG_ICLASS_READER_CC) ? 'Y':'N', - (result_status & FLAG_ICLASS_READER_AIA) ? 'Y':'N' + (result_status & FLAG_ICLASS_READER_AIA) ? 'Y':'N' ); Dbprintf(" aar %c | to %c, | uc %c | frc %c | fra %c | cc %c", abort_after_read ? 'Y':'N', @@ -2027,7 +2027,7 @@ void ReaderIClass(uint8_t arg0) { flagReadCC ? 'Y':'N' ); } - + bool send = (result_status & FLAG_ICLASS_READER_CSN ); if (flagReadCC) send |= (result_status & FLAG_ICLASS_READER_CC ); @@ -2035,9 +2035,9 @@ void ReaderIClass(uint8_t arg0) { send |= (result_status & FLAG_ICLASS_READER_AIA ); if (flagReadConfig) send |= (result_status & FLAG_ICLASS_READER_CONF ); - + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("SEND %c", send?'y':'n'); - + if ( send ) { cmd_send(CMD_ACK, result_status, 0, 0, card_data, sizeof(card_data) ); if (abort_after_read) { @@ -2051,7 +2051,7 @@ void ReaderIClass(uint8_t arg0) { LED_B_OFF(); userCancelled = BUTTON_PRESS() || usb_poll_validate_length(); } - + if (userCancelled) { cmd_send(CMD_ACK, 0xFF, 0, 0, card_data, 0); switch_off(); @@ -2076,14 +2076,14 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { int k2; int lockauth; int keyaccess; - } memory; - + } memory; + setupIclassReader(); while (!BUTTON_PRESS()) { - + WDT_HIT(); - + uint8_t read_status = handshakeIclassTag(card_data); if (read_status < 2) continue; @@ -2176,7 +2176,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { card_data, 0 ); - switch_off(); + switch_off(); } // not used. ?!? ( CMD_ICLASS_READCHECK) @@ -2187,10 +2187,10 @@ void iClass_ReadCheck(uint8_t blockNo, uint8_t keyType) { size_t isOK = 0; isOK = sendCmdGetResponseWithRetries(readcheck, sizeof(readcheck), resp, sizeof(resp), 6); cmd_send(CMD_ACK,isOK,0,0,0,0); - switch_off(); + switch_off(); } -// used with function select_and_auth (cmdhficlass.c) +// used with function select_and_auth (cmdhficlass.c) // which needs to authenticate before doing more things like read/write void iClass_Authentication(uint8_t *mac) { uint8_t check[] = { ICLASS_CMD_CHECK, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; @@ -2202,8 +2202,8 @@ void iClass_Authentication(uint8_t *mac) { check[7] = mac[2]; check[8] = mac[3]; //memcpy(check+5, mac, 4); - - // 6 retries + + // 6 retries bool isOK = sendCmdGetResponseWithRetries(check, sizeof(check), resp, 4, 6); cmd_send(CMD_ACK,isOK,0,0,0,0); } @@ -2213,7 +2213,7 @@ typedef struct iclass_premac { } iclass_premac_t; /* this function works on the following assumptions. -* - one select first, to get CSN / CC (e-purse) +* - one select first, to get CSN / CC (e-purse) * - calculate before diversified keys and precalc mac based on CSN/KEY. * - data in contains of diversified keys, mac * - key loop only test one type of authtication key. Ie two calls needed @@ -2225,77 +2225,77 @@ void iClass_Authentication_fast(uint64_t arg0, uint64_t arg1, uint8_t *datain) { bool use_credit_key =((arg0 >> 16) & 0xFF); uint8_t keyCount = arg1 & 0xFF; uint8_t check[] = { ICLASS_CMD_CHECK, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - uint8_t resp[ICLASS_BUFFER_SIZE]; + uint8_t resp[ICLASS_BUFFER_SIZE]; uint8_t readcheck_cc[] = { ICLASS_CMD_READCHECK_KD, 0x02 }; - if (use_credit_key) + if (use_credit_key) readcheck_cc[0] = ICLASS_CMD_READCHECK_KC; - + // select card / e-purse uint8_t card_data[6 * 8] = {0}; - + iclass_premac_t *keys = (iclass_premac_t *)datain; - + LED_A_ON(); - + switch_off(); SpinDelay(20); - + setupIclassReader(); int read_status = 0; uint8_t startup_limit = 10; while ( read_status != 2) { - + if (BUTTON_PRESS() && !usb_poll_validate_length()) goto out; - + read_status = handshakeIclassTag_ext(card_data, use_credit_key); if ( startup_limit-- == 0 ) { Dbprintf("[-] Handshake status | %d (fail 10)", read_status); - isOK = 99; + isOK = 99; goto out; } }; // since handshakeIclassTag_ext call sends s readcheck, we start with sending first response. - + // Keychunk loop for (i = 0; i < keyCount; i++) { - + // Allow button press / usb cmd to interrupt device if (BUTTON_PRESS() && !usb_poll_validate_length()) break; WDT_HIT(); - LED_B_ON(); - + LED_B_ON(); + // copy MAC to check command (readersignature) check[5] = keys[i].mac[0]; check[6] = keys[i].mac[1]; check[7] = keys[i].mac[2]; check[8] = keys[i].mac[3]; - + // expect 4bytes, 3 retries times.. isOK = sendCmdGetResponseWithRetries(check, sizeof(check), resp, 4, 3); if ( isOK ) goto out; - + SpinDelayUs(400); //iClass (iso15693-2) should timeout after 330us. - // Auth Sequence MUST begin with reading e-purse. (block2) - // Card selected, now read e-purse (cc) (block2) (only 8 bytes no CRC) - ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc)); - - LED_B_OFF(); + // Auth Sequence MUST begin with reading e-purse. (block2) + // Card selected, now read e-purse (cc) (block2) (only 8 bytes no CRC) + ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc)); + + LED_B_OFF(); } - -out: + +out: // send keyindex. cmd_send(CMD_ACK, isOK, i, 0, 0, 0); - + if ( isOK >= 1 || lastChunk ) { switch_off(); LED_A_OFF(); } - + LED_B_OFF(); LED_C_OFF(); } @@ -2318,7 +2318,7 @@ void iClass_ReadBlk(uint8_t blockno) { uint8_t data[] = {0,0,0,0,0,0,0,0,0,0}; bool isOK = iClass_ReadBlock(blockno, data, sizeof(data)); cmd_send(CMD_ACK, isOK, 0, 0, data, sizeof(data)); - switch_off(); + switch_off(); } // turn off afterwards @@ -2339,7 +2339,7 @@ void iClass_Dump(uint8_t blockno, uint8_t numblks) { for (;blkCnt < numblks; blkCnt++) { isOK = iClass_ReadBlock(blockno + blkCnt, blockdata, sizeof(blockdata)); - + // 0xBB is the internal debug separator byte.. if (!isOK || (blockdata[0] == 0xBB || blockdata[7] == 0xBB || blockdata[2] == 0xBB)) { //try again isOK = iClass_ReadBlock(blockno + blkCnt, blockdata, sizeof(blockdata)); @@ -2352,7 +2352,7 @@ void iClass_Dump(uint8_t blockno, uint8_t numblks) { } //return pointer to dump memory in arg3 cmd_send(CMD_ACK, isOK, blkCnt, BigBuf_max_traceLen(), 0, 0); - switch_off(); + switch_off(); BigBuf_free(); } @@ -2372,7 +2372,7 @@ bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) { //if not programming key areas (note key blocks don't get programmed with actual key data it is xor data) if (blockNo != 3 && blockNo != 4) { isOK = sendCmdGetResponseWithRetries(write, sizeof(write), resp, sizeof(resp), 5); - } + } } } return isOK; @@ -2382,7 +2382,7 @@ bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) { void iClass_WriteBlock(uint8_t blockNo, uint8_t *data) { bool isOK = iClass_WriteBlock_ext(blockNo, data); cmd_send(CMD_ACK,isOK,0,0,0,0); - switch_off(); + switch_off(); } // turn off afterwards @@ -2406,8 +2406,8 @@ void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t *data) { if (written == total_block) DbpString("Clone complete"); else - DbpString("Clone incomplete"); + DbpString("Clone incomplete"); cmd_send(CMD_ACK,1,0,0,0,0); - switch_off(); + switch_off(); } \ No newline at end of file diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 4267d28af..9e415fcdb 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -29,8 +29,8 @@ static uint8_t* free_buffer_pointer; // // minimum time between the start bits of consecutive transfers from reader to tag: 7000 carrier (13.56Mhz) cycles #define REQUEST_GUARD_TIME (7000/16 + 1) -// minimum time between last modulation of tag and next start bit from reader to tag: 1172 carrier cycles -#define FRAME_DELAY_TIME_PICC_TO_PCD (1172/16 + 1) +// minimum time between last modulation of tag and next start bit from reader to tag: 1172 carrier cycles +#define FRAME_DELAY_TIME_PICC_TO_PCD (1172/16 + 1) // bool LastCommandWasRequest = false; // @@ -42,8 +42,8 @@ static uint8_t* free_buffer_pointer; // 8 ticks until bit_to_arm is assigned from curbit // 8*16 ticks for the transfer from FPGA to ARM // 4*16 ticks until we measure the time -// - 8*16 ticks because we measure the time of the previous transfer -#define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16) +// - 8*16 ticks because we measure the time of the previous transfer +#define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16) // When the PM acts as a reader and is sending, it takes // 4*16 ticks until we can write data to the sending hold register @@ -60,10 +60,10 @@ static uint8_t* free_buffer_pointer; // 8 ticks until the SSC samples the first data // 7*16 ticks to complete the transfer from FPGA to ARM // 8 ticks until the next ssp_clk rising edge -// 4*16 ticks until we measure the time -// - 8*16 ticks because we measure the time of the previous transfer +// 4*16 ticks until we measure the time +// - 8*16 ticks because we measure the time of the previous transfer #define DELAY_AIR2ARM_AS_TAG (2 + 3 + 8 + 8 + 7*16 + 8 + 4*16 - 8*16) - + // The FPGA will report its internal sending delay in uint16_t FpgaSendQueueDelay; // the 5 first bits are the number of bits buffered in mod_sig_buf @@ -85,16 +85,16 @@ uint16_t FpgaSendQueueDelay; // 8 ticks (on average) until the result is stored in to_arm // + the delays in transferring data - which is the same for // sniffing reader and tag data and therefore not relevant -#define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8) - +#define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8) + // When the PM acts as sniffer and is receiving reader data, it takes -// 2 ticks delay in analogue RF receiver (for the falling edge of the +// 2 ticks delay in analogue RF receiver (for the falling edge of the // start bit, which marks the start of the communication) // 3 ticks A/D conversion // 8 ticks on average until the data is stored in to_arm. // + the delays in transferring data - which is the same for // sniffing reader and tag data and therefore not relevant -#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8) +#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8) //variables used for timing purposes: //these are in ssp_clk cycles: @@ -106,7 +106,7 @@ static uint32_t LastProxToAirDuration; // Sequence D: 11110000 modulation with subcarrier during first half // Sequence E: 00001111 modulation with subcarrier during second half // Sequence F: 00000000 no modulation with subcarrier -// Sequence COLL: 11111111 load modulation over the full bitlenght. +// Sequence COLL: 11111111 load modulation over the full bitlenght. // Tricks the reader to think that multiple cards answer (at least one card with 1 and at least one card with 0). // READER TO CARD - miller // Sequence X: 00001100 drop after half a period @@ -154,7 +154,7 @@ void GetParity(const uint8_t *pbtCmd, uint16_t iLen, uint8_t *par) { } // save remaining parity bits - par[paritybyte_cnt] = parityBits; + par[paritybyte_cnt] = parityBits; } @@ -163,8 +163,8 @@ void GetParity(const uint8_t *pbtCmd, uint16_t iLen, uint8_t *par) { //============================================================================= // Basics: // This decoder is used when the PM3 acts as a tag. -// The reader will generate "pauses" by temporarily switching of the field. -// At the PM3 antenna we will therefore measure a modulated antenna voltage. +// The reader will generate "pauses" by temporarily switching of the field. +// At the PM3 antenna we will therefore measure a modulated antenna voltage. // The FPGA does a comparison with a threshold and would deliver e.g.: // ........ 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 ....... // The Miller decoder needs to identify the following sequences: @@ -216,17 +216,17 @@ void UartInit(uint8_t *data, uint8_t *parity) { // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) { Uart.fourBits = (Uart.fourBits << 8) | bit; - + if (Uart.state == STATE_UNSYNCD) { // not yet synced Uart.syncBit = 9999; // not set - + // 00x11111 2|3 ticks pause followed by 6|5 ticks unmodulated Sequence Z (a "0" or "start of communication") // 11111111 8 ticks unmodulation Sequence Y (a "0" or "end of communication" or "no information") // 111100x1 4 ticks unmodulated followed by 2|3 ticks pause Sequence X (a "1") // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111) - // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern + // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's) #define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00000111 11111111 11101111 10000000 #define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00000111 11111111 10001111 10000000 @@ -247,7 +247,7 @@ RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) { } } else { - if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) { + if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) { if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation in both halves - error UartReset(); } else { // Modulation in first half = Sequence Z = logic "0" @@ -329,8 +329,8 @@ RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) { } } } - } - } + } + } return false; // not finished yet, need more data } @@ -369,12 +369,12 @@ void DemodReset(void) { Demod.len = 0; // number of decoded data bytes Demod.parityLen = 0; Demod.shiftReg = 0; // shiftreg to hold decoded data bits - Demod.parityBits = 0; // + Demod.parityBits = 0; // Demod.collisionPos = 0; // Position of collision bit Demod.twoBits = 0xFFFF; // buffer for 2 Bits Demod.highCnt = 0; Demod.startTime = 0; - Demod.endTime = 0; + Demod.endTime = 0; Demod.bitCount = 0; Demod.syncBit = 0xFFFF; Demod.samples = 0; @@ -389,7 +389,7 @@ void DemodInit(uint8_t *data, uint8_t *parity) { // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time) { Demod.twoBits = (Demod.twoBits << 8) | bit; - + if (Demod.state == DEMOD_UNSYNCD) { if (Demod.highCnt < 2) { // wait for a stable unmodulated signal @@ -400,7 +400,7 @@ RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_t } } else { Demod.syncBit = 0xFFFF; // not set - if ((Demod.twoBits & 0x7700) == 0x7000) Demod.syncBit = 7; + if ((Demod.twoBits & 0x7700) == 0x7000) Demod.syncBit = 7; else if ((Demod.twoBits & 0x3B80) == 0x3800) Demod.syncBit = 6; else if ((Demod.twoBits & 0x1DC0) == 0x1C00) Demod.syncBit = 5; else if ((Demod.twoBits & 0x0EE0) == 0x0E00) Demod.syncBit = 4; @@ -493,21 +493,21 @@ void RAMFUNC SniffIso14443a(uint8_t param) { // bit 0 - trigger from first card answer // bit 1 - trigger from first reader 7-bit request iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - + // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(true); - + // The command (reader -> tag) that we're receiving. uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); uint8_t *receivedCmdPar = BigBuf_malloc(MAX_PARITY_SIZE); - + // The response (tag -> reader) that we're receiving. uint8_t *receivedResp = BigBuf_malloc(MAX_FRAME_SIZE); uint8_t *receivedRespPar = BigBuf_malloc(MAX_PARITY_SIZE); - + // The DMA buffer, used to stream samples from the FPGA uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); uint8_t *data = dmaBuf; @@ -517,29 +517,29 @@ void RAMFUNC SniffIso14443a(uint8_t param) { int dataLen = 0; bool TagIsActive = false; bool ReaderIsActive = false; - + // Set up the demodulator for tag -> reader responses. DemodInit(receivedResp, receivedRespPar); - + // Set up the demodulator for the reader -> tag commands UartInit(receivedCmd, receivedCmdPar); - + // Setup and start DMA. if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE) ){ - if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting"); + if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting"); return; } - + // We won't start recording the frames that we acquire until we trigger; // a good trigger condition to get started is probably when we see a // response from the tag. // triggered == false -- to wait first for card - bool triggered = !(param & 0x03); - + bool triggered = !(param & 0x03); + uint32_t rsamples = 0; DbpString("Starting to sniff"); - + // loop and listen while (!BUTTON_PRESS()) { WDT_HIT(); @@ -551,7 +551,7 @@ void RAMFUNC SniffIso14443a(uint8_t param) { dataLen = dmaBufDataP - readBufDataP; else dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP; - + // test for length of buffer if (dataLen > maxDataLen) { maxDataLen = dataLen; @@ -575,7 +575,7 @@ void RAMFUNC SniffIso14443a(uint8_t param) { } LED_A_OFF(); - + // Need two samples to feed Miller and Manchester-Decoder if (rsamples & 0x01) { @@ -588,11 +588,11 @@ void RAMFUNC SniffIso14443a(uint8_t param) { if ((!triggered) && (param & 0x02) && (Uart.len == 1) && (Uart.bitCount == 7)) triggered = true; if (triggered) { - if (!LogTrace(receivedCmd, - Uart.len, + if (!LogTrace(receivedCmd, + Uart.len, Uart.startTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, - Uart.parity, + Uart.parity, true)) break; } /* ready to receive another command. */ @@ -606,14 +606,14 @@ void RAMFUNC SniffIso14443a(uint8_t param) { } // no need to try decoding tag data if the reader is sending - and we cannot afford the time - if (!ReaderIsActive) { + if (!ReaderIsActive) { uint8_t tagdata = (previous_data << 4) | (*data & 0x0F); if (ManchesterDecoding(tagdata, 0, (rsamples-1)*4)) { LED_B_ON(); - if (!LogTrace(receivedResp, - Demod.len, - Demod.startTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, + if (!LogTrace(receivedResp, + Demod.len, + Demod.startTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, Demod.endTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER, Demod.parity, false)) break; @@ -626,7 +626,7 @@ void RAMFUNC SniffIso14443a(uint8_t param) { UartReset(); //UartInit(receivedCmd, receivedCmdPar); LED_C_OFF(); - } + } TagIsActive = (Demod.state != DEMOD_UNSYNCD); } } @@ -643,14 +643,14 @@ void RAMFUNC SniffIso14443a(uint8_t param) { Dbprintf("maxDataLen=%d, Uart.state=%x, Uart.len=%d", maxDataLen, Uart.state, Uart.len); Dbprintf("traceLen=%d, Uart.output[0]=%08x", BigBuf_get_traceLen(), (uint32_t)Uart.output[0]); } - switch_off(); + switch_off(); } //----------------------------------------------------------------------------- // Prepare tag messages //----------------------------------------------------------------------------- static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *parity, bool collision) { - + //uint8_t localCol = 0; ToSendReset(); @@ -663,7 +663,7 @@ static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par ToSendStuffBit(0); ToSendStuffBit(0); ToSendStuffBit(0); - + // Send startbit ToSend[++ToSendMax] = SEC_D; LastProxToAirDuration = 8 * ToSendMax - 4; @@ -676,7 +676,7 @@ static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par //if (collision && (localCol >= colpos)){ if (collision) { ToSend[++ToSendMax] = SEC_COLL; - //localCol++; + //localCol++; } else { if (b & 1) { ToSend[++ToSendMax] = SEC_D; @@ -689,7 +689,7 @@ static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *par if (collision) { ToSend[++ToSendMax] = SEC_COLL; - LastProxToAirDuration = 8 * ToSendMax; + LastProxToAirDuration = 8 * ToSendMax; } else { // Get the parity bit if (parity[i>>3] & (0x80>>(i&0x0007))) { @@ -817,12 +817,12 @@ bool prepare_tag_modulation(tag_response_info_t* response_info, size_t max_buffe } // "precompile" responses. There are 7 predefined responses with a total of 28 bytes data to transmit. -// Coded responses need one byte per bit to transfer (data, parity, start, stop, correction) +// Coded responses need one byte per bit to transfer (data, parity, start, stop, correction) // 28 * 8 data bits, 28 * 1 parity bits, 7 start bits, 7 stop bits, 7 correction bits // -> need 273 bytes buffer // 44 * 8 data bits, 44 * 1 parity bits, 9 start bits, 9 stop bits, 9 correction bits --370 -// 47 * 8 data bits, 47 * 1 parity bits, 10 start bits, 10 stop bits, 10 correction bits -#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 453 +// 47 * 8 data bits, 47 * 1 parity bits, 10 start bits, 10 stop bits, 10 correction bits +#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 453 bool prepare_allocated_tag_modulation(tag_response_info_t* response_info) { // Retrieve and store the current buffer index @@ -851,14 +851,14 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { #define ATTACK_KEY_COUNT 8 // keep same as define in cmdhfmf.c -> readerAttack() uint8_t sak = 0; - uint32_t cuid = 0; + uint32_t cuid = 0; uint32_t nonce = 0; - + // PACK response to PWD AUTH for EV1/NTAG uint8_t response8[4] = {0,0,0,0}; // Counter for EV1/NTAG uint32_t counters[] = {0,0,0}; - + // The first response contains the ATQA (note: bytes are transmitted in reverse order). uint8_t response1[] = {0,0}; @@ -871,9 +871,9 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { nonces_t ar_nr_nonces[ATTACK_KEY_COUNT]; // for attack types moebius memset(ar_nr_nonces, 0x00, sizeof(ar_nr_nonces)); uint8_t moebius_count = 0; - + switch (tagType) { - case 1: { // MIFARE Classic 1k + case 1: { // MIFARE Classic 1k response1[0] = 0x04; sak = 0x08; } break; @@ -908,14 +908,14 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { compute_crc(CRC_14443_A, response8, 2, &response8[2], &response8[3]); // uid not supplied then get from emulator memory if (data[0]==0) { - uint16_t start = 4 * (0+12); + uint16_t start = 4 * (0+12); uint8_t emdata[8]; emlGetMemBt( emdata, start, sizeof(emdata)); memcpy(data, emdata, 3); // uid bytes 0-2 memcpy(data+3, emdata+4, 4); // uid bytes 3-7 flags |= FLAG_7B_UID_IN_DATA; } - } break; + } break; case 8: { // MIFARE Classic 4k response1[0] = 0x02; sak = 0x18; @@ -930,13 +930,13 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { return; } break; } - + // The second response contains the (mandatory) first 24 bits of the UID uint8_t response2[5] = {0x00}; - // For UID size 7, + // For UID size 7, uint8_t response2a[5] = {0x00}; - + if ( (flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA ) { response2[0] = 0x88; // Cascade Tag marker response2[1] = data[0]; @@ -952,7 +952,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { // Configure the ATQA and SAK accordingly response1[0] |= 0x40; sak |= 0x04; - + cuid = bytes_to_num(data+3, 4); } else { memcpy(response2, data, 4); @@ -975,22 +975,22 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { compute_crc(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]); // Tag NONCE. - uint8_t response5[4]; - - uint8_t response6[] = { 0x04, 0x58, 0x80, 0x02, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS: - - // Format byte = 0x58: FSCI=0x08 (FSC=256), TA(1) and TC(1) present, + uint8_t response5[4]; + + uint8_t response6[] = { 0x04, 0x58, 0x80, 0x02, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS: + + // Format byte = 0x58: FSCI=0x08 (FSC=256), TA(1) and TC(1) present, // TA(1) = 0x80: different divisors not supported, DR = 1, DS = 1 // TB(1) = not present. Defaults: FWI = 4 (FWT = 256 * 16 * 2^4 * 1/fc = 4833us), SFGI = 0 (SFG = 256 * 16 * 2^0 * 1/fc = 302us) // TC(1) = 0x02: CID supported, NAD not supported compute_crc(CRC_14443_A, response6, 4, &response6[4], &response6[5]); - + // Prepare GET_VERSION (different for UL EV-1 / NTAG) // uint8_t response7_EV1[] = {0x00, 0x04, 0x03, 0x01, 0x01, 0x00, 0x0b, 0x03, 0xfd, 0xf7}; //EV1 48bytes VERSION. - // uint8_t response7_NTAG[] = {0x00, 0x04, 0x04, 0x02, 0x01, 0x00, 0x11, 0x03, 0x01, 0x9e}; //NTAG 215 + // uint8_t response7_NTAG[] = {0x00, 0x04, 0x04, 0x02, 0x01, 0x00, 0x11, 0x03, 0x01, 0x9e}; //NTAG 215 // Prepare CHK_TEARING // uint8_t response9[] = {0xBD,0x90,0x3f}; - + #define TAG_RESPONSE_COUNT 10 tag_response_info_t responses[TAG_RESPONSE_COUNT] = { { .response = response1, .response_n = sizeof(response1) }, // Answer to request - respond with card type @@ -1002,10 +1002,10 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { { .response = response6, .response_n = sizeof(response6) }, // dummy ATS (pseudo-ATR), answer to RATS { .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 @@ -1019,7 +1019,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { .modulation = dynamic_modulation_buffer, .modulation_n = 0 }; - + // We need to listen to the high-frequency, peak-detected path. iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); @@ -1050,16 +1050,16 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { tag_response_info_t* p_response; LED_A_ON(); - for (;;) { + for (;;) { WDT_HIT(); - + // Clean receive command buffer if (!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) { Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen()); break; - } + } p_response = NULL; - + // Okay, look at the command now. lastorder = order; if (receivedCmd[0] == ISO14443A_CMD_REQA) { // Received a REQUEST @@ -1073,13 +1073,13 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { } else if (receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received a SELECT (cascade 1) p_response = &responses[3]; order = 3; } else if (receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received a SELECT (cascade 2) - p_response = &responses[4]; order = 30; + p_response = &responses[4]; order = 30; } else if (receivedCmd[0] == ISO14443A_CMD_READBLOCK) { // Received a (plain) READ uint8_t block = receivedCmd[1]; // if Ultralight or NTAG (4 byte blocks) if ( tagType == 7 || tagType == 2 ) { // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature] - uint16_t start = 4 * (block+12); + uint16_t start = 4 * (block+12); uint8_t emdata[MAX_MIFARE_FRAME_SIZE]; emlGetMemBt( emdata, start, 16); AddCrc14A(emdata, 16); @@ -1101,24 +1101,24 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below p_response = NULL; } - } else if (receivedCmd[0] == MIFARE_ULEV1_FASTREAD) { // Received a FAST READ (ranged read) + } else if (receivedCmd[0] == MIFARE_ULEV1_FASTREAD) { // Received a FAST READ (ranged read) uint8_t emdata[MAX_FRAME_SIZE]; // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature] - int start = (receivedCmd[1]+12) * 4; + int start = (receivedCmd[1]+12) * 4; int len = (receivedCmd[2] - receivedCmd[1] + 1) * 4; emlGetMemBt( emdata, start, len); AddCrc14A(emdata, len); - EmSendCmd(emdata, len+2); - p_response = NULL; - } else if (receivedCmd[0] == MIFARE_ULEV1_READSIG && tagType == 7) { // Received a READ SIGNATURE -- + EmSendCmd(emdata, len+2); + p_response = NULL; + } else if (receivedCmd[0] == MIFARE_ULEV1_READSIG && tagType == 7) { // Received a READ SIGNATURE -- // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature] uint16_t start = 4 * 4; uint8_t emdata[34]; emlGetMemBt( emdata, start, 32); AddCrc14A(emdata, 32); EmSendCmd(emdata, sizeof(emdata)); - p_response = NULL; - } else if (receivedCmd[0] == MIFARE_ULEV1_READ_CNT && tagType == 7) { // Received a READ COUNTER -- + p_response = NULL; + } else if (receivedCmd[0] == MIFARE_ULEV1_READ_CNT && tagType == 7) { // Received a READ COUNTER -- uint8_t index = receivedCmd[1]; if (index > 2) { // send NACK 0x0 == invalid argument @@ -1128,10 +1128,10 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { uint8_t cmd[] = {0x00,0x00,0x00,0x14,0xa5}; num_to_bytes(counters[index], 3, cmd); AddCrc14A(cmd, sizeof(cmd)-2); - EmSendCmd(cmd,sizeof(cmd)); + EmSendCmd(cmd,sizeof(cmd)); } p_response = NULL; - } else if (receivedCmd[0] == MIFARE_ULEV1_INCR_CNT && tagType == 7) { // Received a INC COUNTER -- + } else if (receivedCmd[0] == MIFARE_ULEV1_INCR_CNT && tagType == 7) { // Received a INC COUNTER -- uint8_t index = receivedCmd[1]; if ( index > 2) { // send NACK 0x0 == invalid argument @@ -1140,21 +1140,21 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { } else { uint32_t val = bytes_to_num(receivedCmd+2,4); - + // if new value + old value is bigger 24bits, fail if ( val + counters[index] > 0xFFFFFF ) { // send NACK 0x4 == counter overflow uint8_t nack[] = {0x04}; EmSendCmd(nack,sizeof(nack)); - } else { - counters[index] = val; + } else { + counters[index] = val; // send ACK uint8_t ack[] = {0x0a}; EmSendCmd(ack,sizeof(ack)); } } - p_response = NULL; - } else if (receivedCmd[0] == MIFARE_ULEV1_CHECKTEAR && tagType == 7) { // Received a CHECK_TEARING_EVENT -- + p_response = NULL; + } else if (receivedCmd[0] == MIFARE_ULEV1_CHECKTEAR && tagType == 7) { // Received a CHECK_TEARING_EVENT -- // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature] uint8_t emdata[3]; uint8_t index = receivedCmd[1]; @@ -1162,16 +1162,16 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { // send NACK 0x0 == invalid argument uint8_t nack[] = {0x00}; EmSendCmd(nack,sizeof(nack)); - } else { + } else { emlGetMemBt( emdata, 10+index, 1); AddCrc14A(emdata, sizeof(emdata)-2); - EmSendCmd(emdata, sizeof(emdata)); + EmSendCmd(emdata, sizeof(emdata)); } - p_response = NULL; + p_response = NULL; } else if (receivedCmd[0] == ISO14443A_CMD_HALT) { // Received a HALT LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); p_response = NULL; - } else if (receivedCmd[0] == MIFARE_AUTH_KEYA || receivedCmd[0] == MIFARE_AUTH_KEYB) { // Received an authentication request + } else if (receivedCmd[0] == MIFARE_AUTH_KEYA || receivedCmd[0] == MIFARE_AUTH_KEYB) { // Received an authentication request if ( tagType == 7 ) { // IF NTAG /EV1 0x60 == GET_VERSION, not a authentication request. uint8_t emdata[10]; emlGetMemBt( emdata, 0, 8 ); @@ -1179,20 +1179,20 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { EmSendCmd(emdata, sizeof(emdata)); p_response = NULL; } else { - + cardAUTHKEY = receivedCmd[0] - 0x60; cardAUTHSC = receivedCmd[1] / 4; // received block num - - // incease nonce at AUTH requests. this is time consuming. + + // incease nonce at AUTH requests. this is time consuming. nonce = prng_successor( GetTickCount(), 32 ); //num_to_bytes(nonce, 4, response5); - num_to_bytes(nonce, 4, dynamic_response_info.response); + num_to_bytes(nonce, 4, dynamic_response_info.response); dynamic_response_info.response_n = 4; //prepare_tag_modulation(&responses[5], DYNAMIC_MODULATION_BUFFER_SIZE); prepare_tag_modulation(&dynamic_response_info, DYNAMIC_MODULATION_BUFFER_SIZE); p_response = &dynamic_response_info; - //p_response = &responses[5]; + //p_response = &responses[5]; order = 7; } } else if (receivedCmd[0] == ISO14443A_CMD_RATS) { // Received a RATS request @@ -1206,15 +1206,15 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); uint32_t nr = bytes_to_num(receivedCmd,4); uint32_t ar = bytes_to_num(receivedCmd+4,4); - + // Collect AR/NR per keytype & sector if ( (flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK ) { - + int8_t index = -1; int8_t empty = -1; for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) { // find which index to use - if ( (cardAUTHSC == ar_nr_nonces[i].sector) && (cardAUTHKEY == ar_nr_nonces[i].keytype)) + if ( (cardAUTHSC == ar_nr_nonces[i].sector) && (cardAUTHKEY == ar_nr_nonces[i].keytype)) index = i; // keep track of empty slots. @@ -1242,8 +1242,8 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { ar_nr_nonces[index].ar = ar; ar_nr_nonces[index].state = FIRST; break; - } - case FIRST : { + } + case FIRST : { // second nonce collect ar_nr_nonces[index].nonce2 = nonce; ar_nr_nonces[index].nr2 = nr; @@ -1252,11 +1252,11 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { // send to client cmd_send(CMD_ACK, CMD_SIMULATE_MIFARE_CARD, 0, 0, &ar_nr_nonces[index], sizeof(nonces_t)); - + ar_nr_nonces[index].state = EMPTY; ar_nr_nonces[index].sector = 0; ar_nr_nonces[index].keytype = 0; - + moebius_count++; break; } @@ -1264,7 +1264,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { } } p_response = NULL; - + } else if (receivedCmd[0] == MIFARE_ULC_AUTH_1 ) { // ULC authentication, or Desfire Authentication } else if (receivedCmd[0] == MIFARE_ULEV1_AUTH) { // NTAG / EV-1 authentication if ( tagType == 7 ) { @@ -1275,8 +1275,8 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { EmSendCmd(emdata, sizeof(emdata)); p_response = NULL; uint32_t pwd = bytes_to_num(receivedCmd+1,4); - - if ( MF_DBGLEVEL >= 3) Dbprintf("Auth attempt: %08x", pwd); + + if ( MF_DBGLEVEL >= 3) Dbprintf("Auth attempt: %08x", pwd); } } else { // Check for ISO 14443A-4 compliant commands, look at left nibble @@ -1308,7 +1308,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { dynamic_response_info.response[0] = receivedCmd[0] ^ 0x11; dynamic_response_info.response_n = 2; } break; - + case 0xBA: { // ping / pong dynamic_response_info.response[0] = 0xAB; dynamic_response_info.response[1] = 0x00; @@ -1331,7 +1331,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { dynamic_response_info.response_n = 0; } break; } - + if (dynamic_response_info.response_n > 0) { // Copy the CID from the reader query dynamic_response_info.response[1] = receivedCmd[1]; @@ -1339,7 +1339,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { // Add CRC bytes, always used in ISO 14443A-4 compliant cards AddCrc14A(dynamic_response_info.response, dynamic_response_info.response_n); dynamic_response_info.response_n += 2; - + if (prepare_tag_modulation(&dynamic_response_info,DYNAMIC_MODULATION_BUFFER_SIZE) == false) { DbpString("Error preparing tag response"); LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); @@ -1362,25 +1362,25 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) { // do the tracing for the previous reader request and this tag answer: uint8_t par[MAX_PARITY_SIZE] = {0x00}; GetParity(p_response->response, p_response->response_n, par); - - EmLogTrace(Uart.output, - Uart.len, - Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, - Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, + + EmLogTrace(Uart.output, + Uart.len, + Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, + Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, - p_response->response, + p_response->response, p_response->response_n, LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG, - (LastTimeProxToAirStart + p_response->ProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG, + (LastTimeProxToAirStart + p_response->ProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG, par); } } cmd_send(CMD_ACK,1,0,0,0,0); - switch_off(); - + switch_off(); + BigBuf_free_keep_EM(); - + if (MF_DBGLEVEL >= 4){ Dbprintf("-[ Wake ups after halt [%d]", happened); Dbprintf("-[ Messages after halt [%d]", happened2); @@ -1431,13 +1431,13 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing *timing = (GetCountSspClk() + 8) & 0xfffffff8; else 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 { - + uint32_t ThisTransferTime = 0; ThisTransferTime = ((MAX(NextTransferTime, GetCountSspClk()) & 0xfffffff8) + 8); @@ -1445,12 +1445,12 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing LastTimeProxToAirStart = ThisTransferTime; } - + // clear TXRDY AT91C_BASE_SSC->SSC_THR = SEC_Y; volatile uint8_t b; - uint16_t c = 0; + uint16_t c = 0; while (c < len) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = cmd[c++]; @@ -1458,9 +1458,9 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing //iceman test if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { b = (uint16_t)(AT91C_BASE_SSC->SSC_RHR); (void)b; - } + } } - + NextTransferTime = MAX(NextTransferTime, LastTimeProxToAirStart + REQUEST_GUARD_TIME); } @@ -1577,13 +1577,13 @@ int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity) { AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF); // start ADC AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START; - + // Now run a 'software UART' on the stream of incoming samples. UartInit(received, parity); // Clear RXRDY: uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - + for(;;) { WDT_HIT(); @@ -1623,7 +1623,7 @@ int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen) { uint16_t i = 0; uint32_t ThisTransferTime; bool correctionNeeded; - + // Modulate Manchester FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD); @@ -1646,7 +1646,7 @@ int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen) { b = AT91C_BASE_SSC->SSC_RHR; (void) b; while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)); b = AT91C_BASE_SSC->SSC_RHR; (void) b; - + // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line) for (uint8_t j = 0; j < 5; j++) { // allow timeout - better late than never while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)); @@ -1664,15 +1664,15 @@ int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen) { AT91C_BASE_SSC->SSC_THR = resp[i++]; FpgaSendQueueDelay = (uint8_t)AT91C_BASE_SSC->SSC_RHR; } - + if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { b = (uint16_t)(AT91C_BASE_SSC->SSC_RHR); (void)b; - } + } if(BUTTON_PRESS()) break; } // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again: - uint8_t fpga_queued_bits = FpgaSendQueueDelay >> 3; + uint8_t fpga_queued_bits = FpgaSendQueueDelay >> 3; for (i = 0; i <= fpga_queued_bits/8 + 1; ) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = SEC_F; @@ -1690,15 +1690,15 @@ int EmSend4bit(uint8_t resp){ // do the tracing for the previous reader request and this tag answer: uint8_t par[1] = {0x00}; GetParity(&resp, 1, par); - EmLogTrace(Uart.output, - Uart.len, - Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, - Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, + EmLogTrace(Uart.output, + Uart.len, + Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, + Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, - &resp, - 1, + &resp, + 1, LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG, - (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG, + (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG, par); return res; } @@ -1709,15 +1709,15 @@ int EmSendCmdParEx(uint8_t *resp, uint16_t respLen, uint8_t *par, bool collision CodeIso14443aAsTagPar(resp, respLen, par, collision); int res = EmSendCmd14443aRaw(ToSend, ToSendMax); // do the tracing for the previous reader request and this tag answer: - EmLogTrace(Uart.output, - Uart.len, - Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, - Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, + EmLogTrace(Uart.output, + Uart.len, + Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, + Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, - resp, - respLen, + resp, + respLen, LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG, - (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG, + (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG, par); return res; } @@ -1741,10 +1741,10 @@ bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_Start uint16_t exact_fdt = (approx_fdt - 20 + 32)/64 * 64 + 20; reader_EndTime = tag_StartTime - exact_fdt; reader_StartTime = reader_EndTime - reader_modlen; - + if (!LogTrace(reader_data, reader_len, reader_StartTime, reader_EndTime, reader_Parity, true)) return false; - else + else return(!LogTrace(tag_data, tag_len, tag_StartTime, tag_EndTime, tag_Parity, false)); } @@ -1756,13 +1756,13 @@ bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_Start //----------------------------------------------------------------------------- static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receivedResponsePar, uint16_t offset) { uint32_t c = 0; - + // Set FPGA mode to "reader listen mode", no modulation (listen // only, since we are receiving, not transmitting). // Signal field is on with the appropriate LED LED_D_ON(); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN); - + // Now get the answer from the card DemodInit(receivedResponse, receivedResponsePar); @@ -1779,7 +1779,7 @@ static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receive NextTransferTime = MAX(NextTransferTime, Demod.endTime - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER)/16 + FRAME_DELAY_TIME_PICC_TO_PCD); return true; } else if (c++ > timeout && Demod.state == DEMOD_UNSYNCD) { - return false; + return false; } } } @@ -1791,7 +1791,7 @@ void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t // Send command to tag TransmitFor14443a(ToSend, ToSendMax, timing); if(trigger) LED_A_ON(); - + LogTrace(frame, nbytes(bits), (LastTimeProxToAirStart<<4) + DELAY_ARM2AIR_AS_READER, ((LastTimeProxToAirStart + LastProxToAirDuration)<<4) + DELAY_ARM2AIR_AS_READER, par, true); } @@ -1802,7 +1802,7 @@ void ReaderTransmitPar(uint8_t* frame, uint16_t len, uint8_t *par, uint32_t *tim void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect uint8_t par[MAX_PARITY_SIZE] = {0x00}; - GetParity(frame, len/8, par); + GetParity(frame, len/8, par); ReaderTransmitBitsPar(frame, len, par, timing); } @@ -1828,30 +1828,30 @@ int ReaderReceive(uint8_t *receivedAnswer, uint8_t *parity) { } // This function misstreats the ISO 14443a anticollision procedure. -// by fooling the reader there is a collision and forceing the reader to +// by fooling the reader there is a collision and forceing the reader to // increase the uid bytes. The might be an overflow, DoS will occure. void iso14443a_antifuzz(uint32_t flags){ - + // We need to listen to the high-frequency, peak-detected path. iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); BigBuf_free_keep_EM(); clear_trace(); set_tracing(true); - + int len = 0; - + // allocate buffers: uint8_t *received = BigBuf_malloc(MAX_FRAME_SIZE); uint8_t *receivedPar = BigBuf_malloc(MAX_PARITY_SIZE); uint8_t *resp = BigBuf_malloc(20); memset(resp, 0xFF , 20); - + LED_A_ON(); - for (;;) { + for (;;) { WDT_HIT(); - + // Clean receive command buffer if (!GetIso14443aCommandFromReader(received, receivedPar, &len)) { Dbprintf("Anti-fuzz stopped. Trace length: %d ", BigBuf_get_traceLen()); @@ -1860,15 +1860,15 @@ void iso14443a_antifuzz(uint32_t flags){ if ( received[0] == ISO14443A_CMD_WUPA || received[0] == ISO14443A_CMD_REQA) { resp[0] = 0x04; resp[1] = 0x00; - + if ( (flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA ) { resp[0] = 0x44; } - + EmSendCmd(resp, 2); continue; } - + // Received request for UID (cascade 1) //if (received[1] >= 0x20 && received[1] <= 0x57 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { if (received[1] >= 0x20 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { @@ -1878,23 +1878,23 @@ void iso14443a_antifuzz(uint32_t flags){ resp[3] = 0xFF; resp[4] = resp[0] ^ resp[1] ^ resp[2] ^ resp[3]; colpos = 0; - + if ( (flags & FLAG_7B_UID_IN_DATA) == FLAG_7B_UID_IN_DATA ) { - resp[0] = 0x88; + resp[0] = 0x88; colpos = 8; } - + EmSendCmdEx(resp, 5, true); if (MF_DBGLEVEL >= 4) Dbprintf("ANTICOLL or SELECT %x", received[1]); LED_D_INV(); - + continue; } else if (received[1] == 0x20 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received request for UID (cascade 2) if (MF_DBGLEVEL >= 4) Dbprintf("ANTICOLL or SELECT_2"); - } else if (received[1] == 0x70 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received a SELECT (cascade 1) - } else if (received[1] == 0x70 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received a SELECT (cascade 2) + } else if (received[1] == 0x70 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received a SELECT (cascade 1) + } else if (received[1] == 0x70 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received a SELECT (cascade 2) } else { - Dbprintf("unknown command %x", received[0]); + Dbprintf("unknown command %x", received[0]); } } @@ -1906,9 +1906,9 @@ void iso14443a_antifuzz(uint32_t flags){ static void iso14a_set_ATS_times(uint8_t *ats) { uint8_t tb1; - uint8_t fwi, sfgi; + uint8_t fwi, sfgi; uint32_t fwt, sfgt; - + 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) @@ -1937,10 +1937,10 @@ static int GetATQA(uint8_t *resp, uint8_t *resp_par) { uint32_t save_iso14a_timeout = iso14a_get_timeout(); iso14a_set_timeout(1236/(16*8)+1); // response to WUPA is expected at exactly 1236/fc. No need to wait longer. - + uint32_t start_time = GetTickCount(); int len; - + // we may need several tries if we did send an unknown command or a wrong authentication before... do { // Broadcast for a card, WUPA (0x52) will force response from all cards in the field @@ -1948,7 +1948,7 @@ static int GetATQA(uint8_t *resp, uint8_t *resp_par) { // Receive the ATQA len = ReaderReceive(resp, resp_par); } while (len == 0 && GetTickCount() <= start_time + WUPA_RETRY_TIMEOUT); - + iso14a_set_timeout(save_iso14a_timeout); return len; } @@ -1956,11 +1956,11 @@ static int GetATQA(uint8_t *resp, uint8_t *resp_par) { // performs iso14443a anticollision (optional) and card select procedure // fills the uid and cuid pointer unless NULL // fills the card info record unless NULL -// if anticollision is false, then the UID must be provided in uid_ptr[] +// if anticollision is false, then the UID must be provided in uid_ptr[] // and num_cascades must be set (1: 4 Byte UID, 2: 7 Byte UID, 3: 10 Byte UID) // requests ATS unless no_rats is true int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades, bool no_rats) { - + uint8_t sel_all[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT,0x20 }; uint8_t sel_uid[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t rats[] = { ISO14443A_CMD_RATS,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0 @@ -1978,14 +1978,14 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ memset(p_card->uid, 0, 10); p_card->ats_len = 0; } - + if (!GetATQA(resp, resp_par)) { return 0; } if (p_card) { p_card->atqa[0] = resp[0]; - p_card->atqa[1] = resp[1]; + p_card->atqa[1] = resp[1]; } if (anticollision) { @@ -1993,10 +1993,10 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ if (uid_ptr) memset(uid_ptr, 0, 10); } - + // check for proprietary anticollision: 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 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK. @@ -2040,7 +2040,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ } 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; @@ -2064,7 +2064,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ // Receive the SAK if (!ReaderReceive(resp, resp_par)) return 0; - + sak = resp[0]; // Test if more parts of the uid are coming @@ -2073,7 +2073,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ // http://www.nxp.com/documents/application_note/AN10927.pdf uid_resp[0] = uid_resp[1]; uid_resp[1] = uid_resp[2]; - uid_resp[2] = uid_resp[3]; + uid_resp[2] = uid_resp[3]; uid_resp_len = 3; } @@ -2091,7 +2091,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ } // PICC compilant with iso14443a-4 ---> (SAK & 0x20 != 0) - if( (sak & 0x20) == 0) return 2; + if( (sak & 0x20) == 0) return 2; // RATS, Request for answer to select if ( !no_rats ) { @@ -2099,7 +2099,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ AddCrc14A(rats, 2); ReaderTransmit(rats, sizeof(rats), NULL); len = ReaderReceive(resp, resp_par); - + if (!len) return 0; if (p_card) { @@ -2113,7 +2113,7 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_card, uint32_ // set default timeout and delay next transfer based on ATS iso14a_set_ATS_times(resp); } - return 1; + return 1; } int iso14443a_fast_select_card(uint8_t *uid_ptr, uint8_t num_cascades) { @@ -2129,14 +2129,14 @@ int iso14443a_fast_select_card(uint8_t *uid_ptr, uint8_t num_cascades) { if (!GetATQA(resp, resp_par)) { return 0; } - + // 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 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK. for(; sak & 0x04; cascade_level++) { // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97) sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2; - + if (cascade_level < num_cascades - 1) { uid_resp[0] = 0x88; memcpy(uid_resp+1, uid_ptr+cascade_level*3, 3); @@ -2153,7 +2153,7 @@ int iso14443a_fast_select_card(uint8_t *uid_ptr, uint8_t num_cascades) { // Receive the SAK if (!ReaderReceive(resp, resp_par)) return 0; - + sak = resp[0]; // Test if more parts of the uid are coming @@ -2162,10 +2162,10 @@ int iso14443a_fast_select_card(uint8_t *uid_ptr, uint8_t num_cascades) { // http://www.nxp.com/documents/application_note/AN10927.pdf uid_resp[0] = uid_resp[1]; uid_resp[1] = uid_resp[2]; - uid_resp[2] = uid_resp[3]; + uid_resp[2] = uid_resp[3]; } } - return 1; + return 1; } void iso14443a_setup(uint8_t fpga_minor_mode) { @@ -2184,15 +2184,15 @@ void iso14443a_setup(uint8_t fpga_minor_mode) { FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | fpga_minor_mode); SpinDelay(100); - + // Start the timer StartCountSspClk(); - + // Prepare the demodulation functions DemodReset(); UartReset(); NextTransferTime = 2 * DELAY_ARM2AIR_AS_READER; - iso14a_set_timeout(1060); // 106 * 10ms default + iso14a_set_timeout(1060); // 106 * 10ms default } /* Peter Fillmore 2015 @@ -2215,17 +2215,17 @@ b8 b7 b6 b5 b4 b3 b2 b1 b5 = ACK/NACK Coding of S-block: b8 b7 b6 b5 b4 b3 b2 b1 -1 1 x x x 0 1 0 +1 1 x x x 0 1 0 b5,b6 = 00 - DESELECT - 11 - WTX -*/ + 11 - WTX +*/ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, uint8_t *res) { uint8_t parity[MAX_PARITY_SIZE] = {0x00}; uint8_t real_cmd[cmd_len + 4]; - + if (cmd_len) { // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02 - real_cmd[0] = 0x02; // bnr,nad,cid,chn=0; i-block(0x00) + real_cmd[0] = 0x02; // bnr,nad,cid,chn=0; i-block(0x00) if (send_chaining) { real_cmd[0] |= 0x10; } @@ -2234,11 +2234,11 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u memcpy(real_cmd + 1, cmd, cmd_len); } else { // R-block. ACK - real_cmd[0] = 0xA2; // r-block + ACK + real_cmd[0] = 0xA2; // r-block + ACK real_cmd[0] |= iso14_pcb_blocknum; } AddCrc14A(real_cmd, cmd_len + 1); - + ReaderTransmit(real_cmd, cmd_len + 3, NULL); size_t len = ReaderReceive(data, parity); @@ -2247,19 +2247,19 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u if (!len) { return 0; //DATA LINK ERROR } else{ - // S-Block WTX + // S-Block WTX while(len && ((data_bytes[0] & 0xF2) == 0xF2)) { uint32_t save_iso14a_timeout = iso14a_get_timeout(); // temporarily increase timeout iso14a_set_timeout( MAX((data_bytes[1] & 0x3f) * save_iso14a_timeout, MAX_ISO14A_TIMEOUT) ); - // Transmit WTX back + // Transmit WTX back // byte1 - WTXM [1..59]. command FWT=FWT*WTXM data_bytes[1] = data_bytes[1] & 0x3f; // 2 high bits mandatory set to 0b // now need to fix CRC. AddCrc14A(data_bytes, len - 2); // transmit S-Block ReaderTransmit(data_bytes, len, NULL); - // retrieve the result again (with increased timeout) + // retrieve the result again (with increased timeout) len = ReaderReceive(data, parity); data_bytes = data; // restore timeout @@ -2275,7 +2275,7 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u { iso14_pcb_blocknum ^= 1; } - + // if we received I-block with chaining we need to send ACK and receive another block of data if (res) *res = data_bytes[0]; @@ -2284,9 +2284,9 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u if (len >= 3 && !check_crc(CRC_14443_A, data_bytes, len)) { return -1; } - + } - + if (len) { // cut frame byte len -= 1; @@ -2294,7 +2294,7 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u for (int i = 0; i < len; i++) data_bytes[i] = data_bytes[i + 1]; } - + return len; } @@ -2304,8 +2304,8 @@ int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, bool send_chaining, void *data, u // arg0 iso_14a flags // arg1 high :: number of bits, if you want to send 7bits etc // low :: len of commandbytes -// arg2 timeout -// d.asBytes command bytes to send +// arg2 timeout +// d.asBytes command bytes to send void ReaderIso14443a(UsbCommand *c) { iso14a_command_t param = c->arg[0]; size_t len = c->arg[1] & 0xffff; @@ -2315,7 +2315,7 @@ void ReaderIso14443a(UsbCommand *c) { uint32_t arg0 = 0; uint8_t buf[USB_CMD_DATA_SIZE] = {0x00}; uint8_t par[MAX_PARITY_SIZE] = {0x00}; - + if ((param & ISO14A_CONNECT)) clear_trace(); @@ -2348,7 +2348,7 @@ void ReaderIso14443a(UsbCommand *c) { } if ((param & ISO14A_RAW)) { - + if ((param & ISO14A_APPEND_CRC)) { // Don't append crc on empty bytearray... if ( len > 0 ) { @@ -2361,7 +2361,7 @@ void ReaderIso14443a(UsbCommand *c) { if (lenbits) lenbits += 16; } } - + if (lenbits > 0) { // want to send a specific number of bits (e.g. short commands) if ((param & ISO14A_TOPAZMODE)) { int bits_to_send = lenbits; @@ -2397,7 +2397,7 @@ void ReaderIso14443a(UsbCommand *c) { if ((param & ISO14A_NO_DISCONNECT)) return; -OUT: +OUT: FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); set_tracing(false); LEDsoff(); @@ -2409,22 +2409,22 @@ OUT: int32_t dist_nt(uint32_t nt1, uint32_t nt2) { if (nt1 == nt2) return 0; - + uint32_t nttmp1 = nt1; uint32_t nttmp2 = nt2; for (uint16_t i = 1; i < 32768; i++) { nttmp1 = prng_successor(nttmp1, 1); if (nttmp1 == nt2) return i; - + nttmp2 = prng_successor(nttmp2, 1); if (nttmp2 == nt1) return -i; } - + return(-99999); // either nt1 or nt2 are invalid nonces } - + #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 @@ -2436,13 +2436,13 @@ int32_t dist_nt(uint32_t nt1, uint32_t nt2) { // (article by Nicolas T. Courtois, 2009) //----------------------------------------------------------------------------- void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { - + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - BigBuf_free(); BigBuf_Clear_ext(false); + BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(true); - + uint8_t mf_auth[] = { keytype, block, 0x00, 0x00 }; uint8_t mf_nr_ar[] = {0,0,0,0,0,0,0,0}; uint8_t uid[10] = {0,0,0,0,0,0,0,0,0,0}; @@ -2455,47 +2455,47 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { uint32_t nt = 0, previous_nt = 0, cuid = 0; uint32_t sync_time = GetCountSspClk() & 0xfffffff8; - + int32_t catch_up_cycles = 0; int32_t last_catch_up = 0; int32_t isOK = 0; - + uint16_t elapsed_prng_sequences = 1; uint16_t consecutive_resyncs = 0; uint16_t unexpected_random = 0; uint16_t sync_tries = 0; - bool have_uid = false; + bool have_uid = false; bool received_nack; uint8_t cascade_levels = 0; - + // static variables here, is re-used in the next call - static uint32_t nt_attacked = 0; + static uint32_t nt_attacked = 0; static int32_t sync_cycles = 0; static uint8_t par_low = 0; static uint8_t mf_nr_ar3 = 0; - + AddCrc14A(mf_auth, 2); - + if (first_try) { sync_cycles = PRNG_SEQUENCE_LENGTH; // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). nt_attacked = 0; mf_nr_ar3 = 0; par_low = 0; } else { - // we were unsuccessful on a previous call. + // 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(); uint16_t i; for (i = 0; true; ++i) { received_nack = false; - + WDT_HIT(); // Test if the action was cancelled @@ -2503,10 +2503,10 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { isOK = -1; break; } - + // this part is from Piwi's faster nonce collecting part in Hardnested. if (!have_uid) { // need a full select cycle to get the uid first - iso14a_card_select_t card_info; + iso14a_card_select_t card_info; if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card (ALL)"); continue; @@ -2517,7 +2517,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { case 10: cascade_levels = 3; break; default: break; } - have_uid = true; + have_uid = true; } else { // no need for anticollision. We can directly select the card if (!iso14443a_fast_select_card(uid, cascade_levels)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card (UID)"); @@ -2526,29 +2526,29 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { } elapsed_prng_sequences = 1; - - // Sending timeslot of ISO14443a frame + + // Sending timeslot of ISO14443a frame sync_time = (sync_time & 0xfffffff8 ) + sync_cycles + catch_up_cycles; catch_up_cycles = 0; #define SYNC_TIME_BUFFER 16 // if there is only SYNC_TIME_BUFFER left before next planned sync, wait for next PRNG cycle - + // if we missed the sync time already or are about to miss it, advance to the next nonce repeat while ( sync_time < GetCountSspClk() + SYNC_TIME_BUFFER) { ++elapsed_prng_sequences; sync_time = (sync_time & 0xfffffff8 ) + sync_cycles; - } + } // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked) ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time); - // Receive the (4 Byte) "random" TAG nonce + // Receive the (4 Byte) "random" TAG nonce if (!ReaderReceive(receivedAnswer, receivedAnswerPar)) continue; previous_nt = nt; nt = bytes_to_num(receivedAnswer, 4); - + // Transmit reader nonce with fake par ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL); @@ -2558,10 +2558,10 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { // we didn't calibrate our clock yet, // iceman: has to be calibrated every time. - if (previous_nt && !nt_attacked) { + if (previous_nt && !nt_attacked) { int nt_distance = dist_nt(previous_nt, nt); - + // if no distance between, then we are in sync. if (nt_distance == 0) { nt_attacked = nt; @@ -2569,20 +2569,20 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { if (nt_distance == -99999) { // invalid nonce received unexpected_random++; if (unexpected_random > MAX_UNEXPECTED_RANDOM) { - isOK = -3; // Card has an unpredictable PRNG. Give up + isOK = -3; // Card has an unpredictable PRNG. Give up break; - } else { + } else { continue; // continue trying... } } - + if (++sync_tries > MAX_SYNC_TRIES) { isOK = -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly break; } - + sync_cycles = (sync_cycles - nt_distance)/elapsed_prng_sequences; - + // no negative sync_cycles if (sync_cycles <= 0) sync_cycles += PRNG_SEQUENCE_LENGTH; @@ -2591,7 +2591,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { sync_cycles = PRNG_SEQUENCE_LENGTH; sync_time = GetCountSspClk() & 0xfffffff8; } - + if (MF_DBGLEVEL >= 4) 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); @@ -2602,30 +2602,30 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { LED_B_OFF(); 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? + } + // average? catch_up_cycles /= elapsed_prng_sequences; - + if (catch_up_cycles == last_catch_up) { consecutive_resyncs++; } else { last_catch_up = catch_up_cycles; consecutive_resyncs = 0; - } - + } + if (consecutive_resyncs < 3) { if (MF_DBGLEVEL >= 4) { Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, catch_up_cycles, consecutive_resyncs); } - } else { + } else { sync_cycles += catch_up_cycles; - - if (MF_DBGLEVEL >= 4) + + if (MF_DBGLEVEL >= 4) 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; @@ -2634,11 +2634,11 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { } continue; } - + // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding if (received_nack) { catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer - + if (nt_diff == 0) par_low = par[0] & 0xE0; // there is no need to check all parities for other nt_diff. Parity Bits for mf_nr_ar[0..2] won't change @@ -2654,9 +2654,9 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { nt_diff = (nt_diff + 1) & 0x07; mf_nr_ar[3] = (mf_nr_ar[3] & 0x1F) | (nt_diff << 5); par[0] = par_low; - + } else { - // No NACK. + // No NACK. if (nt_diff == 0 && first_try) { par[0]++; if (par[0] == 0) { // tried all 256 possible parities without success. Card doesn't send NACK. @@ -2668,7 +2668,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { par[0] = ((par[0] & 0x1F) + 1) | par_low; } } - + // reset the resyncs since we got a complete transaction on right time. consecutive_resyncs = 0; } // end for loop @@ -2676,7 +2676,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { mf_nr_ar[3] &= 0x1F; if (MF_DBGLEVEL >= 4) Dbprintf("Number of sent auth requestes: %u", i); - + uint8_t buf[32] = {0x00}; memset(buf, 0x00, sizeof(buf)); num_to_bytes(cuid, 4, buf); @@ -2684,7 +2684,7 @@ void ReaderMifare(bool first_try, uint8_t block, uint8_t keytype ) { memcpy(buf + 8, par_list, 8); memcpy(buf + 16, ks_list, 8); memcpy(buf + 24, mf_nr_ar, 8); - + cmd_send(CMD_ACK, isOK, 0, 0, buf, sizeof(buf) ); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); @@ -2714,29 +2714,29 @@ void DetectNACKbug() { uint32_t sync_time = 0; bool have_uid = false; bool received_nack; - - // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). + + // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). uint32_t sync_cycles = PRNG_SEQUENCE_LENGTH; - BigBuf_free(); BigBuf_Clear_ext(false); + BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); - set_tracing(true); + set_tracing(true); iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - sync_time = GetCountSspClk() & 0xfffffff8; - - LED_C_ON(); + sync_time = GetCountSspClk() & 0xfffffff8; + + LED_C_ON(); uint16_t i; for (i = 1; true; ++i) { received_nack = false; - + // Cards always leaks a NACK, no matter the parity if ((i==10) && (num_nacks == i-1)) { isOK = 2; break; } - + WDT_HIT(); // Test if the action was cancelled @@ -2744,10 +2744,10 @@ void DetectNACKbug() { isOK = 99; break; } - + // this part is from Piwi's faster nonce collecting part in Hardnested. if (!have_uid) { // need a full select cycle to get the uid first - iso14a_card_select_t card_info; + iso14a_card_select_t card_info; if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card (ALL)"); continue; @@ -2758,7 +2758,7 @@ void DetectNACKbug() { case 10: cascade_levels = 3; break; default: break; } - have_uid = true; + have_uid = true; } else { // no need for anticollision. We can directly select the card if (!iso14443a_fast_select_card(uid, cascade_levels)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card (UID)"); @@ -2767,16 +2767,16 @@ void DetectNACKbug() { } elapsed_prng_sequences = 1; - - // Sending timeslot of ISO14443a frame + + // Sending timeslot of ISO14443a frame 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 while ( GetCountSspClk() > sync_time) { ++elapsed_prng_sequences; sync_time = (sync_time & 0xfffffff8 ) + sync_cycles; - } + } // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked) ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time); @@ -2784,13 +2784,13 @@ void DetectNACKbug() { // Receive the (4 Byte) "random" TAG nonce if (!ReaderReceive(receivedAnswer, receivedAnswerPar)) continue; - + previous_nt = nt; nt = bytes_to_num(receivedAnswer, 4); - + // Transmit reader nonce with fake par ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL); - + if (ReaderReceive(receivedAnswer, receivedAnswerPar)) { received_nack = true; num_nacks++; @@ -2798,14 +2798,14 @@ void DetectNACKbug() { if ( i == num_nacks ) { continue; } - } + } // we didn't calibrate our clock yet, // iceman: has to be calibrated every time. - if (previous_nt && !nt_attacked) { + if (previous_nt && !nt_attacked) { int nt_distance = dist_nt(previous_nt, nt); - + // if no distance between, then we are in sync. if (nt_distance == 0) { nt_attacked = nt; @@ -2813,32 +2813,32 @@ void DetectNACKbug() { if (nt_distance == -99999) { // invalid nonce received unexpected_random++; if (unexpected_random > MAX_UNEXPECTED_RANDOM ) { - // Card has an unpredictable PRNG. Give up + // Card has an unpredictable PRNG. Give up isOK = 98; break; - } else { + } else { if (sync_cycles <= 0) { sync_cycles += PRNG_SEQUENCE_LENGTH; } continue; } } - + if (++sync_tries > MAX_SYNC_TRIES) { isOK = 97; // Card's PRNG runs at an unexpected frequency or resets unexpectedly break; } - + sync_cycles = (sync_cycles - nt_distance)/elapsed_prng_sequences; - + if (sync_cycles <= 0) sync_cycles += PRNG_SEQUENCE_LENGTH; - + if (sync_cycles > PRNG_SEQUENCE_LENGTH * 2 ) { isOK = 96; // Card's PRNG runs at an unexpected frequency or resets unexpectedly break; } - + if (MF_DBGLEVEL >= 4) 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); @@ -2846,32 +2846,32 @@ void DetectNACKbug() { } } - if ( (nt != nt_attacked) && nt_attacked) { - // we somehow lost sync. Try to catch up again... + if ( (nt != nt_attacked) && nt_attacked) { + // we somehow lost sync. Try to catch up again... catch_up_cycles = -dist_nt(nt_attacked, nt); - + if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one. catch_up_cycles = 0; continue; - } - // average? + } + // average? catch_up_cycles /= elapsed_prng_sequences; - + if (catch_up_cycles == last_catch_up) { consecutive_resyncs++; } else { last_catch_up = catch_up_cycles; consecutive_resyncs = 0; - } - + } + if (consecutive_resyncs < 3) { if (MF_DBGLEVEL >= 4) { Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, catch_up_cycles, consecutive_resyncs); } - } else { + } else { sync_cycles += catch_up_cycles; - + if (MF_DBGLEVEL >= 4) { 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); Dbprintf("nt [%08x] attacted [%08x]", nt, nt_attacked ); @@ -2882,14 +2882,14 @@ void DetectNACKbug() { } continue; } - + // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding if (received_nack) - catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer + catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer - // we are testing all 256 possibilities. + // we are testing all 256 possibilities. par[0]++; - + // tried all 256 possible parities without success. if (par[0] == 0) { if ( num_nacks == 1 ) @@ -2924,7 +2924,7 @@ void DetectNACKbug() { * (unless reader attack mode enabled then it runs util it gets enough nonces to recover all keys attmpted) */ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *datain) { - + int cardSTATE = MFEMUL_NOFIELD; int _UID_LEN = 0; // 4, 7, 10 int vHf = 0; // in mV @@ -2947,25 +2947,25 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE] = {0x00}; uint8_t response[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t response_par[MAX_MIFARE_PARITY_SIZE] = {0x00}; - + uint8_t atqa[] = {0x04, 0x00}; // Mifare classic 1k uint8_t sak_4[] = {0x0C, 0x00, 0x00}; // CL1 - 4b uid uint8_t sak_7[] = {0x0C, 0x00, 0x00}; // CL2 - 7b uid uint8_t sak_10[] = {0x0C, 0x00, 0x00}; // CL3 - 10b uid - // uint8_t sak[] = {0x09, 0x3f, 0xcc }; // Mifare Mini - - uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; - uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; + // uint8_t sak[] = {0x09, 0x3f, 0xcc }; // Mifare Mini + + uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; + uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; uint8_t rUIDBCC3[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // TAG Nonce - Authenticate response uint8_t rAUTH_NT[4]; uint32_t nonce = prng_successor( GetTickCount(), 32 ); num_to_bytes(nonce, 4, rAUTH_NT); - + // uint8_t rAUTH_NT[] = {0x55, 0x41, 0x49, 0x92};// nonce from nested? why this? uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00}; - + // Here, we collect CUID, NT, NR, AR, CUID2, NT2, NR2, AR2 // This can be used in a reader-only attack. nonces_t ar_nr_nonces[ATTACK_KEY_COUNT]; @@ -2976,7 +2976,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * // Length: 4,7,or 10 bytes if ( (flags & FLAG_UID_IN_EMUL) == FLAG_UID_IN_EMUL) emlGetMemBt(datain, 0, 10); // load 10bytes from EMUL to the datain pointer. to be used below. - + if ( (flags & FLAG_4B_UID_IN_DATA) == FLAG_4B_UID_IN_DATA) { memcpy(rUIDBCC1, datain, 4); _UID_LEN = 4; @@ -2993,13 +2993,13 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * switch (_UID_LEN) { case 4: - sak_4[0] &= 0xFB; + sak_4[0] &= 0xFB; // save CUID cuid = bytes_to_num(rUIDBCC1, 4); // BCC rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; if (MF_DBGLEVEL >= 2) { - Dbprintf("4B UID: %02x%02x%02x%02x", + Dbprintf("4B UID: %02x%02x%02x%02x", rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], @@ -3009,14 +3009,14 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * break; case 7: atqa[0] |= 0x40; - sak_7[0] &= 0xFB; + sak_7[0] &= 0xFB; // save CUID - cuid = bytes_to_num(rUIDBCC2, 4); + cuid = bytes_to_num(rUIDBCC2, 4); // CascadeTag, CT rUIDBCC1[0] = 0x88; // BCC - rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; - rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; + rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; + rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; if (MF_DBGLEVEL >= 2) { Dbprintf("7B UID: %02x %02x %02x %02x %02x %02x %02x", rUIDBCC1[1], @@ -3031,7 +3031,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * break; case 10: atqa[0] |= 0x80; - sak_10[0] &= 0xFB; + sak_10[0] &= 0xFB; // save CUID cuid = bytes_to_num(rUIDBCC3, 4); // CascadeTag, CT @@ -3057,14 +3057,14 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * ); } break; - default: + default: break; } // calc some crcs compute_crc(CRC_14443_A, sak_4, 1, &sak_4[1], &sak_4[2]); compute_crc(CRC_14443_A, sak_7, 1, &sak_7[1], &sak_7[2]); compute_crc(CRC_14443_A, sak_10, 1, &sak_10[1], &sak_10[2]); - + // We need to listen to the high-frequency, peak-detected path. iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); @@ -3080,13 +3080,13 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * // find reader field if (cardSTATE == MFEMUL_NOFIELD) { - + vHf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10; if (vHf > MF_MINFIELDV) { cardSTATE_TO_IDLE(); LED_A_ON(); } - } + } if (cardSTATE == MFEMUL_NOFIELD) continue; // Now, get data @@ -3098,7 +3098,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * } else if (res == 1) { break; // return value 1 means button press } - + // REQ or WUP request in ANY state and WUP in HALTED state // this if-statement doesn't match the specification above. (iceman) if (len == 1 && ((receivedCmd[0] == ISO14443A_CMD_REQA && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == ISO14443A_CMD_WUPA)) { @@ -3107,10 +3107,10 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * cardSTATE = MFEMUL_SELECT1; crypto1_destroy(pcs); cardAUTHKEY = 0xff; - nonce = prng_successor(selTimer, 32); + nonce = prng_successor(selTimer, 32); continue; } - + switch (cardSTATE) { case MFEMUL_NOFIELD: case MFEMUL_HALTED: @@ -3125,12 +3125,12 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * break; } // select card - if (len == 9 && + if (len == 9 && ( receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && - receivedCmd[1] == 0x70 && + receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) { - - // SAK 4b + + // SAK 4b EmSendCmd(sak_4, sizeof(sak_4)); switch(_UID_LEN){ case 4: @@ -3150,7 +3150,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * break; } case MFEMUL_SELECT2:{ - if (!len) { + if (!len) { LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); break; } @@ -3158,11 +3158,11 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2)); break; } - if (len == 9 && + if (len == 9 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2 && - receivedCmd[1] == 0x70 && + receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC2, 4) == 0) ) { - + EmSendCmd(sak_7, sizeof(sak_7)); switch(_UID_LEN){ case 7: @@ -3175,12 +3175,12 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * continue; default:break; } - } + } cardSTATE_TO_IDLE(); break; } case MFEMUL_SELECT3:{ - if (!len) { + if (!len) { LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); break; } @@ -3188,9 +3188,9 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * EmSendCmd(rUIDBCC3, sizeof(rUIDBCC3)); break; } - if (len == 9 && + if (len == 9 && (receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3 && - receivedCmd[1] == 0x70 && + receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC3, 4) == 0) ) { EmSendCmd(sak_10, sizeof(sak_10)); @@ -3214,12 +3214,12 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * // Collect AR/NR per keytype & sector if ( (flags & FLAG_NR_AR_ATTACK) == FLAG_NR_AR_ATTACK ) { - + int8_t index = -1; int8_t empty = -1; for (uint8_t i = 0; i < ATTACK_KEY_COUNT; i++) { // find which index to use - if ( (cardAUTHSC == ar_nr_nonces[i].sector) && (cardAUTHKEY == ar_nr_nonces[i].keytype)) + if ( (cardAUTHSC == ar_nr_nonces[i].sector) && (cardAUTHKEY == ar_nr_nonces[i].keytype)) index = i; // keep track of empty slots. @@ -3247,8 +3247,8 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * ar_nr_nonces[index].ar = ar; ar_nr_nonces[index].state = FIRST; break; - } - case FIRST : { + } + case FIRST : { // second nonce collect ar_nr_nonces[index].nonce2 = nonce; ar_nr_nonces[index].nr2 = nr; @@ -3257,7 +3257,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * // send to client cmd_send(CMD_ACK, CMD_SIMULATE_MIFARE_CARD, 0, 0, &ar_nr_nonces[index], sizeof(nonces_t)); - + ar_nr_nonces[index].state = EMPTY; ar_nr_nonces[index].sector = 0; ar_nr_nonces[index].keytype = 0; @@ -3269,10 +3269,10 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * crypto1_word(pcs, nr , 1); uint32_t cardRr = ar ^ crypto1_word(pcs, 0, 0); - + //test if auth OK if (cardRr != prng_successor(nonce, 64)){ - + if (MF_DBGLEVEL >= 3) { Dbprintf("AUTH FAILED for sector %d with key %c. [nr=%08x cardRr=%08x] [nt=%08x succ=%08x]" , cardAUTHSC @@ -3291,15 +3291,15 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); break; } - + ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0); num_to_bytes(ans, 4, rAUTH_AT); EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT)); LED_C_ON(); - + if (MF_DBGLEVEL >= 3) { - Dbprintf("AUTH COMPLETED for sector %d with key %c. time=%d", - cardAUTHSC, + Dbprintf("AUTH COMPLETED for sector %d with key %c. time=%d", + cardAUTHSC, cardAUTHKEY == 0 ? 'A' : 'B', GetTickCount() - authTimer ); @@ -3311,20 +3311,20 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * if (len == 0) { LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); break; - } + } bool encrypted_data = (cardAUTHKEY != 0xFF) ; if(encrypted_data) mf_crypto1_decrypt(pcs, receivedCmd, len); - - if (len == 4 && (receivedCmd[0] == MIFARE_AUTH_KEYA || + + if (len == 4 && (receivedCmd[0] == MIFARE_AUTH_KEYA || receivedCmd[0] == MIFARE_AUTH_KEYB) ) { authTimer = GetTickCount(); cardAUTHSC = receivedCmd[1] / 4; // received block -> sector cardAUTHKEY = receivedCmd[0] & 0x1; crypto1_destroy(pcs); - + // load key into crypto crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY)); @@ -3335,7 +3335,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * num_to_bytes(nonce, 4, rAUTH_AT); } else { // nested authentication - ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0); + ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0); num_to_bytes(ans, 4, rAUTH_AT); if (MF_DBGLEVEL >= 3) Dbprintf("Reader doing nested authentication for block %d (0x%02x) with key %c", receivedCmd[1], receivedCmd[1], cardAUTHKEY == 0 ? 'A' : 'B'); @@ -3345,20 +3345,20 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * cardSTATE = MFEMUL_AUTH1; break; } - + // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued // BUT... ACK --> NACK if (len == 1 && receivedCmd[0] == CARD_ACK) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); break; } - + // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK) if (len == 1 && receivedCmd[0] == CARD_NACK_NA) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK)); break; } - + if(len != 4) { LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); break; @@ -3370,7 +3370,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * receivedCmd[0] == MIFARE_CMD_DEC || receivedCmd[0] == MIFARE_CMD_RESTORE || receivedCmd[0] == MIFARE_CMD_TRANSFER ) { - + if (receivedCmd[1] >= 16 * 4) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking",receivedCmd[0],receivedCmd[1],receivedCmd[1]); @@ -3407,8 +3407,8 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * break; } // increment, decrement, restore - if ( receivedCmd[0] == MIFARE_CMD_INC || - receivedCmd[0] == MIFARE_CMD_DEC || + if ( receivedCmd[0] == MIFARE_CMD_INC || + receivedCmd[0] == MIFARE_CMD_DEC || receivedCmd[0] == MIFARE_CMD_RESTORE) { if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd[0], receivedCmd[1], receivedCmd[1]); @@ -3472,7 +3472,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); cardSTATE_TO_IDLE(); break; - } + } LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true); cardINTREG = cardINTREG + ans; cardSTATE = MFEMUL_WORK; @@ -3506,9 +3506,9 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * } } - if (MF_DBGLEVEL >= 1) + if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen()); - + cmd_send(CMD_ACK,1,0,0,0,0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); set_tracing(false); diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index a23b5d7c2..c5e1e62f1 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -16,7 +16,7 @@ #ifdef __cplusplus extern "C" { #endif - + #include "usb_cmd.h" #include "cmd.h" #include "apps.h" @@ -138,6 +138,6 @@ void DetectNACKbug(); #ifdef __cplusplus } -#endif +#endif #endif /* __ISO14443A_H */ diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 6167ca785..f093fb1a7 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -38,7 +38,7 @@ // 4sample #define SEND4STUFFBIT(x) ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x); //#define SEND4STUFFBIT(x) ToSendStuffBit(x); - // iceman, this threshold value, what makes 8 a good amplitude for this IQ values? + // iceman, this threshold value, what makes 8 a good amplitude for this IQ values? #ifndef SUBCARRIER_DETECT_THRESHOLD # define SUBCARRIER_DETECT_THRESHOLD 8 #endif @@ -130,29 +130,29 @@ static void DemodReset() { Demod.sumI = 0; Demod.sumQ = 0; Demod.startTime = 0; - Demod.endTime = 0; + Demod.endTime = 0; } static void DemodInit(uint8_t *data) { Demod.output = data; DemodReset(); - // memset(Demod.output, 0x00, MAX_FRAME_SIZE); + // memset(Demod.output, 0x00, MAX_FRAME_SIZE); } /* * 9.4395 us = 1 ETU and clock is about 1.5 us -* 13560000Hz +* 13560000Hz * 1000ms/s * timeout in ETUs (time to transfer 1 bit, 9.4395 us) * * Formula to calculate FWT (in ETUs) by timeout (in ms): -* fwt = 13560000 * 1000 / (8*16) * timeout; +* fwt = 13560000 * 1000 / (8*16) * timeout; * Sample: 3sec == 3000ms -* 13560000 * 1000 / (8*16) * 3000 == +* 13560000 * 1000 / (8*16) * 3000 == * 13560000000 / 384000 = 35312 FWT * @param timeout is in frame wait time, fwt, measured in ETUs -*/ +*/ static void iso14b_set_timeout(uint32_t timeout) { #define MAX_TIMEOUT 40542464 // 13560000Hz * 1000ms / (2^32-1) * (8*16) if(timeout > MAX_TIMEOUT) @@ -164,7 +164,7 @@ static void iso14b_set_timeout(uint32_t timeout) { static void iso14b_set_maxframesize(uint16_t size) { if (size > 256) size = MAX_FRAME_SIZE; - + Uart.byteCntMax = size; if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443B Max frame size set to %d bytes", Uart.byteCntMax); } @@ -186,7 +186,7 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1) * * Elementary Time Unit (ETU) is - * - 128 Carrier Cycles (9.4395 µS) = 8 Subcarrier Units + * - 128 Carrier Cycles (9.4395 µS) = 8 Subcarrier Units * - 1 ETU = 1 bit * - 10 ETU = 1 startbit, 8 databits, 1 stopbit (10bits length) * - startbit is a 0 @@ -194,19 +194,19 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { * * Start of frame (SOF) is * - [10-11] ETU of ZEROS, unmodulated time - * - [2-3] ETU of ONES, + * - [2-3] ETU of ONES, * * End of frame (EOF) is * - [10-11] ETU of ZEROS, unmodulated time * * -TO VERIFY THIS BELOW- * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag - * works like this: + * works like this: * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (1.18µS / pulse) == 9.44us * - A 0-bit input to the FPGA becomes an unmodulated time of 1.18µS or does it become 8 nonpulses for 9.44us * * FPGA doesn't seem to work with ETU. It seems to work with pulse / duration instead. - * + * * Card sends data ub 847.e kHz subcarrier * subcar |duration| FC division * -------+--------+------------ @@ -236,17 +236,17 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { * things practical for the ARM (fc/32, 423.8 kbits/s, ~50 kbytes/s) * */ - + int i,j; uint8_t b; - + ToSendReset(); // Transmit a burst of ones, as the initial thing that lets the - // reader get phase sync. + // reader get phase sync. // This loop is TR1, per specification // TR1 minimum must be > 80/fs - // TR1 maximum 200/fs + // TR1 maximum 200/fs // 80/fs < TR1 < 200/fs // 10 ETU < TR1 < 24 ETU @@ -254,14 +254,14 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { // 10-11 ETU * 4times samples ZEROS for(i = 0; i < 10; i++) { SEND4STUFFBIT(0); } //for(i = 0; i < 10; i++) { ToSendStuffBit(0); } - + // 2-3 ETU * 4times samples ONES for(i = 0; i < 3; i++) { SEND4STUFFBIT(1); } //for(i = 0; i < 3; i++) { ToSendStuffBit(1); } - + // data for(i = 0; i < len; ++i) { - + // Start bit SEND4STUFFBIT(0); //ToSendStuffBit(0); @@ -269,8 +269,8 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { // Data bits b = cmd[i]; for(j = 0; j < 8; ++j) { - // if(b & 1) { - // SEND4STUFFBIT(1); + // if(b & 1) { + // SEND4STUFFBIT(1); // //ToSendStuffBit(1); // } else { // SEND4STUFFBIT(0); @@ -283,7 +283,7 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { // Stop bit SEND4STUFFBIT(1); //ToSendStuffBit(1); - + // Extra Guard bit // For PICC it ranges 0-18us (1etu = 9us) SEND4STUFFBIT(1); @@ -294,11 +294,11 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) { // 10-11 ETU * 4 sample rate = ZEROS for(i = 0; i < 10; i++) { SEND4STUFFBIT(0); } //for(i = 0; i < 10; i++) { ToSendStuffBit(0); } - + // why this? for(i = 0; i < 40; i++) { SEND4STUFFBIT(1); } //for(i = 0; i < 40; i++) { ToSendStuffBit(1); } - + // Convert from last byte pos to length ++ToSendMax; } @@ -407,7 +407,7 @@ static RAMFUNC int Handle14443bReaderUartBit(uint8_t bit) { Uart.state = STATE_UNSYNCD; if (Uart.byteCnt != 0) return true; - + } else { // this is an error LED_A_OFF(); @@ -439,18 +439,18 @@ static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) { // Signal field is off with the appropriate LED LED_D_OFF(); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION); - + StartCountSspClk(); - + volatile uint8_t b = 0; // clear receiving shift register and holding register // What does this loop do? Is it TR1? - // loop is a wait/delay ? + // loop is a wait/delay ? /* for(uint8_t c = 0; c < 10;) { - // keep tx buffer in a defined state anyway. + // keep tx buffer in a defined state anyway. if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = 0xFF; ++c; @@ -471,9 +471,9 @@ static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) { // Wait for byte be become available in rx holding register if ( AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY ) { - + b = (uint8_t) AT91C_BASE_SSC->SSC_RHR; - + for ( mask = 0x80; mask != 0; mask >>= 1) { if ( Handle14443bReaderUartBit(b & mask)) { *len = Uart.byteCnt; @@ -481,7 +481,7 @@ static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) { } } } - } + } return false; } @@ -497,20 +497,20 @@ void ClearFpgaShiftingRegisters(void){ while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) {}; b = AT91C_BASE_SSC->SSC_RHR; (void) b; - + // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line) for (uint8_t j = 0; j < 5; j++) { // allow timeout - better late than never while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) {}; if (AT91C_BASE_SSC->SSC_RHR) break; } - + // Clear TXRDY: //AT91C_BASE_SSC->SSC_THR = 0xFF; } void WaitForFpgaDelayQueueIsEmpty( uint16_t delay ){ // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again: - uint8_t fpga_queued_bits = delay >> 3; // twich /8 ?? >>3, + uint8_t fpga_queued_bits = delay >> 3; // twich /8 ?? >>3, for (uint8_t i = 0; i <= fpga_queued_bits/8 + 1; ) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = 0xFF; @@ -522,36 +522,36 @@ void WaitForFpgaDelayQueueIsEmpty( uint16_t delay ){ static void TransmitFor14443b_AsTag( uint8_t *response, uint16_t len) { volatile uint32_t b; - + // Signal field is off with the appropriate LED LED_D_OFF(); //uint16_t fpgasendQueueDelay = 0; - + // Modulate BPSK FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK); SpinDelay(40); - + ClearFpgaShiftingRegisters(); - + FpgaSetupSsc(); // Transmit the response. for(uint16_t i = 0; i < len;) { - + // Put byte into tx holding register as soon as it is ready if(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) { AT91C_BASE_SSC->SSC_THR = response[++i]; } - + // Prevent rx holding register from overflowing if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { b = AT91C_BASE_SSC->SSC_RHR;(void)b; - } + } } - + //WaitForFpgaDelayQueueIsEmpty(fpgasendQueueDelay); - AT91C_BASE_SSC->SSC_THR = 0xFF; -} + AT91C_BASE_SSC->SSC_THR = 0xFF; +} //----------------------------------------------------------------------------- // Main loop of simulated tag: receive commands from reader, decide what // response to send, and send it. @@ -564,7 +564,7 @@ void SimulateIso14443bTag(uint32_t pupi) { SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Set up the synchronous serial port FpgaSetupSsc(); - + // allocate command receive buffer BigBuf_free(); BigBuf_Clear_ext(false); @@ -577,8 +577,8 @@ void SimulateIso14443bTag(uint32_t pupi) { // uint32_t time_0 = 0; // uint32_t t2r_time = 0; // uint32_t r2t_time = 0; - uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - + uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); + // the only commands we understand is WUPB, AFI=0, Select All, N=1: // static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB // ... and REQB, AFI=0, Normal Request, N=1: @@ -589,9 +589,9 @@ void SimulateIso14443bTag(uint32_t pupi) { // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922, // supports only 106kBit/s in both directions, max frame size = 32Bytes, // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported: - uint8_t respATQB[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, + uint8_t respATQB[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 }; - + // response to HLTB and ATTRIB static const uint8_t respOK[] = {0x00, 0x78, 0xF0}; @@ -605,15 +605,15 @@ void SimulateIso14443bTag(uint32_t pupi) { CodeIso14443bAsTag(respATQB, sizeof(respATQB)); uint8_t *encodedATQB = BigBuf_malloc(ToSendMax); uint16_t encodedATQBLen = ToSendMax; - memcpy(encodedATQB, ToSend, ToSendMax); + memcpy(encodedATQB, ToSend, ToSendMax); + - // prepare "OK" tag answer (encoded): CodeIso14443bAsTag(respOK, sizeof(respOK)); uint8_t *encodedOK = BigBuf_malloc(ToSendMax); - uint16_t encodedOKLen = ToSendMax; - memcpy(encodedOK, ToSend, ToSendMax); - + uint16_t encodedOKLen = ToSendMax; + memcpy(encodedOK, ToSend, ToSendMax); + // Simulation loop while (!BUTTON_PRESS() && !usb_poll_validate_length()) { WDT_HIT(); @@ -622,10 +622,10 @@ void SimulateIso14443bTag(uint32_t pupi) { if (cardSTATE == SIM_NOFIELD) { vHf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10; if ( vHf > MF_MINFIELDV ) { - cardSTATE = SIM_IDLE; + cardSTATE = SIM_IDLE; LED_A_ON(); } - } + } if (cardSTATE == SIM_NOFIELD) continue; // Get reader command @@ -635,31 +635,31 @@ void SimulateIso14443bTag(uint32_t pupi) { } // ISO14443-B protocol states: - // REQ or WUP request in ANY state + // REQ or WUP request in ANY state // WUP in HALTED state if (len == 5 ) { if ( (receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8)== 0x8 && cardSTATE == SIM_HALTED) || receivedCmd[0] == ISO14443B_REQB ){ - LogTrace(receivedCmd, len, 0, 0, NULL, true); + LogTrace(receivedCmd, len, 0, 0, NULL, true); cardSTATE = SIM_SELECTING; } } - + /* * How should this flow go? * REQB or WUPB * send response ( waiting for Attrib) * ATTRIB - * send response ( waiting for commands 7816) + * send response ( waiting for commands 7816) * HALT send halt response ( waiting for wupb ) */ - + switch (cardSTATE) { //case SIM_NOFIELD: case SIM_HALTED: case SIM_IDLE: { - LogTrace(receivedCmd, len, 0, 0, NULL, true); + LogTrace(receivedCmd, len, 0, 0, NULL, true); break; } case SIM_SELECTING: { @@ -677,7 +677,7 @@ void SimulateIso14443bTag(uint32_t pupi) { case SIM_ACKNOWLEDGE: { TransmitFor14443b_AsTag( encodedOK, encodedOKLen ); LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false); - cardSTATE = SIM_IDLE; + cardSTATE = SIM_IDLE; break; } case SIM_WORK: { @@ -694,22 +694,22 @@ void SimulateIso14443bTag(uint32_t pupi) { // CRC Check if (len >= 3){ // if crc exists - + if (!check_crc(CRC_14443_B, receivedCmd, len)) DbpString("+++CRC fail"); else DbpString("CRC passes"); } - cardSTATE = SIM_IDLE; + cardSTATE = SIM_IDLE; } break; } default: break; } - + ++cmdsReceived; } - if (MF_DBGLEVEL >= 2) + if (MF_DBGLEVEL >= 2) Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen()); switch_off(); //simulate } @@ -794,9 +794,9 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { case DEMOD_UNSYNCD: CHECK_FOR_SUBCARRIER(); - + // subcarrier detected - + if (v > SUBCARRIER_DETECT_THRESHOLD) { Demod.state = DEMOD_PHASE_REF_TRAINING; Demod.sumI = ci; @@ -809,14 +809,14 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { if (Demod.posCount < 8) { CHECK_FOR_SUBCARRIER(); - + if (v > SUBCARRIER_DETECT_THRESHOLD) { // set the reference phase (will code a logic '1') by averaging over 32 1/fs. // note: synchronization time > 80 1/fs Demod.sumI += ci; Demod.sumQ += cq; Demod.posCount++; - } else { + } else { // subcarrier lost Demod.state = DEMOD_UNSYNCD; } @@ -826,9 +826,9 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { break; case DEMOD_AWAITING_FALLING_EDGE_OF_SOF: - + MAKE_SOFT_DECISION(); - + if (v < 0) { // logic '0' detected Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF; Demod.posCount = 0; // start of SOF sequence @@ -841,12 +841,12 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { case DEMOD_GOT_FALLING_EDGE_OF_SOF: Demod.posCount++; - + MAKE_SOFT_DECISION(); - + if (v > 0) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges - if (Demod.posCount < 9*2) { + if (Demod.posCount < 9*2) { Demod.state = DEMOD_UNSYNCD; } else { LED_C_ON(); // Got SOF @@ -856,7 +856,7 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { } } else { // low phase of SOF too long (> 12 etu) - if (Demod.posCount > 14*2) { + if (Demod.posCount > 14*2) { Demod.state = DEMOD_UNSYNCD; LED_C_OFF(); } @@ -865,9 +865,9 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { case DEMOD_AWAITING_START_BIT: Demod.posCount++; - + MAKE_SOFT_DECISION(); - + if (v > 0) { if (Demod.posCount > 6*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs Demod.state = DEMOD_UNSYNCD; @@ -883,10 +883,10 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { break; case DEMOD_RECEIVING_DATA: - + MAKE_SOFT_DECISION(); - if (Demod.posCount == 0) { + if (Demod.posCount == 0) { // first half of bit Demod.thisBit = v; Demod.posCount = 1; @@ -896,18 +896,18 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { Demod.shiftReg >>= 1; // OR in a logic '1' - if (Demod.thisBit > 0) + if (Demod.thisBit > 0) Demod.shiftReg |= 0x200; Demod.bitCount++; - + // 1 start 8 data 1 stop = 10 if (Demod.bitCount == 10) { - + uint16_t s = Demod.shiftReg; - + // stop bit == '1', start bit == '0' - if ((s & 0x200) && (s & 0x001) == 0 ) { + if ((s & 0x200) && (s & 0x001) == 0 ) { // left shift to drop the startbit uint8_t b = (s >> 1); Demod.output[Demod.len] = b; @@ -917,7 +917,7 @@ static RAMFUNC int Handle14443bTagSamplesDemod(int ci, int cq) { // this one is a bit hard, either its a correc byte or its unsynced. Demod.state = DEMOD_UNSYNCD; LED_C_OFF(); - + // This is EOF (start, stop and all data bits == '0' if (s == 0) return true; } @@ -946,17 +946,17 @@ static void GetTagSamplesFor14443bDemod() { uint32_t time_0 = 0, time_stop = 0; BigBuf_free(); - + // Set up the demodulator for tag -> reader responses. DemodInit(BigBuf_malloc(MAX_FRAME_SIZE)); - + // The DMA buffer, used to stream samples from the FPGA int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); int8_t *upTo = dmaBuf; - + // Setup and start DMA. if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE) ){ - if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting"); + if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting"); return; } @@ -965,7 +965,7 @@ static void GetTagSamplesFor14443bDemod() { // get current clock time_0 = GetCountSspClk(); - + // rx counter - dma counter? (how much?) & (mod) mask > 2. (since 2bytes at the time is read) while ( !finished ) { @@ -992,12 +992,12 @@ static void GetTagSamplesFor14443bDemod() { finished = (time_stop > iso14b_timeout || gotFrame); } - + FpgaDisableSscDma(); - - if ( upTo ) + + if ( upTo ) upTo = NULL; - + if ( Demod.len > 0 ) LogTrace(Demod.output, Demod.len, time_0, time_stop, NULL, false); } @@ -1006,28 +1006,28 @@ static void GetTagSamplesFor14443bDemod() { // Transmit the command (to the tag) that was placed in ToSend[]. //----------------------------------------------------------------------------- static void TransmitFor14443b_AsReader(void) { - int c; - + int c; + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); SpinDelay(60); - + // What does this loop do? Is it TR1? - // 0xFF = 8 bits of 1. 1 bit == 1Etu,.. + // 0xFF = 8 bits of 1. 1 bit == 1Etu,.. // loop 10 * 8 = 80 ETU of delay, with a non modulated signal. why? // 80*9 = 720us. for(c = 0; c < 50;) { - + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = 0xFF; c++; } } - + // Send frame loop for(c = 0; c < ToSendMax;) { - - // Put byte into tx holding register as soon as it is ready + + // Put byte into tx holding register as soon as it is ready if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = ToSend[c++]; } @@ -1056,25 +1056,25 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) { */ int i; uint8_t b; - + ToSendReset(); // Send SOF - // 10-11 ETUs of ZERO + // 10-11 ETUs of ZERO for(i = 0; i < 10; ++i) ToSendStuffBit(0); - + // 2-3 ETUs of ONE ToSendStuffBit(1); ToSendStuffBit(1); // ToSendStuffBit(1); - + // Sending cmd, LSB // from here we add BITS for(i = 0; i < len; ++i) { // Start bit ToSendStuffBit(0); // Data bits - b = cmd[i]; + b = cmd[i]; // if ( b & 1 ) ToSendStuffBit(1); else ToSendStuffBit(0); // if ( (b>>1) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); // if ( (b>>2) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); @@ -1082,17 +1082,17 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) { // if ( (b>>4) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); // if ( (b>>5) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); // if ( (b>>6) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); - // if ( (b>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); + // if ( (b>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0); + + ToSendStuffBit( b & 1); + ToSendStuffBit( (b>>1) & 1); + ToSendStuffBit( (b>>2) & 1); + ToSendStuffBit( (b>>3) & 1); + ToSendStuffBit( (b>>4) & 1); + ToSendStuffBit( (b>>5) & 1); + ToSendStuffBit( (b>>6) & 1); + ToSendStuffBit( (b>>7) & 1); - ToSendStuffBit( b & 1); - ToSendStuffBit( (b>>1) & 1); - ToSendStuffBit( (b>>2) & 1); - ToSendStuffBit( (b>>3) & 1); - ToSendStuffBit( (b>>4) & 1); - ToSendStuffBit( (b>>5) & 1); - ToSendStuffBit( (b>>6) & 1); - ToSendStuffBit( (b>>7) & 1); - // Stop bit ToSendStuffBit(1); // EGT extra guard time @@ -1101,17 +1101,17 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) { ToSendStuffBit(1); ToSendStuffBit(1); } - + // Send EOF // 10-11 ETUs of ZERO for(i = 0; i < 10; ++i) ToSendStuffBit(0); // Transition time. TR0 - guard time // 8ETUS minum? - // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF. + // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF. // I'm guessing this is for the FPGA to be able to send all bits before we switch to listening mode for(i = 0; i < 24 ; ++i) ToSendStuffBit(1); - + // TR1 - Synchronization time // Convert from last character reference to length ToSendMax++; @@ -1123,7 +1123,7 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) { static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) { uint32_t time_start = GetCountSspClk(); - + CodeIso14443bAsReader(cmd, len); TransmitFor14443b_AsReader(); @@ -1154,7 +1154,7 @@ uint8_t iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *r GetTagSamplesFor14443bDemod(); //no if(Demod.len < 3) return 0; - + // VALIDATE CRC if (!check_crc(CRC_14443_B, Demod.output, Demod.len)){ if (MF_DBGLEVEL > 3) Dbprintf("crc fail ICE"); @@ -1175,32 +1175,32 @@ uint8_t iso14443b_select_srx_card(iso14b_card_select_t *card ) { static const uint8_t init_srx[] = { ISO14443B_INITIATE, 0x00, 0x97, 0x5b }; // SELECT command (with space for CRC) uint8_t select_srx[] = { ISO14443B_SELECT, 0x00, 0x00, 0x00}; - + CodeAndTransmit14443bAsReader(init_srx, sizeof(init_srx)); GetTagSamplesFor14443bDemod(); //no if (Demod.len == 0) return 2; - // Randomly generated Chip ID + // Randomly generated Chip ID if (card) card->chipid = Demod.output[0]; - + select_srx[1] = Demod.output[0]; - + AddCrc14B(select_srx, 2); - + CodeAndTransmit14443bAsReader(select_srx, sizeof(select_srx)); GetTagSamplesFor14443bDemod(); //no - + if (Demod.len != 3) return 2; - + // Check the CRC of the answer: if (!check_crc(CRC_14443_B, Demod.output, Demod.len)) return 3; - + // Check response from the tag: should be the same UID as the command we just sent: - if (select_srx[1] != Demod.output[0]) + if (select_srx[1] != Demod.output[0]) return 1; // First get the tag's UID: @@ -1212,8 +1212,8 @@ uint8_t iso14443b_select_srx_card(iso14b_card_select_t *card ) { if (Demod.len != 10) return 2; - - // The check the CRC of the answer + + // The check the CRC of the answer if (!check_crc(CRC_14443_B, Demod.output, Demod.len)) return 3; @@ -1236,19 +1236,19 @@ uint8_t iso14443b_select_card(iso14b_card_select_t *card ) { static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // ATTRIB command (with space for CRC) uint8_t attrib[] = { ISO14443B_ATTRIB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00}; - + // first, wake up the tag CodeAndTransmit14443bAsReader(wupb, sizeof(wupb)); GetTagSamplesFor14443bDemod(); //select_card - + // ATQB too short? if (Demod.len < 14) return 2; - + // VALIDATE CRC if (!check_crc(CRC_14443_B, Demod.output, Demod.len)) return 3; - + if (card) { card->uidlen = 4; memcpy(card->uid, Demod.output+1, 4); @@ -1257,7 +1257,7 @@ uint8_t iso14443b_select_card(iso14b_card_select_t *card ) { // copy the PUPI to ATTRIB ( PUPI == UID ) memcpy(attrib + 1, Demod.output + 1, 4); - + // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3) attrib[7] = Demod.output[10] & 0x0F; AddCrc14B(attrib, 9); @@ -1273,8 +1273,8 @@ uint8_t iso14443b_select_card(iso14b_card_select_t *card ) { if (!check_crc(CRC_14443_B, Demod.output, Demod.len) ) return 3; - if (card) { - + if (card) { + // CID card->cid = Demod.output[0]; @@ -1287,8 +1287,8 @@ uint8_t iso14443b_select_card(iso14b_card_select_t *card ) { else if (maxFrame == 8) maxFrame = 256; else maxFrame = 257; iso14b_set_maxframesize(maxFrame); - - // FWT + + // FWT uint8_t fwt = card->atqb[6] >> 4; if ( fwt < 16 ){ uint32_t fwt_time = (302 << fwt); @@ -1305,7 +1305,7 @@ uint8_t iso14443b_select_card(iso14b_card_select_t *card ) { void iso14443b_setup() { LEDsoff(); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - + // Initialize Demod and Uart structs DemodInit(BigBuf_malloc(MAX_FRAME_SIZE)); UartInit(BigBuf_malloc(MAX_FRAME_SIZE)); @@ -1315,14 +1315,14 @@ void iso14443b_setup() { // Set up the synchronous serial port FpgaSetupSsc(); - + // Signal field is on with the appropriate LED FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); SpinDelay(100); // Start the timer StartCountSspClk(); - + LED_D_ON(); } @@ -1342,7 +1342,7 @@ static bool ReadSTBlock(uint8_t block) { GetTagSamplesFor14443bDemod(); // Check if we got an answer from the tag - if (Demod.len != 6) { + if (Demod.len != 6) { DbpString("[!] expected 6 bytes from tag, got less..."); return false; } @@ -1357,22 +1357,22 @@ void ReadSTMemoryIso14443b(uint8_t numofblocks) { // Make sure that we start from off, since the tags are stateful; // confusing things will happen if we don't reset them between reads. //switch_off(); - + uint8_t i = 0x00; uint8_t *buf = BigBuf_malloc(sizeof(iso14b_card_select_t)); iso14443b_setup(); - + iso14b_card_select_t *card = (iso14b_card_select_t*)buf; uint8_t res = iso14443b_select_srx_card(card); // 0: OK 2: attrib fail, 3:crc fail, if ( res > 0 ) goto out; - + Dbprintf("[+] Tag memory dump, block 0 to %d", numofblocks); ++numofblocks; - + for (;;) { if (i == numofblocks) { DbpString("System area block (0xFF):"); @@ -1383,11 +1383,11 @@ void ReadSTMemoryIso14443b(uint8_t numofblocks) { do { res = ReadSTBlock(i); } while (!res && --retries); - + if (!res && !retries) { goto out; } - + // Now print out the memory location: Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i, (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], @@ -1396,10 +1396,10 @@ void ReadSTMemoryIso14443b(uint8_t numofblocks) { if (i == 0xff) break; ++i; } - -out: + +out: switch_off(); // disconnect raw - SpinDelay(20); + SpinDelay(20); } static void iso1444b_setup_sniff(void){ @@ -1407,7 +1407,7 @@ static void iso1444b_setup_sniff(void){ LEDsoff(); FpgaDownloadAndGo(FPGA_BITSTREAM_HF); BigBuf_free(); - BigBuf_Clear_ext(false); + BigBuf_Clear_ext(false); clear_trace();//setup snoop set_tracing(true); @@ -1432,7 +1432,7 @@ static void iso1444b_setup_sniff(void){ // Set FPGA in the appropriate mode FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP); - SpinDelay(20); + SpinDelay(20); // Start the SSP timer StartCountSspClk(); @@ -1467,40 +1467,40 @@ void RAMFUNC SniffIso14443b(void) { bool ReaderIsActive = false; iso1444b_setup_sniff(); - + // The DMA buffer, used to stream samples from the FPGA int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); int8_t *data = dmaBuf; // Setup and start DMA. if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE) ){ - if (MF_DBGLEVEL > 1) Dbprintf("[!] FpgaSetupSscDma failed. Exiting"); + if (MF_DBGLEVEL > 1) Dbprintf("[!] FpgaSetupSscDma failed. Exiting"); BigBuf_free(); return; } - // time ZERO, the point from which it all is calculated. + // time ZERO, the point from which it all is calculated. time_0 = GetCountSspClk(); - + // loop and listen while (!BUTTON_PRESS()) { WDT_HIT(); ci = data[0]; cq = data[1]; - data += 2; - + data += 2; + if (data >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { data = dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; - AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; } // no need to try decoding reader data if the tag is sending - if (!TagIsActive) { - + if (!TagIsActive) { + LED_A_INV(); - + if (Handle14443bReaderUartBit(ci & 0x01)) { time_stop = GetCountSspClk() - time_0; LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, NULL, true); @@ -1509,8 +1509,8 @@ void RAMFUNC SniffIso14443b(void) { } else { time_start = GetCountSspClk() - time_0; } - - if (Handle14443bReaderUartBit(cq & 0x01)) { + + if (Handle14443bReaderUartBit(cq & 0x01)) { time_stop = GetCountSspClk() - time_0; LogTrace(Uart.output, Uart.byteCnt, time_start, time_stop, NULL, true); UartReset(); @@ -1520,30 +1520,30 @@ void RAMFUNC SniffIso14443b(void) { } ReaderIsActive = (Uart.state > STATE_GOT_FALLING_EDGE_OF_SOF); } - + // no need to try decoding tag data if the reader is sending - and we cannot afford the time if (!ReaderIsActive) { // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103 // LSB is a fpga signal bit. - if (Handle14443bTagSamplesDemod(ci, cq)) { - time_stop = GetCountSspClk() - time_0; + if (Handle14443bTagSamplesDemod(ci, cq)) { + time_stop = GetCountSspClk() - time_0; LogTrace(Demod.output, Demod.len, time_start, time_stop, NULL, false); - UartReset(); - DemodReset(); + UartReset(); + DemodReset(); } else { time_start = GetCountSspClk() - time_0; } TagIsActive = (Demod.state > DEMOD_GOT_FALLING_EDGE_OF_SOF); } } - + if (MF_DBGLEVEL >= 2) { DbpString("[+] Sniff statistics:"); Dbprintf("[+] uart State: %x ByteCount: %i ByteCountMax: %i", Uart.state, Uart.byteCnt, Uart.byteCntMax); Dbprintf("[+] trace length: %i", BigBuf_get_traceLen()); } - + switch_off(); } @@ -1571,54 +1571,54 @@ void SendRawCommand14443B_Ex(UsbCommand *c) { uint8_t buf[USB_CMD_DATA_SIZE] = {0x00}; if (MF_DBGLEVEL > 3) Dbprintf("14b raw: param, %04x", param ); - + // turn on trigger (LED_A) if ((param & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER) iso14b_set_trigger(true); - + if ((param & ISO14B_CONNECT) == ISO14B_CONNECT) { iso14443b_setup(); clear_trace(); } - + set_tracing(true); if ((param & ISO14B_SELECT_STD) == ISO14B_SELECT_STD) { iso14b_card_select_t *card = (iso14b_card_select_t*)buf; - status = iso14443b_select_card(card); + status = iso14443b_select_card(card); cmd_send(CMD_ACK, status, sendlen, 0, buf, sendlen); // 0: OK 2: attrib fail, 3:crc fail, if ( status > 0 ) goto out; - } - + } + if ((param & ISO14B_SELECT_SR) == ISO14B_SELECT_SR) { iso14b_card_select_t *card = (iso14b_card_select_t*)buf; status = iso14443b_select_srx_card(card); cmd_send(CMD_ACK, status, sendlen, 0, buf, sendlen); // 0: OK 2: demod fail, 3:crc fail, if ( status > 0 ) goto out; - } - + } + if ((param & ISO14B_APDU) == ISO14B_APDU) { status = iso14443b_apdu(cmd, len, buf); cmd_send(CMD_ACK, status, status, 0, buf, status); } - + if ((param & ISO14B_RAW) == ISO14B_RAW) { if((param & ISO14B_APPEND_CRC) == ISO14B_APPEND_CRC) { AddCrc14B(cmd, len); len += 2; } - - CodeAndTransmit14443bAsReader(cmd, len); // raw + + CodeAndTransmit14443bAsReader(cmd, len); // raw GetTagSamplesFor14443bDemod(); // raw - + sendlen = MIN(Demod.len, USB_CMD_DATA_SIZE); status = (Demod.len > 0) ? 0 : 1; cmd_send(CMD_ACK, status, sendlen, 0, Demod.output, sendlen); } - -out: + +out: // turn off trigger (LED_A) if ((param & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER) iso14b_set_trigger(false); @@ -1627,6 +1627,6 @@ out: // we don't send a HALT command. if ((param & ISO14B_DISCONNECT) == ISO14B_DISCONNECT) { switch_off(); // disconnect raw - SpinDelay(20); + SpinDelay(20); } } \ No newline at end of file diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index 285ac226d..61e0e1130 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -14,22 +14,22 @@ // Modified to perform modulation onboard in arm rather than on PC // Also added additional reader commands (SELECT, READ etc.) //----------------------------------------------------------------------------- -// The ISO 15693 describes two transmission modes from reader to tag, and 4 -// transmission modes from tag to reader. As of Mar 2010 this code only -// supports one of each: "1of4" mode from reader to tag, and the highspeed +// The ISO 15693 describes two transmission modes from reader to tag, and 4 +// transmission modes from tag to reader. As of Mar 2010 this code only +// supports one of each: "1of4" mode from reader to tag, and the highspeed // variant with one subcarrier from card to reader. -// As long, as the card fully support ISO 15693 this is no problem, since the -// reader chooses both data rates, but some non-standard tags do not. Further for +// As long, as the card fully support ISO 15693 this is no problem, since the +// reader chooses both data rates, but some non-standard tags do not. Further for // the simulation to work, we will need to support all data rates. // // VCD (reader) -> VICC (tag) // 1 out of 256: -// data rate: 1,66 kbit/s (fc/8192) +// data rate: 1,66 kbit/s (fc/8192) // used for long range // 1 out of 4: // data rate: 26,48 kbit/s (fc/512) // used for short range, high speed -// +// // VICC (tag) -> VCD (reader) // Modulation: // ASK / one subcarrier (423,75 khz) @@ -49,11 +49,11 @@ // TODO / BUGS / ISSUES: // *) writing to tags takes longer: we miss the answer from the tag in most cases // -> tweak the read-timeout times -// *) signal decoding from the card is still a bit shaky. +// *) signal decoding from the card is still a bit shaky. // *) signal decoding is unable to detect collissions. -// *) add anti-collission support for inventory-commands +// *) add anti-collission support for inventory-commands // *) read security status of a block -// *) sniffing and simulation do only support one transmission mode. need to support +// *) sniffing and simulation do only support one transmission mode. need to support // all 8 transmission combinations // *) remove or refactor code under "depricated" // *) document all the functions @@ -70,7 +70,7 @@ // This section basicly contains transmission and receiving of bits /////////////////////////////////////////////////////////////////////// -// 32 + 2 crc + 1 +// 32 + 2 crc + 1 #define ISO15_MAX_FRAME 35 #define CMD_ID_RESP 5 #define CMD_READ_RESP 13 @@ -92,7 +92,7 @@ static void BuildIdentifyRequest(uint8_t *cmdout); static void BuildInventoryResponse(uint8_t *cmdout, uint8_t *uid); // --------------------------- -// Signal Processing +// Signal Processing // --------------------------- // prepare data using "1 out of 4" code for later transmission @@ -176,7 +176,7 @@ static void CodeIso15693AsReader(uint8_t *cmd, int n) { } // encode data using "1 out of 256" sheme -// data rate is 1,66 kbit/s (fc/8192) +// data rate is 1,66 kbit/s (fc/8192) // is designed for more robust communication over longer distances static void CodeIso15693AsReader256(uint8_t *cmd, int n) { int i, j; @@ -196,7 +196,7 @@ static void CodeIso15693AsReader256(uint8_t *cmd, int n) { ToSendStuffBit(1); ToSendStuffBit(1); ToSendStuffBit(0); - + for(i = 0; i < n; i++) { for (j = 0; j <= 255; j++) { if (cmd[i] == j) { @@ -205,8 +205,8 @@ static void CodeIso15693AsReader256(uint8_t *cmd, int n) { } else { ToSendStuffBit(1); ToSendStuffBit(1); - } - } + } + } } // EOF ToSendStuffBit(1); @@ -236,19 +236,19 @@ static void TransmitTo15693Tag(const uint8_t *cmd, int len, int *samples, int *w } c = 0; - for(;;) { + for(;;) { if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = cmd[c]; if( ++c >= len) break; } - WDT_HIT(); + WDT_HIT(); } - + if (samples) { if (wait) *samples = (c + *wait) << 3; else - *samples = c << 3; + *samples = c << 3; } } @@ -258,7 +258,7 @@ static void TransmitTo15693Tag(const uint8_t *cmd, int len, int *samples, int *w static void TransmitTo15693Reader(const uint8_t *cmd, int len, int *samples, int *wait) { int c = 0; FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K); - + if (wait) { for (c = 0; c < *wait;) { if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { @@ -269,19 +269,19 @@ static void TransmitTo15693Reader(const uint8_t *cmd, int len, int *samples, int } } - c = 0; + c = 0; for(;;) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = cmd[c]; if( ++c >= len) break; } - WDT_HIT(); + WDT_HIT(); } if (samples) { if (wait) *samples = (c + *wait) << 3; else - *samples = c << 3; + *samples = c << 3; } } @@ -289,7 +289,7 @@ static void TransmitTo15693Reader(const uint8_t *cmd, int len, int *samples, int // DEMODULATE tag answer //----------------------------------------------------------------------------- static int DemodAnswer(uint8_t *received, uint8_t *dest, uint16_t samplecount) { - + int i, j; int max = 0, maxPos = 0, skip = 4; int k = 0; // this will be our return value @@ -308,9 +308,9 @@ static int DemodAnswer(uint8_t *received, uint8_t *dest, uint16_t samplecount) { // DbpString("SOF at %d, correlation %d", maxPos,max/(ARRAYLEN(FrameSOF)/skip)); // greg - If correlation is less than 1 then there's little point in continuing - if ((max / (ARRAYLEN(FrameSOF)/skip) ) < 1) + if ((max / (ARRAYLEN(FrameSOF)/skip) ) < 1) return k; - + i = maxPos + ARRAYLEN(FrameSOF) / skip; uint8_t outBuf[ISO15_MAX_FRAME]; @@ -335,31 +335,31 @@ static int DemodAnswer(uint8_t *received, uint8_t *dest, uint16_t samplecount) { if (corrEOF > corr1 && corrEOF > corr0) break; - + if (corr1 > corr0) { i += ARRAYLEN(Logic1) / skip; outBuf[k] |= mask; } else { i += ARRAYLEN(Logic0) / skip; } - + mask <<= 1; - + if (mask == 0) { k++; mask = 0x01; } - + if ( ( i + (int)ARRAYLEN(FrameEOF)) >= samplecount-1) { //Dbprintf("[!] ran off end! %d | %d",( i + (int)ARRAYLEN(FrameEOF)), samplecount-1); break; } } - + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("ice: demod bytes %u", k); - + if (mask != 0x01) { // this happens, when we miss the EOF - + // TODO: for some reason this happens quite often if (MF_DBGLEVEL >= MF_DBG_ERROR && k != 0) Dbprintf("[!] error, uneven octet! (extra bits!) mask %02x", mask); //if (mask < 0x08) k--; // discard the last uneven octet; @@ -378,7 +378,7 @@ static int DemodAnswer(uint8_t *received, uint8_t *dest, uint16_t samplecount) { // received // samples // elapsed -// returns: +// returns: // number of decoded bytes // logging enabled static int GetIso15693AnswerFromTag(uint8_t *received, int *elapsed) { @@ -392,7 +392,7 @@ static int GetIso15693AnswerFromTag(uint8_t *received, int *elapsed) { uint8_t *buf = BigBuf_malloc(SIGNAL_BUFF_SIZE); if (elapsed) *elapsed = 0; - + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); for(;;) { @@ -414,9 +414,9 @@ static int GetIso15693AnswerFromTag(uint8_t *received, int *elapsed) { // close to what we want. // iceman 2016, amplitude sqrt(abs(i) + abs(q)) if (getNext) { - + buf[counter++] = (uint8_t)(MAX(ci,cq) + (MIN(ci, cq) >> 1)); - + if (counter >= SIGNAL_BUFF_SIZE) break; } else { @@ -424,11 +424,11 @@ static int GetIso15693AnswerFromTag(uint8_t *received, int *elapsed) { } getNext = !getNext; } - } - time_stop = GetCountSspClk() - time_0 ; - int len = DemodAnswer(received, buf, counter); + } + time_stop = GetCountSspClk() - time_0 ; + int len = DemodAnswer(received, buf, counter); LogTrace(received, len, time_0 << 4, time_stop << 4, NULL, false); - BigBuf_free(); + BigBuf_free(); return len; } @@ -444,9 +444,9 @@ static int GetIso15693AnswerFromSniff(uint8_t *received, int *samples, int *elap // get current clock time_0 = GetCountSspClk(); - + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); - + for(;;) { WDT_HIT(); @@ -454,7 +454,7 @@ static int GetIso15693AnswerFromSniff(uint8_t *received, int *samples, int *elap ci = (int8_t)AT91C_BASE_SSC->SSC_RHR; ci = ABS(ci); - + // The samples are correlations against I and Q versions of the // tone that the tag AM-modulates, so every other sample is I, // every other is Q. We just want power, so abs(I) + abs(Q) is @@ -471,11 +471,11 @@ static int GetIso15693AnswerFromSniff(uint8_t *received, int *samples, int *elap getNext = !getNext; } } - + time_stop = GetCountSspClk() - time_0; - int k = DemodAnswer(received, buf, counter); - LogTrace(received, k, time_0 << 4, time_stop << 4, NULL, false); - return k; + int k = DemodAnswer(received, buf, counter); + LogTrace(received, k, time_0 << 4, time_stop << 4, NULL, false); + return k; } //----------------------------------------------------------------------------- @@ -486,26 +486,26 @@ static int GetIso15693AnswerFromSniff(uint8_t *received, int *samples, int *elap void AcquireRawAdcSamplesIso15693(void) { int c = 0, getNext = false; int ci = 0, cq = 0; - + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); FpgaSetupSsc(); - + // Now send the command FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX); SpinDelay(200); uint8_t *buf = BigBuf_get_addr(); - + uint32_t time_start = GetCountSspClk(); uint8_t cmd[CMD_ID_RESP] = {0}; BuildIdentifyRequest(cmd); - + // sending command c = 0; for(;;) { WDT_HIT(); - + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { AT91C_BASE_SSC->SSC_THR = ToSend[c]; c++; @@ -515,31 +515,31 @@ void AcquireRawAdcSamplesIso15693(void) { } } - + LogTrace(cmd, CMD_ID_RESP, time_start << 4, (GetCountSspClk() - time_start) << 4, NULL, true); - + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); c = 0; for(;;) { WDT_HIT(); - + if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { ci = (int8_t)AT91C_BASE_SSC->SSC_RHR; ci = ABS(ci); - + // The samples are correlations against I and Q versions of the // tone that the tag AM-modulates, so every other sample is I, // every other is Q. We just want power, so abs(I) + abs(Q) is // close to what we want. // iceman 2016, amplitude sqrt(abs(i) + abs(q)) if (getNext) { - + buf[c++] = (uint8_t)(MAX(ci,cq) + (MIN(ci, cq) >> 1)); - + if (c >= 7000) break; - + } else { cq = ci; } @@ -553,24 +553,24 @@ void RecordRawAdcSamplesIso15693(void) { int c = 0, getNext = false; int ci = 0, cq = 0; - + Iso15693InitReader(); uint8_t *buf = BigBuf_get_addr(); - for(;;) { + for(;;) { WDT_HIT(); if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - ci = (int8_t)AT91C_BASE_SSC->SSC_RHR; + ci = (int8_t)AT91C_BASE_SSC->SSC_RHR; ci = ABS(ci); // The samples are correlations against I and Q versions of the // tone that the tag AM-modulates, so every other sample is I, // every other is Q. We just want power, so abs(I) + abs(Q) is // close to what we want. if (getNext) { - + buf[c++] = (uint8_t)(MAX(ci,cq) + (MIN(ci, cq) >> 1)); if(c >= 7000) @@ -582,18 +582,18 @@ void RecordRawAdcSamplesIso15693(void) { getNext = !getNext; } } - + Dbprintf("done"); switch_off(); } -// Initialize the proxmark as iso15k reader +// Initialize the proxmark as iso15k reader // (this might produces glitches that confuse some tags void Iso15693InitReader(void) { LEDsoff(); clear_trace(); set_tracing(true); - + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); // Start from off (no field generated) @@ -601,13 +601,13 @@ void Iso15693InitReader(void) { SpinDelay(10); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - + FpgaSetupSsc(); // Give the tags time to energize FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); SpinDelay(200); - + // Start the timer StartCountSspClk(); @@ -672,7 +672,7 @@ static void BuildInventoryResponse(uint8_t *out, uint8_t *uid) { // one sub-carrier, inventory, 1 slot, fast rate // AFI is at bit 5 (1<<4) when doing an INVENTORY //(1 << 2) | (1 << 5) | (1 << 1); - cmd[0] = 0; // + cmd[0] = 0; // cmd[1] = 0; // DSFID (data storage format identifier). 0x00 = not supported // 64-bit UID cmd[2] = uid[7]; //0x32; @@ -691,19 +691,19 @@ static void BuildInventoryResponse(uint8_t *out, uint8_t *uid) { // Universal Method for sending to and recv bytes from a tag // init ... should we initialize the reader? -// speed ... 0 low speed, 1 hi speed +// speed ... 0 low speed, 1 hi speed // **recv will return you a pointer to the received data -// If you do not need the answer use NULL for *recv[] +// If you do not need the answer use NULL for *recv[] // return: lenght of received data // logging enabled int SendDataTag(uint8_t *send, int sendlen, bool init, int speed, uint8_t *outdata) { int t_samples = 0, wait = 0, elapsed = 0, answer_len = 0; - + LEDsoff(); - + if (init) Iso15693InitReader(); - + LED_A_ON(); if (!speed) @@ -712,15 +712,15 @@ int SendDataTag(uint8_t *send, int sendlen, bool init, int speed, uint8_t *outda CodeIso15693AsReader(send, sendlen); // high speed (1 out of 4) LED_A_INV(); - + uint32_t time_start = GetCountSspClk(); TransmitTo15693Tag(ToSend, ToSendMax, &t_samples, &wait); LogTrace(send, sendlen, time_start << 4, (GetCountSspClk() - time_start) << 4, NULL, true); - + // Now wait for a response if (outdata != NULL) { - LED_B_INV(); + LED_B_INV(); answer_len = GetIso15693AnswerFromTag(outdata, &elapsed); } @@ -729,7 +729,7 @@ int SendDataTag(uint8_t *send, int sendlen, bool init, int speed, uint8_t *outda } // -------------------------------------------------------------------- -// Debug Functions +// Debug Functions // -------------------------------------------------------------------- // Decodes a message from a tag and displays its metadata and content @@ -738,37 +738,37 @@ void DbdecodeIso15693Answer(int len, uint8_t *d) { char status[DBD15STATLEN+1] = {0}; if (len > 3) { - if (d[0] & ( 1 << 3 )) + if (d[0] & ( 1 << 3 )) strncat(status, "ProtExt ", DBD15STATLEN); - if (d[0] & 1) { + if (d[0] & 1) { // error strncat(status, "Error ", DBD15STATLEN); switch (d[1]) { - case 0x01: + case 0x01: strncat(status, "01: not supported", DBD15STATLEN); break; - case 0x02: + case 0x02: strncat(status, "02: not recognized", DBD15STATLEN); break; - case 0x03: + case 0x03: strncat(status, "03: opt not supported", DBD15STATLEN); break; - case 0x0f: + case 0x0f: strncat(status, "0F: no info", DBD15STATLEN); break; - case 0x10: + case 0x10: strncat(status, "10: dont exist", DBD15STATLEN); break; - case 0x11: + case 0x11: strncat(status, "11: lock again", DBD15STATLEN); break; - case 0x12: + case 0x12: strncat(status, "12: locked", DBD15STATLEN); break; - case 0x13: + case 0x13: strncat(status, "13: program error", DBD15STATLEN); break; - case 0x14: + case 0x14: strncat(status, "14: lock error", DBD15STATLEN); break; default: @@ -778,7 +778,7 @@ void DbdecodeIso15693Answer(int len, uint8_t *d) { } else { strncat(status ,"No error ", DBD15STATLEN); } - + if (CheckCrc(d, len)) strncat(status, "[+] crc OK", DBD15STATLEN); else @@ -801,12 +801,12 @@ void DbdecodeIso15693Answer(int len, uint8_t *d) { void ReaderIso15693(uint32_t parameter) { int answerLen1 = 0; int tsamples = 0, wait = 0, elapsed = 0; - + uint8_t uid[8] = {0,0,0,0,0,0,0,0}; - // set up device/fpga + // set up device/fpga Iso15693InitReader(); - + uint8_t *answer1 = BigBuf_malloc(50); uint8_t *answer2 = BigBuf_malloc(50); @@ -822,7 +822,7 @@ void ReaderIso15693(uint32_t parameter) { BuildIdentifyRequest( cmd ); TransmitTo15693Tag(ToSend, ToSendMax, &tsamples, &wait); LogTrace(cmd, CMD_ID_RESP, time_start << 4, (GetCountSspClk() - time_start) << 4, NULL, true); - + // Now wait for a response answerLen1 = GetIso15693AnswerFromTag(answer1, &elapsed) ; @@ -834,10 +834,10 @@ void ReaderIso15693(uint32_t parameter) { uid[3] = answer1[6]; uid[4] = answer1[5]; uid[5] = answer1[4]; - uid[6] = answer1[3]; + uid[6] = answer1[3]; uid[7] = answer1[2]; - - if ( MF_DBGLEVEL >= MF_DBG_EXTENDED) { + + if ( MF_DBGLEVEL >= MF_DBG_EXTENDED) { Dbprintf("[+] UID = %02X%02X%02X%02X%02X%02X%02X%02X", uid[0], uid[1], uid[2], uid[3], uid[4], uid[5], uid[5], uid[6] @@ -863,15 +863,15 @@ void ReaderIso15693(uint32_t parameter) { // Simulate an ISO15693 TAG, perform anti-collision and then print any reader commands // all demodulation performed in arm rather than host. - greg void SimTagIso15693(uint32_t parameter, uint8_t *uid) { - + LEDsoff(); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); FpgaSetupSsc(); // Start from off (no field generated) FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelay(200); - + LED_A_ON(); uint32_t time_start = 0; @@ -886,23 +886,23 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) { LED_C_ON(); // Build a suitable reponse to the reader INVENTORY cocmmand - // not so obsvious, but in the call to BuildInventoryResponse, the command is copied to the global ToSend buffer used below. + // not so obsvious, but in the call to BuildInventoryResponse, the command is copied to the global ToSend buffer used below. uint8_t cmd[CMD_INV_RESP] = {0}; BuildInventoryResponse(cmd, uid); - + while (!BUTTON_PRESS() && !usb_poll_validate_length() ) { WDT_HIT(); - + // Listen to reader ans = GetIso15693AnswerFromSniff(buf, &samples, &elapsed) ; // we should do a better check than this if (ans >= 1 ) { - + time_start = GetCountSspClk(); TransmitTo15693Reader(ToSend, ToSendMax, &tsamples, &wait); - LogTrace(cmd, CMD_INV_RESP, time_start << 4, (GetCountSspClk() - time_start) << 4, NULL, true); - + LogTrace(cmd, CMD_INV_RESP, time_start << 4, (GetCountSspClk() - time_start) << 4, NULL, true); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { Dbprintf("[+] %d octets read from reader command: %x %x %x %x %x %x %x %x", ans, buf[0], buf[1], buf[2], buf[3], @@ -916,38 +916,38 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) { // Since there is no standardized way of reading the AFI out of a tag, we will brute force it // (some manufactures offer a way to read the AFI, though) -void BruteforceIso15693Afi(uint32_t speed) { +void BruteforceIso15693Afi(uint32_t speed) { uint8_t data[7] = {0,0,0,0,0,0,0}; uint8_t buf[ISO15_MAX_FRAME]; memset(buf, 0x00, sizeof(buf)); int datalen = 0, recvlen = 0; - + Iso15693InitReader(); - + // first without AFI // Tags should respond wihtout AFI and with AFI=0 even when AFI is active - + data[0] = ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_INVENTORY | ISO15_REQINV_SLOT1; data[1] = ISO15_CMD_INVENTORY; data[2] = 0; // mask length AddCrc(data, 3); datalen += 2; - + recvlen = SendDataTag(data, datalen, false, speed, buf); - + WDT_HIT(); - + if (recvlen >= 12) { Dbprintf("NoAFI UID = %s", sprintUID(NULL, buf + 2) ); } - + // now with AFI data[0] |= ISO15_REQINV_AFI; //data[1] = ISO15_CMD_INVENTORY; data[2] = 0; // AFI data[3] = 0; // mask length - + for (uint16_t i = 0; i < 256; i++) { data[2] = i & 0xFF; AddCrc(data, 4); @@ -957,19 +957,19 @@ void BruteforceIso15693Afi(uint32_t speed) { if (recvlen >= 12) { Dbprintf("AFI = %i UID = %s", i, sprintUID(NULL, buf + 2) ); } - + if (BUTTON_PRESS()) { DbpString("button pressed, aborting.."); break; } - } - + } + DbpString("AFI Bruteforcing done."); switch_off(); } // Allows to directly send commands to the tag via the client -// Has to increase dialog between device and client. +// Has to increase dialog between device and client. void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint8_t *data) { bool init = true; @@ -981,16 +981,16 @@ void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint DbpString("[+] SEND"); Dbhexdump(datalen, data, true); } - + buflen = SendDataTag(data, datalen, init, speed, (recv ? buf : NULL)); - - if (recv) { + + if (recv) { buflen = (buflen > ISO15_MAX_FRAME) ? ISO15_MAX_FRAME : buflen; - + LED_B_ON(); cmd_send(CMD_ACK, buflen, 0, 0, buf, buflen); - LED_B_OFF(); - + LED_B_OFF(); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { DbpString("[+] RECV"); DbdecodeIso15693Answer(buflen, buf); diff --git a/armsrc/lfops.c b/armsrc/lfops.c index 96abd9b99..3296aff8c 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -85,11 +85,11 @@ void setT55xxConfig(uint8_t arg0, t55xx_config *c) { if (arg0 == 0) { return; } - + if (!FlashInit()) { return; } - + uint8_t *buf = BigBuf_malloc(T55XX_CONFIG_LEN); Flash_CheckBusy(BUSY_TIMEOUT); uint16_t res = Flash_ReadDataCont(T55XX_CONFIG_OFFSET, buf, T55XX_CONFIG_LEN); @@ -98,9 +98,9 @@ void setT55xxConfig(uint8_t arg0, t55xx_config *c) { BigBuf_free(); return; } - + memcpy(buf, &t_config, T55XX_CONFIG_LEN); - + Flash_CheckBusy(BUSY_TIMEOUT); Flash_WriteEnable(); Flash_Erase4k(3, 0xD); @@ -109,8 +109,8 @@ void setT55xxConfig(uint8_t arg0, t55xx_config *c) { if ( res == T55XX_CONFIG_LEN && MF_DBGLEVEL > 1) { DbpString("T55XX Config save success"); } - - BigBuf_free(); + + BigBuf_free(); #endif } @@ -125,11 +125,11 @@ void loadT55xxConfig(void) { } uint8_t *buf = BigBuf_malloc(T55XX_CONFIG_LEN); - + Flash_CheckBusy(BUSY_TIMEOUT); uint16_t isok = Flash_ReadDataCont(T55XX_CONFIG_OFFSET, buf, T55XX_CONFIG_LEN); FlashStop(); - + // verify read mem is actual data. uint8_t cntA = T55XX_CONFIG_LEN, cntB = T55XX_CONFIG_LEN; for (int i=0; i< T55XX_CONFIG_LEN; i++) { @@ -140,9 +140,9 @@ void loadT55xxConfig(void) { BigBuf_free(); return; } - + memcpy((uint8_t *)&t_config, buf, T55XX_CONFIG_LEN); - + if ( isok == T55XX_CONFIG_LEN) { if (MF_DBGLEVEL > 1) DbpString("T55XX Config load success"); } @@ -581,7 +581,7 @@ void SimulateTagLowFrequencyEx(int period, int gap, int ledcontrol, int numcycle //FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE ); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT); WaitMS(20); - + int i = 0, x = 0; uint8_t *buf = BigBuf_get_addr(); @@ -598,11 +598,11 @@ void SimulateTagLowFrequencyEx(int period, int gap, int ledcontrol, int numcycle AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT | GPIO_SSC_CLK; AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK; - + uint8_t check = 1; for(;;) { - + if ( numcycles > -1 ) { if ( x != numcycles ) { ++x; @@ -744,7 +744,7 @@ static void fcAll(uint8_t fc, int *n, uint8_t clock, uint16_t *modCnt) *n += fc; } if (mod > 0) (*modCnt)++; - + if ((mod > 0) && modAdjOk){ //fsk2 if ((*modCnt % modAdj) == 0){ //if 4th 8 length wave in a rf/50 add extra 8 length wave memset(dest + (*n), 0, fc - halfFC); @@ -1500,9 +1500,9 @@ void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd) { bool brute_mem = arg0 & 0x4; uint32_t i = 0; - + // regular read mode - bool RegReadMode = (Block == 0xFF); + bool RegReadMode = (Block == 0xFF); uint8_t start_wait = 4; size_t samples = 12000; @@ -1510,7 +1510,7 @@ void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd) { start_wait = 0; samples = 1024; } - + //clear buffer now so it does not interfere with timing later BigBuf_Clear_keep_EM(); @@ -1523,7 +1523,7 @@ void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd) { LFSetupFPGAForADC(95, true); // make sure tag is fully powered up... WaitMS(start_wait); - + // Trigger T55x7 Direct Access Mode with start gap FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); WaitUS(t_config.start_gap); @@ -1570,9 +1570,9 @@ void T55xx_ChkPwds() { // First get baseline and setup LF mode. // tends to mess up BigBuf uint8_t *buf = BigBuf_get_addr(); - + uint32_t b1, baseline = 0; - + // collect baseline for failed attempt uint8_t x = 32; while (x--) { @@ -1580,16 +1580,16 @@ void T55xx_ChkPwds() { T55xxReadBlock(4, 1, 0); for (uint16_t j=0; j < 1024; ++j) b1 += buf[j]; - + b1 *= b1; - b1 >>= 8; + b1 >>= 8; baseline += b1; } baseline >>= 5; - Dbprintf("[=] Baseline determined [%u]", baseline); + Dbprintf("[=] Baseline determined [%u]", baseline); + - uint8_t *pwds = BigBuf_get_EM_addr(); uint16_t pwdCount = 0; uint32_t candidate = 0; @@ -1599,20 +1599,20 @@ void T55xx_ChkPwds() { if ( use_flashmem ) { BigBuf_Clear_EM(); uint16_t isok = 0; - uint8_t counter[2] = {0x00, 0x00}; + uint8_t counter[2] = {0x00, 0x00}; isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET, counter, sizeof(counter) ); if ( isok != sizeof(counter) ) goto OUT; - + pwdCount = counter[1] << 8 | counter[0]; - - if ( pwdCount == 0 && pwdCount == 0xFFFF) + + if ( pwdCount == 0 && pwdCount == 0xFFFF) goto OUT; isok = Flash_ReadData(DEFAULT_T55XX_KEYS_OFFSET+2, pwds, pwdCount * 4); if ( isok != pwdCount * 4 ) goto OUT; - + Dbprintf("[=] Password dictionary count %d ", pwdCount); } #endif @@ -1623,38 +1623,38 @@ void T55xx_ChkPwds() { if (BUTTON_PRESS() && !usb_poll_validate_length()) { goto OUT; } - + pwd = bytes_to_num(pwds + i * 4, 4); - + T55xxReadBlock(5, 0, pwd); - + // calc mean of BigBuf 1024 samples. uint32_t sum = 0; for (uint16_t j=0; j<1024; ++j) { sum += buf[j]; } - + sum *= sum; sum >>= 8; - + int32_t tmp = (sum - baseline); curr = ABS(tmp); - + Dbprintf("[=] Pwd %08X | ABS %u", pwd, curr ); - + if ( curr > prev ) { - - + + Dbprintf("[=] --> ABS %u Candidate %08X <--", curr, pwd ); candidate = pwd; prev = curr; } } - + if ( candidate ) ret = 1; - + OUT: FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); cmd_send(CMD_ACK,ret,candidate,0,0,0); @@ -2122,7 +2122,7 @@ void Cotag(uint32_t arg0) { LED_A_ON(); LFSetupFPGAForADC(89, true); - + //clear buffer now so it does not interfere with timing later BigBuf_Clear_ext(false); diff --git a/armsrc/lfsampling.c b/armsrc/lfsampling.c index 4b036d088..80d95bb4a 100644 --- a/armsrc/lfsampling.c +++ b/armsrc/lfsampling.c @@ -42,7 +42,7 @@ void setSamplingConfig(sample_config *sc) { if(sc->divisor != 0) config.divisor = sc->divisor; if(sc->bits_per_sample != 0) config.bits_per_sample = sc->bits_per_sample; if(sc->trigger_threshold != -1) config.trigger_threshold = sc->trigger_threshold; - + config.decimation = (sc->decimation != 0) ? sc->decimation : 1; config.averaging = sc->averaging; if(config.bits_per_sample > 8) config.bits_per_sample = 8; @@ -136,17 +136,17 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag uint32_t sample_total_numbers = 0; uint32_t sample_total_saved = 0; uint32_t cancel_counter = 0; - + while (!BUTTON_PRESS() && !usb_poll_validate_length() ) { WDT_HIT(); if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - - // Testpoint 8 (TP8) can be used to trigger oscilliscope + + // Testpoint 8 (TP8) can be used to trigger oscilliscope LED_D_OFF(); - - // threshold either high or low values 128 = center 0. if trigger = 178 + + // threshold either high or low values 128 = center 0. if trigger = 178 if ((trigger_threshold > 0) && (sample < (trigger_threshold + 128)) && (sample > (128 - trigger_threshold))) { if (cancel_after > 0) { cancel_counter++; @@ -155,7 +155,7 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag } continue; } - + trigger_threshold = 0; sample_total_numbers++; @@ -168,22 +168,22 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag if (sample_counter < decimation) continue; sample_counter = 0; } - + // averaging if (averaging && decimation > 1) { sample = sample_sum / decimation; sample_sum =0; } - + // store the sample sample_total_saved ++; if (bits_per_sample == 8) { dest[sample_total_saved-1] = sample; - - // Get the return value correct - data.numbits = sample_total_saved << 3; + + // Get the return value correct + data.numbits = sample_total_saved << 3; if (sample_total_saved >= bufsize) break; - + } else { pushBit(&data, sample & 0x80); if (bits_per_sample > 1) pushBit(&data, sample & 0x40); @@ -203,11 +203,11 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag Dbprintf("buffer samples: %02x %02x %02x %02x %02x %02x %02x %02x ...", dest[0], dest[1], dest[2], dest[3], dest[4], dest[5], dest[6], dest[7]); } - + // Ensure that DC offset removal and noise check is performed for any device-side processing removeSignalOffset(dest, bufsize); computeSignalProperties(dest, bufsize); - + return data.numbits; } /** @@ -250,7 +250,7 @@ uint32_t SampleLF(bool printCfg, int sample_size) { BigBuf_Clear_ext(false); uint32_t ret = ReadLF(true, printCfg, sample_size); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - return ret; + return ret; } /** * Initializes the FPGA for snoop-mode (field off), and acquires the samples. @@ -260,7 +260,7 @@ uint32_t SnoopLF() { BigBuf_Clear_ext(false); uint32_t ret = ReadLF(false, true, 0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - return ret; + return ret; } /** @@ -272,10 +272,10 @@ void doT55x7Acquisition(size_t sample_size) { #define T55xx_READ_UPPER_THRESHOLD 128+60 // 60 grph #define T55xx_READ_LOWER_THRESHOLD 128-60 // -60 grph #define T55xx_READ_TOL 5 - + uint8_t *dest = BigBuf_get_addr(); uint16_t bufsize = BigBuf_max_traceLen(); - + if ( bufsize > sample_size ) bufsize = sample_size; @@ -284,18 +284,18 @@ void doT55x7Acquisition(size_t sample_size) { bool startFound = false; bool highFound = false; bool lowFound = false; - - while(!BUTTON_PRESS() && !usb_poll_validate_length() && skipCnt < 1000 && (i < bufsize) ) { - WDT_HIT(); - + while(!BUTTON_PRESS() && !usb_poll_validate_length() && skipCnt < 1000 && (i < bufsize) ) { + WDT_HIT(); + + if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { - curSample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; + curSample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; LED_D_OFF(); - + // skip until the first high sample above threshold if (!startFound && curSample > T55xx_READ_UPPER_THRESHOLD) { - //if (curSample > lastSample) + //if (curSample > lastSample) // lastSample = curSample; highFound = true; } else if (!highFound) { @@ -304,7 +304,7 @@ void doT55x7Acquisition(size_t sample_size) { } // skip until the first low sample below threshold if (!startFound && curSample < T55xx_READ_LOWER_THRESHOLD) { - //if (curSample > lastSample) + //if (curSample > lastSample) lastSample = curSample; lowFound = true; } else if (!lowFound) { @@ -341,22 +341,22 @@ void doCotagAcquisition(size_t sample_size) { uint8_t *dest = BigBuf_get_addr(); uint16_t bufsize = BigBuf_max_traceLen(); - + if ( bufsize > sample_size ) bufsize = sample_size; - dest[0] = 0; - uint8_t sample = 0, firsthigh = 0, firstlow = 0; + dest[0] = 0; + uint8_t sample = 0, firsthigh = 0, firstlow = 0; uint16_t i = 0; uint16_t noise_counter = 0; - + while (!BUTTON_PRESS() && !usb_poll_validate_length() && (i < bufsize) && (noise_counter < (COTAG_T1 << 1)) ) { - WDT_HIT(); + WDT_HIT(); if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { - sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; + sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; LED_D_OFF(); - + // find first peak if ( !firsthigh ) { if (sample < COTAG_ONE_THRESHOLD) { @@ -375,14 +375,14 @@ void doCotagAcquisition(size_t sample_size) { firstlow = 1; } - ++i; - + ++i; + if ( sample > COTAG_ONE_THRESHOLD) dest[i] = 255; - else if ( sample < COTAG_ZERO_THRESHOLD) + else if ( sample < COTAG_ZERO_THRESHOLD) dest[i] = 0; - else - dest[i] = dest[i-1]; + else + dest[i] = dest[i-1]; } } } @@ -391,12 +391,12 @@ uint32_t doCotagAcquisitionManchester() { uint8_t *dest = BigBuf_get_addr(); uint16_t bufsize = BigBuf_max_traceLen(); - + if ( bufsize > COTAG_BITS ) bufsize = COTAG_BITS; - dest[0] = 0; - uint8_t sample = 0, firsthigh = 0, firstlow = 0; + dest[0] = 0; + uint8_t sample = 0, firsthigh = 0, firstlow = 0; uint16_t sample_counter = 0, period = 0; uint8_t curr = 0, prev = 0; uint16_t noise_counter = 0; @@ -405,29 +405,29 @@ uint32_t doCotagAcquisitionManchester() { WDT_HIT(); if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { - sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; + sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; LED_D_OFF(); - + // find first peak if ( !firsthigh ) { if (sample < COTAG_ONE_THRESHOLD) { noise_counter++; continue; - } + } noise_counter = 0; firsthigh = 1; } - + if ( !firstlow ){ if (sample > COTAG_ZERO_THRESHOLD ) { - noise_counter++; + noise_counter++; continue; } - noise_counter = 0; + noise_counter = 0; firstlow = 1; } - - // set sample 255, 0, or previous + + // set sample 255, 0, or previous if ( sample > COTAG_ONE_THRESHOLD){ prev = curr; curr = 1; @@ -438,14 +438,14 @@ uint32_t doCotagAcquisitionManchester() { } else { curr = prev; - } + } - // full T1 periods, + // full T1 periods, if ( period > 0 ) { --period; continue; } - + dest[sample_counter] = curr; ++sample_counter; period = COTAG_T1; diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 5e7375d3d..a10925da7 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -20,8 +20,8 @@ # define HARDNESTED_AUTHENTICATION_TIMEOUT 848 // card times out 1ms after wrong authentication (according to NXP documentation) #endif #ifndef HARDNESTED_PRE_AUTHENTICATION_LEADTIME -# define HARDNESTED_PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication -#endif +# define HARDNESTED_PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication +#endif // send an incomplete dummy response in order to trigger the card's authentication failure timeout #ifndef CHK_TIMEOUT @@ -29,13 +29,13 @@ ReaderTransmit(&dummy_answer, 1, NULL); \ uint32_t timeout = GetCountSspClk() + HARDNESTED_AUTHENTICATION_TIMEOUT; \ while (GetCountSspClk() < timeout) {}; \ - } + } #endif static uint8_t dummy_answer = 0; //----------------------------------------------------------------------------- -// Select, Authenticate, Read a MIFARE tag. +// Select, Authenticate, Read a MIFARE tag. // read block //----------------------------------------------------------------------------- void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) @@ -45,7 +45,7 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) uint8_t keyType = arg1; uint64_t ui64Key = 0; ui64Key = bytes_to_num(datain, 6); - + // variables byte_t isOK = 0; byte_t dataoutbuf[16] = {0x00}; @@ -74,7 +74,7 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); break; }; - + if(mifare_classic_readblock(pcs, cuid, blockNo, dataoutbuf)) { if (MF_DBGLEVEL >= 1) Dbprintf("Read block error"); break; @@ -84,13 +84,13 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); break; }; - + isOK = 1; break; } - + crypto1_destroy(pcs); - + if (MF_DBGLEVEL >= 2) DbpString("READ BLOCK FINISHED"); LED_B_ON(); @@ -117,7 +117,7 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes){ OnError(0); return; }; - + if(!mifare_ultra_auth(keybytes)){ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed"); OnError(1); @@ -175,7 +175,7 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) OnError(1); return; } - } + } if( mifare_ultra_readblock(blockNo, dataout) ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block error"); @@ -195,7 +195,7 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) } //----------------------------------------------------------------------------- -// Select, Authenticate, Read a MIFARE tag. +// Select, Authenticate, Read a MIFARE tag. // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes) //----------------------------------------------------------------------------- void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) @@ -205,7 +205,7 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) uint8_t keyType = arg1; uint64_t ui64Key = 0; ui64Key = bytes_to_num(datain, 6); - + // variables byte_t isOK = 0; byte_t dataoutbuf[16 * 16]; @@ -219,7 +219,7 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) clear_trace(); set_tracing(true); - + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -229,13 +229,13 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) isOK = 0; if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); } - - + + if(isOK && mifare_classic_auth(pcs, cuid, FirstBlockOfSector(sectorNo), keyType, ui64Key, AUTH_FIRST)) { isOK = 0; if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); } - + for (uint8_t blockNo = 0; isOK && blockNo < NumBlocksPerSector(sectorNo); blockNo++) { if(mifare_classic_readblock(pcs, cuid, FirstBlockOfSector(sectorNo) + blockNo, dataoutbuf + 16 * blockNo)) { isOK = 0; @@ -243,7 +243,7 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) break; } } - + if(mifare_classic_halt(pcs, cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); } @@ -275,7 +275,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(true); - + // params uint8_t blockNo = arg0; uint16_t blocks = arg1; @@ -315,7 +315,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) if (!mifare_ul_ev1_auth(pwd, pack)){ OnError(1); - return; + return; } } @@ -326,7 +326,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) } len = mifare_ultra_readblock(blockNo + i, dataout + 4 * i); - + if (len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block %d error",i); // if no blocks read - error out @@ -361,7 +361,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) } //----------------------------------------------------------------------------- -// Select, Authenticate, Write a MIFARE tag. +// Select, Authenticate, Write a MIFARE tag. // read block //----------------------------------------------------------------------------- void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) @@ -374,7 +374,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) ui64Key = bytes_to_num(datain, 6); memcpy(blockdata, datain + 10, 16); - + // variables byte_t isOK = 0; uint8_t uid[10] = {0x00}; @@ -387,7 +387,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) clear_trace(); set_tracing(true); - + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -402,7 +402,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= 1) Dbprintf("Auth error"); break; }; - + if(mifare_classic_writeblock(pcs, cuid, blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); break; @@ -412,13 +412,13 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); break; }; - + isOK = 1; break; } - + crypto1_destroy(pcs); - + if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED"); cmd_send(CMD_ACK,isOK,0,0,0,0); @@ -428,7 +428,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) set_tracing(false); } -/* // Command not needed but left for future testing +/* // Command not needed but left for future testing void MifareUWriteBlockCompat(uint8_t arg0, uint8_t *datain) { uint8_t blockNo = arg0; @@ -483,14 +483,14 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) byte_t blockdata[4] = {0x00}; memcpy(blockdata, datain, 4); - + LEDsoff(); LED_A_ON(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(true); - + if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -499,26 +499,26 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) // UL-C authentication if ( useKey ) { - uint8_t key[16] = {0x00}; + uint8_t key[16] = {0x00}; memcpy(key, datain+4, sizeof(key) ); if ( !mifare_ultra_auth(key) ) { OnError(1); - return; + return; } } - + // UL-EV1 / NTAG authentication - if (usePwd) { + if (usePwd) { uint8_t pwd[4] = {0x00}; memcpy(pwd, datain+4, 4); uint8_t pack[4] = {0,0,0,0}; if (!mifare_ul_ev1_auth(pwd, pack)) { OnError(1); - return; + return; } } - + if (mifare_ultra_writeblock(blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(0); @@ -540,18 +540,18 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) } void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ - + uint8_t pwd[16] = {0x00}; byte_t blockdata[4] = {0x00}; - + memcpy(pwd, datain, 16); - + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(true); - + if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -596,7 +596,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(47); return; - }; + }; if (mifare_ultra_halt()) { if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); @@ -626,25 +626,25 @@ void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t * uint32_t cuid = 0; int16_t isOK = 0; uint16_t num_nonces = 0; - uint8_t cascade_levels = 0; + uint8_t cascade_levels = 0; uint8_t blockNo = arg0 & 0xff; uint8_t keyType = (arg0 >> 8) & 0xff; bool initialize = flags & 0x0001; bool field_off = flags & 0x0004; bool have_uid = false; - + LED_A_ON(); LED_C_OFF(); - BigBuf_free(); BigBuf_Clear_ext(false); + BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(true); - + if (initialize) iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + LED_C_ON(); - + for (uint16_t i = 0; i <= USB_CMD_DATA_SIZE-4; i += 4 ) { // Test if the action was cancelled @@ -655,7 +655,7 @@ void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t * } if (!have_uid) { // need a full select cycle to get the uid first - iso14a_card_select_t card_info; + iso14a_card_select_t card_info; if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Can't select card (ALL)"); continue; @@ -666,31 +666,31 @@ void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t * case 10: cascade_levels = 3; break; default: break; } - have_uid = true; + have_uid = true; } else { // no need for anticollision. We can directly select the card if (!iso14443a_fast_select_card(uid, cascade_levels)) { if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Can't select card (UID)"); continue; } } - - // Transmit MIFARE_CLASSIC_AUTH + + // Transmit MIFARE_CLASSIC_AUTH uint8_t dcmd[4] = {0x60 + (keyType & 0x01), blockNo, 0x00, 0x00}; AddCrc14A(dcmd, 2); ReaderTransmit(dcmd, sizeof(dcmd), NULL); - int len = ReaderReceive(answer, par); + int len = ReaderReceive(answer, par); // wait for the card to become ready again CHK_TIMEOUT(); - + if (len != 4) { if (MF_DBGLEVEL >= 2) Dbprintf("AcquireNonces: Auth1 error"); continue; } - + num_nonces++; - - // Save the tag nonce (nt) + + // Save the tag nonce (nt) buf[i] = answer[0]; buf[i+1] = answer[1]; buf[i+2] = answer[2]; @@ -714,7 +714,7 @@ void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t * //----------------------------------------------------------------------------- // acquire encrypted nonces in order to perform the attack described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain) { @@ -737,7 +737,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t blockNo = arg0 & 0xff; uint8_t keyType = (arg0 >> 8) & 0xff; uint8_t targetBlockNo = arg1 & 0xff; - uint8_t targetKeyType = (arg1 >> 8) & 0xff; + uint8_t targetKeyType = (arg1 >> 8) & 0xff; bool initialize = flags & 0x0001; bool slow = flags & 0x0002; bool field_off = flags & 0x0004; @@ -746,15 +746,15 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, LED_A_ON(); LED_C_OFF(); - BigBuf_free(); BigBuf_Clear_ext(false); + BigBuf_free(); BigBuf_Clear_ext(false); clear_trace(); set_tracing(false); - + if (initialize) iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + LED_C_ON(); - + for (uint16_t i = 0; i <= USB_CMD_DATA_SIZE - 9; ) { // Test if the action was cancelled @@ -765,7 +765,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, } if (!have_uid) { // need a full select cycle to get the uid first - iso14a_card_select_t card_info; + iso14a_card_select_t card_info; if(!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Can't select card (ALL)"); continue; @@ -776,14 +776,14 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, case 10: cascade_levels = 3; break; default: break; } - have_uid = true; + have_uid = true; } else { // no need for anticollision. We can directly select the card if (!iso14443a_fast_select_card(uid, cascade_levels)) { if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Can't select card (UID)"); continue; } } - + if (slow) SpinDelayUs(HARDNESTED_PRE_AUTHENTICATION_LEADTIME); @@ -803,7 +803,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Auth2 error len=%d", len); continue; } - + num_nonces++; if (num_nonces % 2) { memcpy(buf+i, receivedAnswer, 4); @@ -817,7 +817,7 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, } LED_C_OFF(); - crypto1_destroy(pcs); + crypto1_destroy(pcs); LED_B_ON(); cmd_send(CMD_ACK, isOK, cuid, num_nonces, buf, sizeof(buf)); LED_B_OFF(); @@ -833,8 +833,8 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, //----------------------------------------------------------------------------- -// MIFARE nested authentication. -// +// MIFARE nested authentication. +// //----------------------------------------------------------------------------- void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *datain) { @@ -846,7 +846,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat uint64_t ui64Key = 0; ui64Key = bytes_to_num(datain, 6); - + // variables uint16_t rtr, i, j, len; uint16_t davg = 0; @@ -855,7 +855,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat uint32_t cuid = 0, nt1, nt2, nttmp, nttest, ks1; uint8_t par[1] = {0x00}; uint32_t target_nt[2] = {0x00}, target_ks[2] = {0x00}; - + uint8_t par_array[4] = {0x00}; uint16_t ncount = 0; struct Crypto1State mpcs = {0, 0}; @@ -872,7 +872,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // free eventually allocated BigBuf memory BigBuf_free(); BigBuf_Clear_ext(false); - + if (calibrate) clear_trace(); set_tracing(true); @@ -887,7 +887,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat davg = dmax = 0; dmin = 2000; delta_time = 0; - + for (rtr = 0; rtr < 17; rtr++) { // Test if the action was cancelled @@ -948,16 +948,16 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat } davg = (davg + (rtr - 1)/2) / (rtr - 1); - + if (MF_DBGLEVEL >= 3) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time); dmin = davg - 2; dmax = davg + 2; - + LED_B_OFF(); } -// ------------------------------------------------------------------------------------------------- - +// ------------------------------------------------------------------------------------------------- + LED_C_ON(); // get crypted nonces for target sector @@ -965,7 +965,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat target_nt[i] = 0; while(target_nt[i] == 0) { // continue until we have an unambiguous nonce - + // prepare next select. No need to power down the card. if(mifare_classic_halt(pcs, cuid)) { if (MF_DBGLEVEL >= 2) Dbprintf("Nested: Halt error"); @@ -976,7 +976,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat if (MF_DBGLEVEL >= 2) Dbprintf("Nested: Can't select card"); continue; }; - + auth1_time = 0; if(mifare_classic_authex(pcs, cuid, blockNo, keyType, ui64Key, AUTH_FIRST, &nt1, &auth1_time)) { if (MF_DBGLEVEL >= 2) Dbprintf("Nested: Auth1 error"); @@ -991,15 +991,15 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat if (MF_DBGLEVEL >= 2) Dbprintf("Nested: Auth2 error len=%d", len); continue; }; - - nt2 = bytes_to_num(receivedAnswer, 4); + + nt2 = bytes_to_num(receivedAnswer, 4); if (MF_DBGLEVEL >= 3) Dbprintf("Nonce#%d: Testing nt1=%08x nt2enc=%08x nt2par=%02x", i+1, nt1, nt2, par[0]); - + // Parity validity check for (j = 0; j < 4; j++) { par_array[j] = (oddparity8(receivedAnswer[j]) != ((par[0] >> (7-j)) & 0x01)); } - + ncount = 0; nttest = prng_successor(nt1, dmin - 1); for (j = dmin; j < dmax + 1; j++) { @@ -1028,16 +1028,16 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat } LED_C_OFF(); - + crypto1_destroy(pcs); - + uint8_t buf[4 + 4 * 4] = {0}; memcpy(buf, &cuid, 4); memcpy(buf+4, &target_nt[0], 4); memcpy(buf+8, &target_ks[0], 4); memcpy(buf+12, &target_nt[1], 4); memcpy(buf+16, &target_ks[1], 4); - + LED_B_ON(); cmd_send(CMD_ACK, isOK, 0, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); LED_B_OFF(); @@ -1050,9 +1050,9 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat } //----------------------------------------------------------------------------- -// MIFARE check keys. key count up to 85. -// -//----------------------------------------------------------------------------- +// MIFARE check keys. key count up to 85. +// +//----------------------------------------------------------------------------- typedef struct sector_t { uint8_t keyA[6]; uint8_t keyB[6]; @@ -1060,23 +1060,23 @@ typedef struct sector_t { typedef struct chk_t { uint64_t key; - uint32_t cuid; + uint32_t cuid; uint8_t cl; uint8_t block; uint8_t keyType; - uint8_t *uid; + uint8_t *uid; struct Crypto1State *pcs; } chk_t; // checks one key. // fast select, tries 5 times to select -// +// // return: // 2 = failed to select. // 1 = wrong key // 0 = correct key uint8_t chkKey( struct chk_t *c ) { - uint8_t i = 0, res = 2; + uint8_t i = 0, res = 2; while( i < 5 ) { // this part is from Piwi's faster nonce collecting part in Hardnested. // assume: fast select @@ -1087,26 +1087,26 @@ uint8_t chkKey( struct chk_t *c ) { res = mifare_classic_authex(c->pcs, c->cuid, c->block, c->keyType, c->key, AUTH_FIRST, NULL, NULL); CHK_TIMEOUT(); - + // if successfull auth, send HALT - // if ( !res ) + // if ( !res ) // mifare_classic_halt_ex(c->pcs); break; } return res; } -uint8_t chkKey_readb(struct chk_t *c, uint8_t *keyb) { - +uint8_t chkKey_readb(struct chk_t *c, uint8_t *keyb) { + if (!iso14443a_fast_select_card(c->uid, c->cl)) return 2; - + if ( mifare_classic_authex(c->pcs, c->cuid, c->block, 0, c->key, AUTH_FIRST, NULL, NULL) ) return 1; - uint8_t data[16] = {0x00}; + uint8_t data[16] = {0x00}; uint8_t res = mifare_classic_readblock(c->pcs, c->cuid, c->block, data); - + // successful read if ( !res ) { // data was something else than zeros. @@ -1121,40 +1121,40 @@ uint8_t chkKey_readb(struct chk_t *c, uint8_t *keyb) { return res; } -void chkKey_scanA(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) { - for (uint8_t s = 0; s < *sectorcnt; s++) { +void chkKey_scanA(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) { + for (uint8_t s = 0; s < *sectorcnt; s++) { - // skip already found A keys - if ( found[(s*2)] ) + // skip already found A keys + if ( found[(s*2)] ) continue; c->block = FirstBlockOfSector( s ); - if ( chkKey( c ) == 0 ) { + if ( chkKey( c ) == 0 ) { num_to_bytes(c->key, 6, k_sector[s].keyA); - found[(s*2)] = 1; - ++*foundkeys; - + found[(s*2)] = 1; + ++*foundkeys; + if (MF_DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Scan A found (%d)", c->block); } - } + } } -void chkKey_scanB(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) { - for (uint8_t s = 0; s < *sectorcnt; s++) { +void chkKey_scanB(struct chk_t *c, struct sector_t *k_sector, uint8_t *found, uint8_t *sectorcnt, uint8_t *foundkeys) { + for (uint8_t s = 0; s < *sectorcnt; s++) { - // skip already found B keys + // skip already found B keys if ( found[(s*2)+1] ) continue; c->block = FirstBlockOfSector( s ); - if ( chkKey( c ) == 0 ) { - num_to_bytes(c->key, 6, k_sector[s].keyB); - found[(s*2)+1] = 1; - ++*foundkeys; - + if ( chkKey( c ) == 0 ) { + num_to_bytes(c->key, 6, k_sector[s].keyB); + found[(s*2)+1] = 1; + ++*foundkeys; + if (MF_DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Scan B found (%d)", c->block); } - } + } } // loop all A keys, @@ -1163,21 +1163,21 @@ void chkKey_loopBonly(struct chk_t *c, struct sector_t *k_sector, uint8_t *found // read Block B, if A is found. for (uint8_t s = 0; s < *sectorcnt; ++s) { - + if ( found[(s*2)] && found[(s*2)+1] ) continue; - + c->block = (FirstBlockOfSector( s ) + NumBlocksPerSector( s ) - 1); // A but not B - if ( found[(s*2)] && !found[(s*2)+1] ){ + if ( found[(s*2)] && !found[(s*2)+1] ){ c->key = bytes_to_num(k_sector[s].keyA, 6); uint8_t status = chkKey_readb(c, k_sector[s].keyB); - if ( status == 0 ){ + if ( status == 0 ){ found[(s*2)+1] = 1; ++*foundkeys; - if (MF_DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c->block); + if (MF_DBGLEVEL >= 3) Dbprintf("ChkKeys_fast: Reading B found (%d)", c->block); // try quick find all B? // assume: keys comes in groups. Find one B, test against all B. @@ -1199,10 +1199,10 @@ void chkKey_loopBonly(struct chk_t *c, struct sector_t *k_sector, uint8_t *found // datain = keys as array void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) { - // first call or + // first call or uint8_t sectorcnt = arg0 & 0xFF; // 16; - uint8_t firstchunk = (arg0 >> 8) & 0xF; - uint8_t lastchunk = (arg0 >> 12) & 0xF; + uint8_t firstchunk = (arg0 >> 8) & 0xF; + uint8_t lastchunk = (arg0 >> 12) & 0xF; uint8_t strategy = arg1 & 0xFF; uint8_t use_flashmem = (arg1 >> 8) & 0xFF; uint16_t keyCount = arg2 & 0xFF; @@ -1212,7 +1212,7 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da struct Crypto1State *pcs; pcs = &mpcs; struct chk_t chk_data; - + uint8_t allkeys = sectorcnt << 1; static uint32_t cuid = 0; @@ -1222,20 +1222,20 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da static uint8_t found[80]; static uint8_t *uid; -#ifdef WITH_FLASH +#ifdef WITH_FLASH if ( use_flashmem ) { BigBuf_free(); uint16_t isok = 0; - uint8_t size[2] = {0x00, 0x00}; + uint8_t size[2] = {0x00, 0x00}; isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET, size, 2); if ( isok != 2 ) goto OUT; - + keyCount = size[1] << 8 | size[0]; - - if ( keyCount == 0 && keyCount == 0xFFFF) + + if ( keyCount == 0 && keyCount == 0xFFFF) goto OUT; - + datain = BigBuf_malloc( keyCount * 6); if (datain == NULL ) goto OUT; @@ -1243,10 +1243,10 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da isok = Flash_ReadData(DEFAULT_MF_KEYS_OFFSET+2, datain, keyCount * 6); if ( isok != keyCount * 6 ) goto OUT; - + } #endif - + if (uid == NULL || firstchunk) { uid = BigBuf_malloc(10); if (uid == NULL ) @@ -1254,31 +1254,31 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da } iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + LEDsoff(); LED_A_ON(); - + if ( firstchunk ) { clear_trace(); set_tracing(false); - + memset(k_sector, 0x00, 480+10); memset(found, 0x00, sizeof(found)); - foundkeys = 0; - - iso14a_card_select_t card_info; + foundkeys = 0; + + iso14a_card_select_t card_info; if ( !iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("ChkKeys_fast: Can't select card (ALL)"); goto OUT; } - + switch (card_info.uidlen) { case 4 : cascade_levels = 1; break; case 7 : cascade_levels = 2; break; case 10: cascade_levels = 3; break; default: break; } - + CHK_TIMEOUT(); } @@ -1287,8 +1287,8 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da chk_data.cuid = cuid; chk_data.cl = cascade_levels; chk_data.pcs = pcs; - chk_data.block = 0; - + chk_data.block = 0; + // keychunk loop - depth first one sector. if ( strategy == 1 || use_flashmem) { @@ -1304,9 +1304,9 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da continue; for (uint16_t i = s_point; i < keyCount; ++i) { - + //if ( i % 100 == 0) Dbprintf("ChkKeys_fast: sector %d | checking %d | %d found | s_point %d", s, i, foundkeys, s_point); - + // Allow button press / usb cmd to interrupt device if (BUTTON_PRESS() && !usb_poll_validate_length()) { goto OUT; @@ -1317,14 +1317,14 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da goto OUT; WDT_HIT(); - + // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector chk_data.block = FirstBlockOfSector( s ); // new key chk_data.key = bytes_to_num(datain + i * 6, 6); - // skip already found A keys + // skip already found A keys if( !found[(s*2)] ) { chk_data.keyType = 0; status = chkKey( &chk_data); @@ -1332,31 +1332,31 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da memcpy(k_sector[s].keyA, datain + i * 6, 6); found[(s*2)] = 1; ++foundkeys; - - chkKey_scanA(&chk_data, k_sector, found, §orcnt, &foundkeys); - + + chkKey_scanA(&chk_data, k_sector, found, §orcnt, &foundkeys); + // read Block B, if A is found. chkKey_loopBonly( &chk_data, k_sector, found, §orcnt, &foundkeys); - + chk_data.keyType = 1; chkKey_scanB(&chk_data, k_sector, found, §orcnt, &foundkeys); - - chk_data.keyType = 0; + + chk_data.keyType = 0; chk_data.block = FirstBlockOfSector( s ); - + if ( use_flashmem ) { - if ( lastpos != i && lastpos != 0) { + if ( lastpos != i && lastpos != 0) { if ( i - lastpos < 0xF) { s_point = i & 0xFFF0; } } else { - lastpos = i; + lastpos = i; } } } } - - // skip already found B keys + + // skip already found B keys if( !found[(s*2)+1] ) { chk_data.keyType = 1; status = chkKey( &chk_data); @@ -1364,25 +1364,25 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da memcpy(k_sector[s].keyB, datain + i * 6, 6); found[(s*2)+1] = 1; ++foundkeys; - + chkKey_scanB(&chk_data, k_sector, found, §orcnt, &foundkeys); - if ( use_flashmem ) { + if ( use_flashmem ) { if ( lastpos != i && lastpos != 0) { - + if ( i - lastpos < 0xF) s_point = i & 0xFFF0; } else { - lastpos = i; + lastpos = i; } } } } - + if ( found[(s*2)] && found[(s*2)+1] ) break; - - } // end keys test loop - depth first + + } // end keys test loop - depth first // assume1. if no keys found in first sector, get next keychunk from client if ( !use_flashmem && (newfound-foundkeys == 0) ) @@ -1390,41 +1390,41 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da } // end loop - sector } // end strategy 1 - - if ( foundkeys == allkeys ) + + if ( foundkeys == allkeys ) goto OUT; if ( strategy == 2 || use_flashmem ) { - + // Keychunk loop for (uint16_t i = 0; i < keyCount; i++) { - + // Allow button press / usb cmd to interrupt device if (BUTTON_PRESS() && !usb_poll_validate_length()) break; // found all keys? if ( foundkeys == allkeys ) goto OUT; - + WDT_HIT(); - + // new key chk_data.key = bytes_to_num(datain + i * 6, 6); - + // Sector main loop // keep track of how many sectors on card. for (uint8_t s = 0; s < sectorcnt; ++s) { - + if ( found[(s*2)] && found[(s*2)+1] ) continue; - + // found all keys? if ( foundkeys == allkeys ) goto OUT; // assume: block0,1,2 has more read rights in accessbits than the sectortrailer. authenticating against block0 in each sector chk_data.block = FirstBlockOfSector( s ); - - // skip already found A keys + + // skip already found A keys if( !found[(s*2)] ) { chk_data.keyType = 0; status = chkKey( &chk_data); @@ -1432,17 +1432,17 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da memcpy(k_sector[s].keyA, datain + i * 6, 6); found[(s*2)] = 1; ++foundkeys; - + chkKey_scanA( &chk_data, k_sector, found, §orcnt, &foundkeys); - + // read Block B, if A is found. chkKey_loopBonly( &chk_data, k_sector, found, §orcnt, &foundkeys); chk_data.block = FirstBlockOfSector( s ); } } - - // skip already found B keys + + // skip already found B keys if( !found[(s*2)+1] ) { chk_data.keyType = 1; status = chkKey( &chk_data); @@ -1450,12 +1450,12 @@ void MifareChkKeys_fast(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *da memcpy(k_sector[s].keyB, datain + i * 6, 6); found[(s*2)+1] = 1; ++foundkeys; - + chkKey_scanB(&chk_data, k_sector, found, §orcnt, &foundkeys); } } - } // end loop sectors - } // end loop keys + } // end loop sectors + } // end loop keys } // end loop strategy 2 OUT: LEDsoff(); @@ -1475,16 +1475,16 @@ OUT: for (uint8_t m=64; m < sizeof(found); m++) { bar |= ((uint16_t)(found[m] & 1) << j++); } - + uint8_t *tmp = BigBuf_malloc(480+10); memcpy(tmp, k_sector, sectorcnt * sizeof(sector_t) ); - num_to_bytes(foo, 8, tmp+480); + num_to_bytes(foo, 8, tmp+480); tmp[488] = bar & 0xFF; tmp[489] = bar >> 8 & 0xFF; - + cmd_send(CMD_ACK, foundkeys, 0, 0, tmp, 480+10); - set_tracing(false); + set_tracing(false); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); BigBuf_free(); BigBuf_Clear_ext(false); } else { @@ -1509,26 +1509,26 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { uint8_t blockNo = arg0 & 0xFF; uint8_t keyType = (arg0 >> 8) & 0xFF; uint8_t keyCount = arg2; - uint8_t cascade_levels = 0; + uint8_t cascade_levels = 0; uint8_t isOK = 0; bool have_uid = false; bool clearTrace = arg1 & 0xFF; - + LEDsoff(); LED_A_ON(); - + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - if (clearTrace) + if (clearTrace) clear_trace(); - + set_tracing(true); - + for (i = 0; i < keyCount; i++) { // Iceman: use piwi's faster nonce collecting part in hardnested. if (!have_uid) { // need a full select cycle to get the uid first - iso14a_card_select_t card_info; + iso14a_card_select_t card_info; if (!iso14443a_select_card(uid, &card_info, &cuid, true, 0, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Can't select card (ALL)"); --i; // try same key once again @@ -1540,7 +1540,7 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { case 10: cascade_levels = 3; break; default: break; } - have_uid = true; + have_uid = true; } else { // no need for anticollision. We can directly select the card if (!iso14443a_select_card(uid, NULL, NULL, false, cascade_levels, true)) { if (MF_DBGLEVEL >= 1) Dbprintf("ChkKeys: Can't select card (UID)"); @@ -1548,7 +1548,7 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { continue; } } - + key = bytes_to_num(datain + i * 6, 6); res = mifare_classic_auth(pcs, cuid, blockNo, keyType, key, AUTH_FIRST); @@ -1560,20 +1560,20 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { isOK = 1; break; } - + LED_B_ON(); cmd_send(CMD_ACK, isOK, 0, 0, datain + i * 6, 6); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); - + set_tracing(false); crypto1_destroy(pcs); } //----------------------------------------------------------------------------- // MIFARE commands set debug level -// +// //----------------------------------------------------------------------------- void MifareSetDbgLvl(uint16_t arg0){ MF_DBGLEVEL = arg0; @@ -1582,7 +1582,7 @@ void MifareSetDbgLvl(uint16_t arg0){ //----------------------------------------------------------------------------- // Work with emulator memory -// +// // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not // involved in dealing with emulator memory. But if it is called later, it might // destroy the Emulator Memory. @@ -1611,7 +1611,7 @@ void MifareEMemGet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain) //----------------------------------------------------------------------------- // Load a card into the emulator memory -// +// //----------------------------------------------------------------------------- void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ uint8_t numSectors = arg0; @@ -1631,17 +1631,17 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_B_OFF(); LED_C_OFF(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + clear_trace(); set_tracing(true); - + bool isOK = true; if(!iso14443a_select_card(uid, NULL, &cuid, true, 0, true)) { isOK = false; if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); } - + for (uint8_t sectorNo = 0; isOK && sectorNo < numSectors; sectorNo++) { ui64Key = emlGetKey(sectorNo, keyType); if (sectorNo == 0){ @@ -1657,7 +1657,7 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai break; } } - + for (uint8_t blockNo = 0; isOK && blockNo < NumBlocksPerSector(sectorNo); blockNo++) { if(isOK && mifare_classic_readblock(pcs, cuid, FirstBlockOfSector(sectorNo) + blockNo, dataoutbuf)) { isOK = false; @@ -1686,7 +1686,7 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); - + if (MF_DBGLEVEL >= 2) DbpString("EMUL FILL SECTORS FINISHED"); set_tracing(false); @@ -1695,7 +1695,7 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai //----------------------------------------------------------------------------- // Work with "magic Chinese" card (email him: ouyangweidaxian@live.cn) -// +// // PARAMS - workFlags // bit 0 - need get UID // bit 1 - need wupC @@ -1706,26 +1706,26 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai // bit 6 - wipe tag. //----------------------------------------------------------------------------- // magic uid card generation 1 commands -uint8_t wupC1[] = { MIFARE_MAGICWUPC1 }; -uint8_t wupC2[] = { MIFARE_MAGICWUPC2 }; -uint8_t wipeC[] = { MIFARE_MAGICWIPEC }; - +uint8_t wupC1[] = { MIFARE_MAGICWUPC1 }; +uint8_t wupC2[] = { MIFARE_MAGICWUPC2 }; +uint8_t wipeC[] = { MIFARE_MAGICWIPEC }; + void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ - + // params uint8_t workFlags = arg0; uint8_t blockNo = arg1; // detect 1a/1b bool is1b = false; - + // variables bool isOK = false; //assume we will get an error uint8_t errormsg = 0x00; uint8_t uid[10] = {0x00}; uint8_t data[18] = {0x00}; uint32_t cuid = 0; - + uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00}; @@ -1748,7 +1748,7 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ mifare_classic_halt_ex(NULL); break; } - + // wipe tag, fill it with zeros if (workFlags & MAGIC_WIPE){ ReaderTransmitBitsPar(wupC1, 7, NULL, NULL); @@ -1766,7 +1766,7 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ } mifare_classic_halt_ex(NULL); - } + } // write block if (workFlags & MAGIC_WUPC) { @@ -1792,24 +1792,24 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ errormsg = 4; break; } - + memcpy(data, datain, 16); AddCrc14A(data, 16); - + ReaderTransmit(data, sizeof(data), NULL); if ((ReaderReceive(receivedAnswer, receivedAnswerPar) != 1) || (receivedAnswer[0] != 0x0a)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("write block send data error"); errormsg = 0; break; - } - - if (workFlags & MAGIC_HALT) + } + + if (workFlags & MAGIC_HALT) mifare_classic_halt_ex(NULL); - + isOK = true; break; - } // end while + } // end while if (isOK ) cmd_send(CMD_ACK,1,0,0,uid,sizeof(uid)); @@ -1821,26 +1821,26 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ } void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ - + uint8_t workFlags = arg0; uint8_t blockNo = arg1; uint8_t errormsg = 0x00; bool isOK = false; //assume we will get an error - + // detect 1a/1b bool is1b = false; - + // variables uint8_t data[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00}; - + memset(data, 0x00, sizeof(data)); - + if (workFlags & MAGIC_INIT) { LED_A_ON(); LED_B_OFF(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(true); } @@ -1861,19 +1861,19 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ if (MF_DBGLEVEL >= MF_DBG_ALL) Dbprintf("Assuming Magic Gen 1B tag. [wupC2 failed]"); is1b = true; continue; - } + } } } - // read block + // read block if ((mifare_sendcmd_short(NULL, 0, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL) != 18)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("read block send command error"); errormsg = 0; break; } - + memcpy(data, receivedAnswer, sizeof(data)); - + // send HALT if (workFlags & MAGIC_HALT) mifare_classic_halt_ex(NULL); @@ -1886,12 +1886,12 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint8_t *datain){ if (isOK) memcpy(datain, data, sizeof(data)); } else { - if (isOK) - cmd_send(CMD_ACK,1,0,0,data,sizeof(data)); - else - OnErrorMagic(errormsg); + if (isOK) + cmd_send(CMD_ACK,1,0,0,data,sizeof(data)); + else + OnErrorMagic(errormsg); } - + if (workFlags & MAGIC_OFF) OnSuccessMagic(); } @@ -1906,18 +1906,18 @@ void MifareCIdent(){ uint8_t recpar[1] = {0x00}; iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - + // Generation 1 test ReaderTransmitBitsPar(wupC1, 7, NULL, NULL); if(!ReaderReceive(rec, recpar) || (rec[0] != 0x0a)) { goto TEST2; }; isGen = GEN_1B; - + ReaderTransmit(wupC2, sizeof(wupC2), NULL); if(!ReaderReceive(rec, recpar) || (rec[0] != 0x0a)) { goto OUT; - }; + }; isGen = GEN_1A; goto OUT; @@ -1927,17 +1927,17 @@ TEST2:; // halt previous. mifare_classic_halt(NULL, 0); - + //select if (!iso14443a_select_card(NULL, NULL, NULL, true, 0, true)) { goto OUT; }; - + // MIFARE_CLASSIC_WRITEBLOCK 0xA0 // ACK 0x0a uint16_t len = mifare_sendcmd_short(null, 1, 0xA0, 0, rec, recpar, NULL); - if ((len != 1) || (rec[0] != 0x0A)) { - isGen = GEN_2; + if ((len != 1) || (rec[0] != 0x0A)) { + isGen = GEN_2; }; */ OUT:; @@ -1951,7 +1951,7 @@ OUT:; void OnSuccessMagic(){ FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); - set_tracing(false); + set_tracing(false); } void OnErrorMagic(uint8_t reason){ // ACK, ISOK, reason,0,0,0 @@ -2023,7 +2023,7 @@ void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain){ byte_t dataout[12] = {0x00}; uint8_t uid[10] = {0x00}; uint32_t cuid = 0; - + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(true); @@ -2050,13 +2050,13 @@ void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain){ uint8_t key[16] = {0x00}; byte_t dataout[12] = {0x00}; byte_t isOK = 0; - + memcpy(key, datain, 16); - + isOK = mifare_desfire_des_auth2(cuid, key, dataout); - + if( isOK) { - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Authentication part2: Failed"); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Authentication part2: Failed"); OnError(4); return; } diff --git a/armsrc/mifaredesfire.c b/armsrc/mifaredesfire.c index 81a29578b..4cafca16c 100644 --- a/armsrc/mifaredesfire.c +++ b/armsrc/mifaredesfire.c @@ -19,7 +19,7 @@ static uint8_t deselect_cmd[] = {0xc2,0xe0,0xb4}; bool InitDesfireCard(){ iso14a_card_select_t card; - + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); set_tracing(true); @@ -41,7 +41,7 @@ enum { } CmdOptions ; void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain){ - + /* ARG0 contains flags. 0x01 = init card. 0x02 = Disconnect @@ -51,21 +51,21 @@ void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain){ size_t datalen = arg1; uint8_t resp[RECEIVE_SIZE]; memset(resp,0,sizeof(resp)); - + if (MF_DBGLEVEL >= 4) { Dbprintf(" flags : %02X", flags); Dbprintf(" len : %02X", datalen); print_result(" RX : ", datain, datalen); } - + if ( flags & CLEARTRACE ) clear_trace(); - + if ( flags & INIT ){ if ( !InitDesfireCard() ) return; } - + int len = DesfireAPDU(datain, datalen, resp); if (MF_DBGLEVEL >= 4) print_result("ERR <--: ", resp, len); @@ -74,31 +74,31 @@ void MifareSendCommand(uint8_t arg0, uint8_t arg1, uint8_t *datain){ OnError(2); return; } - + // reset the pcb_blocknum, pcb_blocknum = 0; - + if ( flags & DISCONNECT ) OnSuccess(); - + cmd_send(CMD_ACK,1,len,0,resp,len); } void MifareDesfireGetInformation(){ - + int len = 0; iso14a_card_select_t card; uint8_t resp[USB_CMD_DATA_SIZE] = {0x00}; uint8_t dataout[USB_CMD_DATA_SIZE] = {0x00}; - + /* 1 = PCB 1 2 = cid 2 - 3 = desfire command 3 + 3 = desfire command 3 4-5 = crc 4 key - 5-6 crc + 5-6 crc PCB == 0x0A because sending CID byte. - CID == 0x00 first card? + CID == 0x00 first card? */ clear_trace(); set_tracing(true); @@ -110,42 +110,42 @@ void MifareDesfireGetInformation(){ OnError(1); return; } - + if ( card.uidlen != 7 ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Wrong UID size. Expected 7byte got %d", card.uidlen); OnError(2); - return; + return; } - + memcpy(dataout, card.uid, 7); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - - uint8_t cmd[] = {GET_VERSION}; + + uint8_t cmd[] = {GET_VERSION}; size_t cmd_len = sizeof(cmd); - + len = DesfireAPDU(cmd, cmd_len, resp); if ( !len ) { - print_result("ERROR <--: ", resp, len); + print_result("ERROR <--: ", resp, len); OnError(3); return; } - + LED_A_OFF(); LED_B_ON(); memcpy(dataout+7,resp+3,7); - + // ADDITION_FRAME 1 cmd[0] = ADDITIONAL_FRAME; len = DesfireAPDU(cmd, cmd_len, resp); if ( !len ) { - print_result("ERROR <--: ", resp, len); + print_result("ERROR <--: ", resp, len); OnError(3); return; - } - + } + LED_B_OFF(); LED_C_ON(); memcpy(dataout+7+7,resp+3,7); @@ -153,15 +153,15 @@ void MifareDesfireGetInformation(){ // ADDITION_FRAME 2 len = DesfireAPDU(cmd, cmd_len, resp); if ( !len ) { - print_result("ERROR <--: ", resp, len); + print_result("ERROR <--: ", resp, len); OnError(3); return; } - + memcpy(dataout+7+7+7,resp+3,14); - + cmd_send(CMD_ACK,1,0,0,dataout,sizeof(dataout)); - + // reset the pcb_blocknum, pcb_blocknum = 0; OnSuccess(); @@ -173,7 +173,7 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain //uint8_t PICC_MASTER_KEY8[8] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47}; uint8_t PICC_MASTER_KEY16[16] = { 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f }; uint8_t null_key_data8[8] = {0x00}; - //uint8_t null_key_data16[16] = {0x00}; + //uint8_t null_key_data16[16] = {0x00}; //uint8_t new_key_data8[8] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; //uint8_t new_key_data16[16] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF}; @@ -181,7 +181,7 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain uint8_t IV[16] = {0x00}; size_t datalen = datain[0]; - + uint8_t cmd[40] = {0x00}; uint8_t encRndB[16] = {0x00}; uint8_t decRndB[16] = {0x00}; @@ -190,22 +190,22 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain uint8_t encBoth[32] = {0x00}; InitDesfireCard(); - + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - + // 3 olika sätt att authenticera. AUTH (CRC16) , AUTH_ISO (CRC32) , AUTH_AES (CRC32) // 4 olika crypto algo DES, 3DES, 3K3DES, AES // 3 olika kommunikations sätt, PLAIN,MAC,CRYPTO - - // des, nyckel 0, + + // des, nyckel 0, switch (mode){ case 1:{ uint8_t keybytes[16]; uint8_t RndA[8] = {0x00}; uint8_t RndB[8] = {0x00}; - + if (algo == 2) { if (datain[1] == 0xff){ memcpy(keybytes,PICC_MASTER_KEY16,16); @@ -221,15 +221,15 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain } } } - + struct desfire_key defaultkey = {0}; desfirekey_t key = &defaultkey; - + if (algo == 2) Desfire_3des_key_new_with_version(keybytes, key); else if (algo ==1) Desfire_des_key_new(keybytes, key); - + cmd[0] = AUTHENTICATE; cmd[1] = keyno; //keynumber len = DesfireAPDU(cmd, 2, resp); @@ -240,50 +240,50 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain OnError(3); return; } - + if ( resp[2] == 0xaf ){ } else { DbpString("Authentication failed. Invalid key number."); OnError(3); return; } - + memcpy( encRndB, resp+3, 8); if (algo == 2) tdes_dec(&decRndB, &encRndB, key->data); else if (algo == 1) des_dec(&decRndB, &encRndB, key->data); - + memcpy(RndB, decRndB, 8); rol(decRndB,8); - + // This should be random uint8_t decRndA[8] = {0x00}; memcpy(RndA, decRndA, 8); uint8_t encRndA[8] = {0x00}; - + if (algo == 2) tdes_dec(&encRndA, &decRndA, key->data); else if (algo == 1) des_dec(&encRndA, &decRndA, key->data); - + memcpy(both, encRndA, 8); - + for (int x = 0; x < 8; x++) { decRndB[x] = decRndB[x] ^ encRndA[x]; - + } - + if (algo == 2) tdes_dec(&encRndB, &decRndB, key->data); else if (algo == 1) des_dec(&encRndB, &decRndB, key->data); - + memcpy(both + 8, encRndB, 8); - + cmd[0] = ADDITIONAL_FRAME; memcpy(cmd+1, both, 16 ); - + len = DesfireAPDU(cmd, 17, resp); if ( !len ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) { @@ -292,21 +292,21 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain OnError(3); return; } - + if ( resp[2] == 0x00 ){ - + struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; Desfire_session_key_new( RndA, RndB , key, skey ); //print_result("SESSION : ", skey->data, 8); - + memcpy(encRndA, resp+3, 8); - + if (algo == 2) tdes_dec(&encRndA, &encRndA, key->data); else if (algo == 1) des_dec(&encRndA, &encRndA, key->data); - + rol(decRndA,8); for (int x = 0; x < 8; x++) { if (decRndA[x] != encRndA[x]) { @@ -315,86 +315,86 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain return; } } - + //Change the selected key to a new value. /* - + // Current key is a 3DES key, change it to a DES key if (algo == 2) { cmd[0] = CHANGE_KEY; cmd[1] = keyno; - + uint8_t newKey[16] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77}; - + uint8_t first, second; uint8_t buff1[8] = {0x00}; uint8_t buff2[8] = {0x00}; uint8_t buff3[8] = {0x00}; - + memcpy(buff1,newKey, 8); memcpy(buff2,newKey + 8, 8); - + compute_crc(CRC_14443_A, newKey, 16, &first, &second); memcpy(buff3, &first, 1); memcpy(buff3 + 1, &second, 1); - + tdes_dec(&buff1, &buff1, skey->data); memcpy(cmd+2,buff1,8); - + for (int x = 0; x < 8; x++) { buff2[x] = buff2[x] ^ buff1[x]; } tdes_dec(&buff2, &buff2, skey->data); memcpy(cmd+10,buff2,8); - + for (int x = 0; x < 8; x++) { buff3[x] = buff3[x] ^ buff2[x]; } tdes_dec(&buff3, &buff3, skey->data); memcpy(cmd+18,buff3,8); - + // The command always times out on the first attempt, this will retry until a response // is recieved. len = 0; while(!len) { len = DesfireAPDU(cmd,26,resp); } - + } else { // Current key is a DES key, change it to a 3DES key if (algo == 1) { cmd[0] = CHANGE_KEY; cmd[1] = keyno; - + uint8_t newKey[16] = {0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f}; - + uint8_t first, second; uint8_t buff1[8] = {0x00}; uint8_t buff2[8] = {0x00}; uint8_t buff3[8] = {0x00}; - + memcpy(buff1,newKey, 8); memcpy(buff2,newKey + 8, 8); - + compute_crc(CRC_14443_A, newKey, 16, &first, &second); memcpy(buff3, &first, 1); memcpy(buff3 + 1, &second, 1); - + des_dec(&buff1, &buff1, skey->data); memcpy(cmd+2,buff1,8); - + for (int x = 0; x < 8; x++) { buff2[x] = buff2[x] ^ buff1[x]; } des_dec(&buff2, &buff2, skey->data); memcpy(cmd+10,buff2,8); - + for (int x = 0; x < 8; x++) { buff3[x] = buff3[x] ^ buff2[x]; } des_dec(&buff3, &buff3, skey->data); memcpy(cmd+18,buff3,8); - + // The command always times out on the first attempt, this will retry until a response // is recieved. len = 0; @@ -404,7 +404,7 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain } } */ - + OnSuccess(); if (algo == 2) cmd_send(CMD_ACK,1,0,0,skey->data,16); @@ -421,19 +421,19 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain //SendDesfireCommand(AUTHENTICATE_ISO, &keyno, resp); break; case 3:{ - + //defaultkey uint8_t keybytes[16] = {0x00}; if (datain[1] == 0xff){ - memcpy(keybytes,PICC_MASTER_KEY16,16); + memcpy(keybytes,PICC_MASTER_KEY16,16); } else{ memcpy(keybytes, datain+1, datalen); } - + struct desfire_key defaultkey = {0x00}; desfirekey_t key = &defaultkey; Desfire_aes_key_new( keybytes, key); - + AesCtx ctx; if ( AesCtxIni(&ctx, IV, key->data, KEY128, CBC) < 0 ){ if( MF_DBGLEVEL >= 4) { @@ -442,7 +442,7 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain OnError(7); return; } - + cmd[0] = AUTHENTICATE_AES; cmd[1] = 0x00; //keynumber len = DesfireAPDU(cmd, 2, resp); @@ -453,19 +453,19 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain OnError(3); return; } - + memcpy( encRndB, resp+3, 16); - + // dekryptera tagnonce. AesDecrypt(&ctx, encRndB, decRndB, 16); rol(decRndB,16); memcpy(both, nonce,16); memcpy(both+16, decRndB ,16 ); AesEncrypt(&ctx, both, encBoth, 32 ); - + cmd[0] = ADDITIONAL_FRAME; memcpy(cmd+1, encBoth, 32 ); - + len = DesfireAPDU(cmd, 33, resp); // 1 + 32 == 33 if ( !len ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) { @@ -474,9 +474,9 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain OnError(3); return; } - + if ( resp[2] == 0x00 ){ - // Create AES Session key + // Create AES Session key struct desfire_key sessionKey = {0}; desfirekey_t skey = &sessionKey; Desfire_session_key_new( nonce, decRndB , key, skey ); @@ -486,11 +486,11 @@ void MifareDES_Auth1(uint8_t mode, uint8_t algo, uint8_t keyno, uint8_t *datain OnError(7); return; } - + break; - } + } } - + OnSuccess(); cmd_send(CMD_ACK,1,len,0,resp,len); } @@ -506,11 +506,11 @@ int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout){ uint8_t wCmd[USB_CMD_DATA_SIZE] = {0x00}; uint8_t resp[MAX_FRAME_SIZE]; uint8_t par[MAX_PARITY_SIZE]; - + wrappedLen = CreateAPDU( cmd, cmd_len, wCmd); - + if (MF_DBGLEVEL >= 4) - print_result("WCMD <--: ", wCmd, wrappedLen); + print_result("WCMD <--: ", wCmd, wrappedLen); ReaderTransmit( wCmd, wrappedLen, NULL); @@ -526,30 +526,30 @@ int DesfireAPDU(uint8_t *cmd, size_t cmd_len, uint8_t *dataout){ || (resp[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0 && (resp[0] & 0x01) == pcb_blocknum) // equal block numbers { - pcb_blocknum ^= 1; //toggle next block + pcb_blocknum ^= 1; //toggle next block } memcpy(dataout, resp, len); return len; -} +} // CreateAPDU size_t CreateAPDU( uint8_t *datain, size_t len, uint8_t *dataout){ - + size_t cmdlen = MIN(len+4, USB_CMD_DATA_SIZE-1); uint8_t cmd[cmdlen]; memset(cmd, 0, cmdlen); - + cmd[0] = 0x0A; // 0x0A = skicka cid, 0x02 = ingen cid. Särskilda bitar // - cmd[0] |= pcb_blocknum; // OR the block number into the PCB + cmd[0] |= pcb_blocknum; // OR the block number into the PCB cmd[1] = 0x00; // CID: 0x00 //TODO: allow multiple selected cards - + memcpy(cmd+2, datain, len); AddCrc14A(cmd, len+2); - + memcpy(dataout, cmd, cmdlen); - + return cmdlen; } @@ -562,7 +562,7 @@ void OnSuccess(){ pcb_blocknum = 0; ReaderTransmit(deselect_cmd, 3 , NULL); mifare_ultra_halt(); - switch_off(); + switch_off(); } void OnError(uint8_t reason){ diff --git a/armsrc/mifaresniff.c b/armsrc/mifaresniff.c index e832c76cf..43e416086 100644 --- a/armsrc/mifaresniff.c +++ b/armsrc/mifaresniff.c @@ -19,8 +19,8 @@ static uint8_t sniffBuf[17]; static uint32_t timerData = 0; //----------------------------------------------------------------------------- -// MIFARE sniffer. -// +// MIFARE sniffer. +// // if no activity for 2sec, it sends the collected data to the client. //----------------------------------------------------------------------------- // "hf mf sniff" @@ -32,7 +32,7 @@ void RAMFUNC SniffMifare(uint8_t param) { // C(red) A(yellow) B(green) LEDsoff(); iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - + // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); BigBuf_Clear_ext(false); @@ -40,7 +40,7 @@ void RAMFUNC SniffMifare(uint8_t param) { set_tracing(true); // The command (reader -> tag) that we're receiving. - uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00}; + uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t receivedCmdPar[MAX_MIFARE_PARITY_SIZE] = {0x00}; // The response (tag -> reader) that we're receiving. @@ -60,9 +60,9 @@ void RAMFUNC SniffMifare(uint8_t param) { // a good trigger condition to get started is probably when we see a // response from the tag. // triggered == false -- to wait first for card - //bool triggered = !(param & 0x03); - - + //bool triggered = !(param & 0x03); + + // Set up the demodulator for tag -> reader responses. DemodInit(receivedResp, receivedRespPar); @@ -72,15 +72,15 @@ void RAMFUNC SniffMifare(uint8_t param) { // Setup and start DMA. // set transfer address and number of bytes. Start transfer. if ( !FpgaSetupSscDma(dmaBuf, DMA_BUFFER_SIZE) ){ - if (MF_DBGLEVEL > 1) Dbprintf("[!] FpgaSetupSscDma failed. Exiting"); + if (MF_DBGLEVEL > 1) Dbprintf("[!] FpgaSetupSscDma failed. Exiting"); return; } tUart* uart = GetUart(); tDemod* demod = GetDemod(); - + MfSniffInit(); - + uint32_t sniffCounter = 0; // loop and listen while (!BUTTON_PRESS()) { @@ -93,7 +93,7 @@ void RAMFUNC SniffMifare(uint8_t param) { if (BigBuf_get_traceLen()) { MfSniffSend(); // Reset everything - we missed some sniffed data anyway while the DMA was stopped - sniffCounter = 0; + sniffCounter = 0; dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); data = dmaBuf; maxDataLen = 0; @@ -103,10 +103,10 @@ void RAMFUNC SniffMifare(uint8_t param) { } } */ - - // number of bytes we have processed so far - int register readBufDataP = data - dmaBuf; - // number of bytes already transferred + + // number of bytes we have processed so far + int register readBufDataP = data - dmaBuf; + // number of bytes already transferred int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR; if (readBufDataP <= dmaBufDataP) // we are processing the same block of data which is currently being transferred dataLen = dmaBufDataP - readBufDataP; // number of bytes still to be processed @@ -115,9 +115,9 @@ void RAMFUNC SniffMifare(uint8_t param) { // test for length of buffer if (dataLen > maxDataLen) { // we are more behind than ever... - maxDataLen = dataLen; + maxDataLen = dataLen; if (dataLen > (9 * DMA_BUFFER_SIZE / 10)) { - Dbprintf("[!] blew circular buffer! | datalen %u", dataLen); + Dbprintf("[!] blew circular buffer! | datalen %u", dataLen); break; } } @@ -141,7 +141,7 @@ void RAMFUNC SniffMifare(uint8_t param) { if (sniffCounter & 0x01) { // no need to try decoding tag data if the reader is sending - if (!TagIsActive) { + if (!TagIsActive) { uint8_t readerbyte = (previous_data & 0xF0) | (*data >> 4); if (MillerDecoding(readerbyte, (sniffCounter-1)*4)) { LogTrace(receivedCmd, uart->len, 0, 0, NULL, true); @@ -150,9 +150,9 @@ void RAMFUNC SniffMifare(uint8_t param) { } ReaderIsActive = (uart->state != STATE_UNSYNCD); } - + // no need to try decoding tag data if the reader is sending - if (!ReaderIsActive) { + if (!ReaderIsActive) { uint8_t tagbyte = (previous_data << 4) | (*data & 0x0F); if (ManchesterDecoding(tagbyte, 0, (sniffCounter-1)*4)) { LogTrace(receivedResp, demod->len, 0, 0, NULL, false); @@ -170,9 +170,9 @@ void RAMFUNC SniffMifare(uint8_t param) { data = dmaBuf; } // main cycle - + MfSniffEnd(); - switch_off(); + switch_off(); } void MfSniffInit(void){ @@ -194,15 +194,15 @@ void MfSniffEnd(void){ bool RAMFUNC MfSniffLogic(const uint8_t *data, uint16_t len, uint8_t *parity, uint16_t bitCnt, bool reader) { // reset on 7-Bit commands from reader - if (reader && (len == 1) && (bitCnt == 7)) { + if (reader && (len == 1) && (bitCnt == 7)) { sniffState = SNF_INIT; } - - + + switch (sniffState) { case SNF_INIT:{ - // REQA,WUPA or MAGICWUP from reader + // REQA,WUPA or MAGICWUP from reader if ((len == 1) && (reader) && (bitCnt == 7) ) { MfSniffInit(); sniffState = (data[0] == MIFARE_MAGICWUPC1) ? SNF_MAGIC_WUPC2 : SNF_ATQA; @@ -210,7 +210,7 @@ bool RAMFUNC MfSniffLogic(const uint8_t *data, uint16_t len, uint8_t *parity, ui break; } case SNF_MAGIC_WUPC2: { - if ((len == 1) && (reader) && (data[0] == MIFARE_MAGICWUPC2) ) { + if ((len == 1) && (reader) && (data[0] == MIFARE_MAGICWUPC2) ) { sniffState = SNF_CARD_IDLE; } break; @@ -225,14 +225,14 @@ bool RAMFUNC MfSniffLogic(const uint8_t *data, uint16_t len, uint8_t *parity, ui break; } case SNF_UID: { - + if ( !reader ) break; if ( len != 9 ) break; if ( !CheckCrc14443(CRC_14443_A, data, 9)) break; if ( data[1] != 0x70 ) break; - + Dbprintf("[!] UID | %x", data[0]); - + if ((data[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT)) { // UID_4 - select 4 Byte UID from reader memcpy(sniffUID, data+2, 4); @@ -248,7 +248,7 @@ bool RAMFUNC MfSniffLogic(const uint8_t *data, uint16_t len, uint8_t *parity, ui //new uid bytes memcpy(sniffUID+3, data+2, 4); sniffUIDType = SNF_UID_7; - sniffState = SNF_SAK; + sniffState = SNF_SAK; } else if ((data[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3)) { // UID_10 - Select 3nd part of 10 Byte UID // 3+3+4 = 10. @@ -279,7 +279,7 @@ bool RAMFUNC MfSniffLogic(const uint8_t *data, uint16_t len, uint8_t *parity, ui } } break; - } + } case SNF_CARD_IDLE:{ // trace the card select sequence sniffBuf[0] = 0xFF; sniffBuf[1] = 0xFF; @@ -291,11 +291,11 @@ bool RAMFUNC MfSniffLogic(const uint8_t *data, uint16_t len, uint8_t *parity, ui LogTrace(sniffBuf, sizeof(sniffBuf), 0, 0, NULL, true); sniffState = SNF_CARD_CMD; } // intentionally no break; - case SNF_CARD_CMD:{ - LogTrace(data, len, 0, 0, NULL, reader); + case SNF_CARD_CMD:{ + LogTrace(data, len, 0, 0, NULL, reader); timerData = GetTickCount(); break; - } + } default: sniffState = SNF_INIT; break; @@ -308,12 +308,12 @@ void RAMFUNC MfSniffSend() { uint16_t tracelen = BigBuf_get_traceLen(); uint16_t chunksize = 0; int packlen = tracelen; // total number of bytes to send - uint8_t *data = BigBuf_get_addr(); - + uint8_t *data = BigBuf_get_addr(); + while (packlen > 0) { LED_B_ON(); chunksize = MIN(USB_CMD_DATA_SIZE, packlen); // chunk size 512 - cmd_send(CMD_ACK, 1, tracelen, chunksize, data + tracelen - packlen, chunksize); + cmd_send(CMD_ACK, 1, tracelen, chunksize, data + tracelen - packlen, chunksize); packlen -= chunksize; LED_B_OFF(); } diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index df85f6cbd..86048ae88 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -16,7 +16,7 @@ int MF_DBGLEVEL = MF_DBG_ERROR; void mf_crypto1_decryptEx(struct Crypto1State *pcs, uint8_t *data_in, int len, uint8_t *data_out){ uint8_t bt = 0; int i; - + if (len != 1) { for (i = 0; i < len; i++) data_out[i] = crypto1_byte(pcs, 0x00, 0) ^ data_in[i]; @@ -38,14 +38,14 @@ void mf_crypto1_encrypt(struct Crypto1State *pcs, uint8_t *data, uint16_t len, u uint8_t bt = 0; int i; par[0] = 0; - + for (i = 0; i < len; i++) { bt = data[i]; data[i] = crypto1_byte(pcs, 0x00, 0) ^ data[i]; - if ( ( i & 0x0007 ) == 0) + if ( ( i & 0x0007 ) == 0) par[ i >> 3 ] = 0; par[ i >> 3 ] |= (((filter(pcs->odd) ^ oddparity8(bt)) & 0x01)<<(7-(i&0x0007))); - } + } } uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) { @@ -80,22 +80,22 @@ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t par[1] = {0x00}; // 1 Byte parity is enough here AddCrc14A(dcmd, 2); memcpy(ecmd, dcmd, sizeof(dcmd)); - + if (crypted) { par[0] = 0; for (pos = 0; pos < 4; pos++) { ecmd[pos] = crypto1_byte(pcs, 0x00, 0) ^ dcmd[pos]; par[0] |= (((filter(pcs->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7-pos)); - } + } ReaderTransmitPar(ecmd, sizeof(ecmd), par, timing); } else { ReaderTransmit(dcmd, sizeof(dcmd), timing); } int len = ReaderReceive(answer, par); - + if (answer_parity) *answer_parity = par[0]; - + if (crypted == CRYPT_ALL) { if (len == 1) { res = 0; @@ -103,7 +103,7 @@ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 1)) << 1; res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 2)) << 2; res |= (crypto1_bit(pcs, 0, 0) ^ BIT(answer[0], 3)) << 3; - answer[0] = res; + answer[0] = res; } else { for (pos = 0; pos < len; pos++) answer[pos] = crypto1_byte(pcs, 0x00, 0) ^ answer[pos]; @@ -118,7 +118,7 @@ int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, } int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *ntptr, uint32_t *timing) { - int len; + int len; uint32_t pos, nt, ntpp; // Supplied tag nonce uint8_t par[1] = {0x00}; uint8_t nr[4]; @@ -128,11 +128,11 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN // "random" reader nonce: num_to_bytes( prng_successor( GetTickCount(), 32), 4, nr); - + // Transmit MIFARE_CLASSIC_AUTH len = mifare_sendcmd_short(pcs, isNested, 0x60 + (keyType & 0x01), blockNo, receivedAnswer, receivedAnswerPar, timing); if (len != 4) return 1; - + // Save the tag nonce (nt) nt = bytes_to_num(receivedAnswer, 4); @@ -144,7 +144,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN crypto1_create(pcs, ui64Key); if (isNested == AUTH_NESTED) { - // decrypt nt with help of new key + // decrypt nt with help of new key nt = crypto1_word(pcs, nt ^ uid, 1) ^ nt; } else { // Load (plain) uid^nt into the cipher @@ -154,7 +154,7 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN // some statistic if (!ntptr && (MF_DBGLEVEL >= MF_DBG_EXTENDED)) Dbprintf("auth uid: %08x | nr: %08x | nt: %08x", uid, nr, nt); - + // save Nt if (ntptr) *ntptr = nt; @@ -164,8 +164,8 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN for (pos = 0; pos < 4; pos++) { mf_nr_ar[pos] = crypto1_byte(pcs, nr[pos], 0) ^ nr[pos]; par[0] |= (((filter(pcs->odd) ^ oddparity8(nr[pos])) & 0x01) << (7-pos)); - } - + } + // Skip 32 bits in pseudo random generator nt = prng_successor(nt, 32); @@ -174,8 +174,8 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN nt = prng_successor(nt,8); mf_nr_ar[pos] = crypto1_byte(pcs,0x00,0) ^ (nt & 0xff); par[0] |= (((filter(pcs->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7-pos)); - } - + } + // Transmit reader nonce and reader answer ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL); @@ -197,28 +197,28 @@ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockN int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) { - int len; - uint8_t bt[2] = {0x00, 0x00}; + int len; + uint8_t bt[2] = {0x00, 0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00}; - + len = mifare_sendcmd_short(pcs, 1, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL); if (len == 1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); return 1; } if (len != 18) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: wrong response len: %x (expected 18)", len); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: wrong response len: %x (expected 18)", len); return 2; } memcpy(bt, receivedAnswer + 16, 2); AddCrc14A(receivedAnswer, 16); if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) { - if (MF_DBGLEVEL >= MF_DBG_ALL) Dbprintf("Cmd CRC response error."); + if (MF_DBGLEVEL >= MF_DBG_ALL) Dbprintf("Cmd CRC response error."); return 3; } - + memcpy(blockData, receivedAnswer, 16); return 0; } @@ -234,7 +234,7 @@ int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); - + len = mifare_sendcmd(MIFARE_ULEV1_AUTH, key, sizeof(key), resp, respPar, NULL); if (len != 4) { @@ -307,7 +307,7 @@ int mifare_ultra_auth(uint8_t *keybytes){ uint8_t resp_random_a[8] = { 0,0,0,0,0,0,0,0 }; memcpy(enc_resp, resp+1, 8); - // decrypt out, in, length, key, iv + // decrypt out, in, length, key, iv tdes_2key_dec(resp_random_a, enc_resp, 8, key, enc_random_b); if ( memcmp(resp_random_a, random_a, 8) != 0 ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("failed authentication"); @@ -315,7 +315,7 @@ int mifare_ultra_auth(uint8_t *keybytes){ } if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { - Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", + Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", rnd_ab[0],rnd_ab[1],rnd_ab[2],rnd_ab[3], rnd_ab[4],rnd_ab[5],rnd_ab[6],rnd_ab[7]); @@ -339,7 +339,7 @@ int mifare_ultra_readblockEx(uint8_t blockNo, uint8_t *blockData) { uint8_t bt[2] = {0x00, 0x00}; uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00}; - + len = mifare_sendcmd_short(NULL, 1, ISO14443A_CMD_READBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL); if (len == 1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); @@ -349,14 +349,14 @@ int mifare_ultra_readblockEx(uint8_t blockNo, uint8_t *blockData) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: card timeout. len: %x", len); return 2; } - + memcpy(bt, receivedAnswer + 16, 2); AddCrc14A(receivedAnswer, 16); if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd CRC response error."); return 3; } - + memcpy(blockData, receivedAnswer, 14); return 0; } @@ -366,7 +366,7 @@ int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) { for (uint8_t retries = 0; retries < MFU_MAX_RETRIES; ++retries) { res = mifare_ultra_readblockEx(blockNo, blockData); - + // break if OK, or NACK. switch ( res ) { case 0: @@ -381,36 +381,36 @@ 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) { // variables - uint16_t len = 0; + uint16_t len = 0; uint32_t pos = 0; uint8_t par[3] = {0x00, 0x00, 0x00}; // enough for 18 Bytes to send byte_t res = 0; - + uint8_t d_block[18], d_block_enc[18]; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00}; - + // command MIFARE_CLASSIC_WRITEBLOCK len = mifare_sendcmd_short(pcs, 1, ISO14443A_CMD_WRITEBLOCK, blockNo, receivedAnswer, receivedAnswerPar, NULL); if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); return 1; } - + memcpy(d_block, blockData, 16); AddCrc14A(d_block, 16); - + // crypto for (pos = 0; pos < 18; pos++) { d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ d_block[pos]; par[pos>>3] |= (((filter(pcs->odd) ^ oddparity8(d_block[pos])) & 0x01) << (7 - (pos&0x0007))); - } + } ReaderTransmitPar(d_block_enc, sizeof(d_block_enc), par, NULL); // Receive the response - len = ReaderReceive(receivedAnswer, receivedAnswerPar); + len = ReaderReceive(receivedAnswer, receivedAnswerPar); res = 0; res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 0)) << 0; @@ -419,7 +419,7 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl res |= (crypto1_bit(pcs, 0, 0) ^ BIT(receivedAnswer[0], 3)) << 3; if ((len != 1) || (res != 0x0A)) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd send data2 Error: %02x", res); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd send data2 Error: %02x", res); return 2; } return 0; @@ -511,7 +511,7 @@ uint8_t FirstBlockOfSector(uint8_t sectorNo) { return sectorNo * 4; else return 32*4 + (sectorNo - 32) * 16; - + } // work with emulator memory @@ -544,7 +544,7 @@ int emlCheckValBl(int blockNum) { (data[3] != (data[7] ^ 0xff)) || (data[3] != data[11]) || (data[12] != (data[13] ^ 0xff)) || (data[12] != data[14]) || (data[12] != (data[15] ^ 0xff)) - ) + ) return 1; return 0; } @@ -552,10 +552,10 @@ int emlCheckValBl(int blockNum) { int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum) { uint8_t* emCARD = BigBuf_get_EM_addr(); uint8_t* data = emCARD + blockNum * 16; - + if (emlCheckValBl(blockNum)) return 1; - + memcpy(blReg, data, 4); *blBlock = data[12]; return 0; @@ -564,17 +564,17 @@ int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum) { int emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum) { uint8_t* emCARD = BigBuf_get_EM_addr(); uint8_t* data = emCARD + blockNum * 16; - + memcpy(data + 0, &blReg, 4); memcpy(data + 8, &blReg, 4); blReg = blReg ^ 0xffffffff; memcpy(data + 4, &blReg, 4); - + data[12] = blBlock; data[13] = blBlock ^ 0xff; data[14] = blBlock; data[15] = blBlock ^ 0xff; - + return 0; } @@ -590,7 +590,7 @@ void emlClearMem(void) { const uint8_t uid[] = {0xe6, 0x84, 0x87, 0xf3, 0x16, 0x88, 0x04, 0x00, 0x46, 0x8e, 0x45, 0x55, 0x4d, 0x70, 0x41, 0x04}; uint8_t* emCARD = BigBuf_get_EM_addr(); memset(emCARD, 0, CARD_MEMORY_SIZE); - + // fill sectors trailer data for(uint16_t b = 3; b < 256; ((b < 127) ? (b += 4) : (b += 16))) emlSetMem((uint8_t *)trailer, b, 1); @@ -605,7 +605,7 @@ void emlClearMem(void) { int mifare_sendcmd_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) { uint8_t dcmd[5] = {cmd, data[0], data[1], 0x00, 0x00}; AddCrc14A(dcmd, 3); - + ReaderTransmit(dcmd, sizeof(dcmd), NULL); int len = ReaderReceive(answer, answer_parity); if(!len) { @@ -637,14 +637,14 @@ int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData){ uint8_t data[2]={MFDES_AUTHENTICATE, 0x00}; uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00}; - + len = mifare_sendcmd_special(NULL, 1, 0x02, data, receivedAnswer,receivedAnswerPar,NULL); if (len == 1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); return 1; } - + if (len == 12) { if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { Dbprintf("Auth1 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", @@ -663,18 +663,18 @@ int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){ int len; uint8_t data[17] = {MFDES_AUTHENTICATION_FRAME}; memcpy(data+1,key,16); - + uint8_t receivedAnswer[MAX_FRAME_SIZE] = {0x00}; uint8_t receivedAnswerPar[MAX_PARITY_SIZE] = {0x00}; - + len = mifare_sendcmd_special2(NULL, 1, 0x03, data, receivedAnswer, receivedAnswerPar ,NULL); - + if ((receivedAnswer[0] == 0x03) && (receivedAnswer[1] == 0xae)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Auth Error: %02x %02x", receivedAnswer[0], receivedAnswer[1]); return 1; } - + if (len == 12){ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { Dbprintf("Auth2 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index 2406f9068..594b7ca80 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -27,7 +27,7 @@ #define CRYPT_NONE 0 #define CRYPT_ALL 1 #define CRYPT_REQUEST 2 -#define AUTH_FIRST 0 +#define AUTH_FIRST 0 #define AUTH_NESTED 2 #define AUTHENTICATION_TIMEOUT 848 // card times out 1ms after wrong authentication (according to NXP documentation) @@ -65,7 +65,7 @@ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested); int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t * ntptr, uint32_t *timing); int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); -int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); +int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); int mifare_classic_halt_ex(struct Crypto1State *pcs); int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); diff --git a/armsrc/optimized_cipher.c b/armsrc/optimized_cipher.c index 223d73fea..98ab88041 100644 --- a/armsrc/optimized_cipher.c +++ b/armsrc/optimized_cipher.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,9 +31,9 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * - * + * + * + * ****************************************************************************/ /** @@ -138,7 +138,7 @@ void opt_suc(const uint8_t* k,State* s, uint8_t *in, uint8_t length, bool add32Z head = 1 & in[i]; opt_successor(k, &x2, head, s); } - + //For tag MAC, an additional 32 zeroes if (add32Zeroes) { for (i = 0; i < 16; i++) { diff --git a/armsrc/pcf7931.c b/armsrc/pcf7931.c index c9a76bb3b..4c8259ea5 100644 --- a/armsrc/pcf7931.c +++ b/armsrc/pcf7931.c @@ -7,11 +7,11 @@ size_t DemodPCF7931(uint8_t **outBlocks) { uint8_t bits[256] = {0x00}; uint8_t blocks[8][16]; uint8_t *dest = BigBuf_get_addr(); - + int GraphTraceLen = BigBuf_max_traceLen(); if ( GraphTraceLen > 18000 ) GraphTraceLen = 18000; - + int i, j, lastval, bitidx, half_switch; int clock = 64; int tolerance = clock / 8; @@ -155,38 +155,38 @@ bool IsBlock1PCF7931(uint8_t *block) { void ReadPCF7931() { int found_blocks = 0; // successfully read blocks - int max_blocks = 8; // readable blocks + int max_blocks = 8; // readable blocks uint8_t memory_blocks[8][17]; // PCF content - + uint8_t single_blocks[8][17]; // PFC blocks with unknown position int single_blocks_cnt = 0; - size_t n = 0; // transmitted blocks + size_t n = 0; // transmitted blocks uint8_t tmp_blocks[4][16]; // temporary read buffer - + uint8_t found_0_1 = 0; // flag: blocks 0 and 1 were found int errors = 0; // error counter int tries = 0; // tries counter - + memset(memory_blocks, 0, 8*17*sizeof(uint8_t)); memset(single_blocks, 0, 8*17*sizeof(uint8_t)); - + int i = 0, j = 0; do { i = 0; - + memset(tmp_blocks, 0, 4*16*sizeof(uint8_t)); n = DemodPCF7931((uint8_t**)tmp_blocks); if(!n) ++errors; - - // exit if no block is received + + // exit if no block is received if (errors >= 10 && found_blocks == 0 && single_blocks_cnt == 0) { Dbprintf("Error, no tag or bad tag"); return; } - // exit if too many errors during reading + // exit if too many errors during reading if (tries > 50 && (2*errors > tries)) { Dbprintf("Error reading the tag"); Dbprintf("Here is the partial content"); @@ -214,11 +214,11 @@ void ReadPCF7931() { ++tries; continue; } - + Dbprintf("(dbg) got %d blocks (%d/%d found) (%d tries, %d errors)", n, found_blocks, (max_blocks == 0 ? found_blocks : max_blocks), tries, errors); i = 0; - if(!found_0_1) { + if(!found_0_1) { while (i < n - 1) { if (IsBlock0PCF7931(tmp_blocks[i]) && IsBlock1PCF7931(tmp_blocks[i+1])) { found_0_1 = 1; @@ -228,9 +228,9 @@ void ReadPCF7931() { // block 1 tells how many blocks are going to be sent max_blocks = MAX((memory_blocks[1][14] & 0x7f), memory_blocks[1][15]) + 1; found_blocks = 2; - + Dbprintf("Found blocks 0 and 1. PCF is transmitting %d blocks.", max_blocks); - + // handle the following blocks for (j = i + 2; j < n; ++j) { memcpy(memory_blocks[found_blocks], tmp_blocks[j], 16); @@ -298,7 +298,7 @@ void ReadPCF7931() { Dbprintf("-----------------------------------------"); for (i = 0; i < single_blocks_cnt; ++i) print_result("Block", single_blocks[i], 16); - + Dbprintf("-----------------------------------------"); } cmd_send(CMD_ACK,0,0,0,0,0); @@ -354,7 +354,7 @@ static void RealWritePCF7931(uint8_t *pass, uint16_t init_delay, int32_t l, int3 if (data&(1<PWMC_ENA = PWM_CHANNEL(0); - + // 48 MHz / 1024 gives 46.875 kHz AT91C_BASE_PWMC_CH0->PWMC_CMR = PWM_CH_MODE_PRESCALER(10); // Channel Mode Register AT91C_BASE_PWMC_CH0->PWMC_CDTYR = 0; // Channel Duty Cycle Register @@ -63,7 +63,7 @@ uint32_t RAMFUNC GetTickCount(void){ } // ------------------------------------------------------------------------- -// microseconds timer +// microseconds timer // ------------------------------------------------------------------------- void StartCountUS(void) { AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1); @@ -72,19 +72,19 @@ void StartCountUS(void) { // fast clock // tick=1.5mks AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable - AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz) / 32 + AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz) / 32 AT91C_TC_WAVE | AT91C_TC_WAVESEL_UP_AUTO | AT91C_TC_ACPA_CLEAR | AT91C_TC_ACPC_SET | AT91C_TC_ASWTRG_SET; AT91C_BASE_TC0->TC_RA = 1; AT91C_BASE_TC0->TC_RC = 0xBFFF + 1; // 0xC000 - - AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; // timer disable + + AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; // timer disable AT91C_BASE_TC1->TC_CMR = AT91C_TC_CLKS_XC1; // from timer 0 - + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; AT91C_BASE_TCB->TCB_BCR = 1; - + while (AT91C_BASE_TC1->TC_CV > 0); } @@ -95,7 +95,7 @@ uint32_t RAMFUNC GetCountUS(void){ } // ------------------------------------------------------------------------- -// Timer for iso14443 commands. Uses ssp_clk from FPGA +// Timer for iso14443 commands. Uses ssp_clk from FPGA // ------------------------------------------------------------------------- void StartCountSspClk(void) { AT91C_BASE_PMC->PMC_PCER |= (1 << AT91C_ID_TC0) | (1 << AT91C_ID_TC1) | (1 << AT91C_ID_TC2); // Enable Clock to all timers @@ -127,7 +127,7 @@ void StartCountSspClk(void) { AT91C_BASE_TC0->TC_RC = 0; // RC Compare value = 0; increment TC2 on overflow // use TC2 to count TIOA0 pulses (giving us a 32bit counter (TC0/TC2) clocked by ssp_clk) - AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKDIS; // disable TC2 + AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKDIS; // disable TC2 AT91C_BASE_TC2->TC_CMR = AT91C_TC_CLKS_XC2 // TC2 clock = XC2 clock = TIOA0 | AT91C_TC_WAVE // Waveform Mode | AT91C_TC_WAVESEL_UP; // just count @@ -136,8 +136,8 @@ void StartCountSspClk(void) { AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; // enable and reset TC1 AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; // enable and reset TC2 - // synchronize the counter with the ssp_frame signal. - // Note: FPGA must be in any iso14443 mode, otherwise the frame signal would not be present + // synchronize the counter with the ssp_frame signal. + // Note: FPGA must be in any iso14443 mode, otherwise the frame signal would not be present while(!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME)); // wait for ssp_frame to go high (start of frame) while(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_FRAME); // wait for ssp_frame to be low while(!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)); // wait for ssp_clk to go high @@ -150,16 +150,16 @@ void StartCountSspClk(void) { // whenever the last three bits of our counter go 0, we can be sure to be in the middle of a frame transfer. // (just started with the transfer of the 4th Bit). - // The high word of the counter (TC2) will not reset until the low word (TC0) overflows. + // The high word of the counter (TC2) will not reset until the low word (TC0) overflows. // Therefore need to wait quite some time before we can use the counter. while (AT91C_BASE_TC2->TC_CV > 0); } -void ResetSspClk(void) { +void ResetSspClk(void) { //enable clock of timer and software trigger AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; AT91C_BASE_TC2->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; - while (AT91C_BASE_TC2->TC_CV > 0); + while (AT91C_BASE_TC2->TC_CV > 0); } uint32_t RAMFUNC GetCountSspClk(void) { uint32_t tmp_count = (AT91C_BASE_TC2->TC_CV << 16) | AT91C_BASE_TC0->TC_CV; @@ -186,7 +186,7 @@ void StartTicks(void){ AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG; // re-enable timer and wait for TC0 // second configure TC0 (lower, 0x0000FFFF) 16 bit counter - AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz) / 32 + AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz) / 32 AT91C_TC_WAVE | AT91C_TC_WAVESEL_UP_AUTO | AT91C_TC_ACPA_CLEAR | // RA comperator clears TIOA (carry bit) AT91C_TC_ACPC_SET | // RC comperator sets TIOA (carry bit) @@ -224,7 +224,7 @@ void WaitTicks(uint32_t ticks){ while (GetTicks() < ticks); } -// Wait / Spindelay in us (microseconds) +// Wait / Spindelay in us (microseconds) // 1us = 1.5ticks. void WaitUS(uint16_t us){ WaitTicks( (uint32_t)us * 3/2 ); @@ -236,5 +236,5 @@ void WaitMS(uint16_t ms){ // stop clock void StopTicks(void){ AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; - AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; + AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS; } diff --git a/armsrc/util.c b/armsrc/util.c index 77ef3a494..04cf1fc33 100644 --- a/armsrc/util.c +++ b/armsrc/util.c @@ -15,7 +15,7 @@ size_t nbytes(size_t nbits) { /* ref http://www.csm.ornl.gov/~dunigan/crc.html - Returns the value v with the bottom b [0,32] bits reflected. + Returns the value v with the bottom b [0,32] bits reflected. Example: reflect(0x3e23L,3) == 0x3e26 */ uint32_t reflect(uint32_t v, int b) { @@ -35,7 +35,7 @@ uint8_t reflect8(uint8_t b) { } uint16_t reflect16(uint16_t b) { uint16_t v = 0; - v |= (b & 0x8000) >> 15; + v |= (b & 0x8000) >> 15; v |= (b & 0x4000) >> 13; v |= (b & 0x2000) >> 11; v |= (b & 0x1000) >> 9; @@ -165,7 +165,7 @@ void SpinOff(uint32_t pause) { // 0=A, 1=B, 2=C, 3=D void SpinErr(uint8_t led, uint32_t speed, uint8_t times) { SpinOff(speed); - NTIME(times) + NTIME(times) { switch (led) { case 0: diff --git a/bootrom/bootrom.c b/bootrom/bootrom.c index d2a18628a..c037da122 100644 --- a/bootrom/bootrom.c +++ b/bootrom/bootrom.c @@ -19,7 +19,7 @@ void DbpString(char *str) { byte_t len = 0; while (str[len] != 0x00) len++; - + cmd_send(CMD_DEBUG_PRINT_STRING, len, 0, 0, (byte_t*)str, len); } @@ -90,9 +90,9 @@ void UsbPacketReceived(uint8_t *packet, int len) { volatile uint32_t *p; //if ( len != sizeof(UsbCommand)) Fatal(); - + uint32_t arg0 = (uint32_t)c->arg[0]; - + switch(c->cmd) { case CMD_DEVICE_INFO: { dont_ack = 1; @@ -100,10 +100,10 @@ void UsbPacketReceived(uint8_t *packet, int len) { DEVICE_INFO_FLAG_UNDERSTANDS_START_FLASH; if(common_area.flags.osimage_present) arg0 |= DEVICE_INFO_FLAG_OSIMAGE_PRESENT; - + cmd_send(CMD_DEVICE_INFO,arg0,1,2,0,0); } break; - + case CMD_SETUP_WRITE: { /* The temporary write buffer of the embedded flash controller is mapped to the * whole memory region, only the last 8 bits are decoded. @@ -112,16 +112,16 @@ void UsbPacketReceived(uint8_t *packet, int len) { for(i = 0; i < 12; i++) p[i+arg0] = c->d.asDwords[i]; } break; - + case CMD_FINISH_WRITE: { uint32_t* flash_mem = (uint32_t*)(&_flash_start); for ( int j=0; j<2; j++) { for(i = 0+(64*j); i < 64+(64*j); i++) { flash_mem[i] = c->d.asDwords[i]; } - + uint32_t flash_address = arg0 + (0x100*j); - + /* Check that the address that we are supposed to write to is within our allowed region */ if( ((flash_address + AT91C_IFLASH_PAGE_SIZE - 1) >= end_addr) || (flash_address < start_addr) ) { /* Disallow write */ @@ -134,7 +134,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { MC_FLASH_COMMAND_PAGEN(page_n) | AT91C_MC_FCMD_START_PROG; } - + // Wait until flashing of page finishes uint32_t sr; while(!((sr = AT91C_BASE_EFC0->EFC_FSR) & AT91C_MC_FRDY)); @@ -144,18 +144,18 @@ void UsbPacketReceived(uint8_t *packet, int len) { } } } break; - + case CMD_HARDWARE_RESET: { usb_disable(); AT91C_BASE_RSTC->RSTC_RCR = RST_CONTROL_KEY | AT91C_RSTC_PROCRST; } break; - + case CMD_START_FLASH: { - if (c->arg[2] == START_FLASH_MAGIC) + if (c->arg[2] == START_FLASH_MAGIC) bootrom_unlocked = 1; - else + else bootrom_unlocked = 0; - + int prot_start = (int)&_bootrom_start; int prot_end = (int)&_bootrom_end; int allow_start = (int)&_flash_start; @@ -167,7 +167,7 @@ void UsbPacketReceived(uint8_t *packet, int len) { * bootrom area. In any case they must be within the flash area. */ if( (bootrom_unlocked || ((cmd_start >= prot_end) || (cmd_end < prot_start))) && - (cmd_start >= allow_start) && + (cmd_start >= allow_start) && (cmd_end <= allow_end) ) { start_addr = cmd_start; end_addr = cmd_end; @@ -177,12 +177,12 @@ void UsbPacketReceived(uint8_t *packet, int len) { cmd_send(CMD_NACK,0,0,0,0,0); } } break; - + default: { Fatal(); } break; } - + if (!dont_ack) cmd_send(CMD_ACK,arg0,0,0,0,0); } @@ -194,19 +194,19 @@ static void flash_mode(int externally_entered) { uint8_t rx[sizeof(UsbCommand)]; usb_enable(); - + // wait for reset to be complete? for (volatile size_t i=0; i<0x100000; i++) {}; for(;;) { WDT_HIT(); - + // Check if there is a usb packet available if (usb_poll_validate_length()) { if (usb_read(rx, sizeof(rx)) ) UsbPacketReceived(rx, sizeof(rx)); } - + if (!externally_entered && !BUTTON_PRESS()) { /* Perform a reset to leave flash mode */ usb_disable(); @@ -274,7 +274,7 @@ void BootROM(void) { AT91C_BASE_EFC0->EFC_FMR = AT91C_MC_FWS_1FWS | MC_FLASH_MODE_MASTER_CLK_IN_MHZ(48); // 9 = 256, 10+ is 512kb - uint8_t id = ( *(AT91C_DBGU_CIDR) & 0xF00) >> 8; + uint8_t id = ( *(AT91C_DBGU_CIDR) & 0xF00) >> 8; if ( id > 9 ) AT91C_BASE_EFC1->EFC_FMR = AT91C_MC_FWS_1FWS | MC_FLASH_MODE_MASTER_CLK_IN_MHZ(48); @@ -298,11 +298,11 @@ void BootROM(void) { if (!common_area_present){ /* Common area not ok, initialize it */ - int i; + int i; /* Makeshift memset, no need to drag util.c into this */ - for(i=0; idata, plain, &dataKeys); // Generate tag HMAC - mbedtls_md_hmac( mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tagKeys.hmacKey, sizeof(tagKeys.hmacKey), + mbedtls_md_hmac( mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), tagKeys.hmacKey, sizeof(tagKeys.hmacKey), plain + 0x1D4, 0x34, cipher + HMAC_POS_TAG ); // Init mbedtls HMAC context @@ -157,11 +157,11 @@ void nfc3d_amiibo_copy_app_data(const uint8_t * src, uint8_t * dst) { //uint16_t *ami_nb_wr = (uint16_t*)(dst + 0x29); //uint16_t *cfg_nb_wr = (uint16_t*)(dst + 0xB4); - + /* increment write counters */ //*ami_nb_wr = htobe16(be16toh(*ami_nb_wr) + 1); //*cfg_nb_wr = htobe16(be16toh(*cfg_nb_wr) + 1); - + uint16_t ami_nb_wr = ((uint16_t)bytes_to_num(dst + 0x29, 2)) + 1; uint16_t cfg_nb_wr = ((uint16_t)bytes_to_num(dst + 0xB4, 2)) + 1; diff --git a/client/amiitool/amiitool.c b/client/amiitool/amiitool.c index 40e7b05eb..163e6529c 100644 --- a/client/amiitool/amiitool.c +++ b/client/amiitool/amiitool.c @@ -33,7 +33,7 @@ void amiitool_usage() { } static bool LoadAmiikey(nfc3d_amiibo_keys keys, char* keyfile) { - + if (!nfc3d_amiibo_load_keys(&keys, keyfile)) { PrintAndLogEx(ERR, "Could not load keys from '%s'", keyfile); return false; @@ -84,7 +84,7 @@ int main(int argc, char ** argv) { nfc3d_amiibo_keys amiiboKeys; - + uint8_t original[NTAG215_SIZE]; uint8_t modified[NFC3D_AMIIBO_SIZE]; diff --git a/client/cliparser/argtable3.c b/client/cliparser/argtable3.c index abffa9dc2..7e3461b37 100644 --- a/client/cliparser/argtable3.c +++ b/client/cliparser/argtable3.c @@ -114,7 +114,7 @@ enum #define ARG_LOG(x) \ do { if (ARG_ENABLE_LOG) dbg_printf x; } while (0) -#endif +#endif extern void dbg_printf(const char *fmt, ...); @@ -1465,7 +1465,7 @@ static int arg_dbl_scanfn(struct arg_dbl *parent, const char *argval) static int arg_dbl_checkfn(struct arg_dbl *parent) { int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0; - + ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); return errorcode; } @@ -1575,7 +1575,7 @@ struct arg_dbl * arg_dbln( result->count = 0; } - + ARG_TRACE(("arg_dbln() returns %p\n", result)); return result; } @@ -1655,7 +1655,7 @@ static void arg_end_errorfn( fprintf(fp, "invalid option \"-%c\"", error); break; } - + fputc('\n', fp); } @@ -1851,7 +1851,7 @@ static int arg_file_scanfn(struct arg_file *parent, const char *argval) static int arg_file_checkfn(struct arg_file *parent) { int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0; - + ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); return errorcode; } @@ -1962,7 +1962,7 @@ struct arg_file * arg_filen( result->extension[i] = ""; } } - + ARG_TRACE(("arg_filen() returns %p\n", result)); return result; } @@ -2325,7 +2325,7 @@ struct arg_int * arg_intn( result->ival = (int *)(result + 1); result->count = 0; } - + ARG_TRACE(("arg_intn() returns %p\n", result)); return result; } @@ -2473,7 +2473,7 @@ struct arg_lit * arg_litn( /* init local variables */ result->count = 0; } - + ARG_TRACE(("arg_litn() returns %p\n", result)); return result; } @@ -3609,7 +3609,7 @@ static int arg_str_scanfn(struct arg_str *parent, const char *argval) static int arg_str_checkfn(struct arg_str *parent) { int errorcode = (parent->count < parent->hdr.mincount) ? EMINCOUNT : 0; - + ARG_TRACE(("%s:checkfn(%p) returns %d\n", __FILE__, parent, errorcode)); return errorcode; } @@ -3711,7 +3711,7 @@ struct arg_str * arg_strn( for (i = 0; i < maxcount; i++) result->sval[i] = ""; } - + ARG_TRACE(("arg_strn() returns %p\n", result)); return result; } @@ -4252,7 +4252,7 @@ int arg_parse(int argc, char * *argv, void * *argtable) argvcopy[i] = argv[i]; argvcopy[argc] = NULL; - + /* parse the command line (local copy) for tagged options */ arg_parse_tagged(argc, argvcopy, table, endtable); diff --git a/client/cliparser/argtable3.h b/client/cliparser/argtable3.h index 1107de250..452d0283a 100644 --- a/client/cliparser/argtable3.h +++ b/client/cliparser/argtable3.h @@ -39,7 +39,7 @@ extern "C" { #endif #define ARG_REX_ICASE 1 - + /* bit masks for arg_hdr.flag */ enum { @@ -218,7 +218,7 @@ struct arg_str* arg_str0(const char* shortopts, const char* datatype, const char* glossary); struct arg_str* arg_str1(const char* shortopts, - const char* longopts, + const char* longopts, const char* datatype, const char *glossary); struct arg_str* arg_strn(const char* shortopts, diff --git a/client/cliparser/cliparser.c b/client/cliparser/cliparser.c index 954220398..f1f2e3b1e 100644 --- a/client/cliparser/cliparser.c +++ b/client/cliparser/cliparser.c @@ -26,16 +26,16 @@ int CLIParserInit(char *vprogramName, char *vprogramHint, char *vprogramHelp) { programHint = vprogramHint; programHelp = vprogramHelp; memset(buf, 0x00, 500); - + return 0; } -int CLIParserParseArg(int argc, char **argv, void* vargtable[], size_t vargtableLen, bool allowEmptyExec) { +int CLIParserParseArg(int argc, char **argv, void* vargtable[], size_t vargtableLen, bool allowEmptyExec) { int nerrors; - + argtable = vargtable; argtableLen = vargtableLen; - + /* verify the argtable[] entries were allocated sucessfully */ if (arg_nullcheck(argtable) != 0) { /* NULL entries were detected, some allocations must have failed */ @@ -44,9 +44,9 @@ int CLIParserParseArg(int argc, char **argv, void* vargtable[], size_t vargtable } /* Parse the command line as defined by argtable[] */ nerrors = arg_parse(argc, argv, argtable); - + /* special case: '--help' takes precedence over error reporting */ - if ((argc < 2 && !allowEmptyExec) ||((struct arg_lit *)argtable[0])->count > 0) { // help must be the first record + if ((argc < 2 && !allowEmptyExec) ||((struct arg_lit *)argtable[0])->count > 0) { // help must be the first record printf("Usage: %s", programName); arg_print_syntaxv(stdout, argtable, "\n"); if (programHint) @@ -55,7 +55,7 @@ int CLIParserParseArg(int argc, char **argv, void* vargtable[], size_t vargtable printf("\n"); if (programHelp) printf("%s \n", programHelp); - + return 1; } @@ -64,10 +64,10 @@ int CLIParserParseArg(int argc, char **argv, void* vargtable[], size_t vargtable /* Display the error details contained in the arg_end struct.*/ arg_print_errors(stdout, ((struct arg_end *)argtable[vargtableLen - 1]), programName); printf("Try '%s --help' for more information.\n", programName); - + return 3; - } - + } + return 0; } @@ -86,19 +86,19 @@ int CLIParserParseString(const char* str, void* vargtable[], size_t vargtableLen int CLIParserParseStringEx(const char* str, void* vargtable[], size_t vargtableLen, bool allowEmptyExec, bool clueData) { int argc = 0; char *argv[200] = {NULL}; - + int len = strlen(str); char *bufptr = buf; char *spaceptr = NULL; enum ParserState state = PS_FIRST; - - argv[argc++] = bufptr; + + argv[argc++] = bufptr; // param0 = program name memcpy(buf, programName, strlen(programName) + 1); // with 0x00 bufptr += strlen(programName) + 1; if (len) - argv[argc++] = bufptr; - + argv[argc++] = bufptr; + // parse params for (int i = 0; i < len; i++) { switch(state){ @@ -110,7 +110,7 @@ int CLIParserParseStringEx(const char* str, void* vargtable[], size_t vargtableL bufptr = spaceptr; *bufptr = 0x00; bufptr++; - argv[argc++] = bufptr; + argv[argc++] = bufptr; } } spaceptr = NULL; @@ -130,10 +130,10 @@ int CLIParserParseStringEx(const char* str, void* vargtable[], size_t vargtableL *bufptr = 0x00; bufptr++; - argv[argc++] = bufptr; + argv[argc++] = bufptr; break; } - + *bufptr = str[i]; bufptr++; break; @@ -146,20 +146,20 @@ int CLIParserParseStringEx(const char* str, void* vargtable[], size_t vargtableL void CLIParserFree() { arg_freetable(argtable, argtableLen); argtable = NULL; - + return; } // convertors int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen) { *datalen = 0; - + int ibuf = 0; uint8_t buf[256] = {0}; int res = CLIParamStrToBuf(argstr, buf, maxdatalen * 2, &ibuf); // *2 because here HEX if (res || !ibuf) return res; - + switch(param_gethex_to_eol((char *)buf, 0, data, maxdatalen, datalen)) { case 1: printf("Parameter error: Invalid HEX value.\n"); @@ -171,7 +171,7 @@ int CLIParamHexToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int printf("Parameter error: Hex string must have even number of digits.\n"); return 3; } - + return 0; } @@ -179,26 +179,26 @@ int CLIParamStrToBuf(struct arg_str *argstr, uint8_t *data, int maxdatalen, int *datalen = 0; if (!argstr->count) return 0; - + uint8_t buf[256] = {0}; int ibuf = 0; - + for (int i = 0; i < argstr->count; i++) { int len = strlen(argstr->sval[i]); memcpy(&buf[ibuf], argstr->sval[i], len); ibuf += len; } buf[ibuf] = 0; - + if (!ibuf) return 0; if (ibuf > maxdatalen) return 2; - + memcpy(data, buf, ibuf); *datalen = ibuf; - + return 0; } diff --git a/client/cliparser/getopt.h b/client/cliparser/getopt.h index 789b4d1d4..09ff126b4 100644 --- a/client/cliparser/getopt.h +++ b/client/cliparser/getopt.h @@ -76,5 +76,5 @@ extern int optind, opterr, optopt; extern int optreset; /* getopt(3) external variable */ #endif __END_DECLS - + #endif /* !_GETOPT_H_ */ diff --git a/client/cmdanalyse.c b/client/cmdanalyse.c index fea907206..94411f8b5 100644 --- a/client/cmdanalyse.c +++ b/client/cmdanalyse.c @@ -92,7 +92,7 @@ static uint16_t matrixadd ( uint8_t* bytes, uint8_t len){ 0x72 | 0111 0010 0x5e | 0101 1110 ----------------- - C32F 9d74 + C32F 9d74 return 0; } @@ -110,7 +110,7 @@ static uint16_t calcSumCrumbAdd( uint8_t* bytes, uint8_t len, uint32_t mask) { sum += CRUMB(bytes[i], 4); sum += CRUMB(bytes[i], 6); } - sum &= mask; + sum &= mask; return sum; } static uint16_t calcSumCrumbAddOnes( uint8_t* bytes, uint8_t len, uint32_t mask) { @@ -122,7 +122,7 @@ static uint16_t calcSumNibbleAdd( uint8_t* bytes, uint8_t len, uint32_t mask) { sum += NIBBLE_LOW(bytes[i]); sum += NIBBLE_HIGH(bytes[i]); } - sum &= mask; + sum &= mask; return sum; } static uint16_t calcSumNibbleAddOnes( uint8_t* bytes, uint8_t len, uint32_t mask){ @@ -135,7 +135,7 @@ static uint16_t calcSumCrumbXor( uint8_t* bytes, uint8_t len, uint32_t mask) { sum ^= CRUMB(bytes[i], 2); sum ^= CRUMB(bytes[i], 4); sum ^= CRUMB(bytes[i], 6); - } + } sum &= mask; return sum; } @@ -153,7 +153,7 @@ static uint16_t calcSumByteXor( uint8_t* bytes, uint8_t len, uint32_t mask) { for (uint8_t i = 0; i < len; i++) { sum ^= bytes[i]; } - sum &= mask; + sum &= mask; return sum; } static uint16_t calcSumByteAdd( uint8_t* bytes, uint8_t len, uint32_t mask) { @@ -161,7 +161,7 @@ static uint16_t calcSumByteAdd( uint8_t* bytes, uint8_t len, uint32_t mask) { for (uint8_t i = 0; i < len; i++) { sum += bytes[i]; } - sum &= mask; + sum &= mask; return sum; } // Ones complement @@ -174,7 +174,7 @@ static uint16_t calcSumByteSub( uint8_t* bytes, uint8_t len, uint32_t mask) { for (uint8_t i = 0; i < len; i++) { sum -= bytes[i]; } - sum &= mask; + sum &= mask; return sum; } static uint16_t calcSumByteSubOnes( uint8_t* bytes, uint8_t len, uint32_t mask){ @@ -186,7 +186,7 @@ static uint16_t calcSumNibbleSub( uint8_t* bytes, uint8_t len, uint32_t mask) { sum -= NIBBLE_LOW(bytes[i]); sum -= NIBBLE_HIGH(bytes[i]); } - sum &= mask; + sum &= mask; return sum; } static uint16_t calcSumNibbleSubOnes( uint8_t* bytes, uint8_t len, uint32_t mask) { @@ -199,7 +199,7 @@ static uint16_t calcBSDchecksum8( uint8_t* bytes, uint8_t len, uint32_t mask){ for(uint8_t i = 0; i < len; i++){ sum = ((sum & 0xFF) >> 1) | ((sum & 0x1) << 7); // rotate accumulator sum += bytes[i]; // add next byte - sum &= 0xFF; // + sum &= 0xFF; // } sum &= mask; return sum; @@ -210,10 +210,10 @@ static uint16_t calcBSDchecksum4( uint8_t* bytes, uint8_t len, uint32_t mask){ for(uint8_t i = 0; i < len; i++){ sum = ((sum & 0xF) >> 1) | ((sum & 0x1) << 3); // rotate accumulator sum += NIBBLE_HIGH(bytes[i]); // add high nibble - sum &= 0xF; // + sum &= 0xF; // sum = ((sum & 0xF) >> 1) | ((sum & 0x1) << 3); // rotate accumulator sum += NIBBLE_LOW(bytes[i]); // add low nibble - sum &= 0xF; // + sum &= 0xF; // } sum &= mask; return sum; @@ -228,10 +228,10 @@ int CmdAnalyseLfsr(const char *Cmd){ uint8_t iv = param_get8ex(Cmd, 0, 0, 16); uint8_t find = param_get8ex(Cmd, 1, 0, 16); - + PrintAndLogEx(NORMAL, "LEGIC LFSR IV 0x%02X: \n", iv); PrintAndLogEx(NORMAL, " bit# | lfsr | ^0x40 | 0x%02X ^ lfsr \n",find); - + for (uint8_t i = 0x01; i < 0x30; i += 1) { //period = 0; legic_prng_init(iv); @@ -246,7 +246,7 @@ int CmdAnalyseLCR(const char *Cmd) { uint8_t data[50]; char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0|| cmdp == 'h') return usage_analyse_lcr(); - + int len = 0; switch (param_gethex_to_eol(Cmd, 0, data, sizeof(data), &len)) { case 1: @@ -267,10 +267,10 @@ int CmdAnalyseCRC(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_analyse_crc(); - + int len = strlen(Cmd); if ( len & 1 ) return usage_analyse_crc(); - + // add 1 for null terminator. uint8_t *data = calloc(len+1, sizeof(uint8_t)); if ( !data ) return 1; @@ -279,35 +279,35 @@ int CmdAnalyseCRC(const char *Cmd) { free(data); return usage_analyse_crc(); } - len >>= 1; + len >>= 1; PrintAndLogEx(NORMAL, "\nTests with (%d) | %s",len, sprint_hex(data, len)); - - // 51 f5 7a d6 + + // 51 f5 7a d6 uint8_t uid[] = {0x51, 0xf5, 0x7a, 0xd6}; //12 34 56 init_table(CRC_LEGIC); uint8_t legic8 = CRC8Legic(uid, sizeof(uid)); PrintAndLogEx(NORMAL, "Legic 16 | %X (EF6F expected) [legic8 = %02x]", crc16_legic(data, len, legic8), legic8); init_table(CRC_FELICA); PrintAndLogEx(NORMAL, "FeliCa | %X ", crc16_xmodem(data, len)); - - PrintAndLogEx(NORMAL, "\nTests of reflection. Current methods in source code"); + + PrintAndLogEx(NORMAL, "\nTests of reflection. Current methods in source code"); PrintAndLogEx(NORMAL, " reflect(0x3e23L,3) is %04X == 0x3e26", reflect(0x3e23L,3) ); PrintAndLogEx(NORMAL, " reflect8(0x80) is %02X == 0x01", reflect8(0x80)); PrintAndLogEx(NORMAL, " reflect16(0x8000) is %04X == 0x0001", reflect16(0xc6c6)); - + uint8_t b1, b2; // ISO14443 crc B - compute_crc(CRC_14443_B, data, len, &b1, &b2); + compute_crc(CRC_14443_B, data, len, &b1, &b2); uint16_t crcBB_1 = b1 << 8 | b2; uint16_t bbb = crc(CRC_14443_B, data, len); PrintAndLogEx(NORMAL, "ISO14443 crc B | %04x == %04x \n", crcBB_1, bbb ); - - + + // Test of CRC16, '123456789' string. // - - PrintAndLogEx(NORMAL, "\n\nStandard test with 31 32 33 34 35 36 37 38 39 '123456789'\n\n"); + + PrintAndLogEx(NORMAL, "\n\nStandard test with 31 32 33 34 35 36 37 38 39 '123456789'\n\n"); uint8_t dataStr[] = { 0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39 }; legic8 = CRC8Legic(dataStr, sizeof(dataStr)); @@ -321,21 +321,21 @@ int CmdAnalyseCRC(const char *Cmd) { PrintAndLogEx(NORMAL, "CRC16 based\n\n"); // input from commandline - PrintAndLogEx(NORMAL, "CCITT | %X (29B1 expected)", crc(CRC_CCITT, dataStr, sizeof(dataStr))); - + PrintAndLogEx(NORMAL, "CCITT | %X (29B1 expected)", crc(CRC_CCITT, dataStr, sizeof(dataStr))); + uint8_t poll[] = {0xb2,0x4d,0x12,0x01,0x01,0x2e,0x3d,0x17,0x26,0x47,0x80, 0x95,0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00,0xb3,0x7f}; PrintAndLogEx(NORMAL, "FeliCa | %04X (B37F expected)", crc(CRC_FELICA, poll+2, sizeof(poll)-4)); PrintAndLogEx(NORMAL, "FeliCa | %04X (0000 expected)", crc(CRC_FELICA, poll+2, sizeof(poll)-2)); - + uint8_t sel_corr[] = { 0x40, 0xe1, 0xe1, 0xff, 0xfe, 0x5f, 0x02, 0x3c, 0x43, 0x01}; PrintAndLogEx(NORMAL, "iCLASS | %04x (0143 expected)", crc(CRC_ICLASS, sel_corr, sizeof(sel_corr)-2)); PrintAndLogEx(NORMAL, "---------------------------------------------------------------\n\n\n"); - + // ISO14443 crc A compute_crc(CRC_14443_A, dataStr, sizeof(dataStr), &b1, &b2); uint16_t crcAA = b1 << 8 | b2; PrintAndLogEx(NORMAL, "ISO14443 crc A | %04x or %04x (BF05 expected)\n", crcAA, crc(CRC_14443_A, dataStr, sizeof(dataStr)) ); - + // ISO14443 crc B compute_crc(CRC_14443_B, dataStr, sizeof(dataStr), &b1, &b2); uint16_t crcBB = b1 << 8 | b2; @@ -346,7 +346,7 @@ int CmdAnalyseCRC(const char *Cmd) { uint16_t crcCC = b1 << 8 | b2; PrintAndLogEx(NORMAL, "ISO15693 crc X25| %04x or %04x (906E expected)\n", crcCC, crc(CRC_15693, dataStr, sizeof(dataStr)) ); - // ICLASS + // ICLASS compute_crc(CRC_ICLASS, dataStr, sizeof(dataStr), &b1, &b2); uint16_t crcDD = b1 << 8 | b2; PrintAndLogEx(NORMAL, "ICLASS crc | %04x or %04x\n", crcDD, crc(CRC_ICLASS, dataStr, sizeof(dataStr)) ); @@ -355,12 +355,12 @@ int CmdAnalyseCRC(const char *Cmd) { compute_crc(CRC_FELICA, dataStr, sizeof(dataStr), &b1, &b2); uint16_t crcEE = b1 << 8 | b2; PrintAndLogEx(NORMAL, "FeliCa | %04x or %04x (31C3 expected)\n", crcEE, crc(CRC_FELICA, dataStr, sizeof(dataStr))); - + free(data); return 0; } int CmdAnalyseCHKSUM(const char *Cmd){ - + uint8_t data[50]; uint8_t cmdp = 0; uint32_t mask = 0xFFFF; @@ -368,18 +368,18 @@ int CmdAnalyseCHKSUM(const char *Cmd){ bool useHeader = false; int len = 0; memset(data, 0x0, sizeof(data)); - + while(param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch(param_getchar(Cmd, cmdp)) { case 'b': case 'B': param_gethex_ex(Cmd, cmdp+1, data, &len); if ( len%2 ) errors = true; - len >>= 1; + len >>= 1; cmdp += 2; break; case 'm': - case 'M': + case 'M': mask = param_get32ex(Cmd, cmdp+1, 0, 16); cmdp += 2; break; @@ -399,13 +399,13 @@ int CmdAnalyseCHKSUM(const char *Cmd){ } //Validations if (errors || cmdp == 0 ) return usage_analyse_checksum(); - + if (useHeader) { PrintAndLogEx(NORMAL, " add | sub | add 1's compl | sub 1's compl | xor"); PrintAndLogEx(NORMAL, "byte nibble crumb | byte nibble | byte nibble cumb | byte nibble | byte nibble cumb | BSD |"); PrintAndLogEx(NORMAL, "------------------+-------------+------------------+-----------------+--------------------"); } - PrintAndLogEx(NORMAL, "0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X |\n", + PrintAndLogEx(NORMAL, "0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X | 0x%X 0x%X 0x%X | 0x%X 0x%X |\n", calcSumByteAdd(data, len, mask) , calcSumNibbleAdd(data, len, mask) , calcSumCrumbAdd(data, len, mask) @@ -421,7 +421,7 @@ int CmdAnalyseCHKSUM(const char *Cmd){ , calcSumCrumbXor(data, len, mask) , calcBSDchecksum8(data, len, mask) , calcBSDchecksum4(data, len, mask) - ); + ); return 0; } @@ -431,7 +431,7 @@ int CmdAnalyseDates(const char *Cmd){ return 0; } int CmdAnalyseTEASelfTest(const char *Cmd){ - + uint8_t v[8], v_le[8]; memset(v, 0x00, sizeof(v)); memset(v_le, 0x00, sizeof(v_le)); @@ -439,26 +439,26 @@ int CmdAnalyseTEASelfTest(const char *Cmd){ uint8_t cmdlen = strlen(Cmd); cmdlen = ( sizeof(v)<<2 < cmdlen ) ? sizeof(v)<<2 : cmdlen; - + if ( param_gethex(Cmd, 0, v, cmdlen) > 0 ){ PrintAndLogEx(WARNING, "Can't read hex chars, uneven? :: %u", cmdlen); return 1; } - + SwapEndian64ex(v , 8, 4, v_ptr); - - // ENCRYPTION KEY: + + // ENCRYPTION KEY: uint8_t key[16] = {0x55,0xFE,0xF6,0x30,0x62,0xBF,0x0B,0xC1,0xC9,0xB3,0x7C,0x34,0x97,0x3E,0x29,0xFB }; uint8_t keyle[16]; uint8_t* key_ptr = keyle; SwapEndian64ex(key , sizeof(key), 4, key_ptr); - + PrintAndLogEx(NORMAL, "TEST LE enc| %s", sprint_hex(v_ptr, 8)); - - tea_decrypt(v_ptr, key_ptr); + + tea_decrypt(v_ptr, key_ptr); PrintAndLogEx(NORMAL, "TEST LE dec | %s", sprint_hex_ascii(v_ptr, 8)); - - tea_encrypt(v_ptr, key_ptr); + + tea_encrypt(v_ptr, key_ptr); tea_encrypt(v_ptr, key_ptr); PrintAndLogEx(NORMAL, "TEST enc2 | %s", sprint_hex_ascii(v_ptr, 8)); @@ -469,14 +469,14 @@ char* pb(uint32_t b) { static char buf1[33] = {0}; static char buf2[33] = {0}; static char *s; - + if (s != buf1) s = buf1; - else + else s = buf2; - + memset(s, 0, sizeof(buf1)); - + uint32_t mask = 0x80000000; for (uint8_t i=0; i<32;i++) { s[i] = (mask & b)?'1':'0'; @@ -491,7 +491,7 @@ int CmdAnalyseA(const char *Cmd){ uint8_t cmdp = 0; bool errors = false; uint8_t data[USB_CMD_DATA_SIZE] = {0x00}; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'd': @@ -500,7 +500,7 @@ int CmdAnalyseA(const char *Cmd){ if ( hexlen != sizeof(data) ) { PrintAndLogEx(WARNING, "Read %d bytes of %u", hexlen, sizeof(data) ); } - cmdp += 2; + cmdp += 2; break; case 'h': return usage_analyse_a(); @@ -513,7 +513,7 @@ int CmdAnalyseA(const char *Cmd){ //Validations if (errors || cmdp == 0 ) return usage_analyse_a(); - + UsbCommand c = {CMD_FPC_SEND, {0, 0, 0}}; memcpy(c.d.asBytes, data, USB_CMD_DATA_SIZE); clearCommandBuffer(); @@ -525,16 +525,16 @@ int CmdAnalyseA(const char *Cmd){ } PrintAndLogEx(NORMAL, "got ack. Status %d", resp.arg[0]); return 0; - + PrintAndLogEx(NORMAL, "-- " _BLUE_(its my message) "\n"); PrintAndLogEx(NORMAL, "-- " _RED_(its my message) "\n"); PrintAndLogEx(NORMAL, "-- " _YELLOW_(its my message) "\n"); PrintAndLogEx(NORMAL, "-- " _GREEN_(its my message) "\n"); - + //uint8_t syncBit = 99; // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111) - // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern + // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's) # define SYNC_16BIT 0xB24D uint32_t shiftReg = param_get32ex(Cmd, 0, 0xb24d, 16); @@ -554,7 +554,7 @@ int CmdAnalyseA(const char *Cmd){ n1 = (n1 << 4) | (rev & (uint8_t)(~(0xFF << 4))); PrintAndLogEx(NORMAL, "rev %02X | %02X %s | %02X %s |\n", rev, n0, pb(n0), n1, pb(n1) ); - + /* hex(0xb24d shr 0) 0xB24D 0b1011001001001101 hex(0xb24d shr 1) 0x5926 @@ -568,29 +568,29 @@ for ( int i =0; i< 16; i++) { if ((( shiftReg >> 7) & 0xFFFF ) == SYNC_16BIT) byte_offset = 7; else if ((( shiftReg >> 6) & 0xFFFF ) == SYNC_16BIT) byte_offset = 6; else if ((( shiftReg >> 5) & 0xFFFF ) == SYNC_16BIT) byte_offset = 5; - else if ((( shiftReg >> 4) & 0xFFFF ) == SYNC_16BIT) byte_offset = 4; + else if ((( shiftReg >> 4) & 0xFFFF ) == SYNC_16BIT) byte_offset = 4; else if ((( shiftReg >> 3) & 0xFFFF ) == SYNC_16BIT) byte_offset = 3; else if ((( shiftReg >> 2) & 0xFFFF ) == SYNC_16BIT) byte_offset = 2; else if ((( shiftReg >> 1) & 0xFFFF ) == SYNC_16BIT) byte_offset = 1; else if ((( shiftReg >> 0) & 0xFFFF ) == SYNC_16BIT) byte_offset = 0; PrintAndLogEx(NORMAL, "Offset %u \n", byte_offset); - if ( byte_offset != 99 ) + if ( byte_offset != 99 ) break; - - shiftReg >>=1; + + shiftReg >>=1; } uint8_t p1 = (rev & (uint8_t)(~(0xFF << byte_offset))); PrintAndLogEx(NORMAL, "Offset %u | leftovers %02x %s \n", byte_offset, p1, pb(p1) ); - - /* + + /* pm3 --> da hex2bin 4db2 0100110110110010 */ return 0; -/* +/* // split byte into two parts. uint8_t offset = 3, n0 = 0, n1 = 0; rev = 0xB2; @@ -605,47 +605,47 @@ pm3 --> da hex2bin 4db2 0100110110110010 //PrintAndLogEx(NORMAL, "~(0xFF >> (8-offset)) == %s |\n", pb( (uint8_t)(~(0xFF >> (8-offset))) ) ); //PrintAndLogEx(NORMAL, " rev & xxx == %s\n\n", pb( (rev & (uint8_t)(~(0xFF << offset))) )); } -return 0; +return 0; // from A -- x bits into B and the rest into C. - - for ( uint8_t i=0; i<8; i++){ + + for ( uint8_t i=0; i<8; i++){ PrintAndLogEx(NORMAL, "%u | %02X %s | %02X %s |\n", i, a, pb(a), b, pb(b) ); b = a & (a & (0xFF >> (8-i))); a >>=1; } - + */ return 0; - // 14443-A - uint8_t u14_c[] = {0x09, 0x78, 0x00, 0x92, 0x02, 0x54, 0x13, 0x02, 0x04, 0x2d, 0xe8 }; // atqs w crc + // 14443-A + uint8_t u14_c[] = {0x09, 0x78, 0x00, 0x92, 0x02, 0x54, 0x13, 0x02, 0x04, 0x2d, 0xe8 }; // atqs w crc uint8_t u14_w[] = {0x09, 0x78, 0x00, 0x92, 0x02, 0x54, 0x13, 0x02, 0x04, 0x2d, 0xe7 }; // atqs w crc - PrintAndLogEx(FAILED, "14a check wrong crc | %s\n", (check_crc(CRC_14443_A, u14_w, sizeof(u14_w))) ? "YES": "NO" ); + PrintAndLogEx(FAILED, "14a check wrong crc | %s\n", (check_crc(CRC_14443_A, u14_w, sizeof(u14_w))) ? "YES": "NO" ); PrintAndLogEx(SUCCESS, "14a check correct crc | %s\n", (check_crc(CRC_14443_A, u14_c, sizeof(u14_c))) ? "YES": "NO" ); - + // 14443-B uint8_t u14b[] = {0x05,0x00,0x08,0x39,0x73}; - PrintAndLogEx(NORMAL, "14b check crc | %s\n", (check_crc(CRC_14443_B, u14b, sizeof(u14b))) ? "YES": "NO"); + PrintAndLogEx(NORMAL, "14b check crc | %s\n", (check_crc(CRC_14443_B, u14b, sizeof(u14b))) ? "YES": "NO"); // 15693 test uint8_t u15_c[] = {0x05,0x00,0x08,0x39,0x73}; // correct uint8_t u15_w[] = {0x05,0x00,0x08,0x39,0x72}; // wrong - PrintAndLogEx(FAILED, "15 check wrong crc | %s\n", (check_crc(CRC_15693, u15_w, sizeof(u15_w))) ? "YES": "NO"); - PrintAndLogEx(SUCCESS, "15 check correct crc | %s\n", (check_crc(CRC_15693, u15_c, sizeof(u15_c))) ? "YES": "NO"); + PrintAndLogEx(FAILED, "15 check wrong crc | %s\n", (check_crc(CRC_15693, u15_w, sizeof(u15_w))) ? "YES": "NO"); + PrintAndLogEx(SUCCESS, "15 check correct crc | %s\n", (check_crc(CRC_15693, u15_c, sizeof(u15_c))) ? "YES": "NO"); // iCLASS test - wrong crc , swapped bytes. uint8_t iclass_w[] = { 0x40, 0xe1, 0xe1, 0xff, 0xfe, 0x5f, 0x02, 0x3c, 0x01, 0x43}; uint8_t iclass_c[] = { 0x40, 0xe1, 0xe1, 0xff, 0xfe, 0x5f, 0x02, 0x3c, 0x43, 0x01}; - PrintAndLogEx(FAILED, "iCLASS check wrong crc | %s\n", (check_crc(CRC_ICLASS, iclass_w, sizeof(iclass_w))) ? "YES": "NO"); - PrintAndLogEx(SUCCESS, "iCLASS check correct crc | %s\n", (check_crc(CRC_ICLASS, iclass_c, sizeof(iclass_c))) ? "YES": "NO"); - + PrintAndLogEx(FAILED, "iCLASS check wrong crc | %s\n", (check_crc(CRC_ICLASS, iclass_w, sizeof(iclass_w))) ? "YES": "NO"); + PrintAndLogEx(SUCCESS, "iCLASS check correct crc | %s\n", (check_crc(CRC_ICLASS, iclass_c, sizeof(iclass_c))) ? "YES": "NO"); + // FeliCa test uint8_t felica_w[] = {0x12,0x01,0x01,0x2e,0x3d,0x17,0x26,0x47,0x80, 0x95,0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00,0xb3,0x7e}; uint8_t felica_c[] = {0x12,0x01,0x01,0x2e,0x3d,0x17,0x26,0x47,0x80, 0x95,0x00,0xf1,0x00,0x00,0x00,0x01,0x43,0x00,0xb3,0x7f}; - PrintAndLogEx(FAILED, "FeliCa check wrong crc | %s\n", (check_crc(CRC_FELICA, felica_w, sizeof(felica_w))) ? "YES": "NO"); - PrintAndLogEx(SUCCESS, "FeliCa check correct crc | %s\n", (check_crc(CRC_FELICA, felica_c, sizeof(felica_c))) ? "YES": "NO"); - - PrintAndLogEx(NORMAL, "\n\n"); + PrintAndLogEx(FAILED, "FeliCa check wrong crc | %s\n", (check_crc(CRC_FELICA, felica_w, sizeof(felica_w))) ? "YES": "NO"); + PrintAndLogEx(SUCCESS, "FeliCa check correct crc | %s\n", (check_crc(CRC_FELICA, felica_c, sizeof(felica_c))) ? "YES": "NO"); + + PrintAndLogEx(NORMAL, "\n\n"); return 0; /* @@ -656,7 +656,7 @@ return 0; star[1] = '\\'; star[2] = '|'; star[3] = '/'; - + for (uint8_t k=0; k<4; k = (k+1) % 4 ) { PrintAndLogEx(NORMAL, "\e[s%c\e[u", star[k]); fflush(stdout); @@ -667,19 +667,19 @@ return 0; } } */ - + //piwi // uid(2e086b1a) nt(230736f6) ks(0b0008000804000e) nr(000000000) // uid(2e086b1a) nt(230736f6) ks(0e0b0e0b090c0d02) nr(000000001) // uid(2e086b1a) nt(230736f6) ks(0e05060e01080b08) nr(000000002) //uint64_t d1[] = {0x2e086b1a, 0x230736f6, 0x0000001, 0x0e0b0e0b090c0d02}; //uint64_t d2[] = {0x2e086b1a, 0x230736f6, 0x0000002, 0x0e05060e01080b08}; - + // uid(17758822) nt(c0c69e59) ks(080105020705040e) nr(00000001) // uid(17758822) nt(c0c69e59) ks(01070a05050c0705) nr(00000002) //uint64_t d1[] = {0x17758822, 0xc0c69e59, 0x0000001, 0x080105020705040e}; //uint64_t d2[] = {0x17758822, 0xc0c69e59, 0x0000002, 0x01070a05050c0705}; - + // uid(6e442129) nt(8f699195) ks(090d0b0305020f02) nr(00000001) // uid(6e442129) nt(8f699195) ks(03030508030b0c0e) nr(00000002) // uid(6e442129) nt(8f699195) ks(02010f030c0d050d) nr(00000003) @@ -687,7 +687,7 @@ return 0; //uint64_t d1[] = {0x6e442129, 0x8f699195, 0x0000001, 0x090d0b0305020f02}; //uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0x00040f0f0305030e}; -/* +/* uid(3e172b29) nt(039b7bd2) ks(0c0e0f0505080800) nr(00000001) uid(3e172b29) nt(039b7bd2) ks(0e06090d03000b0f) nr(00000002) */ @@ -697,7 +697,7 @@ uid(3e172b29) nt(039b7bd2) ks(0e06090d03000b0f) nr(00000002) // uint64_t d2[] = {0x3e172b29, 0x039b7bd2, 0x0000002, 0, 0x0e06090d03000b0f}; uint64_t d1[] = {0x6e442129, 0x8f699195, 0x0000001, 0, 0x090d0b0305020f02}; uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; - + keycountA = nonce2key(d1[0], d1[1], d1[2], 0, d1[3], d1[4] ,&keylistA); keycountB = nonce2key(d2[0], d2[1], d2[2], 0, d2[3], d2[4], &keylistB); @@ -708,11 +708,11 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; switch (keycountB) { case 0: PrintAndLogEx(FAILED, "Key test B failed\n"); break; case 1: PrintAndLogEx(SUCCESS, "KEY B | %012" PRIX64 " ", keylistB[0]); break; - } - + } + free(keylistA); free(keylistB); - + // qsort(keylist, keycount, sizeof(*keylist), compare_uint64); // keycount = intersection(last_keylist, keylist); @@ -727,7 +727,7 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; 0x8211b0607367, 0xe2936b320f76, 0xaff501e84378, 0x82b31cedb21b, 0xb725d31d4cd3, 0x3b984145b2f1, 0x3b4adb3e82ba, 0x8779075210fe }; - + uint64_t keya[] = { 0x7b5b8144a32f, 0x76b46ccc461e, 0x03c3c36ea7a2, 0x171414d31961, 0xe2bfc7153eea, 0x48023d1d1985, 0xff7e1a410953, 0x49a3110249d3, @@ -740,9 +740,9 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; 0x8211b0607367, 0xe2936b320f76, 0xaff501e84378, 0x82b31cedb21b, 0xb725d31d4cd3, 0x3b984145b2f1, 0x3b4adb3e82ba, 0x8779075210fe }; - + */ - + /* uint64_t xor[] = { 0x0DEFED88E531, 0x7577AFA2E1BC, 0x14D7D7BDBEC3, 0xF5ABD3C6278B, @@ -754,7 +754,7 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; 0x6082DB527C11, 0x4D666ADA4C0E, 0x2D461D05F163, 0x3596CFF0FEC8, 0x8CBD9258FE22, 0x00D29A7B304B, 0xBC33DC6C9244 }; - + uint64_t xorA[] = { 0x0DEFED88E531, 0x7577AFA2E1BC, 0x14D7D7BDBEC3, 0xF5ABD3C6278B, @@ -769,7 +769,7 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; 0x8CBD9258FE22, 0x00D29A7B304B, 0xBC33DC6C9244 }; */ - /* + /* // xor key A | xor key B 1 | 0DEFED88E531 | 2F87A1BDC230 2 | 7577AFA2E1BC | E43F502B984C @@ -795,12 +795,12 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; PrintAndLogEx(NORMAL, "%u | %012" PRIX64 " | \n", i, a); } */ - + /* - uint32_t id = param_get32ex(Cmd, 0, 0x93290142, 16); + uint32_t id = param_get32ex(Cmd, 0, 0x93290142, 16); uint8_t uid[6] = {0}; num_to_bytes(id,4,uid); - + uint8_t key_s0a[] = { uid[1] ^ uid[2] ^ uid[3] ^ 0x11, uid[1] ^ 0x72, @@ -812,20 +812,20 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; PrintAndLogEx(NORMAL, "UID | %s\n", sprint_hex(uid,4 )); PrintAndLogEx(NORMAL, "KEY A | %s\n", sprint_hex(key_s0a, 6)); - + // arrays w all keys uint64_t foo[32] = {0}; - + //A foo[0] = bytes_to_num(key_s0a, 6); //B //foo[16] = 0xcafe71411fbf; foo[16] = 0xeafe51411fbf; - - for (uint8_t i=0; i<15; i++){ + + for (uint8_t i=0; i<15; i++){ foo[i+1] = foo[i] ^ xorA[i]; foo[i+16+1] = foo[i+16] ^ xorB[i]; - + } for (uint8_t i=0; i<15; i++){ uint64_t a = foo[i]; @@ -836,7 +836,7 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; a, ( a == keya[i])?"ok":"err", b, - ( b == keyb[i])?"ok":"err" + ( b == keyb[i])?"ok":"err" ); } */ @@ -846,7 +846,7 @@ uint64_t d2[] = {0x6e442129, 0x8f699195, 0x0000004, 0, 0x00040f0f0305030e}; void generate4bNUID(uint8_t *uid, uint8_t *nuid){ uint16_t crc; uint8_t b1, b2; - + compute_crc(CRC_14443_A, uid, 3, &b1, &b2); nuid[0] = (b2 & 0xE0) | 0xF; nuid[1] = b1; @@ -858,7 +858,7 @@ void generate4bNUID(uint8_t *uid, uint8_t *nuid){ } int CmdAnalyseNuid(const char *Cmd){ - uint8_t nuid[4] = {0}; + uint8_t nuid[4] = {0}; uint8_t uid[7] = {0}; int len = 0; char cmdp = tolower(param_getchar(Cmd, 0)); @@ -870,13 +870,13 @@ int CmdAnalyseNuid(const char *Cmd){ if (cmdp == 't') { memcpy(uid, "\x04\x0d\x68\x1a\xb5\x22\x81", 7); generate4bNUID(uid, nuid); - + bool test1 = (0 == memcmp(nuid, "\x8f\x43\x0f\xef", 4)); PrintAndLogEx(SUCCESS, "Selftest1 %s\n", test1 ? _GREEN_(OK): _RED_(Fail)); - + memcpy(uid, "\x04\x18\x3f\x09\x32\x1b\x85", 7); generate4bNUID(uid, nuid); - bool test2 = (0 == memcmp(nuid, "\x4f\x50\x5d\x7d", 4)); + bool test2 = (0 == memcmp(nuid, "\x4f\x50\x5d\x7d", 4)); PrintAndLogEx(SUCCESS, "Selftest2 %s\n", test2 ? _GREEN_(OK) : _RED_(Fail)); return 0; } @@ -885,7 +885,7 @@ int CmdAnalyseNuid(const char *Cmd){ if ( len%2 || len != 14) return usage_analyse_nuid(); generate4bNUID(uid, nuid); - + PrintAndLogEx(NORMAL, "UID | %s \n", sprint_hex(uid, 7)); PrintAndLogEx(NORMAL, "NUID | %s \n", sprint_hex(nuid, 4)); return 0; diff --git a/client/cmdanalyse.h b/client/cmdanalyse.h index ab7606f5c..c362744c0 100644 --- a/client/cmdanalyse.h +++ b/client/cmdanalyse.h @@ -23,7 +23,7 @@ #include "tea.h" #include "legic_prng.h" #include "loclass/elite_crack.h" -#include "mifare/mfkey.h" //nonce2key +#include "mifare/mfkey.h" //nonce2key #include "util_posix.h" // msclock diff --git a/client/cmdcrc.c b/client/cmdcrc.c index a34c7d351..a54653d3e 100644 --- a/client/cmdcrc.c +++ b/client/cmdcrc.c @@ -55,7 +55,7 @@ int CmdCrc(const char *Cmd) { for(int i = 0; i < argc; ++i) { free(argv[i]); } - return 0; + return 0; } //returns array of model names and the count of models returning @@ -75,7 +75,7 @@ int GetModels(char *Models[], int *count, uint8_t *width){ #endif /* _WIN32 */ SETBMP(); - + int args = 0, psets, pass; int Cnt = 0; if (width[0] == 0) { //reveng -D @@ -100,7 +100,7 @@ int GetModels(char *Models[], int *count, uint8_t *width){ mfree(&model); } else { //reveng -s - if (~model.flags & P_MULXN){ + if (~model.flags & P_MULXN){ PrintAndLogEx(WARNING, "cannot search for non-Williams compliant models"); return 0; } @@ -131,7 +131,7 @@ int GetModels(char *Models[], int *count, uint8_t *width){ while (psets) { mbynum(&pset, --psets); - + /* skip if different width, or refin or refout don't match */ if( plen(pset.spoly) != width[0] || (model.flags ^ pset.flags) & (P_REFIN | P_REFOUT)) continue; @@ -142,14 +142,14 @@ int GetModels(char *Models[], int *count, uint8_t *width){ continue; if (rflags & R_HAVEX && psncmp(&model.xorout, &pset.xorout)) continue; - + //for additional args (not used yet, maybe future?) apoly = pclone(pset.xorout); - + if (pset.flags & P_REFOUT) prev(&apoly); - - + + for (qptr = apolys; qptr < pptr; ++qptr) { crc = pcrc(*qptr, pset.spoly, pset.init, apoly, 0); if (ptst(crc)) { @@ -159,12 +159,12 @@ int GetModels(char *Models[], int *count, uint8_t *width){ pfree(&crc); } pfree(&apoly); - + if (qptr == pptr) { /* the selected model solved all arguments */ mcanon(&pset); - + size_t size = (pset.name && *pset.name) ? strlen(pset.name) : 7; //PrintAndLogEx(NORMAL, "Size: %d, %s, count: %d",size,pset.name, Cnt); char *tmp = calloc(size+1, sizeof(char)); @@ -201,8 +201,8 @@ int GetModels(char *Models[], int *count, uint8_t *width){ PrintAndLogEx(WARNING, "no models found"); return 0; } - - if (!(model.flags & P_REFIN) != !(model.flags & P_REFOUT)){ + + if (!(model.flags & P_REFIN) != !(model.flags & P_REFOUT)){ PrintAndLogEx(WARNING, "cannot search for crossed-endian models"); return 0; } @@ -223,13 +223,13 @@ int GetModels(char *Models[], int *count, uint8_t *width){ } } } while (~rflags & R_HAVERI && ++pass < 2); - + for (qptr = apolys; qptr < pptr; ++qptr) { pfree(qptr); } free(apolys); mfree(&model); - + if (~uflags & C_RESULT){ PrintAndLogEx(WARNING, "no models found"); return 0; @@ -248,9 +248,9 @@ int GetModels(char *Models[], int *count, uint8_t *width){ int RunModel(char *inModel, char *inHexStr, bool reverse, char endian, char *result){ /* default values */ static model_t model = MZERO; - + int ibperhx = 8, obperhx = 8; - int rflags = 0; // search flags + int rflags = 0; // search flags int c; poly_t apoly, crc; @@ -273,7 +273,7 @@ int RunModel(char *inModel, char *inHexStr, bool reverse, char endian, char *res return 0; } rflags |= R_HAVEP | R_HAVEI | R_HAVERI | R_HAVERO | R_HAVEX; - + //set flags switch (endian) { case 'b': /* b big-endian (RefIn = false, RefOut = false ) */ @@ -376,12 +376,12 @@ int CmdrevengTestC(const char *Cmd){ dataLen = param_getstr(Cmd, cmdp++, inHexStr, sizeof(inHexStr)); if (dataLen < 4) return 0; bool reverse = (param_get8(Cmd, cmdp++)) ? true : false; - endian = param_getchar(Cmd, cmdp++); + endian = param_getchar(Cmd, cmdp++); //PrintAndLogEx(NORMAL, "mod: %s, hex: %s, rev %d", inModel, inHexStr, reverse); int ans = RunModel(inModel, inHexStr, reverse, endian, result); if (!ans) return 0; - + PrintAndLogEx(SUCCESS, "result: %s",result); return 1; } @@ -401,8 +401,8 @@ char *SwapEndianStr(const char *inStr, const size_t len, const uint8_t blockSize // takes hex string in and searches for a matching result (hex string must include checksum) int CmdrevengSearch(const char *Cmd){ -#define NMODELS 105 - +#define NMODELS 105 + char inHexStr[100] = {0x00}; int dataLen = param_getstr(Cmd, 0, inHexStr, sizeof(inHexStr)); if (dataLen < 4) return 0; @@ -418,7 +418,7 @@ int CmdrevengSearch(const char *Cmd){ int ans = GetModels(Models, &count, width); bool found = false; if (!ans) return 0; - + // try each model and get result for (int i = 0; i < count; i++){ /*if (found) { @@ -426,9 +426,9 @@ int CmdrevengSearch(const char *Cmd){ continue; }*/ // round up to # of characters in this model's crc - crcChars = ((width[i]+7)/8)*2; + crcChars = ((width[i]+7)/8)*2; // can't test a model that has more crc digits than our data - if (crcChars >= dataLen) + if (crcChars >= dataLen) continue; memset(result, 0, 30); char *inCRC = calloc(crcChars+1, sizeof(char)); @@ -480,7 +480,7 @@ int CmdrevengSearch(const char *Cmd){ free(outHex); free(Models[i]); } - + if (!found) PrintAndLogEx(FAILED, "\nno matches found\n"); return 1; } \ No newline at end of file diff --git a/client/cmddata.c b/client/cmddata.c index 0403c4f28..998ce3779 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -24,14 +24,14 @@ int usage_data_printdemodbuf(void){ PrintAndLogEx(NORMAL, " x output in hex (omit for binary output)"); PrintAndLogEx(NORMAL, " o enter offset in # of bits"); PrintAndLogEx(NORMAL, " l enter length to print in # of bits or hex characters respectively"); - return 0; + return 0; } int usage_data_manrawdecode(void){ PrintAndLogEx(NORMAL, "Usage: data manrawdecode [invert] [maxErr]"); PrintAndLogEx(NORMAL, " Takes 10 and 01 and converts to 0 and 1 respectively"); PrintAndLogEx(NORMAL, " --must have binary sequence in demodbuffer (run data askrawdemod first)"); - PrintAndLogEx(NORMAL, " [invert] invert output"); - PrintAndLogEx(NORMAL, " [maxErr] set number of errors allowed (default = 20)"); + PrintAndLogEx(NORMAL, " [invert] invert output"); + PrintAndLogEx(NORMAL, " [maxErr] set number of errors allowed (default = 20)"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " Example: data manrawdecode = decode manchester bitstream from the demodbuffer"); return 0; @@ -52,10 +52,10 @@ int usage_data_biphaserawdecode(void){ } int usage_data_rawdemod(void){ PrintAndLogEx(NORMAL, "Usage: data rawdemod [modulation] |"); - PrintAndLogEx(NORMAL, " [modulation] as 2 char, 'ab' for ask/biphase, 'am' for ask/manchester, 'ar' for ask/raw, 'fs' for fsk, ..."); + PrintAndLogEx(NORMAL, " [modulation] as 2 char, 'ab' for ask/biphase, 'am' for ask/manchester, 'ar' for ask/raw, 'fs' for fsk, ..."); PrintAndLogEx(NORMAL, " 'nr' for nrz/direct, 'p1' for psk1, 'p2' for psk2"); - PrintAndLogEx(NORMAL, " as 'h', prints the help for the specific modulation"); - PrintAndLogEx(NORMAL, " see specific modulation help for optional parameters"); + PrintAndLogEx(NORMAL, " as 'h', prints the help for the specific modulation"); + PrintAndLogEx(NORMAL, " see specific modulation help for optional parameters"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " Example: data rawdemod fs h = print help specific to fsk demod"); PrintAndLogEx(NORMAL, " : data rawdemod fs = demod GraphBuffer using: fsk - autodetect"); @@ -132,7 +132,7 @@ int usage_data_rawdemod_fs(void){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " Example: data rawdemod fs = demod an fsk tag from GraphBuffer using autodetect"); PrintAndLogEx(NORMAL, " : data rawdemod fs 32 = demod an fsk tag from GraphBuffer using a clock of RF/32, autodetect fc"); - PrintAndLogEx(NORMAL, " : data rawdemod fs 1 = demod an fsk tag from GraphBuffer using autodetect, invert output"); + PrintAndLogEx(NORMAL, " : data rawdemod fs 1 = demod an fsk tag from GraphBuffer using autodetect, invert output"); PrintAndLogEx(NORMAL, " : data rawdemod fs 32 1 = demod an fsk tag from GraphBuffer using a clock of RF/32, invert output, autodetect fc"); PrintAndLogEx(NORMAL, " : data rawdemod fs 64 0 8 5 = demod an fsk1 RF/64 tag from GraphBuffer"); PrintAndLogEx(NORMAL, " : data rawdemod fs 50 0 10 8 = demod an fsk2 RF/50 tag from GraphBuffer"); @@ -232,7 +232,7 @@ int usage_data_fsktonrz() { PrintAndLogEx(NORMAL, " c enter the a clock (omit to autodetect)"); PrintAndLogEx(NORMAL, " l enter a field clock (omit to autodetect)"); PrintAndLogEx(NORMAL, " f enter a field clock (omit to autodetect)"); - return 0; + return 0; } //set the demod buffer with given array of binary (one bit per byte) @@ -242,10 +242,10 @@ void setDemodBuf(uint8_t *buf, size_t size, size_t start_idx) { if ( size > MAX_DEMOD_BUF_LEN - start_idx) size = MAX_DEMOD_BUF_LEN - start_idx; - + for (size_t i = 0; i < size; i++) DemodBuffer[i] = buf[start_idx++]; - + DemodBufferLen = size; } @@ -271,13 +271,13 @@ double rms(double *v, size_t n) { int cmp_int( const void *a, const void *b) { if (*(const int *)a < *(const int *)b) return -1; - else + else return *(const int *)a > *(const int *)b; } int cmp_uint8( const void *a, const void *b) { if (*(const uint8_t *)a < *(const uint8_t *)b) return -1; - else + else return *(const uint8_t *)a > *(const uint8_t *)b; } // Median of a array of values @@ -306,7 +306,7 @@ static double compute_variance(const int *data, size_t n) { for (size_t i=0; i < n; i++) variance += pow(( data[i] - mean), 2.0); - variance /= n; + variance /= n; return variance; } @@ -319,10 +319,10 @@ static double compute_autoc(const int *data, size_t n, int lag) { double ac_value; // Computed autocorrelation value to be returned double variance; // Computed variance double mean; - + mean = compute_mean(data, n); variance = compute_variance(data, n); - + for (size_t i=0; i < (n - lag); i++) autocv += (data[i] - mean) * (data[i+lag] - mean); @@ -350,13 +350,13 @@ void save_restoreDB(uint8_t saveOpt) { savedDemodStartIdx = g_DemodStartIdx; savedDemodClock = g_DemodClock; } else if (DB_Saved) { //restore - + memcpy(DemodBuffer, SavedDB, sizeof(DemodBuffer)); DemodBufferLen = SavedDBlen; g_DemodClock = savedDemodClock; g_DemodStartIdx = savedDemodStartIdx; } -} +} int CmdSetDebugMode(const char *Cmd) { int demod = 0; @@ -373,7 +373,7 @@ void printDemodBuff(void) { PrintAndLogEx(NORMAL, "(printDemodBuff) no bits found in demod buffer"); return; } - if (len > 512) len = 512; + if (len > 512) len = 512; PrintAndLogEx(NORMAL, "%s", sprint_bin_break(DemodBuffer, len, 16) ); } @@ -411,12 +411,12 @@ int CmdPrintDemodBuff(const char *Cmd) { } //Validations if (errors) return usage_data_printdemodbuf(); - + if (DemodBufferLen == 0) { PrintAndLogEx(NORMAL, "Demodbuffer is empty"); return 0; } - length = (length > (DemodBufferLen-offset)) ? DemodBufferLen-offset : length; + length = (length > (DemodBufferLen-offset)) ? DemodBufferLen-offset : length; int numBits = (length) & 0x00FFC; //make sure we don't exceed our string if (hexMode){ @@ -426,7 +426,7 @@ int CmdPrintDemodBuff(const char *Cmd) { if (numBits == 0) { return 0; } - PrintAndLogEx(NORMAL, "DemodBuffer: %s", hex); + PrintAndLogEx(NORMAL, "DemodBuffer: %s", hex); } else { PrintAndLogEx(NORMAL, "DemodBuffer:\n%s", sprint_bin_break(DemodBuffer+offset, numBits, 16)); } @@ -439,7 +439,7 @@ int CmdGetBitStream(const char *Cmd) { CmdHpf(Cmd); for (uint32_t i = 0; i < GraphTraceLen; i++) GraphBuffer[i] = (GraphBuffer[i] >= 1) ? 1 : 0; - + RepaintGraphWindow(); return 0; } @@ -449,7 +449,7 @@ int CmdGetBitStream(const char *Cmd) { // (amp may not be needed anymore) //verbose will print results and demoding messages //emSearch will auto search for EM410x format in bitstream -//askType switches decode: ask/raw = 0, ask/manchester = 1 +//askType switches decode: ask/raw = 0, ask/manchester = 1 int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck) { int invert = 0; int clk = 0; @@ -484,11 +484,11 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, int foundclk = 0; //amp before ST check if (amp == 'a') - askAmp(bits, BitLen); + askAmp(bits, BitLen); bool st = false; size_t ststart = 0, stend = 0; - if (*stCheck) + if (*stCheck) st = DetectST(bits, &BitLen, &foundclk, &ststart, &stend); if (st) { @@ -496,7 +496,7 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, clk = (clk == 0) ? foundclk : clk; CursorCPos = ststart; CursorDPos = stend; - if (verbose || g_debugMode) + if (verbose || g_debugMode) PrintAndLogEx(NORMAL, "Found Sequence Terminator - First one is shown by orange and blue graph markers"); } @@ -512,7 +512,7 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Too many errors found, errors:%d, bits:%d, clock:%d", errCnt, BitLen, clk); return 0; } - + if (verbose || g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: (ASKDemod_ext) Using clock:%d, invert:%d, bits found:%d", clk, invert, BitLen); //output @@ -520,14 +520,14 @@ int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, setClockGrid(clk, startIdx); if (verbose || g_debugMode){ - if (errCnt > 0) + if (errCnt > 0) PrintAndLogEx(NORMAL, "# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); - if (askType) + if (askType) PrintAndLogEx(NORMAL, "ASK/Manchester - Clock: %d - Decoded bitstream:",clk); - else + else PrintAndLogEx(NORMAL, "ASK/Raw - Clock: %d - Decoded bitstream:",clk); // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); + printDemodBuff(); } uint64_t lo = 0; uint32_t hi = 0; @@ -570,17 +570,17 @@ int Cmdmandecoderaw(const char *Cmd) { if (strlen(Cmd) > 5 || cmdp == 'h') return usage_data_manrawdecode(); if (DemodBufferLen == 0) return 0; - + uint8_t bits[MAX_DEMOD_BUF_LEN] = {0}; - + for (; i < DemodBufferLen; ++i){ - if (DemodBuffer[i] > high) + if (DemodBuffer[i] > high) high = DemodBuffer[i]; - else if(DemodBuffer[i] < low) + else if(DemodBuffer[i] < low) low = DemodBuffer[i]; bits[i] = DemodBuffer[i]; } - + if (high > 7 || low < 0 ){ PrintAndLogEx(WARNING, "Error: please raw demod the wave first then manchester raw decode"); return 0; @@ -594,10 +594,10 @@ int Cmdmandecoderaw(const char *Cmd) { PrintAndLogEx(WARNING, "Too many errors: %d",errCnt); return 0; } - + PrintAndLogEx(NORMAL, "Manchester Decoded - # errors:%d - data:",errCnt); PrintAndLogEx(NORMAL, "%s", sprint_bin_break(bits, size, 16)); - + if (errCnt == 0){ uint64_t id = 0; uint32_t hi = 0; @@ -628,11 +628,11 @@ int CmdBiphaseDecodeRaw(const char *Cmd) { PrintAndLogEx(NORMAL, "DemodBuffer Empty - run 'data rawdemod ar' first"); return 0; } - + uint8_t bits[MAX_DEMOD_BUF_LEN] = {0}; size = sizeof(bits); if ( !getDemodBuf(bits, &size) ) return 0; - + errCnt = BiphaseRawDecode(bits, &size, &offset, invert); if (errCnt < 0){ PrintAndLogEx(WARNING, "Error during decode:%d", errCnt); @@ -648,11 +648,11 @@ int CmdBiphaseDecodeRaw(const char *Cmd) { PrintAndLogEx(NORMAL, "Biphase Decoded using offset: %d - # invert:%d - data:",offset,invert); PrintAndLogEx(NORMAL, "%s", sprint_bin_break(bits, size, 16)); - + //remove first bit from raw demod - if (offset) + if (offset) setDemodBuf(DemodBuffer,DemodBufferLen-offset, offset); - + setClockGrid(g_DemodClock, g_DemodStartIdx + g_DemodClock*offset/2); return 1; } @@ -664,27 +664,27 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) //ask raw demod GraphBuffer first int offset=0, clk=0, invert=0, maxErr=0; sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); - + uint8_t BitStream[MAX_DEMOD_BUF_LEN]; - size_t size = getFromGraphBuf(BitStream); + size_t size = getFromGraphBuf(BitStream); if (size == 0 ) { - PrintAndLogEx(DEBUG, "DEBUG: no data in graphbuf"); - return 0; + PrintAndLogEx(DEBUG, "DEBUG: no data in graphbuf"); + return 0; } - int startIdx = 0; + int startIdx = 0; //invert here inverts the ask raw demoded bits which has no effect on the demod, but we need the pointer - int errCnt = askdemod_ext(BitStream, &size, &clk, &invert, maxErr, 0, 0, &startIdx); - if ( errCnt < 0 || errCnt > maxErr ) { - PrintAndLogEx(DEBUG, "DEBUG: no data or error found %d, clock: %d", errCnt, clk); - return 0; - } + int errCnt = askdemod_ext(BitStream, &size, &clk, &invert, maxErr, 0, 0, &startIdx); + if ( errCnt < 0 || errCnt > maxErr ) { + PrintAndLogEx(DEBUG, "DEBUG: no data or error found %d, clock: %d", errCnt, clk); + return 0; + } //attempt to Biphase decode BitStream errCnt = BiphaseRawDecode(BitStream, &size, &offset, invert); if (errCnt < 0){ if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: Error BiphaseRawDecode: %d", errCnt); return 0; - } + } if (errCnt > maxErr) { if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: Error BiphaseRawDecode too many errors: %d", errCnt); return 0; @@ -712,16 +712,16 @@ int Cmdaskrawdemod(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) > 25 || cmdp == 'h') return usage_data_rawdemod_ar(); - + return ASKDemod(Cmd, true, false, 0); } int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph, bool verbose) { // sanity check if ( window > len ) window = len; - + if (verbose) PrintAndLogEx(INFO, "performing %d correlations", GraphTraceLen - window); - + //test double autocv = 0.0; // Autocovariance value double ac_value; // Computed autocorrelation value to be returned @@ -729,13 +729,13 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph double mean; size_t correlation = 0; int lastmax = 0; - + // in, len, 4000 mean = compute_mean(in, len); variance = compute_variance(in, len); - + static int CorrelBuffer[MAX_GRAPH_TRACE_LEN]; - + for (int i = 0; i < len - window; ++i) { for (size_t j=0; j < (len - i); j++) { @@ -744,7 +744,7 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph autocv = (1.0 / (len - i)) * autocv; CorrelBuffer[i] = autocv; - + // Autocorrelation is autocovariance divided by variance ac_value = autocv / variance; @@ -754,8 +754,8 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph lastmax = i; } } - - // + + // int hi = 0, idx = 0; int distance = 0, hi_1 = 0, idx_1 = 0; for (int i = 0; i <= len; ++i){ @@ -764,7 +764,7 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph idx = i; } } - + for (int i = idx+1; i <= window; ++i){ if ( CorrelBuffer[i] > hi_1 ) { hi_1 = CorrelBuffer[i]; @@ -773,7 +773,7 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph } int foo = ABS(hi-hi_1); - int bar = (int)((int)((hi+hi_1) / 2) * 0.03); + int bar = (int)((int)((hi+hi_1) / 2) * 0.03); if ( verbose && foo < bar ) { distance = idx_1 - idx; PrintAndLogEx(SUCCESS, "possible 3% visible correlation %4d samples", distance); @@ -782,7 +782,7 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph } else { PrintAndLogEx(FAILED, "no repeating pattern found, try increasing window size"); } - + int retval = correlation; if (SaveGrph) { //GraphTraceLen = GraphTraceLen - window; @@ -792,14 +792,14 @@ int AutoCorrelate(const int *in, int *out, size_t len, int window, bool SaveGrph retval = distance; } else - setClockGrid(correlation, idx); - + setClockGrid(correlation, idx); + CursorCPos = idx_1; CursorDPos = idx_1+retval; DemodBufferLen = 0; - RepaintGraphWindow(); + RepaintGraphWindow(); } - + return retval; } @@ -809,7 +809,7 @@ int CmdAutoCorr(const char *Cmd) { uint8_t cmdp = 0; bool updateGrph = false; bool errors = false; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -818,7 +818,7 @@ int CmdAutoCorr(const char *Cmd) { updateGrph = true; cmdp++; break; - case 'w': + case 'w': window = param_get32ex(Cmd, cmdp+1, 4000, 10); if (window >= GraphTraceLen) { PrintAndLogEx(WARNING, "window must be smaller than trace (%d samples)", GraphTraceLen); @@ -834,7 +834,7 @@ int CmdAutoCorr(const char *Cmd) { } //Validations if (errors || cmdp == 0 ) return usage_data_autocorr(); - + return AutoCorrelate(GraphBuffer, GraphBuffer, GraphTraceLen, window, updateGrph, true); } @@ -847,7 +847,7 @@ int CmdBitsamples(const char *Cmd) PrintAndLogEx(WARNING, "command execution time out"); return false; } - + for (int j = 0; j < sizeof(got); j++) { for (int k = 0; k < 8; k++) { if(got[j] & (1 << (7 - k))) @@ -865,7 +865,7 @@ int CmdBuffClear(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (cmdp == 'h' || cmdp == 'H') return usage_data_buffclear(); - + UsbCommand c = {CMD_BUFF_CLEAR, {0,0,0}}; clearCommandBuffer(); SendCommand(&c); @@ -924,12 +924,12 @@ int CmdGraphShiftZero(const char *Cmd) { for(int i = 0; i < GraphTraceLen; i++){ if ( i+shift >= GraphTraceLen) shiftedVal = GraphBuffer[i]; - else + else shiftedVal = GraphBuffer[i] + shift; - - if (shiftedVal > 127) + + if (shiftedVal > 127) shiftedVal = 127; - else if (shiftedVal < -127) + else if (shiftedVal < -127) shiftedVal = -127; GraphBuffer[i] = shiftedVal; } @@ -951,12 +951,12 @@ int AskEdgeDetect(const int *in, int *out, int len, int threshold) { //by marshmellow //use large jumps in read samples to identify edges of waves and then amplify that wave to max -//similar to dirtheshold, threshold commands +//similar to dirtheshold, threshold commands //takes a threshold length which is the measured length between two samples then determines an edge int CmdAskEdgeDetect(const char *Cmd) { int thresLen = 25; int ans = 0; - sscanf(Cmd, "%i", &thresLen); + sscanf(Cmd, "%i", &thresLen); ans = AskEdgeDetect(GraphBuffer, GraphBuffer, GraphTraceLen, thresLen); RepaintGraphWindow(); @@ -996,23 +996,23 @@ int CmdDetectClockRate(const char *Cmd) { char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert) { static char fType[8]; - memset(fType, 0x00, 8); + memset(fType, 0x00, 8); char *fskType = fType; - + if (fchigh == 10 && fclow == 8){ - + if (invert) memcpy(fskType, "FSK2a", 5); else memcpy(fskType, "FSK2", 4); - + } else if (fchigh == 8 && fclow == 5) { - + if (invert) memcpy(fskType, "FSK1", 4); else memcpy(fskType, "FSK1a", 5); - + } else { memcpy(fskType, "FSK??", 5); } @@ -1033,7 +1033,7 @@ int FSKrawDemod(const char *Cmd, bool verbose) { invert = param_get8(Cmd, 1); fchigh = param_get8(Cmd, 2); fclow = param_get8(Cmd, 3); - + if (strlen(Cmd) > 0 && strlen(Cmd) <= 2) { if (rfLen == 1) { invert = 1; //if invert option only is used @@ -1044,7 +1044,7 @@ int FSKrawDemod(const char *Cmd, bool verbose) { uint8_t bits[MAX_GRAPH_TRACE_LEN] = {0}; size_t BitLen = getFromGraphBuf(bits); if (BitLen == 0) return 0; - + //get field clock lengths uint16_t fcs = 0; if (!fchigh || !fclow) { @@ -1115,7 +1115,7 @@ int PSKDemod(const char *Cmd, bool verbose) { if (errCnt > maxErr){ if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, BitLen, errCnt); return 0; - } + } if (errCnt < 0|| BitLen < 16){ //throw away static - allow 1 and -1 (in case of threshold command first) if (g_debugMode || verbose) PrintAndLogEx(DEBUG, "DEBUG: (PSKdemod) no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, BitLen, errCnt); return 0; @@ -1154,7 +1154,7 @@ int CmdPSKIdteck(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: size not correct: %d", size); else PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: idx: %d",idx); - + // if didn't find preamble try again inverting if (!PSKDemod("1", false)) { PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck PSKDemod failed"); @@ -1162,11 +1162,11 @@ int CmdPSKIdteck(const char *Cmd) { } idx = detectIdteck(DemodBuffer, &size); if (idx < 0){ - + if (idx == -1) PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: not enough samples"); else if (idx == -2) - PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: just noise"); + PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: just noise"); else if (idx == -3) PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: preamble not found"); else if (idx == -4) @@ -1175,15 +1175,15 @@ int CmdPSKIdteck(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - Idteck: idx: %d",idx); return 0; - } + } } setDemodBuf(DemodBuffer, 64, idx); - + //got a good demod uint32_t id = 0; uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); - + //parity check (TBD) //checksum check (TBD) @@ -1205,22 +1205,22 @@ int NRZrawDemod(const char *Cmd, bool verbose) { invert = 1; clk = 0; } - + if (invert != 0 && invert != 1) { PrintAndLogEx(WARNING, "(NRZrawDemod) Invalid argument: %s", Cmd); return 0; } - + uint8_t bits[MAX_GRAPH_TRACE_LEN] = {0}; size_t BitLen = getFromGraphBuf(bits); - + if (BitLen == 0) return 0; - + errCnt = nrzRawDemod(bits, &BitLen, &clk, &invert, &clkStartIdx); if (errCnt > maxErr){ PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt); return 0; - } + } if (errCnt < 0 || BitLen < 16){ //throw away static - allow 1 and -1 (in case of threshold command first) PrintAndLogEx(DEBUG, "DEBUG: (NRZrawDemod) no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d", clk, invert, BitLen, errCnt); return 0; @@ -1237,7 +1237,7 @@ int NRZrawDemod(const char *Cmd, bool verbose) { // Now output the bitstream to the scrollback by line of 16 bits printDemodBuff(); } - return 1; + return 1; } int CmdNRZrawDemod(const char *Cmd) { @@ -1258,7 +1258,7 @@ int CmdPSK1rawDemod(const char *Cmd) { int ans = PSKDemod(Cmd, true); //output if (!ans){ - if (g_debugMode) PrintAndLogEx(WARNING, "Error demoding: %d",ans); + if (g_debugMode) PrintAndLogEx(WARNING, "Error demoding: %d",ans); return 0; } PrintAndLogEx(NORMAL, "PSK1 demoded bitstream:"); @@ -1275,13 +1275,13 @@ int CmdPSK2rawDemod(const char *Cmd) { int ans = PSKDemod(Cmd, true); if (!ans){ - if (g_debugMode) PrintAndLogEx(WARNING, "Error demoding: %d",ans); + if (g_debugMode) PrintAndLogEx(WARNING, "Error demoding: %d",ans); return 0; - } + } psk1TOpsk2(DemodBuffer, DemodBufferLen); PrintAndLogEx(NORMAL, "PSK2 demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); + printDemodBuff(); return 1; } @@ -1291,7 +1291,7 @@ int CmdRawDemod(const char *Cmd) { if (strlen(Cmd) > 35 || strlen(Cmd) < 2) return usage_data_rawdemod(); - + str_lower( (char *)Cmd); if (str_startswith(Cmd, "fs")) ans = CmdFSKrawdemod(Cmd+2); @@ -1355,7 +1355,7 @@ int CmdHexsamples(const char *Cmd) { /* if no args send something */ if (requested == 0) requested = 8; - + if (offset + requested > sizeof(got)) { PrintAndLogEx(NORMAL, "Tried to read past end of buffer, + > %d", BIGBUF_SIZE); return 0; @@ -1365,7 +1365,7 @@ int CmdHexsamples(const char *Cmd) { PrintAndLogEx(WARNING, "command execution time out"); return false; } - + i = 0; for (j = 0; j < requested; j++) { i++; @@ -1438,7 +1438,7 @@ int getSamples(int n, bool silent) { } if (!silent) PrintAndLogEx(NORMAL, "Data fetched"); - + uint8_t bits_per_sample = 8; //Old devices without this feature would send 0 at arg[0] @@ -1447,11 +1447,11 @@ int getSamples(int n, bool silent) { if (!silent) PrintAndLogEx(NORMAL, "Samples @ %d bits/smpl, decimation 1:%d ", sc->bits_per_sample, sc->decimation); bits_per_sample = sc->bits_per_sample; } - + if (bits_per_sample < 8) { - + if (!silent) PrintAndLogEx(NORMAL, "Unpacking..."); - + BitstreamOut bout = { got, bits_per_sample * n, 0}; int j =0; for (j = 0; j * bits_per_sample < n * 8 && j < n; j++) { @@ -1459,9 +1459,9 @@ int getSamples(int n, bool silent) { GraphBuffer[j] = ((int) sample )- 128; } GraphTraceLen = j; - + if (!silent) PrintAndLogEx(NORMAL, "Unpacked %d samples" , j ); - + } else { for (int j = 0; j < n; j++) { GraphBuffer[j] = ((int)got[j]) - 128; @@ -1497,8 +1497,8 @@ int CmdTuneSamples(const char *Cmd) { DemodBufferLen = 0; setClockGrid(0, 0); RepaintGraphWindow(); - - + + int timeout = 0; PrintAndLogEx(INFO, "\nmeasuring antenna characteristics, please wait..."); @@ -1515,14 +1515,14 @@ int CmdTuneSamples(const char *Cmd) { } } PrintAndLogEx(NORMAL, "\n"); - + uint32_t v_lf125 = resp.arg[0]; uint32_t v_lf134 = resp.arg[0] >> 32; - + uint32_t v_hf = resp.arg[1]; uint32_t peakf = resp.arg[2]; uint32_t peakv = resp.arg[2] >> 32; - + if ( v_lf125 > NON_VOLTAGE ) PrintAndLogEx(SUCCESS, "LF antenna: %5.2f V - 125.00 kHz", (v_lf125 * ANTENNA_ERROR)/1000.0); if ( v_lf134 > NON_VOLTAGE ) @@ -1531,7 +1531,7 @@ int CmdTuneSamples(const char *Cmd) { PrintAndLogEx(SUCCESS, "LF optimal: %5.2f V - %6.2f kHz", (peakv * ANTENNA_ERROR)/1000.0, 12000.0/(peakf+1)); char judgement[20]; - memset(judgement, 0, sizeof(judgement)); + memset(judgement, 0, sizeof(judgement)); // LF evaluation if (peakv < LF_UNUSABLE_V) sprintf(judgement, _RED_(UNUSABLE) ); @@ -1539,25 +1539,25 @@ int CmdTuneSamples(const char *Cmd) { sprintf(judgement, _YELLOW_(MARGINAL) ); else sprintf(judgement, _GREEN_(OK) ); - + PrintAndLogEx(NORMAL, "%sLF antenna is %s \n" , (peakv < LF_UNUSABLE_V) ? _CYAN_([!]) : _GREEN_([+]) , judgement ); - + // HF evaluation if ( v_hf > NON_VOLTAGE ) PrintAndLogEx(SUCCESS, "HF antenna: %5.2f V - 13.56 MHz", (v_hf * ANTENNA_ERROR)/1000.0); memset(judgement, 0, sizeof(judgement)); - - if (v_hf < HF_UNUSABLE_V) + + if (v_hf < HF_UNUSABLE_V) sprintf(judgement, _RED_(UNUSABLE) ); else if (v_hf < HF_MARGINAL_V) sprintf(judgement, _YELLOW_(MARGINAL) ); else sprintf(judgement, _GREEN_(OK) ); - + PrintAndLogEx(NORMAL, "%sHF antenna is %s" , (v_hf < HF_UNUSABLE_V) ? _CYAN_([!]) : _GREEN_([+]) , judgement @@ -1590,7 +1590,7 @@ int CmdLoad(const char *Cmd) { len = strlen(Cmd); if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, Cmd, len); - + FILE *f = fopen(filename, "r"); if (!f) { PrintAndLogEx(WARNING, "couldn't open '%s'", filename); @@ -1607,7 +1607,7 @@ int CmdLoad(const char *Cmd) { fclose(f); PrintAndLogEx(SUCCESS, "loaded %d samples", GraphTraceLen); - + uint8_t bits[GraphTraceLen]; size_t size = getFromGraphBuf(bits); // set signal properties low/high/mean/amplitude and is_noise detection @@ -1639,7 +1639,7 @@ int CmdLtrim(const char *Cmd) { // trim graph from the beginning int CmdRtrim(const char *Cmd) { - + int ds = atoi(Cmd); // sanitycheck @@ -1656,7 +1656,7 @@ int CmdMtrim(const char *Cmd) { sscanf(Cmd, "%i %i", &start, &stop); if (start > GraphTraceLen || stop > GraphTraceLen || start > stop) return 1; - + // leave start position sample start++; @@ -1706,7 +1706,7 @@ int CmdSave(const char *Cmd) { len = strlen(Cmd); if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, Cmd, len); - + FILE *f = fopen(filename, "w"); if(!f) { PrintAndLogEx(WARNING, "couldn't open '%s'", filename); @@ -1736,10 +1736,10 @@ int CmdScale(const char *Cmd) { int directionalThreshold(const int* in, int *out, size_t len, int8_t up, int8_t down) { int lastValue = in[0]; - + // Will be changed at the end, but init 0 as we adjust to last samples // value if no threshold kicks in. - out[0] = 0; + out[0] = 0; for (size_t i = 1; i < len; ++i) { // Apply first threshold to samples heading up @@ -1760,9 +1760,9 @@ int directionalThreshold(const int* in, int *out, size_t len, int8_t up, int8_t out[i] = out[i-1]; } } - + // Align with first edited sample. - out[0] = out[1]; + out[0] = out[1]; return 0; } @@ -1773,7 +1773,7 @@ int CmdDirectionalThreshold(const char *Cmd) { PrintAndLogEx(INFO, "Applying Up Threshold: %d, Down Threshold: %d\n", up, down); directionalThreshold(GraphBuffer, GraphBuffer, GraphTraceLen, up, down); - + // set signal properties low/high/mean/amplitude and isnoice detection uint8_t bits[GraphTraceLen]; size_t size = getFromGraphBuf(bits); @@ -1836,9 +1836,9 @@ int Cmdbin2hex(const char *Cmd) { char c = Cmd[bg]; if( c == '1') pushBit(&bout, 1); - else if( c == '0') + else if( c == '0') pushBit(&bout, 0); - else + else PrintAndLogEx(NORMAL, "Ignoring '%c'", c); } @@ -1901,7 +1901,7 @@ void GetHiLoTone(int *LowTone, int *HighTone, int clk, int LowToneFC, int HighTo //int HighToneMod = clk mod HighToneFC; int LeftHalfFCCnt = (LowToneFC % 2) + (LowToneFC/2); //truncate int FCs_per_clk = clk / LowToneFC; - + // need to correctly split up the clock to field clocks. // First attempt uses modifiers on each end to make up for when FCs don't evenly divide into Clk @@ -1955,7 +1955,7 @@ void GetHiLoTone(int *LowTone, int *HighTone, int clk, int LowToneFC, int HighTo } } -//old CmdFSKdemod adapted by marshmellow +//old CmdFSKdemod adapted by marshmellow //converts FSK to clear NRZ style wave. (or demodulates) int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { uint8_t ans = 0; @@ -1973,7 +1973,7 @@ int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { } return 0; } - + int i, j; int LowTone[clk]; int HighTone[clk]; @@ -1996,7 +1996,7 @@ int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { } // now we have the abs( [average sample value per clk] * 100 ) for each tone - // loop through again [all samples] - clk - 16 + // loop through again [all samples] - clk - 16 // note why 16??? is 16 the largest FC? changed to LowToneFC as that should be the > fc for(i = 0; i < *dataLen - clk - LowToneFC; ++i) { int lowTot = 0, highTot = 0; @@ -2009,8 +2009,8 @@ int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { highTot += (data[i + j] >> 16); } - // subtract the sum of lowTone averages by the sum of highTone averages as it - // and write back the new graph value + // subtract the sum of lowTone averages by the sum of highTone averages as it + // and write back the new graph value data[i] = lowTot - highTot; } // update dataLen to what we put back to the data sample buffer @@ -2019,7 +2019,7 @@ int FSKToNRZ(int *data, int *dataLen, int clk, int LowToneFC, int HighToneFC) { } int CmdFSKToNRZ(const char *Cmd) { - // take clk, fc_low, fc_high + // take clk, fc_low, fc_high // blank = auto; bool errors = false; char cmdp = 0; @@ -2097,7 +2097,7 @@ static command_t CommandTable[] = { {"norm", CmdNorm, 1, "Normalize max/min to +/-128"}, {"plot", CmdPlot, 1, "Show graph window (hit 'h' in window for keystroke help)"}, {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] [o] [l] -- print the data in the DemodBuffer - 'x' for hex output"}, - {"rawdemod", CmdRawDemod, 1, "[modulation] ... -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"}, + {"rawdemod", CmdRawDemod, 1, "[modulation] ... -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"}, {"samples", CmdSamples, 0, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"}, {"save", CmdSave, 1, " -- Save trace (from graph window)"}, {"setgraphmarkers", CmdSetGraphMarkers, 1, "[orange_marker] [blue_marker] (in graph window)"}, diff --git a/client/cmdflashmem.c b/client/cmdflashmem.c index cedb9516d..b576f43f7 100644 --- a/client/cmdflashmem.c +++ b/client/cmdflashmem.c @@ -29,7 +29,7 @@ static int CmdHelp(const char *Cmd); int usage_flashmem_spibaud(void){ PrintAndLogEx(NORMAL, "Usage: mem spibaud [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h this help"); + PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, " SPI baudrate in MHz [24|48]"); PrintAndLogEx(NORMAL, " "); PrintAndLogEx(NORMAL, " If >= 24Mhz, FASTREADS instead of READS instruction will be used."); @@ -48,7 +48,7 @@ int usage_flashmem_read(void){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " mem read o 0 l 32"); // read 32 bytes starting at offset 0 - PrintAndLogEx(NORMAL, " mem read o 1024 l 10"); // read 10 bytes starting at offset 1024 + PrintAndLogEx(NORMAL, " mem read o 1024 l 10"); // read 10 bytes starting at offset 1024 return 0; } int usage_flashmem_load(void){ @@ -82,7 +82,7 @@ int usage_flashmem_save(void){ return 0; } int usage_flashmem_wipe(void){ - + PrintAndLogEx(WARNING, "[OBS] use with caution."); PrintAndLogEx(NORMAL, "Wipe flash memory on device, which fills memory with 0xFF\n"); @@ -104,7 +104,7 @@ int usage_flashmem_info(void){ PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " mem info"); PrintAndLogEx(NORMAL, " mem info s"); - return 0; + return 0; } int CmdFlashMemRead(const char *Cmd) { @@ -112,7 +112,7 @@ int CmdFlashMemRead(const char *Cmd) { uint8_t cmdp = 0; bool errors = false; uint32_t start_index = 0, len = 0; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'o': @@ -121,7 +121,7 @@ int CmdFlashMemRead(const char *Cmd) { break; case 'l': len = param_get32ex(Cmd, cmdp+1, 0, 10); - cmdp += 2; + cmdp += 2; break; case 'h': return usage_flashmem_read(); @@ -131,16 +131,16 @@ int CmdFlashMemRead(const char *Cmd) { break; } } - + //Validations - if (errors || cmdp == 0 ) return usage_flashmem_read(); - + if (errors || cmdp == 0 ) return usage_flashmem_read(); + if (start_index + len > FLASH_MEM_MAX_SIZE) { PrintAndLogDevice(WARNING, "error, start_index + length is larger than available memory"); return 1; } - UsbCommand c = {CMD_FLASHMEM_READ, {start_index, len, 0}}; + UsbCommand c = {CMD_FLASHMEM_READ, {start_index, len, 0}}; clearCommandBuffer(); SendCommand(&c); return 0; @@ -161,11 +161,11 @@ int CmdFlashmemSpiBaudrate(const char *Cmd) { int CmdFlashMemLoad(const char *Cmd){ uint32_t start_index = 0; - char filename[FILE_PATH_SIZE] = {0}; + char filename[FILE_PATH_SIZE] = {0}; bool errors = false; - uint8_t cmdp = 0; + uint8_t cmdp = 0; Dictionary_t d = DICTIONARY_NONE; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -175,8 +175,8 @@ int CmdFlashMemLoad(const char *Cmd){ PrintAndLogEx(FAILED, "Filename too long"); errors = true; break; - } - cmdp += 2; + } + cmdp += 2; break; case 'o': start_index = param_get32ex(Cmd, cmdp+1, 0, 10); @@ -200,15 +200,15 @@ int CmdFlashMemLoad(const char *Cmd){ break; } } - + //Validations - if (errors || cmdp == 0 ) return usage_flashmem_load(); + if (errors || cmdp == 0 ) return usage_flashmem_load(); size_t datalen = 0; uint16_t keycount = 0; int res = 0; uint8_t *data = calloc(FLASH_MEM_MAX_SIZE, sizeof(uint8_t)); - + switch (d) { case DICTIONARY_MIFARE: start_index = DEFAULT_MF_KEYS_OFFSET; @@ -218,8 +218,8 @@ int CmdFlashMemLoad(const char *Cmd){ return 1; } data[0] = (keycount >> 0) & 0xFF; - data[1] = (keycount >> 8) & 0xFF; - datalen += 2; + data[1] = (keycount >> 8) & 0xFF; + datalen += 2; break; case DICTIONARY_T55XX: start_index = DEFAULT_T55XX_KEYS_OFFSET; @@ -229,7 +229,7 @@ int CmdFlashMemLoad(const char *Cmd){ return 1; } data[0] = (keycount >> 0) & 0xFF; - data[1] = (keycount >> 8) & 0xFF; + data[1] = (keycount >> 8) & 0xFF; datalen += 2; break; case DICTIONARY_ICLASS: @@ -240,26 +240,26 @@ int CmdFlashMemLoad(const char *Cmd){ return 1; } data[0] = (keycount >> 0) & 0xFF; - data[1] = (keycount >> 8) & 0xFF; - datalen += 2; + data[1] = (keycount >> 8) & 0xFF; + datalen += 2; break; default: - + res = loadFile(filename, "bin", data, &datalen); //int res = loadFileEML( filename, "eml", data, &datalen); if ( res ) { free(data); return 1; } - + if (datalen > FLASH_MEM_MAX_SIZE) { PrintAndLogDevice(WARNING, "error, filesize is larger than available memory"); free(data); return 1; } - break; + break; } - + data = realloc(data, datalen); //Send to device @@ -268,40 +268,40 @@ int CmdFlashMemLoad(const char *Cmd){ while (bytes_remaining > 0){ uint32_t bytes_in_packet = MIN(FLASH_MEM_BLOCK_SIZE, bytes_remaining); - + UsbCommand c = {CMD_FLASHMEM_WRITE, {start_index + bytes_sent, bytes_in_packet, 0}}; - + memcpy(c.d.asBytes, data + bytes_sent, bytes_in_packet); clearCommandBuffer(); SendCommand(&c); bytes_remaining -= bytes_in_packet; bytes_sent += bytes_in_packet; - + UsbCommand resp; if ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); free(data); return 1; } - + uint8_t isok = resp.arg[0] & 0xFF; if (!isok) PrintAndLogEx(FAILED, "Flash write fail [offset %u]", bytes_sent); - + } free(data); - + PrintAndLogEx(SUCCESS, "Wrote %u bytes to offset %u", datalen, start_index); return 0; } int CmdFlashMemSave(const char *Cmd){ - char filename[FILE_PATH_SIZE] = {0}; + char filename[FILE_PATH_SIZE] = {0}; uint8_t cmdp = 0; bool errors = false; uint32_t start_index = 0, len = FLASH_MEM_MAX_SIZE; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_flashmem_save(); @@ -319,8 +319,8 @@ int CmdFlashMemSave(const char *Cmd){ PrintAndLogEx(FAILED, "Filename too long"); errors = true; break; - } - cmdp += 2; + } + cmdp += 2; break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); @@ -328,7 +328,7 @@ int CmdFlashMemSave(const char *Cmd){ break; } } - + //Validations if (errors || cmdp == 0 ) return usage_flashmem_save(); @@ -337,7 +337,7 @@ int CmdFlashMemSave(const char *Cmd){ PrintAndLogDevice(WARNING, "error, cannot allocate memory "); return 1; } - + PrintAndLogEx(NORMAL, "downloading %u bytes from flashmem", len); if ( !GetFromDevice(FLASH_MEM, dump, len, start_index, NULL, -1, true) ) { PrintAndLogEx(FAILED, "ERROR; downloading flashmem"); @@ -355,10 +355,10 @@ int CmdFlashMemWipe(const char *Cmd){ uint8_t cmdp = 0; bool errors = false; bool initalwipe = false; - uint8_t page = 0; + uint8_t page = 0; while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { - case 'h': return usage_flashmem_wipe(); + case 'h': return usage_flashmem_wipe(); case 'p': page = param_get8ex(Cmd, cmdp+1, 0, 10); if ( page > 2 ) { @@ -378,10 +378,10 @@ int CmdFlashMemWipe(const char *Cmd){ break; } } - + //Validations - if (errors || cmdp == 0 ) return usage_flashmem_wipe(); - + if (errors || cmdp == 0 ) return usage_flashmem_wipe(); + UsbCommand c = {CMD_FLASHMEM_WIPE, {page, initalwipe, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -393,7 +393,7 @@ int CmdFlashMemWipe(const char *Cmd){ uint8_t isok = resp.arg[0] & 0xFF; if (isok) PrintAndLogEx(SUCCESS, "Flash WIPE ok"); - else + else PrintAndLogEx(FAILED, "Flash WIPE failed"); return 0; @@ -402,18 +402,18 @@ int CmdFlashMemInfo(const char *Cmd){ uint8_t sha_hash[20] = {0}; mbedtls_rsa_context rsa; - + uint8_t cmdp = 0; bool errors = false, shall_write = false, shall_sign = false; while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { - case 'h': return usage_flashmem_info(); + case 'h': return usage_flashmem_info(); case 's': { shall_sign = true; cmdp++; break; } - case 'w': + case 'w': shall_write = true; cmdp++; break; @@ -423,10 +423,10 @@ int CmdFlashMemInfo(const char *Cmd){ break; } } - + //Validations if (errors ) return usage_flashmem_info(); - + UsbCommand c = {CMD_FLASHMEM_INFO, {0, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -435,12 +435,12 @@ int CmdFlashMemInfo(const char *Cmd){ PrintAndLogEx(WARNING, "timeout while waiting for reply."); return 1; } - + uint8_t isok = resp.arg[0] & 0xFF; if (!isok) { PrintAndLogEx(FAILED, "failed"); return 1; - } + } // validate signature here rdv40_validation_t mem; @@ -448,18 +448,18 @@ int CmdFlashMemInfo(const char *Cmd){ // Flash ID hash (sha1) mbedtls_sha1( mem.flashid, sizeof(mem.flashid), sha_hash ); - + // print header PrintAndLogEx(INFO, "\n--- Flash memory Information ---------"); - PrintAndLogEx(INFO, "-------------------------------------------------------------"); + PrintAndLogEx(INFO, "-------------------------------------------------------------"); PrintAndLogEx(INFO, "ID | %s", sprint_hex(mem.flashid, sizeof(mem.flashid) )); PrintAndLogEx(INFO, "SHA1 | %s", sprint_hex(sha_hash, sizeof(sha_hash))); PrintAndLogEx(INFO, "RSA SIGNATURE |"); print_hex_break( mem.signature, sizeof(mem.signature), 32); -//------------------------------------------------------------------------------- +//------------------------------------------------------------------------------- // Example RSA-1024 keypair, for test purposes (from common/polarssl/rsa.c) -// +// // public key modulus N #define RSA_N "9292758453063D803DD603D5E777D788" \ @@ -484,7 +484,7 @@ int CmdFlashMemInfo(const char *Cmd){ "AF1FEDFDDE2BEB674CA15F3E81A1521E" \ "071513A1E85B5DFA031F21ECAE91A34D" -// prime P +// prime P #define RSA_P "C36D0EB7FCD285223CFB5AABA5BDA3D8" \ "2C01CAD19EA484A87EA4377637E75500" \ "FCB2005C5C7DD6EC4AC023CDA285D796" \ @@ -511,7 +511,7 @@ int CmdFlashMemInfo(const char *Cmd){ "F5A3B2A5D33605AEBBCCBA7FEB9F2D2F" \ "A74206CEC169D74BF5A8C50D6F48EA08" - + #define KEY_LEN 128 mbedtls_rsa_init(&rsa, MBEDTLS_RSA_PKCS_V15, 0); @@ -528,53 +528,53 @@ int CmdFlashMemInfo(const char *Cmd){ mbedtls_mpi_read_string( &rsa.QP, 16, RSA_QP ); PrintAndLogEx(INFO, "KEY length | %d", KEY_LEN); - + bool is_keyok = ( mbedtls_rsa_check_pubkey( &rsa ) == 0 || mbedtls_rsa_check_privkey( &rsa ) == 0 ); if (is_keyok) PrintAndLogEx(SUCCESS, "RSA key validation ok"); else PrintAndLogEx(FAILED, "RSA key validation failed"); - - // + + // uint8_t from_device[KEY_LEN]; uint8_t sign[KEY_LEN]; // to be verified memcpy(from_device, mem.signature, KEY_LEN); - + // to be signed (all zeros memset(sign, 0, KEY_LEN); - + // Signing (private key) if (shall_sign) { - + int is_signed = mbedtls_rsa_pkcs1_sign( &rsa, NULL, NULL, MBEDTLS_RSA_PRIVATE, MBEDTLS_MD_SHA1, 20, sha_hash, sign ); - if (is_signed == 0) + if (is_signed == 0) PrintAndLogEx(SUCCESS, "RSA Signing ok"); else PrintAndLogEx(FAILED, "RSA Signing failed"); if (shall_write) { // save to mem - c = (UsbCommand){CMD_FLASHMEM_WRITE, {FLASH_MEM_SIGNATURE_OFFSET, FLASH_MEM_SIGNATURE_LEN, 0}}; - memcpy(c.d.asBytes, sign, sizeof(sign)); + c = (UsbCommand){CMD_FLASHMEM_WRITE, {FLASH_MEM_SIGNATURE_OFFSET, FLASH_MEM_SIGNATURE_LEN, 0}}; + memcpy(c.d.asBytes, sign, sizeof(sign)); clearCommandBuffer(); SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); } else { - + if (!resp.arg[0]) PrintAndLogEx(FAILED, "Writing signature failed"); else PrintAndLogEx(SUCCESS, "Writing signature ok [offset: %u]", FLASH_MEM_SIGNATURE_OFFSET); - + } } PrintAndLogEx(INFO, "Signed | "); print_hex_break( sign, sizeof(sign), 32); } - + // Verify (public key) int is_verified = mbedtls_rsa_pkcs1_verify( &rsa, NULL, NULL, MBEDTLS_RSA_PUBLIC, MBEDTLS_MD_SHA1, 20, sha_hash, from_device ); if (is_verified == 0) diff --git a/client/cmdhf.c b/client/cmdhf.c index cb4e424da..af5aa4c2b 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -38,14 +38,14 @@ int usage_hf_snoop(){ int CmdHFSearch(const char *Cmd){ - char cmdp = param_getchar(Cmd, 0); + char cmdp = param_getchar(Cmd, 0); if (cmdp == 'h' || cmdp == 'H') return usage_hf_search(); - + int ans = CmdHF14AInfo("s"); if (ans > 0) { PrintAndLogEx(SUCCESS, "\nValid ISO14443-A Tag Found\n"); return ans; - } + } ans = HF15Reader("", false); if (ans) { PrintAndLogEx(SUCCESS, "\nValid ISO15693 Tag Found\n"); @@ -80,7 +80,7 @@ int CmdHFSearch(const char *Cmd){ return ans; } */ - + PrintAndLogEx(FAILED, "\nno known/supported 13.56 MHz tags found\n"); return 0; } @@ -94,12 +94,12 @@ int CmdHFTune(const char *Cmd) { } int CmdHFSnoop(const char *Cmd) { - char cmdp = param_getchar(Cmd, 0); + char cmdp = param_getchar(Cmd, 0); if (cmdp == 'h' || cmdp == 'H') return usage_hf_snoop(); - + int skippairs = param_get32ex(Cmd, 0, 0, 10); int skiptriggers = param_get32ex(Cmd, 1, 0, 10); - + UsbCommand c = {CMD_HF_SNIFFER, {skippairs, skiptriggers, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -121,7 +121,7 @@ static command_t CommandTable[] = { {"mfdes", CmdHFMFDes, 1, "{ MIFARE Desfire RFIDs... }"}, {"topaz", CmdHFTopaz, 1, "{ TOPAZ (NFC Type 1) RFIDs... }"}, {"fido", CmdHFFido, 1, "{ FIDO and FIDO2 authenticators... }"}, - {"list", CmdTraceList, 0, "List protocol data in trace buffer"}, + {"list", CmdTraceList, 0, "List protocol data in trace buffer"}, {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, {"search", CmdHFSearch, 1, "Search for known HF tags [preliminary]"}, {"snoop", CmdHFSnoop, 0, " Generic HF Snoop"}, @@ -131,7 +131,7 @@ static command_t CommandTable[] = { int CmdHF(const char *Cmd) { clearCommandBuffer(); CmdsParse(CommandTable, Cmd); - return 0; + return 0; } int CmdHelp(const char *Cmd) { diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index 27f670fac..90753fef8 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -21,14 +21,14 @@ static const manufactureName manufactureMapping[] = { // ID, "Vendor Country" { 0x01, "Motorola UK" }, { 0x02, "ST Microelectronics SA France" }, - { 0x03, "Hitachi, Ltd Japan" }, - { 0x04, "NXP Semiconductors Germany" }, - { 0x05, "Infineon Technologies AG Germany" }, - { 0x06, "Cylink USA" }, + { 0x03, "Hitachi, Ltd Japan" }, + { 0x04, "NXP Semiconductors Germany" }, + { 0x05, "Infineon Technologies AG Germany" }, + { 0x06, "Cylink USA" }, { 0x07, "Texas Instrument France" }, - { 0x08, "Fujitsu Limited Japan" }, - { 0x09, "Matsushita Electronics Corporation, Semiconductor Company Japan" }, - { 0x0A, "NEC Japan" }, + { 0x08, "Fujitsu Limited Japan" }, + { 0x09, "Matsushita Electronics Corporation, Semiconductor Company Japan" }, + { 0x0A, "NEC Japan" }, { 0x0B, "Oki Electric Industry Co. Ltd Japan" }, { 0x0C, "Toshiba Corp. Japan" }, { 0x0D, "Mitsubishi Electric Corp. Japan" }, @@ -69,7 +69,7 @@ static const manufactureName manufactureMapping[] = { { 0x30, "BeeDar Technology Inc. USA" }, { 0x31, "RFIDsec Denmark" }, { 0x32, "Schweizer Electronic AG Germany" }, - { 0x33, "AMIC Technology Corp Taiwan" }, + { 0x33, "AMIC Technology Corp Taiwan" }, { 0x34, "Mikron JSC Russia" }, { 0x35, "Fraunhofer Institute for Photonic Microsystems Germany" }, { 0x36, "IDS Microchip AG Switzerland" }, @@ -81,7 +81,7 @@ static const manufactureName manufactureMapping[] = { { 0x3C, "Verayo Inc. USA" }, { 0x3D, "HID Global USA" }, { 0x3E, "Productivity Engineering Gmbh Germany" }, - { 0x3F, "Austriamicrosystems AG (reserved) Austria" }, + { 0x3F, "Austriamicrosystems AG (reserved) Austria" }, { 0x40, "Gemalto SA France" }, { 0x41, "Renesas Electronics Corporation Japan" }, { 0x42, "3Alogics Inc Korea" }, @@ -129,24 +129,24 @@ static const manufactureName manufactureMapping[] = { { 0x6C, "Wisesec Ltd Israel" }, { 0x7C, "DB HiTek Co Ltd Korea" }, { 0x7D, "SATO Vicinity Australia" }, - { 0x7E, "Holtek Taiwan" }, + { 0x7E, "Holtek Taiwan" }, { 0x00, "no tag-info available" } // must be the last entry }; // get a product description based on the UID // uid[8] tag uid -// returns description of the best match +// returns description of the best match char* getTagInfo(uint8_t uid) { int i; int len = sizeof(manufactureMapping) / sizeof(manufactureName); - - for ( i = 0; i < len; ++i ) - if ( uid == manufactureMapping[i].uid) + + for ( i = 0; i < len; ++i ) + if ( uid == manufactureMapping[i].uid) return manufactureMapping[i].desc; //No match, return default - return manufactureMapping[len-1].desc; + return manufactureMapping[len-1].desc; } // iso14a apdu input frame length @@ -171,7 +171,7 @@ int usage_hf_14a_sim(void) { // PrintAndLogEx(NORMAL, " u : 4, 7 or 10 byte UID"); PrintAndLogEx(NORMAL, " u : 4, 7 byte UID"); PrintAndLogEx(NORMAL, " x : (Optional) Performs the 'reader attack', nr/ar attack against a reader"); - PrintAndLogEx(NORMAL, " e : (Optional) Fill simulator keys from found keys"); + PrintAndLogEx(NORMAL, " e : (Optional) Fill simulator keys from found keys"); PrintAndLogEx(NORMAL, " v : (Optional) Verbose"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf 14a sim t 1 u 11223344 x"); @@ -232,11 +232,11 @@ int Hf14443_4aGetCardData(iso14a_card_select_t * card) { UsbCommand resp; WaitForResponse(CMD_ACK,&resp); - + memcpy(card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - + if(select_status == 0) { PrintAndLog("E->iso14443a card select failed"); return 1; @@ -261,22 +261,22 @@ int Hf14443_4aGetCardData(iso14a_card_select_t * card) { return 1; } PrintAndLog(" ATS: %s", sprint_hex(card->ats, card->ats_len)); - + return 0; } int CmdHF14AReader(const char *Cmd) { uint32_t cm = ISO14A_CONNECT; - bool disconnectAfter = true, silent = false; + bool disconnectAfter = true, silent = false; int cmdp = 0; - + while (param_getchar(Cmd, cmdp) != 0x00) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_hf_14a_reader(); case '3': - cm |= ISO14A_NO_RATS; + cm |= ISO14A_NO_RATS; break; case 'k': disconnectAfter = false; @@ -290,13 +290,13 @@ int CmdHF14AReader(const char *Cmd) { default: PrintAndLogEx(WARNING, "Unknown command."); return 1; - } + } cmdp++; } if (!disconnectAfter) - cm |= ISO14A_NO_DISCONNECT; - + cm |= ISO14A_NO_DISCONNECT; + UsbCommand c = {CMD_READER_ISO_14443a, {cm, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -308,18 +308,18 @@ int CmdHF14AReader(const char *Cmd) { DropField(); return 1; } - + iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); - /* + /* 0: couldn't read 1: OK, with ATS 2: OK, no ATS - 3: proprietary Anticollision + 3: proprietary Anticollision */ uint64_t select_status = resp.arg[0]; - + if (select_status == 0) { if (!silent) PrintAndLogEx(WARNING, "iso14443a card select failed"); DropField(); @@ -340,7 +340,7 @@ int CmdHF14AReader(const char *Cmd) { if(card.ats_len >= 3) { // a valid ATS consists of at least the length byte (TL) and 2 CRC bytes PrintAndLogEx(NORMAL, " ATS : %s", sprint_hex(card.ats, card.ats_len)); } - + if (!disconnectAfter) { if (!silent) PrintAndLogEx(SUCCESS, "Card is selected. You can now start sending commands"); } @@ -354,12 +354,12 @@ int CmdHF14AReader(const char *Cmd) { } int CmdHF14AInfo(const char *Cmd) { - + if (Cmd[0] == 'h' || Cmd[0] == 'H') return usage_hf_14a_info(); - + bool silent = (Cmd[0] == 's' || Cmd[0] == 'S'); bool do_nack_test = (Cmd[0] == 'n' || Cmd[0] == 'N'); - + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -369,18 +369,18 @@ int CmdHF14AInfo(const char *Cmd) { DropField(); return 0; } - + iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); - /* + /* 0: couldn't read 1: OK, with ATS 2: OK, no ATS - 3: proprietary Anticollision + 3: proprietary Anticollision */ uint64_t select_status = resp.arg[0]; - + if (select_status == 0) { if (!silent) PrintAndLogEx(WARNING, "iso14443a card select failed"); DropField(); @@ -400,16 +400,16 @@ int CmdHF14AInfo(const char *Cmd) { bool isMifareClassic = true; switch (card.sak) { - case 0x00: + case 0x00: isMifareClassic = false; - + // ******** is card of the MFU type (UL/ULC/NTAG/ etc etc) DropField(); - + uint32_t tagT = GetHF14AMfU_Type(); if (tagT != UL_ERROR) ul_print_type(tagT, 0); - else + else PrintAndLogEx(NORMAL, "TYPE: Possible AZTEK (iso14443a compliant)"); // reconnect for further tests @@ -420,11 +420,11 @@ int CmdHF14AInfo(const char *Cmd) { SendCommand(&c); UsbCommand resp; WaitForResponse(CMD_ACK, &resp); - + memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS - + if(select_status == 0) { DropField(); return 0; @@ -451,7 +451,7 @@ int CmdHF14AInfo(const char *Cmd) { if ( card.uidlen > 4 ) { PrintAndLogEx(NORMAL, "MANUFACTURER : %s", getTagInfo(card.uid[0])); } - + // try to request ATS even if tag claims not to support it if (select_status == 2) { uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 @@ -462,10 +462,10 @@ int CmdHF14AInfo(const char *Cmd) { clearCommandBuffer(); SendCommand(&c); WaitForResponse(CMD_ACK,&resp); - + memcpy(card.ats, resp.d.asBytes, resp.arg[0]); card.ats_len = resp.arg[0]; // note: ats_len includes CRC Bytes - } + } if(card.ats_len >= 3) { // a valid ATS consists of at least the length byte (TL) and 2 CRC bytes bool ta1 = 0, tb1 = 0, tc1 = 0; @@ -479,13 +479,13 @@ int CmdHF14AInfo(const char *Cmd) { if (card.ats[0] != card.ats_len - 2) { PrintAndLogEx(NORMAL, "ATS may be corrupted. Length of ATS (%d bytes incl. 2 Bytes CRC) doesn't match TL", card.ats_len); } - + if (card.ats[0] > 1) { // there is a format byte (T0) ta1 = (card.ats[1] & 0x10) == 0x10; tb1 = (card.ats[1] & 0x20) == 0x20; tc1 = (card.ats[1] & 0x40) == 0x40; int16_t fsci = card.ats[1] & 0x0f; - + PrintAndLogEx(NORMAL, " - T0 : TA1 is%s present, TB1 is%s present, " "TC1 is%s present, FSCI is %d (FSC = %ld)", (ta1 ? "" : " NOT"), @@ -538,7 +538,7 @@ int CmdHF14AInfo(const char *Cmd) { } else if (memcmp(card.ats + pos, "\xC1\x05\x2F\x2F\x00\x35\xC7", 7) == 0) { tip = "-> MIFARE Plus S 2K or 4K"; } - } + } PrintAndLogEx(NORMAL, " - HB : %s%s", sprint_hex(card.ats + pos, card.ats[0] - pos), tip); if (card.ats[pos] == 0xC1) { PrintAndLogEx(NORMAL, " c1 -> Mifare or (multiple) virtual cards of various type"); @@ -573,9 +573,9 @@ int CmdHF14AInfo(const char *Cmd) { } else { PrintAndLogEx(INFO, "proprietary non iso14443-4 card found, RATS not supported"); } - + detect_classic_magic(); - + if (isMifareClassic) { int res = detect_classic_prng(); if ( res == 1 ) @@ -584,11 +584,11 @@ int CmdHF14AInfo(const char *Cmd) { PrintAndLogEx(SUCCESS, "Prng detection: " _YELLOW_(HARD)); else PrintAndLogEx(FAILED, "prng detection: " _RED_(failed)); - + if ( do_nack_test ) detect_classic_nackbug(silent); } - + return select_status; } @@ -610,11 +610,11 @@ int CmdHF14ACUIDs(const char *Cmd) { PrintAndLogEx(NORMAL, "\n[!] aborted via keyboard!\n"); break; } - + // execute anticollision procedure UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_RATS, 0, 0}}; SendCommand(&c); - + UsbCommand resp; WaitForResponse(CMD_ACK,&resp); @@ -639,7 +639,7 @@ int CmdHF14ACUIDs(const char *Cmd) { int CmdHF14ASim(const char *Cmd) { bool errors = false; uint8_t flags = 0; - uint8_t tagtype = 1; + uint8_t tagtype = 1; uint8_t cmdp = 0; uint8_t uid[10] = {0,0,0,0,0,0,0,0,0,0}; int uidlen = 0; @@ -647,7 +647,7 @@ int CmdHF14ASim(const char *Cmd) { bool setEmulatorMem = false; bool verbose = false; nonces_t data[1]; - + while(param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch(param_getchar(Cmd, cmdp)) { case 'h': @@ -658,19 +658,19 @@ int CmdHF14ASim(const char *Cmd) { // Retrieve the tag type tagtype = param_get8ex(Cmd, cmdp+1, 0, 10); if (tagtype == 0) - errors = true; + errors = true; cmdp += 2; break; case 'u': case 'U': - // Retrieve the full 4,7,10 byte long uid + // Retrieve the full 4,7,10 byte long uid param_gethex_ex(Cmd, cmdp+1, uid, &uidlen); switch(uidlen) { //case 20: flags |= FLAG_10B_UID_IN_DATA; break; case 14: flags |= FLAG_7B_UID_IN_DATA; break; case 8: flags |= FLAG_4B_UID_IN_DATA; break; default: errors = true; break; - } + } if (!errors) { PrintAndLogEx(SUCCESS, "Emulating ISO/IEC 14443 type A tag with %d byte UID (%s)", uidlen>>1, sprint_hex(uid, uidlen>>1)); useUIDfromEML = false; @@ -691,7 +691,7 @@ int CmdHF14ASim(const char *Cmd) { case 'E': setEmulatorMem = true; cmdp++; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -702,22 +702,22 @@ int CmdHF14ASim(const char *Cmd) { //Validations if (errors || cmdp == 0) return usage_hf_14a_sim(); - if ( useUIDfromEML ) + if ( useUIDfromEML ) flags |= FLAG_UID_IN_EMUL; - - UsbCommand c = {CMD_SIMULATE_TAG_ISO_14443a,{ tagtype, flags, 0 }}; + + UsbCommand c = {CMD_SIMULATE_TAG_ISO_14443a,{ tagtype, flags, 0 }}; memcpy(c.d.asBytes, uid, uidlen>>1); clearCommandBuffer(); - SendCommand(&c); + SendCommand(&c); UsbCommand resp; - + PrintAndLogEx(SUCCESS, "press pm3-button to abort simulation"); - + while( !ukbhit() ){ if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) continue; if ( !(flags & FLAG_NR_AR_ATTACK) ) break; if ( (resp.arg[0] & 0xffff) != CMD_SIMULATE_MIFARE_CARD ) break; - + memcpy(data, resp.d.asBytes, sizeof(data) ); readerAttack(data[0], setEmulatorMem, verbose); } @@ -726,7 +726,7 @@ int CmdHF14ASim(const char *Cmd) { } int CmdHF14ASniff(const char *Cmd) { - int param = 0; + int param = 0; uint8_t ctmp; for (int i = 0; i < 2; i++) { ctmp = tolower(param_getchar(Cmd, i)); @@ -744,7 +744,7 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav static bool responseNum = false; uint16_t cmdc = 0; *dataoutlen = 0; - + if (activateField) { responseNum = false; UsbCommand resp; @@ -769,8 +769,8 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav } if (resp.arg[0] == 2) { // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - // get ATS - UsbCommand cr = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0}}; + // get ATS + UsbCommand cr = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0}}; uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 memcpy(cr.d.asBytes, rats, 2); SendCommand(&cr); @@ -778,52 +778,52 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav PrintAndLogEx(ERR, "Proxmark connection timeout."); return 1; } - + if (resp.arg[0] <= 0) { // ats_len PrintAndLogEx(ERR, "Can't get ATS."); return 1; } } } - + if (leaveSignalON) cmdc |= ISO14A_NO_DISCONNECT; - UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_APPEND_CRC | cmdc, (datainlen & 0xFFFF) + 2, 0}}; + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_APPEND_CRC | cmdc, (datainlen & 0xFFFF) + 2, 0}}; uint8_t header[] = {0x0a | responseNum, 0x00}; responseNum ^= 1; memcpy(c.d.asBytes, header, 2); memcpy(&c.d.asBytes[2], datain, datainlen); SendCommand(&c); - + uint8_t *recv; UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { recv = resp.d.asBytes; int iLen = resp.arg[0]; - + if(!iLen) { PrintAndLogEx(ERR, "No card response."); return 1; } - + *dataoutlen = iLen - 2; if (*dataoutlen < 0) *dataoutlen = 0; - + if (maxdataoutlen && *dataoutlen > maxdataoutlen) { PrintAndLogEx(ERR, "Buffer too small(%d). Needs %d bytes", *dataoutlen, maxdataoutlen); return 2; } - + if (recv[0] != header[0]) { PrintAndLogEx(ERR, "iso14443-4 framing error. Card send %2x must be %2x", dataout[0], header[0]); return 2; } - + memcpy(dataout, &recv[2], *dataoutlen); - + // CRC Check if (iLen == -1) { PrintAndLogEx(ERR, "ISO 14443A CRC error."); @@ -835,7 +835,7 @@ int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leav PrintAndLogEx(ERR, "Reply timeout."); return 4; } - + return 0; } @@ -846,8 +846,8 @@ int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) { if (card) memset(card, 0, sizeof(iso14a_card_select_t)); - - DropField(); + + DropField(); // Anticollision + SELECT card UsbCommand ca = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}}; @@ -869,8 +869,8 @@ int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) { } if (resp.arg[0] == 2) { // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - // get ATS - UsbCommand cr = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0}}; + // get ATS + UsbCommand cr = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT, 2, 0}}; uint8_t rats[] = { 0xE0, 0x80 }; // FSDI=8 (FSD=256), CID=0 memcpy(cr.d.asBytes, rats, 2); SendCommand(&cr); @@ -878,7 +878,7 @@ int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) { PrintAndLogEx(ERR, "Proxmark connection timeout."); return 1; } - + if (resp.arg[0] <= 0) { // ats_len PrintAndLogEx(ERR, "Can't get ATS."); return 1; @@ -898,39 +898,39 @@ int SelectCard14443_4(bool disconnect, iso14a_card_select_t *card) { if (fsci < sizeof(atsFSC)) frameLength = atsFSC[fsci]; } - + if (card) memcpy(card, vcard, sizeof(iso14a_card_select_t)); } - + if (disconnect) - DropField(); + DropField(); return 0; } int CmdExchangeAPDU(bool chainingin, uint8_t *datain, int datainlen, bool activateField, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, bool *chainingout) { *chainingout = false; - + if (activateField) { // select with no disconnect and set frameLength int selres = SelectCard14443_4(false, NULL); if (selres) return selres; } - + uint16_t cmdc = 0; if (chainingin) cmdc = ISO14A_SEND_CHAINING; - + // "Command APDU" length should be 5+255+1, but javacard's APDU buffer might be smaller - 133 bytes // https://stackoverflow.com/questions/32994936/safe-max-java-card-apdu-data-command-and-respond-size // here length USB_CMD_DATA_SIZE=512 // timeout must be authomatically set by "get ATS" - UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_APDU | ISO14A_NO_DISCONNECT | cmdc, (datainlen & 0xFFFF), 0}}; + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_APDU | ISO14A_NO_DISCONNECT | cmdc, (datainlen & 0xFFFF), 0}}; memcpy(c.d.asBytes, datain, datainlen); SendCommand(&c); - + uint8_t *recv; UsbCommand resp; @@ -938,24 +938,24 @@ int CmdExchangeAPDU(bool chainingin, uint8_t *datain, int datainlen, bool activa recv = resp.d.asBytes; int iLen = resp.arg[0]; uint8_t res = resp.arg[1]; - + int dlen = iLen - 2; if (dlen < 0) dlen = 0; *dataoutlen += dlen; - + if (maxdataoutlen && *dataoutlen > maxdataoutlen) { PrintAndLogEx(ERR, "APDU: Buffer too small(%d). Needs %d bytes", *dataoutlen, maxdataoutlen); return 2; } - + // I-block ACK if ((res & 0xf2) == 0xa2) { *dataoutlen = 0; *chainingout = true; return 0; } - + if(!iLen) { PrintAndLogEx(ERR, "APDU: No APDU response."); return 1; @@ -966,7 +966,7 @@ int CmdExchangeAPDU(bool chainingin, uint8_t *datain, int datainlen, bool activa PrintAndLogEx(ERR, "APDU: Small APDU response. Len=%d", iLen); return 2; } - + // check block TODO if (iLen == -2) { PrintAndLogEx(ERR, "APDU: Block type mismatch."); @@ -974,12 +974,12 @@ int CmdExchangeAPDU(bool chainingin, uint8_t *datain, int datainlen, bool activa } memcpy(dataout, recv, dlen); - + // chaining if ((res & 0x10) != 0) { *chainingout = true; } - + // CRC Check if (iLen == -1) { PrintAndLogEx(ERR, "APDU: ISO 14443A CRC error."); @@ -999,12 +999,12 @@ int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool lea int res; // 3 byte here - 1b framing header, 2b crc16 - if (APDUInFramingEnable && + if (APDUInFramingEnable && ( (frameLength && (datainlen > frameLength - 3)) || (datainlen > USB_CMD_DATA_SIZE - 3)) ) { int clen = 0; - + bool vActivateField = activateField; - + do { int vlen = MIN(frameLength - 3, datainlen - clen); bool chainBlockNotLast = ((clen + vlen) < datainlen); @@ -1022,10 +1022,10 @@ int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool lea if ((*dataoutlen == 0) && (*dataoutlen != 0 || chaining != chainBlockNotLast)) { if (!leaveSignalON) DropField(); - + return 201; } - + clen += vlen; vActivateField = false; if (*dataoutlen) { @@ -1033,32 +1033,32 @@ int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool lea PrintAndLogEx(WARNING, "APDU: I-block/R-block sequence error. Data len=%d, Sent=%d, Last packet len=%d", datainlen, clen, *dataoutlen); break; } - } while (clen < datainlen); + } while (clen < datainlen); } else { res = CmdExchangeAPDU(false, datain, datainlen, activateField, dataout, maxdataoutlen, dataoutlen, &chaining); if (res) { if (!leaveSignalON) DropField(); - + return res; } } - + while (chaining) { // I-block with chaining res = CmdExchangeAPDU(false, NULL, 0, false, &dataout[*dataoutlen], maxdataoutlen, dataoutlen, &chaining); - + if (res) { if (!leaveSignalON) DropField(); - + return 100; } - } - + } + if (!leaveSignalON) DropField(); - + return 0; } @@ -1070,8 +1070,8 @@ int CmdHF14AAPDU(const char *cmd) { bool leaveSignalON = false; bool decodeTLV = false; - CLIParserInit("hf 14a apdu", - "Sends an ISO 7816-4 APDU via ISO 14443-4 block transmission protocol (T=CL)", + CLIParserInit("hf 14a apdu", + "Sends an ISO 7816-4 APDU via ISO 14443-4 block transmission protocol (T=CL)", "Sample:\n\thf 14a apdu -st 00A404000E325041592E5359532E444446303100\n"); void* argtable[] = { @@ -1083,7 +1083,7 @@ int CmdHF14AAPDU(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, false); - + activateField = arg_get_lit(1); leaveSignalON = arg_get_lit(2); decodeTLV = arg_get_lit(3); @@ -1092,21 +1092,21 @@ int CmdHF14AAPDU(const char *cmd) { CLIParserFree(); PrintAndLogEx(NORMAL, ">>>>[%s%s%s] %s", activateField ? "sel ": "", leaveSignalON ? "keep ": "", decodeTLV ? "TLV": "", sprint_hex(data, datalen)); - + int res = ExchangeAPDU14a(data, datalen, activateField, leaveSignalON, data, USB_CMD_DATA_SIZE, &datalen); if (res) return res; PrintAndLogEx(NORMAL, "<<<< %s", sprint_hex(data, datalen)); - - PrintAndLogEx(SUCCESS, "APDU response: %02x %02x - %s", data[datalen - 2], data[datalen - 1], GetAPDUCodeDescription(data[datalen - 2], data[datalen - 1])); + + PrintAndLogEx(SUCCESS, "APDU response: %02x %02x - %s", data[datalen - 2], data[datalen - 1], GetAPDUCodeDescription(data[datalen - 2], data[datalen - 1])); // TLV decoder if (decodeTLV && datalen > 4) { TLVPrintFromBuffer(data, datalen - 2); } - + return 0; } @@ -1140,7 +1140,7 @@ int CmdHF14ACmdRaw(const char *cmd) { case 'H': case 'h': return usage_hf_14a_raw(); - case 'r': + case 'r': reply = false; break; case 'c': @@ -1155,7 +1155,7 @@ int CmdHF14ACmdRaw(const char *cmd) { case 's': active_select = true; break; - case 'b': + case 'b': sscanf(cmd+i+2, "%d", &temp); numbits = temp & 0xFFFF; i+=3; @@ -1235,21 +1235,21 @@ int CmdHF14ACmdRaw(const char *cmd) { if (power) { c.arg[0] |= ISO14A_NO_DISCONNECT; } - + if (datalen > 0) { c.arg[0] |= ISO14A_RAW; } - + if (topazmode) { c.arg[0] |= ISO14A_TOPAZMODE; } if (no_rats) { c.arg[0] |= ISO14A_NO_RATS; } - + // Max buffer is USB_CMD_DATA_SIZE datalen = (datalen > USB_CMD_DATA_SIZE) ? USB_CMD_DATA_SIZE : datalen; - + c.arg[1] = (datalen & 0xFFFF) | ((uint32_t)(numbits << 16)); memcpy(c.d.asBytes, data, datalen); @@ -1270,7 +1270,7 @@ static int waitCmd(uint8_t iSelect) { UsbCommand resp; uint16_t len = 0; - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { len = (resp.arg[0] & 0xFFFF); if (iSelect){ len = (resp.arg[1] & 0xFFFF); @@ -1282,10 +1282,10 @@ static int waitCmd(uint8_t iSelect) { } else { PrintAndLogEx(NORMAL, "received %i bytes", len); } - + if (!len) return 1; - + PrintAndLogEx(NORMAL, "%s", sprint_hex(resp.d.asBytes, len) ); } else { PrintAndLogEx(WARNING, "timeout while waiting for reply."); @@ -1295,9 +1295,9 @@ static int waitCmd(uint8_t iSelect) { } int CmdHF14AAntiFuzz(const char *cmd) { - - CLIParserInit("hf 14a antifuzz", - "Tries to fuzz the ISO14443a anticollision phase", + + CLIParserInit("hf 14a antifuzz", + "Tries to fuzz the ISO14443a anticollision phase", "Usage:\n" "\thf 14a antifuzz -4\n"); @@ -1312,21 +1312,21 @@ int CmdHF14AAntiFuzz(const char *cmd) { uint8_t arg0 = FLAG_4B_UID_IN_DATA; if (arg_get_lit(2)) - arg0 = FLAG_7B_UID_IN_DATA; + arg0 = FLAG_7B_UID_IN_DATA; if (arg_get_lit(3)) arg0 = FLAG_10B_UID_IN_DATA; CLIParserFree(); - UsbCommand c = {CMD_ANTIFUZZ_ISO_14443a, {arg0, 0, 0}}; + UsbCommand c = {CMD_ANTIFUZZ_ISO_14443a, {arg0, 0, 0}}; clearCommandBuffer(); - SendCommand(&c); + SendCommand(&c); return 0; } int CmdHF14AChaining(const char *cmd) { - - CLIParserInit("hf 14a chaining", - "Enable/Disable ISO14443a input chaining. Maximum input length goes from ATS.", + + CLIParserInit("hf 14a chaining", + "Enable/Disable ISO14443a input chaining. Maximum input length goes from ATS.", "Usage:\n" "\thf 14a chaining disable -> disable chaining\n" "\thf 14a chaining -> show chaining enable/disable state\n"); @@ -1340,17 +1340,17 @@ int CmdHF14AChaining(const char *cmd) { struct arg_str *str = arg_get_str(1); int len = arg_get_str_len(1); - + if (len && (!strcmp(str->sval[0], "enable") || !strcmp(str->sval[0], "1"))) APDUInFramingEnable = true; - + if (len && (!strcmp(str->sval[0], "disable") || !strcmp(str->sval[0], "0"))) APDUInFramingEnable = false; CLIParserFree(); PrintAndLogEx(INFO, "\nISO 14443-4 input chaining %s.\n", APDUInFramingEnable ? "enabled" : "disabled"); - + return 0; } diff --git a/client/cmdhf14a.h b/client/cmdhf14a.h index 3fe04d26c..4396c4b79 100644 --- a/client/cmdhf14a.h +++ b/client/cmdhf14a.h @@ -31,13 +31,13 @@ #include "cmdhf.h" // list cmd #include "mifare/mifarehost.h" #include "emv/apduinfo.h" -#include "emv/emvcore.h" +#include "emv/emvcore.h" -// structure and database for uid -> tagtype lookups -typedef struct { +// structure and database for uid -> tagtype lookups +typedef struct { uint8_t uid; char* desc; -} manufactureName; +} manufactureName; extern int CmdHF14A(const char *Cmd); extern int CmdHF14AList(const char *Cmd); @@ -51,7 +51,7 @@ extern int CmdHF14AAntiFuzz(const char *cmd); extern char* getTagInfo(uint8_t uid); extern int Hf14443_4aGetCardData(iso14a_card_select_t * card); -extern int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); +extern int ExchangeAPDU14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); extern int ExchangeRAW14a(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen); extern int usage_hf_14a_sim(void); diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 4109a999a..f74ca9a34 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -43,7 +43,7 @@ int usage_hf_14b_raw(void){ PrintAndLogEx(NORMAL, " -ss active signal field ON with select for SRx ST Microelectronics tags"); PrintAndLogEx(NORMAL, "Example:"); PrintAndLogEx(NORMAL, " hf 14b raw -s -c -p 0200a40400"); - return 0; + return 0; } int usage_hf_14b_sniff(void){ PrintAndLogEx(NORMAL, "It get data from the field and saves it into command buffer."); @@ -53,7 +53,7 @@ int usage_hf_14b_sniff(void){ PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, "Example:"); PrintAndLogEx(NORMAL, " hf 14b sniff"); - return 0; + return 0; } int usage_hf_14b_sim(void){ PrintAndLogEx(NORMAL, "Emulating ISO/IEC 14443 type B tag with 4 UID / PUPI"); @@ -64,7 +64,7 @@ int usage_hf_14b_sim(void){ PrintAndLogEx(NORMAL, "Example:"); PrintAndLogEx(NORMAL, " hf 14b sim"); PrintAndLogEx(NORMAL, " hf 14b sim u 11223344"); - return 0; + return 0; } int usage_hf_14b_read_srx(void){ PrintAndLogEx(NORMAL, "Usage: hf 14b sriread [h] <1|2>"); @@ -94,7 +94,7 @@ int usage_hf_14b_dump(void){ PrintAndLogEx(NORMAL, "This command dumps the contents of a ISO-14443-B tag and save it to file\n" "\n" "Usage: hf 14b dump [h] [card memory] \n" - "Options:\n" + "Options:\n" "\th this help\n" "\t[card memory] 1 = SRIX4K (default), 2 = SRI512" "\tf filename, if no UID will be used as filename\n" @@ -128,12 +128,12 @@ int CmdHF14BList(const char *Cmd) { int CmdHF14BSim(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_hf_14b_sim(); - + uint32_t pupi = 0; if (cmdp == 'u') { pupi = param_get32ex(Cmd, 1, 0, 16); } - + UsbCommand c = {CMD_SIMULATE_TAG_ISO_14443B, {pupi, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -141,10 +141,10 @@ int CmdHF14BSim(const char *Cmd) { } int CmdHF14BSniff(const char *Cmd) { - + char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_hf_14b_sniff(); - + UsbCommand c = {CMD_SNOOP_ISO_14443B, {0, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -159,25 +159,25 @@ int CmdHF14BCmdRaw (const char *Cmd) { uint16_t datalen = 0; uint32_t flags = ISO14B_CONNECT; uint32_t temp = 0; - + if ( strlen(Cmd) < 3 ) return usage_hf_14b_raw(); // strip while (*Cmd==' ' || *Cmd=='\t') ++Cmd; - + while (Cmd[i]!='\0') { if (Cmd[i]==' ' || Cmd[i]=='\t') { ++i; continue; } if (Cmd[i]=='-') { switch (tolower(Cmd[i+1])) { case 'h': return usage_hf_14b_raw(); - case 'r': + case 'r': reply = false; break; case 'c': flags |= ISO14B_APPEND_CRC; break; - case 'p': + case 'p': power = true; break; case 's': @@ -201,7 +201,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { buf[strlen(buf)+1]=0; buf[strlen(buf)]=Cmd[i]; i++; - + if (strlen(buf)>=2) { sscanf(buf,"%x",&temp); data[datalen++] = (uint8_t)(temp & 0xff); @@ -213,7 +213,7 @@ int CmdHF14BCmdRaw (const char *Cmd) { PrintAndLogEx(WARNING, "unknown parameter '%c'\n", param_getchar(Cmd, i)); return 0; } - + if (!power) flags |= ISO14B_DISCONNECT; @@ -223,16 +223,16 @@ int CmdHF14BCmdRaw (const char *Cmd) { // Max buffer is USB_CMD_DATA_SIZE datalen = (datalen > USB_CMD_DATA_SIZE) ? USB_CMD_DATA_SIZE : datalen; - UsbCommand c = {CMD_ISO_14443B_COMMAND, {flags, datalen, 0}}; + UsbCommand c = {CMD_ISO_14443B_COMMAND, {flags, datalen, 0}}; memcpy(c.d.asBytes, data, datalen); clearCommandBuffer(); SendCommand(&c); - if (!reply) return 1; + if (!reply) return 1; bool success = true; // get back iso14b_card_select_t, don't print it. - if (select) + if (select) success = waitCmd14b(false); // get back response from the raw bytes you sent. @@ -245,47 +245,47 @@ static bool get_14b_UID(iso14b_card_select_t *card) { if (!card) return false; - + int8_t retry = 3; UsbCommand resp; UsbCommand c = {CMD_ISO_14443B_COMMAND, {ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT, 0, 0}}; - - // test for 14b SR + + // test for 14b SR while (retry--) { clearCommandBuffer(); - SendCommand(&c); + SendCommand(&c); if (WaitForResponseTimeout(CMD_ACK, &resp, TIMEOUT)) { - + uint8_t status = resp.arg[0]; if ( status == 0) { memcpy(card, (iso14b_card_select_t *)resp.d.asBytes, sizeof(iso14b_card_select_t)); return true; } - } + } } // retry // test 14b standard - c.arg[0] = ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT; + c.arg[0] = ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT; retry = 3; while (retry--) { clearCommandBuffer(); - SendCommand(&c); + SendCommand(&c); if (WaitForResponseTimeout(CMD_ACK, &resp, TIMEOUT)) { - + uint8_t status = resp.arg[0]; if ( status == 0) { memcpy(card, (iso14b_card_select_t *)resp.d.asBytes, sizeof(iso14b_card_select_t)); return true; } - } - } // retry - + } + } // retry + if ( retry <= 0 ) PrintAndLogEx(WARNING, "timeout while waiting for reply."); - + return false; } @@ -302,11 +302,11 @@ static void print_atqb_resp(uint8_t *data, uint8_t cid){ uint8_t BitRate = data[4]; if (!BitRate) PrintAndLogEx(NORMAL, " Bit Rate: 106 kbit/s only PICC <-> PCD"); if (BitRate & 0x10) PrintAndLogEx(NORMAL, " Bit Rate: 212 kbit/s PICC -> PCD supported"); - if (BitRate & 0x20) PrintAndLogEx(NORMAL, " Bit Rate: 424 kbit/s PICC -> PCD supported"); - if (BitRate & 0x40) PrintAndLogEx(NORMAL, " Bit Rate: 847 kbit/s PICC -> PCD supported"); + if (BitRate & 0x20) PrintAndLogEx(NORMAL, " Bit Rate: 424 kbit/s PICC -> PCD supported"); + if (BitRate & 0x40) PrintAndLogEx(NORMAL, " Bit Rate: 847 kbit/s PICC -> PCD supported"); if (BitRate & 0x01) PrintAndLogEx(NORMAL, " Bit Rate: 212 kbit/s PICC <- PCD supported"); - if (BitRate & 0x02) PrintAndLogEx(NORMAL, " Bit Rate: 424 kbit/s PICC <- PCD supported"); - if (BitRate & 0x04) PrintAndLogEx(NORMAL, " Bit Rate: 847 kbit/s PICC <- PCD supported"); + if (BitRate & 0x02) PrintAndLogEx(NORMAL, " Bit Rate: 424 kbit/s PICC <- PCD supported"); + if (BitRate & 0x04) PrintAndLogEx(NORMAL, " Bit Rate: 847 kbit/s PICC <- PCD supported"); if (BitRate & 0x80) PrintAndLogEx(NORMAL, " Same bit rate <-> required"); uint16_t maxFrame = data[5] >> 4; @@ -316,12 +316,12 @@ static void print_atqb_resp(uint8_t *data, uint8_t cid){ else if (maxFrame == 7) maxFrame = 128; else if (maxFrame == 8) maxFrame = 256; else maxFrame = 257; - + PrintAndLogEx(NORMAL, "Max Frame Size: %u%s bytes", maxFrame, (maxFrame == 257) ? "+ RFU" : ""); uint8_t protocolT = data[5] & 0xF; PrintAndLogEx(NORMAL, " Protocol Type: Protocol is %scompliant with ISO/IEC 14443-4",(protocolT) ? "" : "not " ); - + uint8_t fwt = data[6]>>4; if ( fwt < 16 ){ uint32_t etus = (32 << fwt); @@ -330,7 +330,7 @@ static void print_atqb_resp(uint8_t *data, uint8_t cid){ } else { PrintAndLogEx(NORMAL, "Frame Wait Integer: %u - RFU", fwt); } - + PrintAndLogEx(NORMAL, " App Data Code: Application is %s",(data[6]&4) ? "Standard" : "Proprietary"); PrintAndLogEx(NORMAL, " Frame Options: NAD is %ssupported",(data[6]&2) ? "" : "not "); PrintAndLogEx(NORMAL, " Frame Options: CID is %ssupported",(data[6]&1) ? "" : "not "); @@ -429,33 +429,33 @@ static void print_st_general_info(uint8_t *data, uint8_t len){ // 0200a4040010a000000018300301000000000000000000 (resp 02 6a 82 [4b 4c]) //03 = ? (resp 03 [e3 c2]) //c2 = ? (resp c2 [66 15]) -//b2 = ? (resp a3 [e9 67]) +//b2 = ? (resp a3 [e9 67]) //a2 = ? (resp 02 [6a d3]) // 14b get and print Full Info (as much as we know) bool HF14B_Std_Info(bool verbose){ bool isSuccess = false; - - // 14b get and print UID only (general info) + + // 14b get and print UID only (general info) UsbCommand c = {CMD_ISO_14443B_COMMAND, {ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT, 0, 0}}; clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + if (!WaitForResponseTimeout(CMD_ACK, &resp, TIMEOUT)) { if (verbose) PrintAndLogEx(WARNING, "command execution timeout"); - switch_off_field_14b(); + switch_off_field_14b(); return false; } - + iso14b_card_select_t card; memcpy(&card, (iso14b_card_select_t *)resp.d.asBytes, sizeof(iso14b_card_select_t)); - - uint64_t status = resp.arg[0]; - + + uint64_t status = resp.arg[0]; + switch( status ){ - case 0: + case 0: PrintAndLogEx(NORMAL, " UID : %s", sprint_hex(card.uid, card.uidlen)); PrintAndLogEx(NORMAL, " ATQB : %s", sprint_hex(card.atqb, sizeof(card.atqb))); PrintAndLogEx(NORMAL, " CHIPID : %02X", card.chipid); @@ -465,20 +465,20 @@ bool HF14B_Std_Info(bool verbose){ case 2: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ATTRIB fail"); break; - case 3: + case 3: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail"); break; default: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b card select failed"); break; } - + return isSuccess; } // SRx get and print full info (needs more info...) bool HF14B_ST_Info(bool verbose){ - + UsbCommand c = {CMD_ISO_14443B_COMMAND, {ISO14B_CONNECT | ISO14B_SELECT_SR | ISO14B_DISCONNECT, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -491,9 +491,9 @@ bool HF14B_ST_Info(bool verbose){ iso14b_card_select_t card; memcpy(&card, (iso14b_card_select_t *)resp.d.asBytes, sizeof(iso14b_card_select_t)); - - uint64_t status = resp.arg[0]; - if ( status > 0 ) + + uint64_t status = resp.arg[0]; + if ( status > 0 ) return false; print_st_general_info(card.uid, card.uidlen); @@ -507,16 +507,16 @@ bool HF14B_ST_Info(bool verbose){ // // if (model == 0x2) { //SR176 has special command: // data[1] = 0xf; - // resplen = 4; + // resplen = 4; // } else { // data[1] = 0xff; // resplen = 6; // } // //std read cmd - // if (HF14BCmdRaw(true, true, data, &datalen, false)==0) + // if (HF14BCmdRaw(true, true, data, &datalen, false)==0) // return rawClose(); - + // if (datalen != resplen || !crc) return rawClose(); //print_ST_Lock_info(data[5]>>2); return true; @@ -541,7 +541,7 @@ bool HF14BInfo(bool verbose){ int CmdHF14Binfo(const char *Cmd){ char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_hf_14b_info(); - + bool verbose = !(cmdp == 's'); return HF14BInfo(verbose); } @@ -559,14 +559,14 @@ bool HF14B_ST_Reader(bool verbose){ if (verbose) PrintAndLogEx(WARNING, "command execution timeout"); return false; } - + iso14b_card_select_t card; memcpy(&card, (iso14b_card_select_t *)resp.d.asBytes, sizeof(iso14b_card_select_t)); uint64_t status = resp.arg[0]; switch( status ){ - case 0: + case 0: print_st_general_info(card.uid, card.uidlen); isSuccess = true; break; @@ -576,38 +576,38 @@ bool HF14B_ST_Reader(bool verbose){ case 2: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ATTRIB fail"); break; - case 3: + case 3: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail"); break; default: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b card select SRx failed"); break; } - return isSuccess; + return isSuccess; } bool HF14B_Std_Reader(bool verbose){ bool isSuccess = false; - // 14b get and print UID only (general info) + // 14b get and print UID only (general info) UsbCommand c = {CMD_ISO_14443B_COMMAND, {ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_DISCONNECT, 0, 0}}; clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + if (!WaitForResponseTimeout(CMD_ACK, &resp, TIMEOUT)) { if (verbose) PrintAndLogEx(WARNING, "command execution timeout"); return false; } - + iso14b_card_select_t card; memcpy(&card, (iso14b_card_select_t *)resp.d.asBytes, sizeof(iso14b_card_select_t)); - - uint64_t status = resp.arg[0]; - + + uint64_t status = resp.arg[0]; + switch( status ){ - case 0: + case 0: PrintAndLogEx(NORMAL, " UID : %s", sprint_hex(card.uid, card.uidlen)); PrintAndLogEx(NORMAL, " ATQB : %s", sprint_hex(card.atqb, sizeof(card.atqb))); PrintAndLogEx(NORMAL, " CHIPID : %02X", card.chipid); @@ -617,14 +617,14 @@ bool HF14B_Std_Reader(bool verbose){ case 2: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 ATTRIB fail"); break; - case 3: + case 3: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-3 CRC fail"); break; default: if (verbose) PrintAndLogEx(FAILED, "ISO 14443-b card select failed"); break; } - return isSuccess; + return isSuccess; } // test for other 14b type tags (mimic another reader - don't have tags to identify) @@ -633,17 +633,17 @@ bool HF14B_Other_Reader(){ // uint8_t data[] = {0x00, 0x0b, 0x3f, 0x80}; // uint8_t datalen = 4; - // // 14b get and print UID only (general info) + // // 14b get and print UID only (general info) // uint32_t flags = ISO14B_CONNECT | ISO14B_SELECT_STD | ISO14B_RAW | ISO14B_APPEND_CRC; - - // UsbCommand c = {CMD_ISO_14443B_COMMAND, {flags, datalen, 0}}; + + // UsbCommand c = {CMD_ISO_14443B_COMMAND, {flags, datalen, 0}}; // memcpy(c.d.asBytes, data, datalen); // clearCommandBuffer(); // SendCommand(&c); // UsbCommand resp; // WaitForResponse(CMD_ACK,&resp); - + // if (datalen > 2 ) { // PrintAndLogEx(NORMAL, "\n14443-3b tag found:"); // PrintAndLogEx(NORMAL, "unknown tag type answered to a 0x000b3f80 command ans:"); @@ -658,7 +658,7 @@ bool HF14B_Other_Reader(){ // SendCommand(&c); // UsbCommand resp; // WaitForResponse(CMD_ACK, &resp); - + // if (datalen > 0) { // PrintAndLogEx(NORMAL, "\n14443-3b tag found:"); // PrintAndLogEx(NORMAL, "Unknown tag type answered to a 0x0A command ans:"); @@ -681,14 +681,14 @@ bool HF14B_Other_Reader(){ // rawClose(); // return true; // } - + // rawClose(); return false; } // get and print general info about all known 14b chips bool HF14BReader(bool verbose){ - + // try std 14b (atqb) if (HF14B_Std_Reader(verbose)) return true; @@ -707,7 +707,7 @@ bool HF14BReader(bool verbose){ int CmdHF14BReader(const char *Cmd){ char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_hf_14b_reader(); - + bool verbose = !(cmdp == 's'); return HF14BReader(verbose); } @@ -722,7 +722,7 @@ int CmdHF14BReadSri(const char *Cmd){ uint8_t tagtype = param_get8(Cmd, 0); uint8_t blocks = (tagtype == 1) ? 0x7F : 0x0F; - + UsbCommand c = {CMD_READ_SRI_TAG, {blocks, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -736,7 +736,7 @@ int CmdHF14BWriteSri(const char *Cmd){ * * For SR512 blocks 00 - 0F * hf 14b raw -c -p 09 $sr512wblock $sr512wdata - * + * * Special block FF = otp_lock_reg block. * Data len 4 bytes- */ @@ -744,38 +744,38 @@ int CmdHF14BWriteSri(const char *Cmd){ uint8_t blockno = -1; uint8_t data[4] = {0x00}; bool isSrix4k = true; - char str[30]; + char str[30]; memset(str, 0x00, sizeof(str)); if (strlen(Cmd) < 1 || cmdp == 'h') return usage_hf_14b_write_srx(); if ( cmdp == '2' ) isSrix4k = false; - + //blockno = param_get8(Cmd, 1); - + if ( param_gethex(Cmd, 1, &blockno, 2) ) { PrintAndLogEx(WARNING, "block number must include 2 HEX symbols"); return 0; } - + if ( isSrix4k ){ if ( blockno > 0x7f && blockno != 0xff ){ PrintAndLogEx(FAILED, "block number out of range"); return 0; - } + } } else { if ( blockno > 0x0f && blockno != 0xff ){ PrintAndLogEx(FAILED, "block number out of range"); return 0; - } + } } - + if (param_gethex(Cmd, 2, data, 8)) { PrintAndLogEx(WARNING, "data must include 8 HEX symbols"); return 0; } - + if ( blockno == 0xff) { PrintAndLogEx(SUCCESS, "[%s] Write special block %02X [ %s ]", (isSrix4k) ? "SRIX4K":"SRI512", @@ -785,11 +785,11 @@ int CmdHF14BWriteSri(const char *Cmd){ } else { PrintAndLogEx(SUCCESS, "[%s] Write block %02X [ %s ]", (isSrix4k) ? "SRIX4K":"SRI512", - blockno, + blockno, sprint_hex(data,4) ); } - + sprintf(str, "-ss -c %02x %02x %02x %02x %02x %02x", ISO14443B_WRITE_BLK, blockno, data[0], data[1], data[2], data[3]); CmdHF14BCmdRaw(str); return 0; @@ -797,7 +797,7 @@ int CmdHF14BWriteSri(const char *Cmd){ // need to write to file int CmdHF14BDump(const char*Cmd) { - + uint8_t fileNameLen = 0; char filename[FILE_PATH_SIZE] = {0}; char * fptr = filename; @@ -806,13 +806,13 @@ int CmdHF14BDump(const char*Cmd) { uint16_t cardsize = 0; uint8_t blocks = 0; iso14b_card_select_t card; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_hf_14b_dump(); case 'f': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); cmdp += 2; break; default: @@ -839,26 +839,26 @@ int CmdHF14BDump(const char*Cmd) { default: cardsize = (4096/8) + 4; blocks = 0x7F; - break; + break; } - + if (!get_14b_UID(&card)) { PrintAndLogEx(WARNING, "No tag found."); return 1; } - + if (fileNameLen < 1) { PrintAndLogEx(INFO, "Using UID as filename"); - fptr += sprintf(fptr, "hf-14b-"); + fptr += sprintf(fptr, "hf-14b-"); FillFileNameByUID(fptr, card.uid, "-dump", card.uidlen); - } + } - // detect blocksize from card :) + // detect blocksize from card :) PrintAndLogEx(NORMAL, "Reading memory from tag UID %s", sprint_hex(card.uid, card.uidlen)); - + uint8_t data[cardsize]; memset(data, 0, sizeof(data)); - + int blocknum = 0; uint8_t *recv = NULL; @@ -874,30 +874,30 @@ int CmdHF14BDump(const char*Cmd) { goto out; } } - + c.arg[0] = ISO14B_APPEND_CRC | ISO14B_RAW; c.arg[1] = 2; - + uint8_t *req = c.d.asBytes; - req[0] = ISO14443B_READ_BLK; - + req[0] = ISO14443B_READ_BLK; + for (int retry = 0; retry < 5; retry++) { - + req[1] = blocknum; - + clearCommandBuffer(); SendCommand(&c); - + if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { uint8_t status = resp.arg[0] & 0xFF; if ( status > 0 ) { - continue; + continue; } - + uint16_t len = (resp.arg[1] & 0xFFFF); recv = resp.d.asBytes; - + if ( !check_crc(CRC_14443_B, recv, len) ) { PrintAndLogEx(FAILED, "crc fail, retrying one more time"); continue; @@ -909,43 +909,43 @@ int CmdHF14BDump(const char*Cmd) { //last read. break; } - - + + retry = 0; blocknum++; if ( blocknum > blocks ) { // read config block blocknum = 0xFF; } - + printf("."); fflush(stdout); - } + } } - + if ( blocknum != 0xFF) { PrintAndLogEx(NORMAL, "\n Dump failed"); goto out; } - + PrintAndLogEx(NORMAL, "\n"); PrintAndLogEx(NORMAL, "block# | data | ascii"); - PrintAndLogEx(NORMAL, "---------+--------------+----------"); + PrintAndLogEx(NORMAL, "---------+--------------+----------"); for (int i = 0; i <= blocks; i++) { PrintAndLogEx(NORMAL, - "%3d/0x%02X | %s | %s", + "%3d/0x%02X | %s | %s", i, i, sprint_hex(data + (i*4), 4 ), sprint_ascii(data + (i*4), 4) ); } - + PrintAndLogEx(NORMAL, "\n"); - + size_t datalen = (blocks+1) * 4; - saveFileEML(filename, "eml", data, datalen, 4); + saveFileEML(filename, "eml", data, datalen, 4); saveFile(filename, "bin", data, datalen); out: return switch_off_field_14b(); @@ -955,16 +955,16 @@ uint32_t srix4kEncode(uint32_t value) { /* // vv = value // pp = position -// vv vv vv pp +// vv vv vv pp 4 bytes : 00 1A 20 01 */ // only the lower crumbs. uint8_t block = (value & 0xFF); uint8_t i = 0; uint8_t valuebytes[] = {0,0,0}; - + num_to_bytes(value, 3, valuebytes); - + // Scrambled part // Crumb swapping of value. uint8_t temp[] = {0,0}; @@ -975,7 +975,7 @@ uint32_t srix4kEncode(uint32_t value) { // chksum part uint32_t chksum = 0xFF - block; - + // chksum is reduced by each nibbles of value. for (i = 0; i < 3; ++i){ chksum -= NIBBLE_HIGH(valuebytes[i]); @@ -984,23 +984,23 @@ uint32_t srix4kEncode(uint32_t value) { // base4 conversion and left shift twice i = 3; - uint8_t base4[] = {0,0,0,0}; + uint8_t base4[] = {0,0,0,0}; while( chksum !=0 ){ base4[i--] = (chksum % 4 << 2); chksum /= 4; } - + // merge scambled and chksum parts - uint32_t encvalue = + uint32_t encvalue = ( NIBBLE_LOW ( base4[0]) << 28 ) | ( NIBBLE_HIGH( temp[0]) << 24 ) | - + ( NIBBLE_LOW ( base4[1]) << 20 ) | ( NIBBLE_LOW ( temp[0]) << 16 ) | - + ( NIBBLE_LOW ( base4[2]) << 12 ) | ( NIBBLE_HIGH( temp[1]) << 8 ) | - + ( NIBBLE_LOW ( base4[3]) << 4 ) | NIBBLE_LOW ( temp[1] ); @@ -1040,12 +1040,12 @@ int srix4kValid(const char *Cmd){ uint32_t block18 = 0xC04F42C5; uint32_t block19 = 0xC1484807; uint32_t block21 = 0xD1BCABA4; - + uint32_t test_b18 = 0x00313918; uint32_t test_b18_enc = srix4kEncode(test_b18); //uint32_t test_b18_dec = srix4kDecode(test_b18_enc); PrintAndLogEx(SUCCESS, "ENCODE & CHECKSUM | %08X -> %08X (%s)", test_b18, test_b18_enc , ""); - + uint32_t magic = srix4kGetMagicbytes(uid, block6, block18, block19); PrintAndLogEx(SUCCESS, "BLOCK 21 | %08X -> %08X (no XOR)", block21, magic ^ block21); return 0; @@ -1056,22 +1056,22 @@ bool waitCmd14b(bool verbose) { bool crc = false; uint8_t data[USB_CMD_DATA_SIZE] = {0x00}; uint8_t status = 0; - uint16_t len = 0; + uint16_t len = 0; UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK, &resp, TIMEOUT)) { status = (resp.arg[0] & 0xFF); if ( status > 0 ) return false; - + len = (resp.arg[1] & 0xFFFF); - + memcpy(data, resp.d.asBytes, len); - + if (verbose) { if ( len >= 3 ) { crc = check_crc(CRC_14443_B, data, len); - + PrintAndLogEx(NORMAL, "[LEN %u] %s[%02X %02X] %s", len, sprint_hex(data, len-2), @@ -1082,7 +1082,7 @@ bool waitCmd14b(bool verbose) { } else { PrintAndLogEx(NORMAL, "[LEN %u] %s", len, sprint_hex(data, len) ); } - } + } return true; } else { PrintAndLogEx(WARNING, "command execution timeout"); @@ -1092,7 +1092,7 @@ bool waitCmd14b(bool verbose) { static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"dump", CmdHF14BDump, 0, "Read all memory pages of an ISO14443-B tag, save to file"}, + {"dump", CmdHF14BDump, 0, "Read all memory pages of an ISO14443-B tag, save to file"}, {"info", CmdHF14Binfo, 0, "Tag information"}, {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443B history"}, {"raw", CmdHF14BCmdRaw, 0, "Send raw hex data to tag"}, diff --git a/client/cmdhf14b.h b/client/cmdhf14b.h index 793949c86..74b279620 100644 --- a/client/cmdhf14b.h +++ b/client/cmdhf14b.h @@ -51,7 +51,7 @@ extern bool HF14BInfo(bool verbose); extern bool HF14BReader(bool verbose); extern int CmdHF14BCmdRaw (const char *Cmd); -// SRi ST Microelectronics read/write +// SRi ST Microelectronics read/write extern int CmdHF14BReadSri(const char *Cmd); extern int CmdHF14BWriteSri(const char *Cmd); diff --git a/client/cmdhf15.c b/client/cmdhf15.c index 097a52704..dc1a47f40 100644 --- a/client/cmdhf15.c +++ b/client/cmdhf15.c @@ -15,13 +15,13 @@ // Mode 1: // All steps are done on the proxmark, the output of the commands is returned via // USB-debug-print commands. -// Mode 2: +// Mode 2: // The protocol is done on the PC, passing only Iso15693 data frames via USB. This // allows direct communication with a tag on command level // Mode 3: // The proxmark just samples the antenna and passes this "analog" data via USB to // the client. Signal Processing & decoding is done on the pc. This is the slowest -// variant, but offers the possibility to analyze the waveforms directly. +// variant, but offers the possibility to analyze the waveforms directly. #include "cmdhf15.h" #define FrameSOF Iso15693FrameSOF @@ -35,18 +35,18 @@ #define sprintUID(target, uid) Iso15693sprintUID((target), (uid)) -// structure and database for uid -> tagtype lookups -typedef struct { +// structure and database for uid -> tagtype lookups +typedef struct { uint64_t uid; int mask; // how many MSB bits used char* desc; -} productName; +} productName; const productName uidmapping[] = { // UID, #significant Bits, "Vendor(+Product)" { 0xE001000000000000LL, 16, "Motorola UK" }, - + // E0 02 xx // 02 = ST Microelectronics // XX = IC id (Chip ID Family) @@ -56,8 +56,8 @@ const productName uidmapping[] = { { 0xE0020A0000000000LL, 24, "ST Microelectronics; LRIS2K [IC id = 10]"}, { 0xE002440000000000LL, 24, "ST Microelectronics; LRIS64K [IC id = 68]"}, - { 0xE003000000000000LL, 16, "Hitachi, Ltd Japan" }, - + { 0xE003000000000000LL, 16, "Hitachi, Ltd Japan" }, + // E0 04 xx // 04 = Manufacturer code (Philips/NXP) // XX = IC id (Chip ID Family) @@ -67,7 +67,7 @@ const productName uidmapping[] = { //I-Code SLIX [IC id = 01 + bit36 set to 1 (starting from bit0 - different from normal SLI)] //I-Code SLIX-S [IC id = 02 + bit36 set to 1] //I-Code SLIX-L [IC id = 03 + bit36 set to 1] - { 0xE004000000000000LL, 16, "NXP Semiconductors Germany (Philips)" }, + { 0xE004000000000000LL, 16, "NXP Semiconductors Germany (Philips)" }, { 0xE004010000000000LL, 24, "NXP(Philips); IC SL2 ICS20/ICS21(SLI) ICS2002/ICS2102(SLIX)" }, { 0xE004020000000000LL, 24, "NXP(Philips); IC SL2 ICS53/ICS54(SLI-S) ICS5302/ICS5402(SLIX-S)" }, { 0xE004030000000000LL, 24, "NXP(Philips); IC SL2 ICS50/ICS51(SLI-L) ICS5002/ICS5102(SLIX-L)" }, @@ -75,7 +75,7 @@ const productName uidmapping[] = { // E0 05 XX .. .. .. // 05 = Manufacturer code (Infineon) // XX = IC id (Chip ID Family) - { 0xE005000000000000LL, 16, "Infineon Technologies AG Germany" }, + { 0xE005000000000000LL, 16, "Infineon Technologies AG Germany" }, { 0xE005A10000000000LL, 24, "Infineon; SRF55V01P [IC id = 161] plain mode 1kBit"}, { 0xE005A80000000000LL, 24, "Infineon; SRF55V01P [IC id = 168] pilot series 1kBit"}, { 0xE005400000000000LL, 24, "Infineon; SRF55V02P [IC id = 64] plain mode 2kBit"}, @@ -84,10 +84,10 @@ const productName uidmapping[] = { { 0xE005100000000000LL, 24, "Infineon; SRF55V10S [IC id = 16] secure mode 10KBit"}, { 0xE0051E0000000000LL, 23, "Infineon; SLE66r01P [IC id = 3x = My-d Move or My-d move NFC]"}, { 0xE005200000000000LL, 21, "Infineon; SLE66r01P [IC id = 3x = My-d Move or My-d move NFC]"}, - - { 0xE006000000000000LL, 16, "Cylink USA" }, - - + + { 0xE006000000000000LL, 16, "Cylink USA" }, + + // E0 07 xx // 07 = Texas Instruments // XX = from bit 41 to bit 43 = product configuration - from bit 44 to bit 47 IC id (Chip ID Family) @@ -101,11 +101,11 @@ const productName uidmapping[] = { { 0xE007100000000000LL, 20, "Texas Instrument; Tag-it HF-I Plus Chip; 64x32bit" }, { 0xE007800000000000LL, 23, "Texas Instrument; Tag-it HF-I Plus (RF-HDT-DVBB tag or Third Party Products)" }, { 0xE007C00000000000LL, 23, "Texas Instrument; Tag-it HF-I Standard; 8x32bit" }, - { 0xE007C40000000000LL, 23, "Texas Instrument; Tag-it HF-I Pro; 8x23bit; password" }, + { 0xE007C40000000000LL, 23, "Texas Instrument; Tag-it HF-I Pro; 8x23bit; password" }, - { 0xE008000000000000LL, 16, "Fujitsu Limited Japan" }, - { 0xE009000000000000LL, 16, "Matsushita Electronics Corporation, Semiconductor Company Japan" }, - { 0xE00A000000000000LL, 16, "NEC Japan" }, + { 0xE008000000000000LL, 16, "Fujitsu Limited Japan" }, + { 0xE009000000000000LL, 16, "Matsushita Electronics Corporation, Semiconductor Company Japan" }, + { 0xE00A000000000000LL, 16, "NEC Japan" }, { 0xE00B000000000000LL, 16, "Oki Electric Industry Co. Ltd Japan" }, { 0xE00C000000000000LL, 16, "Toshiba Corp. Japan" }, { 0xE00D000000000000LL, 16, "Mitsubishi Electric Corp. Japan" }, @@ -119,13 +119,13 @@ const productName uidmapping[] = { { 0xE013000000000000LL, 16, "ORGA Kartensysteme GmbH Germany" }, { 0xE014000000000000LL, 16, "SHARP Corporation Japan" }, { 0xE015000000000000LL, 16, "ATMEL France" }, - + { 0xE016000000000000LL, 16, "EM Microelectronic-Marin SA Switzerland (Skidata)"}, { 0xE016040000000000LL, 24, "EM-Marin SA (Skidata Keycard-eco); EM4034 [IC id = 01] (Read/Write - no AFI)"}, { 0xE0160C0000000000LL, 24, "EM-Marin SA (Skidata); EM4035 [IC id = 03] (Read/Write - replaced by 4233)"}, { 0xE016100000000000LL, 24, "EM-Marin SA (Skidata); EM4135 [IC id = 04] (Read/Write - replaced by 4233) 36x64bit start page 13"}, { 0xE016140000000000LL, 24, "EM-Marin SA (Skidata); EM4036 [IC id = 05] 28pF"}, - { 0xE016180000000000LL, 24, "EM-Marin SA (Skidata); EM4006 [IC id = 06] (Read Only)"}, + { 0xE016180000000000LL, 24, "EM-Marin SA (Skidata); EM4006 [IC id = 06] (Read Only)"}, { 0xE0161C0000000000LL, 24, "EM-Marin SA (Skidata); EM4133 [IC id = 07] 23,5pF (Read/Write)"}, { 0xE016200000000000LL, 24, "EM-Marin SA (Skidata); EM4033 [IC id = 08] 23,5pF (Read Only - no AFI / no DSFID / no security blocks)"}, { 0xE016240000000000LL, 24, "EM-Marin SA (Skidata); EM4233 [IC id = 09] 23,5pF CustomerID-102"}, @@ -165,7 +165,7 @@ const productName uidmapping[] = { { 0xE030000000000000LL, 16, "BeeDar Technology Inc. USA" }, { 0xE031000000000000LL, 16, "RFIDsec Denmark" }, { 0xE032000000000000LL, 16, "Schweizer Electronic AG Germany" }, - { 0xE033000000000000LL, 16, "AMIC Technology Corp Taiwan" }, + { 0xE033000000000000LL, 16, "AMIC Technology Corp Taiwan" }, { 0xE034000000000000LL, 16, "Mikron JSC Russia" }, { 0xE035000000000000LL, 16, "Fraunhofer Institute for Photonic Microsystems Germany" }, { 0xE036000000000000LL, 16, "IDS Microchip AG Switzerland" }, @@ -177,7 +177,7 @@ const productName uidmapping[] = { { 0xE03C000000000000LL, 16, "Verayo Inc. USA" }, { 0xE03D000000000000LL, 16, "HID Global USA" }, { 0xE03E000000000000LL, 16, "Productivity Engineering Gmbh Germany" }, - { 0xE03F000000000000LL, 16, "Austriamicrosystems AG (reserved) Austria" }, + { 0xE03F000000000000LL, 16, "Austriamicrosystems AG (reserved) Austria" }, { 0xE040000000000000LL, 16, "Gemalto SA France" }, { 0xE041000000000000LL, 16, "Renesas Electronics Corporation Japan" }, { 0xE042000000000000LL, 16, "3Alogics Inc Korea" }, @@ -202,53 +202,53 @@ int getUID(uint8_t *buf) { c.arg[0] = 5; // len uint8_t retry; - - // don't give up the at the first try + + // don't give up the at the first try for (retry = 0; retry < 3; retry++) { clearCommandBuffer(); SendCommand(&c); - + if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { - + uint8_t resplen = resp.arg[0]; if (resplen >= 12 && CheckCrc(resp.d.asBytes, 12)) { memcpy(buf, resp.d.asBytes + 2, 8); return 1; - } - } + } + } } // retry - + if ( retry >= 3 ) PrintAndLogEx(WARNING, "timeout while waiting for reply."); - + return 0; } // get a product description based on the UID // uid[8] tag uid -// returns description of the best match +// returns description of the best match static char* getTagInfo_15(uint8_t *uid) { uint64_t myuid, mask; - int i = 0, best = -1; + int i = 0, best = -1; memcpy(&myuid, uid, sizeof(uint64_t)); while (uidmapping[i].mask > 0) { mask = (~0LL) << (64-uidmapping[i].mask); if ((myuid & mask) == uidmapping[i].uid) { - if (best == -1) { + if (best == -1) { best = i; } else { if (uidmapping[i].mask > uidmapping[best].mask) { best=i; } - } - } + } + } i++; - } + } if (best >= 0) return uidmapping[best].desc; - return uidmapping[i].desc; + return uidmapping[i].desc; } // return a clear-text message to an errorcode @@ -333,7 +333,7 @@ int usage_15_dump(void){ return 0; } int usage_15_restore(void){ - char *options[][2]={ + char *options[][2]={ {"h", "this help"}, {"-2", "use slower '1 out of 256' mode"}, {"-o", "set OPTION Flag (needed for TI)"}, @@ -398,7 +398,7 @@ int usage_15_readmulti(void){ int CmdHF15Demod(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_15_demod(); - + // The sampling rate is 106.353 ksps/s, for T = 18.8 us int i, j; int max = 0, maxPos = 0; @@ -419,7 +419,7 @@ int CmdHF15Demod(const char *Cmd) { } PrintAndLogEx(NORMAL, "SOF at %d, correlation %d", maxPos, max / (ARRAYLEN(FrameSOF) / skip)); - + i = maxPos + ARRAYLEN(FrameSOF) / skip; int k = 0; uint8_t outBuf[20]; @@ -439,7 +439,7 @@ int CmdHF15Demod(const char *Cmd) { // Even things out by the length of the target waveform. corr0 *= 4; corr1 *= 4; - + if (corrEOF > corr1 && corrEOF > corr0) { PrintAndLogEx(NORMAL, "EOF at %d", i); break; @@ -459,13 +459,13 @@ int CmdHF15Demod(const char *Cmd) { break; } } - + if (mask != 0x01) { PrintAndLogEx(WARNING, "Error, uneven octet! (discard extra bits!)"); PrintAndLogEx(NORMAL, " mask = %02x", mask); } PrintAndLogEx(NORMAL, "%d octets", k); - + for (i = 0; i < k; i++) PrintAndLogEx(NORMAL, "# %2d: %02x ", i, outBuf[i]); @@ -480,10 +480,10 @@ int CmdHF15Samples(const char *Cmd) { if (cmdp == 'h' || cmdp == 'H') return usage_15_samples(); UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693, {0,0,0}}; - clearCommandBuffer(); + clearCommandBuffer(); SendCommand(&c); - - //download samples + + //download samples getSamples(0, false); return 0; } @@ -504,17 +504,17 @@ int CmdHF15Info(const char *Cmd) { char cmdbuf[100]; char *cmd = cmdbuf; memset(cmdbuf, 0, sizeof(cmdbuf)); - + strncpy(cmd, Cmd, 99); - + if ( !prepareHF15Cmd(&cmd, &c, ISO15_CMD_SYSINFO) ) return 0; AddCrc(req, c.arg[0]); c.arg[0] += 2; - //PrintAndLogEx(NORMAL, "cmd %s", sprint_hex(c.d.asBytes, reqlen) ); - + //PrintAndLogEx(NORMAL, "cmd %s", sprint_hex(c.d.asBytes, reqlen) ); + clearCommandBuffer(); SendCommand(&c); @@ -522,44 +522,44 @@ int CmdHF15Info(const char *Cmd) { PrintAndLogEx(WARNING, "iso15693 card select failed"); return 1; } - + uint32_t status = resp.arg[0]; - + if ( status < 2 ) { PrintAndLogEx(WARNING, "iso15693 card doesn't answer to systeminfo command"); - return 1; + return 1; } - - recv = resp.d.asBytes; - + + recv = resp.d.asBytes; + if ( recv[0] & ISO15_RES_ERROR ) { - PrintAndLogEx(WARNING, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); + PrintAndLogEx(WARNING, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); return 3; } - + PrintAndLogEx(NORMAL, " UID : %s", sprintUID(NULL, recv+2)); PrintAndLogEx(NORMAL, " TYPE : %s", getTagInfo_15(recv+2)); PrintAndLogEx(NORMAL, " SYSINFO : %s", sprint_hex(recv, status-2)); // DSFID - if (recv[1] & 0x01) + if (recv[1] & 0x01) PrintAndLogEx(NORMAL, " - DSFID supported [0x%02X]", recv[10]); - else + else PrintAndLogEx(NORMAL, " - DSFID not supported"); - + // AFI - if (recv[1] & 0x02) + if (recv[1] & 0x02) PrintAndLogEx(NORMAL, " - AFI supported [0x%02X]", recv[11]); - else + else PrintAndLogEx(NORMAL, " - AFI not supported"); // IC reference - if (recv[1] & 0x08) + if (recv[1] & 0x08) PrintAndLogEx(NORMAL, " - IC reference supported [0x%02X]", recv[14]); - else + else PrintAndLogEx(NORMAL, " - IC reference not supported"); - // memory + // memory if (recv[1] & 0x04) { PrintAndLogEx(NORMAL, " - Tag provides info on memory layout (vendor dependent)"); uint8_t blocks = recv[12]+1; @@ -577,7 +577,7 @@ int CmdHF15Info(const char *Cmd) { int CmdHF15Record(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_15_record(); - + UsbCommand c = {CMD_RECORD_RAW_ADC_SAMPLES_ISO_15693, {0,0,0}}; clearCommandBuffer(); SendCommand(&c); @@ -586,7 +586,7 @@ int CmdHF15Record(const char *Cmd) { // used with 'hf search' int HF15Reader(const char *Cmd, bool verbose) { - uint8_t uid[8] = {0,0,0,0,0,0,0,0}; + uint8_t uid[8] = {0,0,0,0,0,0,0,0}; if (!getUID(uid)) { if (verbose) PrintAndLogEx(WARNING, "No tag found."); return 0; @@ -600,7 +600,7 @@ int HF15Reader(const char *Cmd, bool verbose) { int CmdHF15Reader(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_15_reader(); - + HF15Reader(Cmd, true); return 0; } @@ -611,12 +611,12 @@ int CmdHF15Sim(const char *Cmd) { char cmdp =tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) < 1 || cmdp == 'h') return usage_15_sim(); - uint8_t uid[8] = {0,0,0,0,0,0,0,0}; + uint8_t uid[8] = {0,0,0,0,0,0,0,0}; if (param_gethex(Cmd, 0, uid, 16)) { PrintAndLogEx(WARNING, "UID must include 16 HEX symbols"); return 0; } - + PrintAndLogEx(SUCCESS, "Starting simulating UID %s", sprint_hex(uid, sizeof(uid)) ); UsbCommand c = {CMD_SIMTAG_ISO_15693, {0, 0, 0}}; @@ -634,7 +634,7 @@ int CmdHF15Afi(const char *Cmd) { if (cmdp == 'h') return usage_15_findafi(); PrintAndLogEx(SUCCESS, "press pm3-button to cancel"); - + UsbCommand c = {CMD_ISO_15693_FIND_AFI, {strtol(Cmd, NULL, 0), 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -649,20 +649,20 @@ typedef struct { // Reads all memory pages // need to write to file int CmdHF15Dump(const char*Cmd) { - + uint8_t fileNameLen = 0; char filename[FILE_PATH_SIZE] = {0}; char * fptr = filename; bool errors = false; uint8_t cmdp = 0; - uint8_t uid[8] = {0,0,0,0,0,0,0,0}; - + uint8_t uid[8] = {0,0,0,0,0,0,0,0}; + while(param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_15_dump(); case 'f': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); cmdp += 2; break; default: @@ -674,7 +674,7 @@ int CmdHF15Dump(const char*Cmd) { //Validations if (errors) return usage_15_dump(); - + if (fileNameLen < 1) { PrintAndLogEx(INFO, "Using UID as filename"); @@ -683,12 +683,12 @@ int CmdHF15Dump(const char*Cmd) { PrintAndLogEx(WARNING, "No tag found."); return 1; } - - fptr += sprintf(fptr, "hf-15-"); + + fptr += sprintf(fptr, "hf-15-"); FillFileNameByUID(fptr,uid,"-dump",sizeof(uid)); - } + } // detect blocksize from card :) - + PrintAndLogEx(NORMAL, "Reading memory from tag UID " _YELLOW_(%s), sprintUID(NULL, uid)); int blocknum = 0; @@ -696,7 +696,7 @@ int CmdHF15Dump(const char*Cmd) { // memory. t15memory mem[256]; - + uint8_t data[256*4] = {0}; memset(data, 0, sizeof(data)); @@ -708,64 +708,64 @@ int CmdHF15Dump(const char*Cmd) { // copy uid to read command memcpy(req+2, uid, sizeof(uid)); - + for (int retry = 0; retry < 5; retry++) { - + req[10] = blocknum; AddCrc(req, 11); c.arg[0] = 13; - + clearCommandBuffer(); SendCommand(&c); - + if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { uint8_t len = resp.arg[0]; if ( len < 2 ) { PrintAndLogEx(FAILED, "iso15693 card select failed"); - continue; + continue; } - + recv = resp.d.asBytes; - + if ( !CheckCrc(recv, len) ) { PrintAndLogEx(FAILED, "crc fail"); continue; } if (recv[0] & ISO15_RES_ERROR) { - PrintAndLogEx(FAILED, "Tag returned Error %i: %s", recv[1], TagErrorStr(recv[1]) ); + PrintAndLogEx(FAILED, "Tag returned Error %i: %s", recv[1], TagErrorStr(recv[1]) ); break; } - + mem[blocknum].lock = resp.d.asBytes[0]; - memcpy(mem[blocknum].block, resp.d.asBytes + 1, 4); + memcpy(mem[blocknum].block, resp.d.asBytes + 1, 4); memcpy(data + (blocknum * 4), resp.d.asBytes + 1, 4); - + retry = 0; blocknum++; - + printf("."); fflush(stdout); - } + } } PrintAndLogEx(NORMAL, "\n"); PrintAndLogEx(NORMAL, "block# | data |lck| ascii"); - PrintAndLogEx(NORMAL, "---------+--------------+---+----------"); + PrintAndLogEx(NORMAL, "---------+--------------+---+----------"); for (int i = 0; i < blocknum; i++) { PrintAndLogEx(NORMAL, "%3d/0x%02X | %s | %d | %s", i, i, sprint_hex(mem[i].block, 4 ), mem[i].lock, sprint_ascii(mem[i].block, 4) ); } PrintAndLogEx(NORMAL, "\n"); size_t datalen = blocknum * 4; - saveFileEML(filename, "eml", data, datalen, 4); + saveFileEML(filename, "eml", data, datalen, 4); saveFile(filename, "bin", data, datalen); return 0; } int CmdHF15Restore(const char*Cmd) { FILE *f; - + uint8_t uid[8]={0x00}; char filename[FILE_PATH_SIZE] = {0x00}; char buff[255] = {0x00}; @@ -796,20 +796,20 @@ int CmdHF15Restore(const char*Cmd) { break; case 'f': param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); - cmdp++; + cmdp++; break; case 'r': retries=param_get8ex(Cmd, cmdp+1, 3, 10); - cmdp++; + cmdp++; break; case 'b': blocksize=param_get8ex(Cmd, cmdp+1, 4, 10); - cmdp++; + cmdp++; break; case 'u': param_getstr(Cmd, cmdp+1, buff, FILE_PATH_SIZE); - cmdp++; - snprintf(filename,sizeof(filename),"hf-15-dump-%s-bin",buff); + cmdp++; + snprintf(filename,sizeof(filename),"hf-15-dump-%s-bin",buff); break; case 'h': return usage_15_restore(); @@ -821,7 +821,7 @@ int CmdHF15Restore(const char*Cmd) { } PrintAndLogEx(INFO,"Blocksize: %u",blocksize); - + if ( !strlen(filename)) { PrintAndLogEx(WARNING,"Please provide a filename"); return usage_15_restore(); @@ -831,18 +831,18 @@ int CmdHF15Restore(const char*Cmd) { PrintAndLogEx(WARNING, "Could not find file %s", filename); return 2; } - + if (!getUID(uid)) { PrintAndLogEx(WARNING, "No tag found"); fclose(f); return 3; } - + while (1) { tried = 0; hex[0] = 0x00; tmpCmd[0] = 0x00; - + bytes_read = fread( buff, 1, blocksize, f ); if ( bytes_read == 0) { PrintAndLogEx(SUCCESS, "File reading done `%s`", filename); @@ -853,13 +853,13 @@ int CmdHF15Restore(const char*Cmd) { fclose(f); return 2; } - + for(int j=0; j < blocksize; j++) snprintf(hex+j*2, 3, "%02X", buff[j]); - + for(int j=0; j < sizeof(uid)/sizeof(uid[0]); j++) snprintf(buff+j*2,3,"%02X", uid[j]); - + //TODO: Addressed mode currently not work //snprintf(tmpCmd, sizeof(tmpCmd), "%s %s %d %s", newCmdPrefix, buff, i, hex); snprintf(tmpCmd, sizeof(tmpCmd), "%s u %u %s", newCmdPrefix, i, hex); @@ -894,23 +894,23 @@ int CmdHF15Raw(const char *Cmd) { char buf[5] = ""; uint8_t data[100]; uint32_t datalen = 0, temp; - + // strip while (*Cmd==' ' || *Cmd=='\t') Cmd++; - + while (Cmd[i]!='\0') { if (Cmd[i]==' ' || Cmd[i]=='\t') { i++; continue; } if (Cmd[i]=='-') { switch (Cmd[i+1]) { - case 'r': - case 'R': + case 'r': + case 'R': reply = 0; break; case '2': fast = 0; break; case 'c': - case 'C': + case 'C': crc = true; break; default: @@ -926,7 +926,7 @@ int CmdHF15Raw(const char *Cmd) { buf[strlen(buf)+1] = 0; buf[strlen(buf)] = Cmd[i]; i++; - + if (strlen(buf) >= 2) { sscanf(buf, "%x", &temp); data[datalen] = (uint8_t)(temp & 0xff); @@ -938,20 +938,20 @@ int CmdHF15Raw(const char *Cmd) { PrintAndLogEx(WARNING, "Invalid char on input"); return 0; } - + if (crc) { AddCrc(data, datalen); datalen += 2; } - + c.arg[0] = datalen; c.arg[1] = fast; c.arg[2] = reply; memcpy(c.d.asBytes, data, datalen); - clearCommandBuffer(); + clearCommandBuffer(); SendCommand(&c); - + if (reply) { if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { uint8_t len = resp.arg[0]; @@ -959,7 +959,7 @@ int CmdHF15Raw(const char *Cmd) { PrintAndLogEx(NORMAL, "%s", sprint_hex(resp.d.asBytes, len) ); } else { PrintAndLogEx(WARNING, "timeout while waiting for reply."); - } + } } return 0; } @@ -977,7 +977,7 @@ int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd) { // strip while (**cmd==' ' || **cmd=='\t') (*cmd)++; - + if (strstr(*cmd, "-2") == *cmd) { c->arg[1] = 0; // use 1of256 (*cmd) += 2; @@ -985,15 +985,15 @@ int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd) { // strip while (**cmd==' ' || **cmd=='\t') (*cmd)++; - + if (strstr(*cmd, "-o") == *cmd) { req[reqlen] = ISO15_REQ_OPTION; (*cmd) += 2; } - + // strip while (**cmd == ' ' || **cmd == '\t') (*cmd)++; - + switch (**cmd) { case 0: PrintAndLogEx(WARNING, "missing addr"); @@ -1017,28 +1017,28 @@ int prepareHF15Cmd(char **cmd, UsbCommand *c, uint8_t iso15cmd) { memcpy(&req[reqlen], uid, sizeof(uid)); PrintAndLogEx(NORMAL, "Detected UID %s", sprintUID(NULL, uid)); reqlen += sizeof(uid); - break; + break; default: req[reqlen++] |= ISO15_REQ_SUBCARRIER_SINGLE | ISO15_REQ_DATARATE_HIGH | ISO15_REQ_NONINVENTORY | ISO15_REQ_ADDRESS; req[reqlen++] = iso15cmd; - + // parse UID for (int i=0; i<8 && (*cmd)[i*2] && (*cmd)[i*2+1]; i++) { sscanf((char[]){(*cmd)[i*2], (*cmd)[i*2+1],0}, "%X", &temp); uid[7-i] = temp & 0xff; - } - + } + PrintAndLogEx(NORMAL, "Using UID %s", sprintUID(NULL, uid)); memcpy(&req[reqlen], uid, sizeof(uid)); reqlen += sizeof(uid); break; } - // skip to next space + // skip to next space while (**cmd!=' ' && **cmd!='\t') (*cmd)++; // skip over the space while (**cmd==' ' || **cmd=='\t') (*cmd)++; - - c->arg[0] = reqlen; + + c->arg[0] = reqlen; return 1; } @@ -1066,7 +1066,7 @@ int CmdHF15Readmulti(const char *Cmd) { // add OPTION flag, in order to get lock-info req[0] |= ISO15_REQ_OPTION; - + reqlen = c.arg[0]; // decimal @@ -1074,11 +1074,11 @@ int CmdHF15Readmulti(const char *Cmd) { pagecount = param_get8ex(cmd, 1, 0, 10); //PrintAndLogEx(NORMAL, "ice %d %d\n", pagenum, pagecount); - + // 0 means 1 page, - // 1 means 2 pages, ... - if (pagecount > 0) pagecount--; - + // 1 means 2 pages, ... + if (pagecount > 0) pagecount--; + req[reqlen++] = pagenum; req[reqlen++] = pagecount; AddCrc(req, reqlen); @@ -1086,27 +1086,27 @@ int CmdHF15Readmulti(const char *Cmd) { clearCommandBuffer(); SendCommand(&c); - + if ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { PrintAndLogEx(FAILED, "iso15693 card select failed"); return 1; } - - uint32_t status = resp.arg[0]; + + uint32_t status = resp.arg[0]; if ( status < 2 ) { PrintAndLogEx(FAILED, "iso15693 card select failed"); - return 1; + return 1; } - recv = resp.d.asBytes; - + recv = resp.d.asBytes; + if (!CheckCrc(recv, status)) { PrintAndLogEx(FAILED, "CRC failed"); return 2; - } - + } + if ( recv[0] & ISO15_RES_ERROR ) { - PrintAndLogEx(FAILED, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); + PrintAndLogEx(FAILED, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); return 3; } @@ -1116,7 +1116,7 @@ int CmdHF15Readmulti(const char *Cmd) { // print response PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "block# | data |lck| ascii"); - PrintAndLogEx(NORMAL, "---------+--------------+---+----------"); + PrintAndLogEx(NORMAL, "---------+--------------+---+----------"); for (int i = start; i < stop; i += 5) { PrintAndLogEx(NORMAL, "%3d/0x%02X | %s | %d | %s", currblock, currblock, sprint_hex(recv+i+1, 4 ), recv[i], sprint_ascii(recv+i+1, 4) ); currblock++; @@ -1133,7 +1133,7 @@ int CmdHF15Read(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd)<3 || cmdp == 'h' || cmdp == 'H') return usage_15_read(); - + UsbCommand resp; uint8_t *recv; @@ -1141,27 +1141,27 @@ int CmdHF15Read(const char *Cmd) { // arg0 (datalen, cmd len? .arg0 == crc?) // arg1 (speed == 0 == 1 of 256, == 1 == 1 of 4 ) // arg2 (recv == 1 == expect a response) - UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; + UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; uint8_t *req = c.d.asBytes; int reqlen = 0, blocknum; char cmdbuf[100]; char *cmd = cmdbuf; strncpy(cmd, Cmd, 99); - + if ( !prepareHF15Cmd(&cmd, &c, ISO15_CMD_READ) ) return 0; // add OPTION flag, in order to get lock-info req[0] |= ISO15_REQ_OPTION; - + reqlen = c.arg[0]; blocknum = strtol(cmd, NULL, 0); - + req[reqlen++] = (uint8_t)blocknum; - + AddCrc(req, reqlen); - + c.arg[0] = reqlen+2; clearCommandBuffer(); @@ -1171,31 +1171,31 @@ int CmdHF15Read(const char *Cmd) { PrintAndLogEx(NORMAL, "iso15693 card select failed"); return 1; } - - uint32_t status = resp.arg[0]; + + uint32_t status = resp.arg[0]; if ( status < 2 ) { PrintAndLogEx(NORMAL, "iso15693 card select failed"); - return 1; + return 1; } - recv = resp.d.asBytes; - + recv = resp.d.asBytes; + if ( !CheckCrc(recv, status) ) { PrintAndLogEx(NORMAL, "CRC failed"); return 2; - } - + } + if ( recv[0] & ISO15_RES_ERROR ) { - PrintAndLogEx(WARNING, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); + PrintAndLogEx(WARNING, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); return 3; } - + // print response PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "block #%3d |lck| ascii", blocknum ); PrintAndLogEx(NORMAL, "------------+---+------" ); PrintAndLogEx(NORMAL, "%s| %d | %s", sprint_hex(recv+2, status-4), recv[1], sprint_ascii(recv+2, status-4) ); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); return 0; } @@ -1207,7 +1207,7 @@ int CmdHF15Write(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd)<3 || cmdp == 'h' || cmdp == 'H') return usage_15_write(); - + UsbCommand resp; uint8_t *recv; UsbCommand c = {CMD_ISO_15693_COMMAND, {0, 1, 1}}; // len,speed,recv? @@ -1216,38 +1216,38 @@ int CmdHF15Write(const char *Cmd) { char cmdbuf[100]; char *cmd = cmdbuf; char *cmd2; - + strncpy(cmd, Cmd, 99); if ( !prepareHF15Cmd(&cmd, &c, ISO15_CMD_WRITE) ) return 0; reqlen = c.arg[0]; - - // *cmd -> page num ; *cmd2 -> data + + // *cmd -> page num ; *cmd2 -> data cmd2=cmd; while (*cmd2!=' ' && *cmd2!='\t' && *cmd2) cmd2++; *cmd2 = 0; - cmd2++; - + cmd2++; + pagenum = strtol(cmd, NULL, 0); - req[reqlen++] = (uint8_t)pagenum; - - while (cmd2[0] && cmd2[1]) { // hexdata, read by 2 hexchars + req[reqlen++] = (uint8_t)pagenum; + + while (cmd2[0] && cmd2[1]) { // hexdata, read by 2 hexchars if (*cmd2==' ') { - cmd2++; - continue; + cmd2++; + continue; } sscanf((char[]){cmd2[0],cmd2[1],0},"%X",&temp); req[reqlen++]=temp & 0xff; cmd2+=2; - } + } AddCrc(req, reqlen); c.arg[0] = reqlen+2; - + PrintAndLogEx(NORMAL, "iso15693 writing to page %02d (0x%02X) | data ", pagenum, pagenum); - + clearCommandBuffer(); SendCommand(&c); @@ -1255,25 +1255,25 @@ int CmdHF15Write(const char *Cmd) { PrintAndLogEx(FAILED, "iso15693 card timeout, data may be written anyway"); return 1; } - - uint32_t status = resp.arg[0]; + + uint32_t status = resp.arg[0]; if ( status < 2 ) { PrintAndLogEx(FAILED, "iso15693 card select failed"); - return 1; + return 1; } - recv = resp.d.asBytes; - + recv = resp.d.asBytes; + if ( !CheckCrc(recv, status) ) { PrintAndLogEx(FAILED, "CRC failed"); return 2; - } - + } + if ( recv[0] & ISO15_RES_ERROR ) { - PrintAndLogEx(NORMAL, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); + PrintAndLogEx(NORMAL, "iso15693 card returned error %i: %s", recv[0], TagErrorStr(recv[0])); return 3; } - + PrintAndLogEx(NORMAL, "OK"); return 0; } @@ -1283,22 +1283,22 @@ static command_t CommandTable15[] = { {"demod", CmdHF15Demod, 1, "Demodulate ISO15693 from tag"}, {"dump", CmdHF15Dump, 0, "Read all memory pages of an ISO15693 tag, save to file"}, {"findafi", CmdHF15Afi, 0, "Brute force AFI of an ISO15693 tag"}, - {"info", CmdHF15Info, 0, "Tag information"}, + {"info", CmdHF15Info, 0, "Tag information"}, {"list", CmdHF15List, 0, "[Deprecated] List ISO15693 history"}, - {"raw", CmdHF15Raw, 0, "Send raw hex data to tag"}, + {"raw", CmdHF15Raw, 0, "Send raw hex data to tag"}, {"reader", CmdHF15Reader, 0, "Act like an ISO15693 reader"}, {"record", CmdHF15Record, 0, "Record Samples (ISO15693)"}, {"restore", CmdHF15Restore, 0, "Restore from file to all memory pages of an ISO15693 tag"}, {"sim", CmdHF15Sim, 0, "Fake an ISO15693 tag"}, {"samples", CmdHF15Samples, 0, "Acquire Samples as Reader (enables carrier, sends inquiry)"}, - {"read", CmdHF15Read, 0, "Read a block"}, - {"write", CmdHF15Write, 0, "Write a block"}, + {"read", CmdHF15Read, 0, "Read a block"}, + {"write", CmdHF15Write, 0, "Write a block"}, {"readmulti", CmdHF15Readmulti, 0, "Reads multiple Blocks"}, {NULL, NULL, 0, NULL} }; int CmdHF15(const char *Cmd) { - clearCommandBuffer(); + clearCommandBuffer(); CmdsParse(CommandTable15, Cmd); return 0; } diff --git a/client/cmdhfepa.c b/client/cmdhfepa.c index dd110c9c0..4e7510fe0 100644 --- a/client/cmdhfepa.c +++ b/client/cmdhfepa.c @@ -127,8 +127,8 @@ int CmdHFEPAPACEReplay(const char *Cmd) memcpy(usb_cmd.d.asBytes, // + (j * sizeof(usb_cmd.d.asBytes)), apdus[i] + (j * sizeof(usb_cmd.d.asBytes)), packet_length); - - clearCommandBuffer(); + + clearCommandBuffer(); SendCommand(&usb_cmd); WaitForResponse(CMD_ACK, &resp); if (resp.arg[0] != 0) { diff --git a/client/cmdhffelica.c b/client/cmdhffelica.c index efb6b68d7..2a0380fc5 100644 --- a/client/cmdhffelica.c +++ b/client/cmdhffelica.c @@ -82,20 +82,20 @@ int CmdHFFelicaReader(const char *Cmd) { //SendCommand(&cDisconnect); return 0; } - + felica_card_select_t card; memcpy(&card, (felica_card_select_t *)resp.d.asBytes, sizeof(felica_card_select_t)); uint64_t status = resp.arg[0]; - + switch(status) { case 1: { - if (!silent) - PrintAndLogEx(WARNING, "card timeout"); + if (!silent) + PrintAndLogEx(WARNING, "card timeout"); break; } case 2: { if (!silent) - PrintAndLogEx(WARNING, "card answered wrong"); + PrintAndLogEx(WARNING, "card answered wrong"); break; } case 3: { @@ -105,15 +105,15 @@ int CmdHFFelicaReader(const char *Cmd) { } case 0: { PrintAndLogEx(SUCCESS, "FeliCa tag info"); - + PrintAndLogEx(NORMAL, "IDm %s", sprint_hex(card.IDm, sizeof(card.IDm))); PrintAndLogEx(NORMAL, " - CODE %s", sprint_hex(card.code, sizeof(card.code))); PrintAndLogEx(NORMAL, " - NFCID2 %s", sprint_hex(card.uid, sizeof(card.uid))); - + PrintAndLogEx(NORMAL, "Parameter (PAD) | %s", sprint_hex(card.PMm, sizeof(card.PMm))); PrintAndLogEx(NORMAL, " - IC CODE %s", sprint_hex(card.iccode, sizeof(card.iccode))); PrintAndLogEx(NORMAL, " - MRT %s", sprint_hex(card.mrt, sizeof(card.mrt))); - + PrintAndLogEx(NORMAL, "SERVICE CODE %s", sprint_hex(card.servicecode, sizeof(card.servicecode))); break; } @@ -125,12 +125,12 @@ int CmdHFFelicaReader(const char *Cmd) { int CmdHFFelicaSim(const char *Cmd) { bool errors = false; uint8_t flags = 0; - uint8_t tagtype = 1; + uint8_t tagtype = 1; uint8_t cmdp = 0; uint8_t uid[10] = {0,0,0,0,0,0,0,0,0,0}; int uidlen = 0; bool verbose = false; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (param_getchar(Cmd, cmdp)) { case 'h': @@ -141,12 +141,12 @@ int CmdHFFelicaSim(const char *Cmd) { // Retrieve the tag type tagtype = param_get8ex(Cmd, cmdp+1, 0, 10); if (tagtype == 0) - errors = true; + errors = true; cmdp += 2; break; case 'u': case 'U': - // Retrieve the full 4,7,10 byte long uid + // Retrieve the full 4,7,10 byte long uid param_gethex_ex(Cmd, cmdp+1, uid, &uidlen); if (!errors) { PrintAndLogEx(NORMAL, "Emulating ISO18092/FeliCa tag with %d byte UID (%s)", uidlen>>1, sprint_hex(uid, uidlen>>1)); @@ -161,7 +161,7 @@ int CmdHFFelicaSim(const char *Cmd) { case 'e': case 'E': cmdp++; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -171,29 +171,29 @@ int CmdHFFelicaSim(const char *Cmd) { //Validations if (errors || cmdp == 0) return usage_hf_felica_sim(); - - UsbCommand c = {CMD_FELICA_SIMULATE_TAG,{ tagtype, flags, 0 }}; + + UsbCommand c = {CMD_FELICA_SIMULATE_TAG,{ tagtype, flags, 0 }}; memcpy(c.d.asBytes, uid, uidlen>>1); clearCommandBuffer(); - SendCommand(&c); + SendCommand(&c); UsbCommand resp; - + if ( verbose ) PrintAndLogEx(NORMAL, "Press pm3-button to abort simulation"); - + while( !ukbhit() ){ - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) continue; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) continue; } return 0; } -int CmdHFFelicaSniff(const char *Cmd) { +int CmdHFFelicaSniff(const char *Cmd) { uint8_t cmdp = 0; uint64_t samples2skip = 0; uint64_t triggers2skip = 0; bool errors = false; - + while(param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch(param_getchar(Cmd, cmdp)) { case 'h': @@ -204,7 +204,7 @@ int CmdHFFelicaSniff(const char *Cmd) { samples2skip = param_get32ex(Cmd, cmdp+1, 0, 10); cmdp += 2; break; - case 't': + case 't': case 'T': triggers2skip = param_get32ex(Cmd, cmdp+1, 0, 10); cmdp += 2; @@ -217,7 +217,7 @@ int CmdHFFelicaSniff(const char *Cmd) { } //Validations if (errors || cmdp == 0) return usage_hf_felica_sniff(); - + UsbCommand c = {CMD_FELICA_SNOOP, {samples2skip, triggers2skip, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -231,21 +231,21 @@ int CmdHFFelicaSimLite(const char *Cmd) { if (!uid) return usage_hf_felica_simlite(); - + UsbCommand c = {CMD_FELICA_LITE_SIM, {uid, 0, 0} }; clearCommandBuffer(); SendCommand(&c); return 0; } - + static void printSep() { PrintAndLogEx(NORMAL, "------------------------------------------------------------------------------------"); } uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace, uint16_t tracelen) { - if (tracepos+19 >= tracelen) + if (tracepos+19 >= tracelen) return tracelen; - + trace += tracepos; uint8_t blocknum = trace[0]; uint8_t status1 = trace[1]; @@ -276,23 +276,23 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace, uint16_t tracelen) { uint32_t regA = trace[3] | trace[4] << 8 | trace[5] << 16 | trace[ 6] << 24; uint32_t regB = trace[7] | trace[8] << 8 | trace[9] << 16 | trace[10] << 24; line[0] = 0; - for (int j = 0; j < 8; j++) + for (int j = 0; j < 8; j++) snprintf(line + (j*2), sizeof(line)-1-(j*2), "%02x", trace[j+11]); - + PrintAndLogEx(NORMAL, "REG: regA: %d regB: %d regC: %s ", regA, regB, line); } break; - case 0x80: PrintAndLogEx(NORMAL, "Random Challenge, WO: %s ", line); break; - case 0x81: PrintAndLogEx(NORMAL, "MAC, only set on dual read: %s ", line); break; + case 0x80: PrintAndLogEx(NORMAL, "Random Challenge, WO: %s ", line); break; + case 0x81: PrintAndLogEx(NORMAL, "MAC, only set on dual read: %s ", line); break; case 0x82: { char idd[20]; char idm[20]; - for (int j = 0; j < 8; j++) + for (int j = 0; j < 8; j++) snprintf(idd + (j*2), sizeof(idd)-1-(j*2), "%02x", trace[j+3]); - - for (int j = 0; j < 6; j++) + + for (int j = 0; j < 6; j++) snprintf(idm + (j*2), sizeof(idm)-1-(j*2), "%02x", trace[j+13]); - + PrintAndLogEx(NORMAL, "ID Block, IDd: 0x%s DFC: 0x%02x%02x Arb: %s ", idd, trace[11], trace [12], idm); } break; @@ -301,16 +301,16 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace, uint16_t tracelen) { char pmm[20]; for (int j = 0; j < 8; j++) snprintf(idm + (j*2), sizeof(idm)-1-(j*2), "%02x", trace[j+3]); - + for (int j = 0; j < 8; j++) snprintf(pmm + (j*2), sizeof(pmm)-1-(j*2), "%02x", trace[j+11]); - + PrintAndLogEx(NORMAL, "DeviceId: IDm: 0x%s PMm: 0x%s ", idm, pmm); } - break; + break; case 0x84: PrintAndLogEx(NORMAL, "SER_C: 0x%02x%02x ", trace[3], trace[4]); break; - case 0x85: PrintAndLogEx(NORMAL, "SYS_Cl 0x%02x%02x ", trace[3], trace[4]); break; - case 0x86: PrintAndLogEx(NORMAL, "CKV (key version): 0x%02x%02x ", trace[3], trace[4]); break; + case 0x85: PrintAndLogEx(NORMAL, "SYS_Cl 0x%02x%02x ", trace[3], trace[4]); break; + case 0x86: PrintAndLogEx(NORMAL, "CKV (key version): 0x%02x%02x ", trace[3], trace[4]); break; case 0x87: PrintAndLogEx(NORMAL, "CK (card key), WO: %s ", line); break; case 0x88: { PrintAndLogEx(NORMAL, "Memory Configuration (MC):"); @@ -325,15 +325,15 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace, uint16_t tracelen) { PrintAndLogEx(NORMAL, "Memory config writable : %s", (trace[3+2] == 0xff) ? "yes" : "no"); PrintAndLogEx(NORMAL, "RW access for S_PAD : %s ", sprint_bin(trace+3, 2) ); } - break; + break; case 0x90: { PrintAndLogEx(NORMAL, "Write count, RO: %02x %02x %02x ", trace[3], trace[4], trace[5]); } - break; + break; case 0x91: { PrintAndLogEx(NORMAL, "MAC_A, RW (auth): %s ", line); } - break; + break; case 0x92: PrintAndLogEx(NORMAL, "State:"); PrintAndLogEx(NORMAL, "Polling disabled: %s", trace[3+8] ? "yes" : "no"); @@ -342,7 +342,7 @@ uint16_t PrintFliteBlock(uint16_t tracepos, uint8_t *trace, uint16_t tracelen) { case 0xa0: PrintAndLogEx(NORMAL, "CRC of all bloacks match : %s", (trace[3+2]==0xff) ? "no" : "yes"); break; - default: + default: PrintAndLogEx(WARNING, "INVALID %d: %s", blocknum, line); break; } @@ -360,7 +360,7 @@ int CmdHFFelicaDumpLite(const char *Cmd) { clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + uint8_t timeout = 0; while ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { timeout++; @@ -381,32 +381,32 @@ int CmdHFFelicaDumpLite(const char *Cmd) { PrintAndLogEx(WARNING, "\nButton pressed. Aborted."); return 1; } - - uint64_t tracelen = resp.arg[1]; + + uint64_t tracelen = resp.arg[1]; uint8_t *trace = calloc(tracelen, sizeof(uint8_t)); if ( trace == NULL ) { - PrintAndLogEx(WARNING, "Cannot allocate memory for trace"); + PrintAndLogEx(WARNING, "Cannot allocate memory for trace"); return 1; } // only download data if there is any. - if ( tracelen > 0 ) { - + if ( tracelen > 0 ) { + if ( !GetFromDevice(BIG_BUF, trace, tracelen, 0, NULL, 2500, false) ){ PrintAndLogEx(WARNING, "command execution time out"); free(trace); return 0; } - + PrintAndLogEx(SUCCESS, "Recorded Activity (trace len = %d bytes)", tracelen); - + print_hex_break(trace, tracelen, 32); - + printSep(); uint16_t tracepos = 0; while (tracepos < tracelen) tracepos = PrintFliteBlock(tracepos, trace, tracelen); - + printSep(); } @@ -440,7 +440,7 @@ int CmdHFFelicaCmdRaw(const char *cmd) { case 'H': case 'h': return usage_hf_felica_raw(); - case 'r': + case 'r': reply = false; break; case 'c': @@ -455,7 +455,7 @@ int CmdHFFelicaCmdRaw(const char *cmd) { case 's': active_select = true; break; - case 'b': + case 'b': sscanf(cmd+i+2, "%d", &temp); numbits = temp & 0xFFFF; i+=3; @@ -507,14 +507,14 @@ int CmdHFFelicaCmdRaw(const char *cmd) { if (power) { c.arg[0] |= FELICA_NO_DISCONNECT; } - + if (datalen > 0) { c.arg[0] |= FELICA_RAW; } - + // Max buffer is USB_CMD_DATA_SIZE datalen = (datalen > USB_CMD_DATA_SIZE) ? USB_CMD_DATA_SIZE : datalen; - + c.arg[1] = (datalen & 0xFFFF) | (uint32_t)(numbits << 16); memcpy(c.d.asBytes, data, datalen); @@ -534,7 +534,7 @@ void waitCmdFelica(uint8_t iSelect) { UsbCommand resp; uint16_t len = 0; - if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { + if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { len = iSelect ? (resp.arg[1] & 0xffff) : (resp.arg[0] & 0xffff); PrintAndLogEx(NORMAL, "received %i octets", len); if(!len) diff --git a/client/cmdhffido.c b/client/cmdhffido.c index 6d7741153..ea5d55c66 100644 --- a/client/cmdhffido.c +++ b/client/cmdhffido.c @@ -50,17 +50,17 @@ static int CmdHelp(const char *Cmd); int CmdHFFidoInfo(const char *cmd) { - + if (cmd && strlen(cmd) > 0) PrintAndLog("WARNING: command don't have any parameters.\n"); - + // info about 14a part CmdHF14AInfo(""); // FIDO info - PrintAndLog("--------------------------------------------"); + PrintAndLog("--------------------------------------------"); SetAPDULogging(false); - + uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; uint16_t sw = 0; @@ -70,27 +70,27 @@ int CmdHFFidoInfo(const char *cmd) { DropField(); return res; } - + if (sw != 0x9000) { if (sw) - PrintAndLog("Not a FIDO card! APDU response: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("Not a FIDO card! APDU response: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); else - PrintAndLog("APDU exchange error. Card returns 0x0000."); - + PrintAndLog("APDU exchange error. Card returns 0x0000."); + DropField(); return 0; } - + if (!strncmp((char *)buf, "U2F_V2", 7)) { if (!strncmp((char *)buf, "FIDO_2_0", 8)) { - PrintAndLog("FIDO2 authenricator detected. Version: %.*s", len, buf); + PrintAndLog("FIDO2 authenricator detected. Version: %.*s", len, buf); } else { - PrintAndLog("FIDO authenricator detected (not standard U2F)."); - PrintAndLog("Non U2F authenticator version:"); + PrintAndLog("FIDO authenricator detected (not standard U2F)."); + PrintAndLog("Non U2F authenticator version:"); dump_buffer((const unsigned char *)buf, len, NULL, 0); } } else { - PrintAndLog("FIDO U2F authenricator detected. Version: %.*s", len, buf); + PrintAndLog("FIDO U2F authenricator detected. Version: %.*s", len, buf); } res = FIDO2GetInfo(buf, sizeof(buf), &len, &sw); @@ -99,32 +99,32 @@ int CmdHFFidoInfo(const char *cmd) { return res; } if (sw != 0x9000) { - PrintAndLog("FIDO2 version not exists (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); - + PrintAndLog("FIDO2 version not exists (%04x - %s).", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + return 0; } - + if(buf[0]) { - PrintAndLog("FIDO2 ger version error: %d - %s", buf[0], fido2GetCmdErrorDescription(buf[0])); + PrintAndLog("FIDO2 ger version error: %d - %s", buf[0], fido2GetCmdErrorDescription(buf[0])); return 0; } if (len > 1) { // if (false) { -// PrintAndLog("FIDO2 version: (len=%d)", len); +// PrintAndLog("FIDO2 version: (len=%d)", len); // dump_buffer((const unsigned char *)buf, len, NULL, 0); // } - PrintAndLog("FIDO2 version CBOR decoded:"); + PrintAndLog("FIDO2 version CBOR decoded:"); TinyCborPrintFIDOPackage(fido2CmdGetInfo, true, &buf[1], len - 1); } else { - PrintAndLog("FIDO2 version length error"); + PrintAndLog("FIDO2 version length error"); } - + return 0; } -json_t *OpenJson(int paramnum, char *fname, void* argtable[], bool *err) { +json_t *OpenJson(int paramnum, char *fname, void* argtable[], bool *err) { json_t *root = NULL; json_error_t error; *err = false; @@ -132,17 +132,17 @@ json_t *OpenJson(int paramnum, char *fname, void* argtable[], bool *err) { uint8_t jsonname[250] ={0}; char *cjsonname = (char *)jsonname; int jsonnamelen = 0; - + // CLIGetStrWithReturn(paramnum, jsonname, &jsonnamelen); if (CLIParamStrToBuf(arg_get_str(paramnum), jsonname, sizeof(jsonname), &jsonnamelen)) { CLIParserFree(); return NULL; } - + // current path + file name if (!strstr(cjsonname, ".json")) strcat(cjsonname, ".json"); - + if (jsonnamelen) { strcpy(fname, get_my_executable_directory()); strcat(fname, cjsonname); @@ -151,16 +151,16 @@ json_t *OpenJson(int paramnum, char *fname, void* argtable[], bool *err) { if (!root) { PrintAndLog("ERROR: json error on line %d: %s", error.line, error.text); *err = true; - return NULL; + return NULL; } - + if (!json_is_object(root)) { PrintAndLog("ERROR: Invalid json format. root must be an object."); json_decref(root); *err = true; - return NULL; + return NULL; } - + } else { root = json_object(); } @@ -175,9 +175,9 @@ int CmdHFFidoRegister(const char *cmd) { int applen = 0; uint8_t adata[250] = {0}; json_t *root = NULL; - - CLIParserInit("hf fido reg", - "Initiate a U2F token registration. Needs two 32-byte hash number. \nchallenge parameter (32b) and application parameter (32b).", + + CLIParserInit("hf fido reg", + "Initiate a U2F token registration. Needs two 32-byte hash number. \nchallenge parameter (32b) and application parameter (32b).", "Usage:\n\thf fido reg -> execute command with 2 parameters, filled 0x00\n" "\thf fido reg 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f -> execute command with parameters" "\thf fido reg -p s0 s1 -> execute command with plain parameters"); @@ -194,7 +194,7 @@ int CmdHFFidoRegister(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool APDULogging = arg_get_lit(1); bool verbose = arg_get_lit(2); bool verbose2 = arg_get_lit(2) > 1; @@ -206,12 +206,12 @@ int CmdHFFidoRegister(const char *cmd) { root = OpenJson(5, fname, argtable, &err); if(err) return 1; - if (root) { + if (root) { size_t jlen; JsonLoadBufAsHex(root, "$.ChallengeParam", data, 32, &jlen); JsonLoadBufAsHex(root, "$.ApplicationParam", &data[32], 32, &jlen); } - + if (paramsPlain) { memset(cdata, 0x00, 32); CLIGetStrWithReturn(6, cdata, &chlen); @@ -228,8 +228,8 @@ int CmdHFFidoRegister(const char *cmd) { } if (chlen) memmove(data, cdata, 32); - - + + if (paramsPlain) { memset(adata, 0x00, 32); CLIGetStrWithReturn(7, adata, &applen); @@ -246,14 +246,14 @@ int CmdHFFidoRegister(const char *cmd) { } if (applen) memmove(&data[32], adata, 32); - - CLIParserFree(); - + + CLIParserFree(); + SetAPDULogging(APDULogging); // challenge parameter [32 bytes] - The challenge parameter is the SHA-256 hash of the Client Data, a stringified JSON data structure that the FIDO Client prepares // application parameter [32 bytes] - The application parameter is the SHA-256 hash of the UTF-8 encoding of the application identity - + uint8_t buf[2048] = {0}; size_t len = 0; uint16_t sw = 0; @@ -266,9 +266,9 @@ int CmdHFFidoRegister(const char *cmd) { DropField(); return res; } - + if (sw != 0x9000) { - PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); DropField(); return 2; } @@ -279,12 +279,12 @@ int CmdHFFidoRegister(const char *cmd) { PrintAndLog("Can't execute register command. res=%x. Exit...", res); return res; } - + if (sw != 0x9000) { - PrintAndLog("ERROR execute register command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("ERROR execute register command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); return 3; } - + PrintAndLog(""); if (APDULogging) PrintAndLog("---------------------------------------------------------------"); @@ -300,10 +300,10 @@ int CmdHFFidoRegister(const char *cmd) { return 5; } PrintAndLog("User public key: %s", sprint_hex(&buf[1], 65)); - + uint8_t keyHandleLen = buf[66]; PrintAndLog("Key handle[%d]: %s", keyHandleLen, sprint_hex(&buf[67], keyHandleLen)); - + int derp = 67 + keyHandleLen; int derLen = (buf[derp + 2] << 8) + buf[derp + 3] + 4; if (verbose2) { @@ -315,26 +315,26 @@ int CmdHFFidoRegister(const char *cmd) { PrintAndLog("------------------DER-------------------"); PrintAndLog("DER certificate[%d]: %s...", derLen, sprint_hex(&buf[derp], 20)); } - + // check and print DER certificate uint8_t public_key[65] = {0}; - + // print DER certificate in TLV view if (showDERTLV) { PrintAndLog("----------------DER TLV-----------------"); asn1_print(&buf[derp], derLen, " "); PrintAndLog("----------------DER TLV-----------------"); } - + FIDOCheckDERAndGetKey(&buf[derp], derLen, verbose, public_key, sizeof(public_key)); - + // get hash int hashp = 1 + 65 + 1 + keyHandleLen + derLen; PrintAndLog("Hash[%d]: %s", len - hashp, sprint_hex(&buf[hashp], len - hashp)); // check ANSI X9.62 format ECDSA signature (on P-256) - uint8_t rval[300] = {0}; - uint8_t sval[300] = {0}; + uint8_t rval[300] = {0}; + uint8_t sval[300] = {0}; res = ecdsa_asn1_get_signature(&buf[hashp], len - hashp, rval, sval); if (!res) { if (verbose) { @@ -346,7 +346,7 @@ int CmdHFFidoRegister(const char *cmd) { size_t xbuflen = 0; res = FillBuffer(xbuf, sizeof(xbuf), &xbuflen, "\x00", 1, - &data[32], 32, // application parameter + &data[32], 32, // application parameter &data[0], 32, // challenge parameter &buf[67], keyHandleLen, // keyHandle &buf[1], 65, // user public key @@ -362,11 +362,11 @@ int CmdHFFidoRegister(const char *cmd) { } else { PrintAndLog("Signature is OK."); } - + } else { PrintAndLog("Invalid signature. res=%d.", res); } - + PrintAndLog("\nauth command: "); printf("hf fido auth %s%s", paramsPlain?"-p ":"", sprint_hex_inrow(&buf[67], keyHandleLen)); if(chlen || applen) @@ -374,7 +374,7 @@ int CmdHFFidoRegister(const char *cmd) { if(applen) printf(" %s", paramsPlain?(char *)adata:sprint_hex_inrow(adata, 32)); printf("\n"); - + if (root) { JsonSaveBufAsHex(root, "ChallengeParam", data, 32); JsonSaveBufAsHex(root, "ApplicationParam", &data[32], 32); @@ -382,18 +382,18 @@ int CmdHFFidoRegister(const char *cmd) { JsonSaveInt(root, "KeyHandleLen", keyHandleLen); JsonSaveBufAsHexCompact(root, "KeyHandle", &buf[67], keyHandleLen); JsonSaveBufAsHexCompact(root, "DER", &buf[67 + keyHandleLen], derLen); - + res = json_dump_file(root, fname, JSON_INDENT(2)); if (res) { PrintAndLog("ERROR: can't save the file: %s", fname); return 200; } PrintAndLog("File `%s` saved.", fname); - + // free json object json_decref(root); } - + return 0; }; @@ -401,13 +401,13 @@ int CmdHFFidoAuthenticate(const char *cmd) { uint8_t data[512] = {0}; uint8_t hdata[250] = {0}; bool public_key_loaded = false; - uint8_t public_key[65] = {0}; + uint8_t public_key[65] = {0}; int hdatalen = 0; uint8_t keyHandleLen = 0; json_t *root = NULL; - - CLIParserInit("hf fido auth", - "Initiate a U2F token authentication. Needs key handle and two 32-byte hash number. \nkey handle(var 0..255), challenge parameter (32b) and application parameter (32b).", + + CLIParserInit("hf fido auth", + "Initiate a U2F token authentication. Needs key handle and two 32-byte hash number. \nkey handle(var 0..255), challenge parameter (32b) and application parameter (32b).", "Usage:\n\thf fido auth 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f -> execute command with 2 parameters, filled 0x00 and key handle\n" "\thf fido auth 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f " "000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f 000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f -> execute command with parameters"); @@ -428,7 +428,7 @@ int CmdHFFidoAuthenticate(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool APDULogging = arg_get_lit(1); bool verbose = arg_get_lit(2); bool paramsPlain = arg_get_lit(3); @@ -443,7 +443,7 @@ int CmdHFFidoAuthenticate(const char *cmd) { root = OpenJson(7, fname, argtable, &err); if(err) return 1; - if (root) { + if (root) { size_t jlen; JsonLoadBufAsHex(root, "$.ChallengeParam", data, 32, &jlen); JsonLoadBufAsHex(root, "$.ApplicationParam", &data[32], 32, &jlen); @@ -452,7 +452,7 @@ int CmdHFFidoAuthenticate(const char *cmd) { data[64] = keyHandleLen; JsonLoadBufAsHex(root, "$.PublicKey", public_key, 65, &jlen); public_key_loaded = (jlen > 0); - } + } // public key CLIGetHexWithReturn(8, hdata, &hdatalen); @@ -463,8 +463,8 @@ int CmdHFFidoAuthenticate(const char *cmd) { if (hdatalen) { memmove(public_key, hdata, hdatalen); public_key_loaded = true; - } - + } + CLIGetHexWithReturn(9, hdata, &hdatalen); if (hdatalen > 255) { PrintAndLog("ERROR: application parameter length must be less than 255."); @@ -510,8 +510,8 @@ int CmdHFFidoAuthenticate(const char *cmd) { if (hdatalen) memmove(&data[32], hdata, 32); - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); // (in parameter) conrtol byte 0x07 - check only, 0x03 - user presense + cign. 0x08 - sign only @@ -521,7 +521,7 @@ int CmdHFFidoAuthenticate(const char *cmd) { // key handle [N] uint8_t datalen = 32 + 32 + 1 + keyHandleLen; - + uint8_t buf[2048] = {0}; size_t len = 0; uint16_t sw = 0; @@ -534,9 +534,9 @@ int CmdHFFidoAuthenticate(const char *cmd) { DropField(); return res; } - + if (sw != 0x9000) { - PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); DropField(); return 2; } @@ -547,12 +547,12 @@ int CmdHFFidoAuthenticate(const char *cmd) { PrintAndLog("Can't execute authentication command. res=%x. Exit...", res); return res; } - + if (sw != 0x9000) { - PrintAndLog("ERROR execute authentication command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("ERROR execute authentication command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); return 3; } - + PrintAndLog("---------------------------------------------------------------"); PrintAndLog("User presence: %s", (buf[0]?"verified":"not verified")); uint32_t cntr = (uint32_t)bytes_to_num(&buf[1], 4); @@ -560,8 +560,8 @@ int CmdHFFidoAuthenticate(const char *cmd) { PrintAndLog("Hash[%d]: %s", len - 5, sprint_hex(&buf[5], len - 5)); // check ANSI X9.62 format ECDSA signature (on P-256) - uint8_t rval[300] = {0}; - uint8_t sval[300] = {0}; + uint8_t rval[300] = {0}; + uint8_t sval[300] = {0}; res = ecdsa_asn1_get_signature(&buf[5], len - 5, rval, sval); if (!res) { if (verbose) { @@ -588,27 +588,27 @@ int CmdHFFidoAuthenticate(const char *cmd) { } else { PrintAndLog("Signature is OK."); } - } else { + } else { PrintAndLog("No public key provided. can't check signature."); } } else { PrintAndLog("Invalid signature. res=%d.", res); } - + if (root) { JsonSaveBufAsHex(root, "ChallengeParam", data, 32); JsonSaveBufAsHex(root, "ApplicationParam", &data[32], 32); JsonSaveInt(root, "KeyHandleLen", keyHandleLen); JsonSaveBufAsHexCompact(root, "KeyHandle", &data[65], keyHandleLen); JsonSaveInt(root, "Counter", cntr); - + res = json_dump_file(root, fname, JSON_INDENT(2)); if (res) { PrintAndLog("ERROR: can't save the file: %s", fname); return 200; } PrintAndLog("File `%s` saved.", fname); - + // free json object json_decref(root); } @@ -616,7 +616,7 @@ int CmdHFFidoAuthenticate(const char *cmd) { }; void CheckSlash(char *fileName) { - if ((fileName[strlen(fileName) - 1] != '/') && + if ((fileName[strlen(fileName) - 1] != '/') && (fileName[strlen(fileName) - 1] != '\\')) strcat(fileName, "/"); } @@ -625,22 +625,22 @@ int GetExistsFileNameJson(char *prefixDir, char *reqestedFileName, char *fileNam fileName[0] = 0x00; strcpy(fileName, get_my_executable_directory()); CheckSlash(fileName); - + strcat(fileName, prefixDir); CheckSlash(fileName); - + strcat(fileName, reqestedFileName); if (!strstr(fileName, ".json")) strcat(fileName, ".json"); - + if (access(fileName, F_OK) < 0) { strcpy(fileName, get_my_executable_directory()); CheckSlash(fileName); - + strcat(fileName, reqestedFileName); if (!strstr(fileName, ".json")) strcat(fileName, ".json"); - + if (access(fileName, F_OK) < 0) { return 1; // file not found } @@ -652,9 +652,9 @@ int CmdHFFido2MakeCredential(const char *cmd) { json_error_t error; json_t *root = NULL; char fname[300] = {0}; - - CLIParserInit("hf fido make", - "Execute a FIDO2 Make Credentional command. Needs json file with parameters. Sample file `fido2.json`. File can be placed in proxmark directory or in `proxmark/fido` directory.", + + CLIParserInit("hf fido make", + "Execute a FIDO2 Make Credentional command. Needs json file with parameters. Sample file `fido2.json`. File can be placed in proxmark directory or in `proxmark/fido` directory.", "Usage:\n\thf fido make -> execute command default parameters file `fido2.json`\n" "\thf fido make test.json -> execute command with parameters file `text.json`"); @@ -668,7 +668,7 @@ int CmdHFFido2MakeCredential(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool APDULogging = arg_get_lit(1); bool verbose = arg_get_lit(2); bool verbose2 = arg_get_lit(2) > 1; @@ -685,8 +685,8 @@ int CmdHFFido2MakeCredential(const char *cmd) { jsonnamelen = strlen(cjsonname); } - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); int res = GetExistsFileNameJson("fido", cjsonname, fname); @@ -695,12 +695,12 @@ int CmdHFFido2MakeCredential(const char *cmd) { return res; } PrintAndLog("fname: %s\n", fname); - root = json_load_file(fname, 0, &error); + root = json_load_file(fname, 0, &error); if (!root) { PrintAndLog("ERROR: json error on line %d: %s", error.line, error.text); return 1; } - + uint8_t data[2048] = {0}; size_t datalen = 0; uint8_t buf[2048] = {0}; @@ -715,9 +715,9 @@ int CmdHFFido2MakeCredential(const char *cmd) { DropField(); return res; } - + if (sw != 0x9000) { - PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); DropField(); return 2; } @@ -725,28 +725,28 @@ int CmdHFFido2MakeCredential(const char *cmd) { res = FIDO2CreateMakeCredentionalReq(root, data, sizeof(data), &datalen); if (res) return res; - + if (showCBOR) { PrintAndLog("CBOR make credentional request:"); PrintAndLog("---------------- CBOR ------------------"); TinyCborPrintFIDOPackage(fido2CmdMakeCredential, false, data, datalen); PrintAndLog("---------------- CBOR ------------------"); } - + res = FIDO2MakeCredential(data, datalen, buf, sizeof(buf), &len, &sw); DropField(); if (res) { PrintAndLog("Can't execute make credential command. res=%x. Exit...", res); return res; } - + if (sw != 0x9000) { - PrintAndLog("ERROR execute make credential command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("ERROR execute make credential command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); return 3; } - + if(buf[0]) { - PrintAndLog("FIDO2 make credential error: %d - %s", buf[0], fido2GetCmdErrorDescription(buf[0])); + PrintAndLog("FIDO2 make credential error: %d - %s", buf[0], fido2GetCmdErrorDescription(buf[0])); return 0; } @@ -760,7 +760,7 @@ int CmdHFFido2MakeCredential(const char *cmd) { // parse returned cbor FIDO2MakeCredentionalParseRes(root, &buf[1], len - 1, verbose, verbose2, showCBOR, showDERTLV); - + if (root) { res = json_dump_file(root, fname, JSON_INDENT(2)); if (res) { @@ -769,7 +769,7 @@ int CmdHFFido2MakeCredential(const char *cmd) { } PrintAndLog("File `%s` saved.", fname); } - + json_decref(root); return 0; @@ -779,9 +779,9 @@ int CmdHFFido2GetAssertion(const char *cmd) { json_error_t error; json_t *root = NULL; char fname[300] = {0}; - - CLIParserInit("hf fido assert", - "Execute a FIDO2 Get Assertion command. Needs json file with parameters. Sample file `fido2.json`. File can be placed in proxmark directory or in `proxmark/fido` directory.", + + CLIParserInit("hf fido assert", + "Execute a FIDO2 Get Assertion command. Needs json file with parameters. Sample file `fido2.json`. File can be placed in proxmark directory or in `proxmark/fido` directory.", "Usage:\n\thf fido assert -> execute command default parameters file `fido2.json`\n" "\thf fido assert test.json -l -> execute command with parameters file `text.json` and add to request CredentialId"); @@ -795,7 +795,7 @@ int CmdHFFido2GetAssertion(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool APDULogging = arg_get_lit(1); bool verbose = arg_get_lit(2); bool verbose2 = arg_get_lit(2) > 1; @@ -812,8 +812,8 @@ int CmdHFFido2GetAssertion(const char *cmd) { jsonnamelen = strlen(cjsonname); } - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); int res = GetExistsFileNameJson("fido", "fido2", fname); @@ -822,12 +822,12 @@ int CmdHFFido2GetAssertion(const char *cmd) { return res; } PrintAndLog("fname: %s\n", fname); - root = json_load_file(fname, 0, &error); + root = json_load_file(fname, 0, &error); if (!root) { PrintAndLog("ERROR: json error on line %d: %s", error.line, error.text); return 1; } - + uint8_t data[2048] = {0}; size_t datalen = 0; uint8_t buf[2048] = {0}; @@ -842,9 +842,9 @@ int CmdHFFido2GetAssertion(const char *cmd) { DropField(); return res; } - + if (sw != 0x9000) { - PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("Can't select FIDO application. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); DropField(); return 2; } @@ -852,28 +852,28 @@ int CmdHFFido2GetAssertion(const char *cmd) { res = FIDO2CreateGetAssertionReq(root, data, sizeof(data), &datalen, createAllowList); if (res) return res; - + if (showCBOR) { PrintAndLog("CBOR get assertion request:"); PrintAndLog("---------------- CBOR ------------------"); TinyCborPrintFIDOPackage(fido2CmdGetAssertion, false, data, datalen); PrintAndLog("---------------- CBOR ------------------"); } - + res = FIDO2GetAssertion(data, datalen, buf, sizeof(buf), &len, &sw); DropField(); if (res) { PrintAndLog("Can't execute get assertion command. res=%x. Exit...", res); return res; } - + if (sw != 0x9000) { - PrintAndLog("ERROR execute get assertion command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLog("ERROR execute get assertion command. APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); return 3; } - + if(buf[0]) { - PrintAndLog("FIDO2 get assertion error: %d - %s", buf[0], fido2GetCmdErrorDescription(buf[0])); + PrintAndLog("FIDO2 get assertion error: %d - %s", buf[0], fido2GetCmdErrorDescription(buf[0])); return 0; } @@ -887,7 +887,7 @@ int CmdHFFido2GetAssertion(const char *cmd) { // parse returned cbor FIDO2GetAssertionParseRes(root, &buf[1], len - 1, verbose, verbose2, showCBOR); - + if (root) { res = json_dump_file(root, fname, JSON_INDENT(2)); if (res) { @@ -898,7 +898,7 @@ int CmdHFFido2GetAssertion(const char *cmd) { } json_decref(root); - + return 0; }; diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index 82e14d5ea..25be7df47 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -58,7 +58,7 @@ int usage_hf_iclass_decrypt(void) { PrintAndLogEx(NORMAL, "which is defined by the configuration block."); PrintAndLogEx(NORMAL, "OBS! In order to use this function, the file 'iclass_decryptionkey.bin' must reside"); PrintAndLogEx(NORMAL, "in the working directory. The file should be 16 bytes binary data"); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: hf iclass decrypt f "); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); @@ -192,14 +192,14 @@ int usage_hf_iclass_replay(void) { PrintAndLogEx(NORMAL, " h This help text"); PrintAndLogEx(NORMAL, " Mac bytes to replay (8 hexsymbols)"); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " hf iclass replay 00112233"); + PrintAndLogEx(NORMAL, " hf iclass replay 00112233"); return 0; } int usage_hf_iclass_sniff(void) { PrintAndLogEx(NORMAL, "Sniff the communication between reader and tag"); PrintAndLogEx(NORMAL, "Usage: hf iclass sniff [h]"); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " hf iclass sniff"); + PrintAndLogEx(NORMAL, " hf iclass sniff"); return 0; } int usage_hf_iclass_loclass(void) { @@ -218,7 +218,7 @@ int usage_hf_iclass_loclass(void) { return 0; } int usage_hf_iclass_chk(void) { - PrintAndLogEx(NORMAL, "Checkkeys loads a dictionary text file with 8byte hex keys to test authenticating against a iClass tag"); + PrintAndLogEx(NORMAL, "Checkkeys loads a dictionary text file with 8byte hex keys to test authenticating against a iClass tag"); PrintAndLogEx(NORMAL, "Usage: hf iclass chk [h|e|r] [f (*.dic)]"); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h Show this help"); @@ -227,12 +227,12 @@ int usage_hf_iclass_chk(void) { PrintAndLogEx(NORMAL, " e elite"); PrintAndLogEx(NORMAL, " c credit key (if not use, default is debit)"); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " hf iclass chk f default_iclass_keys.dic"); + PrintAndLogEx(NORMAL, " hf iclass chk f default_iclass_keys.dic"); PrintAndLogEx(NORMAL, " hf iclass chk f default_iclass_keys.dic e"); return 0; } int usage_hf_iclass_lookup(void) { - PrintAndLogEx(NORMAL, "Lookup keys takes some sniffed trace data and tries to verify what key was used against a dictionary file"); + PrintAndLogEx(NORMAL, "Lookup keys takes some sniffed trace data and tries to verify what key was used against a dictionary file"); PrintAndLogEx(NORMAL, "Usage: hf iclass lookup [h|e|r] [f (*.dic)] [u ] [p ] [m ]"); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h Show this help"); @@ -308,33 +308,33 @@ int CmdHFiClassSim(const char *Cmd) { } uint8_t numberOfCSNs = 0; - + /* // pre-defined 8 CSN by Holiman - uint8_t csns[8*NUM_CSNS] = { - 0x00, 0x0B, 0x0F, 0xFF, 0xF7, 0xFF, 0x12, 0xE0, - 0x00, 0x13, 0x94, 0x7E, 0x76, 0xFF, 0x12, 0xE0, - 0x2A, 0x99, 0xAC, 0x79, 0xEC, 0xFF, 0x12, 0xE0, - 0x17, 0x12, 0x01, 0xFD, 0xF7, 0xFF, 0x12, 0xE0, - 0xCD, 0x56, 0x01, 0x7C, 0x6F, 0xFF, 0x12, 0xE0, - 0x4B, 0x5E, 0x0B, 0x72, 0xEF, 0xFF, 0x12, 0xE0, - 0x00, 0x73, 0xD8, 0x75, 0x58, 0xFF, 0x12, 0xE0, - 0x0C, 0x90, 0x32, 0xF3, 0x5D, 0xFF, 0x12, 0xE0 + uint8_t csns[8*NUM_CSNS] = { + 0x00, 0x0B, 0x0F, 0xFF, 0xF7, 0xFF, 0x12, 0xE0, + 0x00, 0x13, 0x94, 0x7E, 0x76, 0xFF, 0x12, 0xE0, + 0x2A, 0x99, 0xAC, 0x79, 0xEC, 0xFF, 0x12, 0xE0, + 0x17, 0x12, 0x01, 0xFD, 0xF7, 0xFF, 0x12, 0xE0, + 0xCD, 0x56, 0x01, 0x7C, 0x6F, 0xFF, 0x12, 0xE0, + 0x4B, 0x5E, 0x0B, 0x72, 0xEF, 0xFF, 0x12, 0xE0, + 0x00, 0x73, 0xD8, 0x75, 0x58, 0xFF, 0x12, 0xE0, + 0x0C, 0x90, 0x32, 0xF3, 0x5D, 0xFF, 0x12, 0xE0 }; */ /* - pre-defined 9 CSN by iceman - only one csn depend on several others. + pre-defined 9 CSN by iceman + only one csn depend on several others. six depends only on the first csn, (0,1, 0x45) */ uint8_t csns[8*NUM_CSNS] = { - 0x01, 0x0A, 0x0F, 0xFF, 0xF7, 0xFF, 0x12, 0xE0, - 0x0C, 0x06, 0x0C, 0xFE, 0xF7, 0xFF, 0x12, 0xE0, - 0x10, 0x97, 0x83, 0x7B, 0xF7, 0xFF, 0x12, 0xE0, - 0x13, 0x97, 0x82, 0x7A, 0xF7, 0xFF, 0x12, 0xE0, - 0x07, 0x0E, 0x0D, 0xF9, 0xF7, 0xFF, 0x12, 0xE0, - 0x14, 0x96, 0x84, 0x76, 0xF7, 0xFF, 0x12, 0xE0, - 0x17, 0x96, 0x85, 0x71, 0xF7, 0xFF, 0x12, 0xE0, + 0x01, 0x0A, 0x0F, 0xFF, 0xF7, 0xFF, 0x12, 0xE0, + 0x0C, 0x06, 0x0C, 0xFE, 0xF7, 0xFF, 0x12, 0xE0, + 0x10, 0x97, 0x83, 0x7B, 0xF7, 0xFF, 0x12, 0xE0, + 0x13, 0x97, 0x82, 0x7A, 0xF7, 0xFF, 0x12, 0xE0, + 0x07, 0x0E, 0x0D, 0xF9, 0xF7, 0xFF, 0x12, 0xE0, + 0x14, 0x96, 0x84, 0x76, 0xF7, 0xFF, 0x12, 0xE0, + 0x17, 0x96, 0x85, 0x71, 0xF7, 0xFF, 0x12, 0xE0, 0xCE, 0xC5, 0x0F, 0x77, 0xF7, 0xFF, 0x12, 0xE0, 0xD2, 0x5A, 0x82, 0xF8, 0xF7, 0xFF, 0x12, 0xE0 //0x04, 0x08, 0x9F, 0x78, 0x6E, 0xFF, 0x12, 0xE0 @@ -357,10 +357,10 @@ int CmdHFiClassSim(const char *Cmd) { 0x00, 0x02, 0x04, 0x1E, 0xF7, 0xFF, 0x12, 0xE0, 0x00, 0x07, 0x03, 0x1B, 0xF7, 0xFF, 0x12, 0xE0, 0x00, 0x00, 0x02, 0x24, 0xF7, 0xFF, 0x12, 0xE0, - 0x00, 0x05, 0x01, 0x21, 0xF7, 0xFF, 0x12, 0xE0 - }; + 0x00, 0x05, 0x01, 0x21, 0xF7, 0xFF, 0x12, 0xE0 + }; */ - + /* DUMPFILE FORMAT: * * <8-byte CSN><8-byte CC><4 byte NR><4 byte MAC>.... @@ -372,9 +372,9 @@ int CmdHFiClassSim(const char *Cmd) { * CC are all zeroes, CSN is the same as was sent in **/ uint8_t tries = 0; - + switch(simType) { - + case 2: { PrintAndLogEx(INFO, "Starting iCLASS sim 2 attack (elite mode)"); PrintAndLogEx(INFO, "press keyboard to cancel"); @@ -383,7 +383,7 @@ int CmdHFiClassSim(const char *Cmd) { memcpy(c.d.asBytes, csns, 8 * NUM_CSNS); clearCommandBuffer(); SendCommand(&c); - + while ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { tries++; if (ukbhit()) { @@ -402,19 +402,19 @@ int CmdHFiClassSim(const char *Cmd) { if ( num_mac == 0 ) break; - + size_t datalen = NUM_CSNS * 24; void* dump = calloc(datalen, sizeof(uint8_t)); if ( !dump ) { PrintAndLogEx(WARNING, "Failed to allocate memory"); return 2; } - + memset(dump, 0, datalen);//<-- Need zeroes for the EPURSE - field (offical) - + uint8_t i = 0; for (i = 0 ; i < NUM_CSNS ; i++) { - //copy CSN + //copy CSN memcpy(dump + i*24, csns + i*8, 8); //copy epurse memcpy(dump + i*24 + 8, resp.d.asBytes + i*16, 8); @@ -423,7 +423,7 @@ int CmdHFiClassSim(const char *Cmd) { } /** Now, save to dumpfile **/ saveFile("iclass_mac_attack", "bin", dump, datalen); - free(dump); + free(dump); break; } case 4: { @@ -454,16 +454,16 @@ int CmdHFiClassSim(const char *Cmd) { if ( num_mac == 0 ) break; - + size_t datalen = NUM_CSNS * 24; void* dump = calloc(datalen, sizeof(uint8_t)); if ( !dump ) { PrintAndLogEx(WARNING, "Failed to allocate memory"); return 2; } - + #define MAC_ITEM_SIZE 24 - + //KEYROLL 1 //Need zeroes for the CC-field memset(dump, 0, datalen); @@ -483,17 +483,17 @@ int CmdHFiClassSim(const char *Cmd) { for (uint8_t i = 0; i < NUM_CSNS; i++) { resp_index = (i + NUM_CSNS) * 16; // Copy CSN - memcpy(dump + i*MAC_ITEM_SIZE, csns + i*8, 8); + memcpy(dump + i*MAC_ITEM_SIZE, csns + i*8, 8); // copy EPURSE memcpy(dump + i*MAC_ITEM_SIZE + 8, resp.d.asBytes + resp_index, 8); // copy NR_MAC (eight bytes from the response) ( 8b csn + 8 epurse == 16) memcpy(dump + i*MAC_ITEM_SIZE + 16, resp.d.asBytes + resp_index + 8, 8); resp_index++; - } - saveFile("iclass_mac_attack_keyroll_B", "bin", dump, datalen); - free(dump); + } + saveFile("iclass_mac_attack_keyroll_B", "bin", dump, datalen); + free(dump); break; - } + } case 1: case 3: default: { @@ -502,7 +502,7 @@ int CmdHFiClassSim(const char *Cmd) { clearCommandBuffer(); SendCommand(&c); break; - } + } } return 0; } @@ -513,12 +513,12 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { uint32_t flags = FLAG_ICLASS_READER_CSN | FLAG_ICLASS_READER_CC | FLAG_ICLASS_READER_AIA | FLAG_ICLASS_READER_CONF | FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_ONE_TRY; - + UsbCommand c = {CMD_READER_ICLASS, {flags, 0, 0}}; // loop in client not device - else on windows have a communication error UsbCommand resp; while (!ukbhit()){ - + clearCommandBuffer(); SendCommand(&c); if (WaitForResponseTimeout(CMD_ACK,&resp, 4500)) { @@ -530,7 +530,7 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { if ( (readStatus == 0 && !loop) || readStatus == 0xFF) { // abort if (verbose) { - PrintAndLogEx(FAILED, "Quitting..."); + PrintAndLogEx(FAILED, "Quitting..."); DropField(); return 0; } @@ -539,7 +539,7 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { PrintAndLogEx(NORMAL, " CSN: %s", sprint_hex(data, 8)); tagFound = true; } - if (readStatus & FLAG_ICLASS_READER_CC) { + if (readStatus & FLAG_ICLASS_READER_CC) { PrintAndLogEx(NORMAL, " CC: %s", sprint_hex(data+16, 8)); } if (readStatus & FLAG_ICLASS_READER_CONF) { @@ -547,9 +547,9 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { } if (readStatus & FLAG_ICLASS_READER_AIA) { bool legacy = ( memcmp( (uint8_t *)(data + 8*5), "\xff\xff\xff\xff\xff\xff\xff\xff", 8) == 0 ); - + bool se_enabled = ( memcmp( (uint8_t *)(data + 8*5), "\xff\xff\xff\x00\x06\xff\xff\xff", 8) == 0 ); - + PrintAndLogEx(NORMAL, " App IA: %s", sprint_hex(data+8*5, 8)); if ( legacy ) PrintAndLogEx(SUCCESS, " : Possible iClass (legacy credential tag)"); @@ -564,7 +564,7 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { return 1; } } else { - if (verbose) + if (verbose) PrintAndLogEx(WARNING, "command execute timeout"); } if (!loop) break; @@ -573,7 +573,7 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) { return 0; } -int CmdHFiClassReader(const char *Cmd) { +int CmdHFiClassReader(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (cmdp == 'h' || cmdp == 'H') return usage_hf_iclass_reader(); bool findone = (cmdp == '1') ? false : true; @@ -581,13 +581,13 @@ int CmdHFiClassReader(const char *Cmd) { } int CmdHFiClassReader_Replay(const char *Cmd) { - + char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd)<1 || cmdp == 'H' || cmdp == 'h') return usage_hf_iclass_replay(); - + uint8_t readerType = 0; uint8_t MAC[4] = {0x00, 0x00, 0x00, 0x00}; - + if (param_gethex(Cmd, 0, MAC, 8)) { PrintAndLogEx(FAILED, "MAC must include 8 HEX symbols"); return 1; @@ -612,24 +612,24 @@ int CmdHFiClassELoad(const char *Cmd) { char ctmp = param_getchar(Cmd, 0); if (strlen(Cmd)< 1 || ctmp == 'h' || ctmp == 'H') return usage_hf_iclass_eload(); - + if ( ctmp != 'f' && ctmp != 'F') return usage_hf_iclass_eload(); - + //File handling and reading FILE *f; char filename[FILE_PATH_SIZE]; - + if ( param_getstr(Cmd, 1, filename, FILE_PATH_SIZE) >= FILE_PATH_SIZE ) { PrintAndLogEx(FAILED, "Filename too long"); return 1; } - + f = fopen(filename, "rb"); if ( !f ){ PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename); return 1; } - + // get filesize in order to malloc memory fseek(f, 0, SEEK_END); long fsize = ftell(f); @@ -647,7 +647,7 @@ int CmdHFiClassELoad(const char *Cmd) { fclose(f); return 1; } - + size_t bytes_read = fread(dump, 1, fsize, f); fclose(f); @@ -688,12 +688,12 @@ static int readKeyfile(const char *filename, size_t len, uint8_t* buffer) { fseek(f, 0, SEEK_SET); size_t bytes_read = fread(buffer, 1, len, f); fclose(f); - + if (fsize != len) { PrintAndLogEx(WARNING, "Warning, file size is %d, expected %d", fsize, len); return 1; } - + if (bytes_read != len) { PrintAndLogEx(WARNING, "Warning, could only read %d bytes, expected %d" ,bytes_read, len); return 1; @@ -705,10 +705,10 @@ int CmdHFiClassDecrypt(const char *Cmd) { char opt = param_getchar(Cmd, 0); if (strlen(Cmd)<1 || opt == 'h' || opt == 'H') return usage_hf_iclass_decrypt(); - + uint8_t key[16] = { 0 }; if (readKeyfile("iclass_decryptionkey.bin", 16, key)) return usage_hf_iclass_decrypt(); - + PrintAndLogEx(SUCCESS, "decryption key loaded from file"); //Open the tagdump-file @@ -719,28 +719,28 @@ int CmdHFiClassDecrypt(const char *Cmd) { if (!f) { PrintAndLogEx(WARNING, "could not find file %s", filename); return 1; - } + } } else { return usage_hf_iclass_decrypt(); - } + } fseek(f, 0, SEEK_END); long fsize = ftell(f); fseek(f, 0, SEEK_SET); - + if ( fsize < 0 ) { PrintAndLogEx(WARNING, "error, when getting filesize"); fclose(f); return 2; } - + uint8_t *decrypted = calloc(fsize, sizeof(uint8_t)); if ( !decrypted ) { PrintAndLogEx(WARNING, "Failed to allocate memory"); fclose(f); return 1; } - + size_t bytes_read = fread(decrypted, 1, fsize, f); fclose(f); if ( bytes_read == 0) { @@ -750,15 +750,15 @@ int CmdHFiClassDecrypt(const char *Cmd) { } picopass_hdr *hdr = (picopass_hdr *)decrypted; - + uint8_t mem = hdr->conf.mem_config; uint8_t chip = hdr->conf.chip_config; uint8_t applimit = hdr->conf.app_limit; uint8_t kb = 2; uint8_t app_areas = 2; uint8_t max_blk = 31; - getMemConfig(mem, chip, &max_blk, &app_areas, &kb); - + getMemConfig(mem, chip, &max_blk, &app_areas, &kb); + //Use the first block (CSN) for filename char outfilename[FILE_PATH_SIZE] = {0}; snprintf(outfilename, FILE_PATH_SIZE, "iclass_tagdump-%02x%02x%02x%02x%02x%02x%02x%02x-decrypted", @@ -772,18 +772,18 @@ int CmdHFiClassDecrypt(const char *Cmd) { uint8_t enc_dump[8] = {0}; uint8_t empty[8] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; for(uint16_t blocknum=0; blocknum < applimit; ++blocknum) { - + uint8_t idx = blocknum*8; memcpy(enc_dump, decrypted + idx, 8); - + // block 7 or higher, and not empty 0xFF if(blocknum > 6 && memcmp(enc_dump, empty, 8) != 0 ) { mbedtls_des3_crypt_ecb(&ctx, enc_dump, decrypted + idx ); } } - + saveFile(outfilename, "bin", decrypted, fsize); - free(decrypted); + free(decrypted); printIclassDumpContents(decrypted, 1, (fsize/8), fsize); return 0; } @@ -799,7 +799,7 @@ static int iClassEncryptBlkData(uint8_t *blkData) { uint8_t *encrypted = encryptedData; mbedtls_des3_context ctx; mbedtls_des3_set2key_enc( &ctx, key); - + mbedtls_des3_crypt_ecb(&ctx, blkData,encrypted); memcpy(blkData,encrypted,8); return 1; @@ -832,7 +832,7 @@ static bool select_only(uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool v UsbCommand resp; UsbCommand c = {CMD_READER_ICLASS, {0}}; c.arg[0] = FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_CC | FLAG_ICLASS_READER_ONE_TRY; - + if (use_credit_key) c.arg[0] |= FLAG_ICLASS_READER_CEDITKEY; @@ -847,20 +847,20 @@ static bool select_only(uint8_t *CSN, uint8_t *CCNR, bool use_credit_key, bool v uint8_t *data = resp.d.asBytes; memcpy(CSN, data, 8); - - if (CCNR != NULL) + + if (CCNR != NULL) memcpy(CCNR, data+16, 8); - + if (isOK > 0 && verbose) { PrintAndLogEx(SUCCESS, "CSN | %s", sprint_hex(CSN, 8)); PrintAndLogEx(SUCCESS, "CCNR | %s", sprint_hex(CCNR, 8)); } - + if (isOK <= 1){ PrintAndLogEx(FAILED, "failed to obtain CC! Tag-select is aborting... (%d)", isOK); return false; } - return true; + return true; } static bool select_and_auth(uint8_t *KEY, uint8_t *MAC, uint8_t *div_key, bool use_credit_key, bool elite, bool rawkey, bool verbose) { @@ -876,7 +876,7 @@ static bool select_and_auth(uint8_t *KEY, uint8_t *MAC, uint8_t *div_key, bool u memcpy(div_key, KEY, 8); else HFiClassCalcDivKey(CSN, KEY, div_key, elite); - + if (verbose) PrintAndLogEx(SUCCESS, "authing with %s: %s", rawkey ? "raw key" : "diversified key", sprint_hex(div_key, 8) ); doMAC(CCNR, div_key, MAC); @@ -955,7 +955,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { break; case 'f': case 'F': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); if (fileNameLen < 1) { PrintAndLogEx(WARNING, "no filename found after f"); errors = true; @@ -966,7 +966,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { case 'K': have_debit_key = true; dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); - if (dataLen == 16) { + if (dataLen == 16) { errors = param_gethex(tempStr, 0, KEY, dataLen); } else if (dataLen == 1) { keyNbr = param_get8(Cmd, cmdp+1); @@ -991,7 +991,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { case 'V': verbose = true; cmdp++; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); errors = true; @@ -999,16 +999,16 @@ int CmdHFiClassReader_Dump(const char *Cmd) { } } if (errors || cmdp < 2) return usage_hf_iclass_dump(); - + // if no debit key given try credit key on AA1 (not for iclass but for some picopass this will work) if (!have_debit_key && have_credit_key) use_credit_key = true; uint32_t flags = FLAG_ICLASS_READER_CSN | FLAG_ICLASS_READER_CC | FLAG_ICLASS_READER_CONF | FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_ONE_TRY; - + //get config and first 3 blocks - UsbCommand c = {CMD_READER_ICLASS, {flags, 0, 0}}; + UsbCommand c = {CMD_READER_ICLASS, {flags, 0, 0}}; UsbCommand resp; uint8_t tag_data[255*8]; @@ -1020,7 +1020,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { return 0; } DropField(); - + uint8_t readStatus = resp.arg[0] & 0xff; uint8_t *data = resp.d.asBytes; @@ -1028,7 +1028,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { PrintAndLogEx(FAILED, "no tag found"); return 0; } - + if( readStatus & (FLAG_ICLASS_READER_CSN | FLAG_ICLASS_READER_CONF | FLAG_ICLASS_READER_CC)){ memcpy(tag_data, data, 8*3); blockno += 2; // 2 to force re-read of block 2 later. (seems to respond differently..) @@ -1037,7 +1037,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { // large memory - not able to dump pages currently if (numblks > maxBlk) numblks = maxBlk; } - + // authenticate debit key and get div_key - later store in dump block 3 if (!select_and_auth(KEY, MAC, div_key, use_credit_key, elite, rawkey, verbose)){ //try twice - for some reason it sometimes fails the first time... @@ -1048,7 +1048,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { return 0; } } - + // begin dump UsbCommand w = {CMD_ICLASS_DUMP, {blockno, numblks-blockno+1}}; clearCommandBuffer(); @@ -1061,31 +1061,31 @@ int CmdHFiClassReader_Dump(const char *Cmd) { DropField(); return 0; } - + if (WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) break; } // dump cmd switch off at device when finised. - + uint32_t blocksRead = resp.arg[1]; uint8_t isOK = resp.arg[0] & 0xff; if (!isOK && !blocksRead) { PrintAndLogEx(WARNING, "read block failed"); return 0; } - + uint32_t startindex = resp.arg[2]; if (blocksRead*8 > sizeof(tag_data) - (blockno*8)) { PrintAndLogEx(FAILED, "data exceeded buffer size!"); blocksRead = (sizeof(tag_data)/8) - blockno; } - + // response ok - now get bigbuf content of the dump if ( !GetFromDevice(BIG_BUF, tag_data+(blockno*8), blocksRead*8, startindex, NULL, 2500, false) ) { PrintAndLogEx(WARNING, "command execution time out"); return 0; } - + size_t gotBytes = blocksRead*8 + blockno*8; // try AA2 @@ -1118,7 +1118,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) { if (!isOK && !blocksRead) { PrintAndLogEx(WARNING, "read block failed 2"); return 0; - } + } startindex = resp.arg[2]; if (blocksRead * 8 > sizeof(tag_data) - gotBytes) { @@ -1131,19 +1131,19 @@ int CmdHFiClassReader_Dump(const char *Cmd) { return 0; } - gotBytes += blocksRead * 8; + gotBytes += blocksRead * 8; } } DropField(); - + // add diversified keys to dump if (have_debit_key) memcpy(tag_data+(3*8),div_key,8); if (have_credit_key) memcpy(tag_data+(4*8),c_div_key,8); // print the dump PrintAndLogEx(NORMAL, "------+--+-------------------------+\n"); - PrintAndLogEx(NORMAL, "CSN |00| %s|\n", sprint_hex(tag_data, 8)); + PrintAndLogEx(NORMAL, "CSN |00| %s|\n", sprint_hex(tag_data, 8)); printIclassDumpContents(tag_data, 1, (gotBytes/8), gotBytes); if (filename[0] == 0){ @@ -1170,7 +1170,7 @@ static int WriteBlock(uint8_t blockno, uint8_t *bldata, uint8_t *KEY, bool use_c UsbCommand w = {CMD_ICLASS_WRITEBLOCK, {blockno}}; memcpy(w.d.asBytes, bldata, 8); memcpy(w.d.asBytes + 8, MAC, 4); - + clearCommandBuffer(); SendCommand(&w); if (!WaitForResponseTimeout(CMD_ACK, &resp, 4500)) { @@ -1232,7 +1232,7 @@ int CmdHFiClass_WriteBlock(const char *Cmd) { case 'k': case 'K': dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); - if (dataLen == 16) { + if (dataLen == 16) { errors = param_gethex(tempStr, 0, KEY, dataLen); } else if (dataLen == 1) { keyNbr = param_get8(Cmd, cmdp+1); @@ -1257,7 +1257,7 @@ int CmdHFiClass_WriteBlock(const char *Cmd) { case 'V': verbose = true; cmdp++; - break; + break; default: PrintAndLogEx(WARNING, "unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); errors = true; @@ -1311,7 +1311,7 @@ int CmdHFiClassCloneTag(const char *Cmd) { break; case 'f': case 'F': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); if (fileNameLen < 1) { PrintAndLogEx(WARNING, "No filename found after f"); errors = true; @@ -1321,7 +1321,7 @@ int CmdHFiClassCloneTag(const char *Cmd) { case 'k': case 'K': dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); - if (dataLen == 16) { + if (dataLen == 16) { errors = param_gethex(tempStr, 0, KEY, dataLen); } else if (dataLen == 1) { keyNbr = param_get8(Cmd, cmdp+1); @@ -1354,7 +1354,7 @@ int CmdHFiClassCloneTag(const char *Cmd) { case 'V': verbose = true; cmdp++; - break; + break; default: PrintAndLogEx(WARNING, "unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); errors = true; @@ -1380,7 +1380,7 @@ int CmdHFiClassCloneTag(const char *Cmd) { if (startblock<5) { PrintAndLogEx(WARNING, "you cannot write key blocks this way. yet... make your start block > 4"); - fclose(f); + fclose(f); return 0; } // now read data from the file from block 6 --- 19 @@ -1455,7 +1455,7 @@ static int ReadBlock(uint8_t *KEY, uint8_t blockno, uint8_t keyType, bool elite, PrintAndLogEx(WARNING, "Command execute timeout"); return 0; } - + uint8_t isOK = resp.arg[0] & 0xff; if (!isOK) { PrintAndLogEx(WARNING, "read block failed"); @@ -1506,7 +1506,7 @@ int CmdHFiClass_ReadBlock(const char *Cmd) { case 'K': auth = true; dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); - if (dataLen == 16) { + if (dataLen == 16) { errors = param_gethex(tempStr, 0, KEY, dataLen); } else if (dataLen == 1) { keyNbr = param_get8(Cmd, cmdp+1); @@ -1531,7 +1531,7 @@ int CmdHFiClass_ReadBlock(const char *Cmd) { case 'V': verbose = true; cmdp++; - break; + break; default: PrintAndLogEx(WARNING, "unknown parameter '%c'\n", param_getchar(Cmd, cmdp)); errors = true; @@ -1550,7 +1550,7 @@ int CmdHFiClass_loclass(const char *Cmd) { if (strlen(Cmd)<1 || opt == 'h') usage_hf_iclass_loclass(); - + char fileName[FILE_PATH_SIZE] = {0}; if (opt == 'f') { if (param_getstr(Cmd, 1, fileName, sizeof(fileName)) > 0) { @@ -1575,7 +1575,7 @@ void printIclassDumpContents(uint8_t *iclass_dump, uint8_t startblock, uint8_t e uint8_t mem_config; memcpy(&mem_config, iclass_dump + 13,1); uint8_t maxmemcount; - + uint8_t filemaxblock = filesize / 8; if (mem_config & 0x80) @@ -1585,21 +1585,21 @@ void printIclassDumpContents(uint8_t *iclass_dump, uint8_t startblock, uint8_t e if (startblock == 0) startblock = 6; - + if ((endblock > maxmemcount) || (endblock == 0)) endblock = maxmemcount; - + // remember endblock needs to relate to zero-index arrays. if (endblock > filemaxblock-1) endblock = filemaxblock-1; //PrintAndLog ("startblock: %d, endblock: %d, filesize: %d, maxmemcount: %d, filemaxblock: %d",startblock, endblock,filesize, maxmemcount, filemaxblock); - + int i = startblock; PrintAndLogEx(NORMAL, "------+--+-------------------------+\n"); while (i <= endblock){ uint8_t *blk = iclass_dump + (i * 8); - PrintAndLogEx(NORMAL, " |%02X| %s\n", i, sprint_hex_ascii(blk, 8) ); + PrintAndLogEx(NORMAL, " |%02X| %s\n", i, sprint_hex_ascii(blk, 8) ); i++; } PrintAndLogEx(NORMAL, "------+--+-------------------------+\n"); @@ -1613,7 +1613,7 @@ int CmdHFiClassReadTagFile(const char *Cmd) { char filename[FILE_PATH_SIZE]; if (param_getstr(Cmd, 0, filename, sizeof(filename)) < 1) return usage_hf_iclass_readtagfile(); - + if (param_getstr(Cmd, 1, tempnum, sizeof(tempnum)) < 1) startblock = 0; else @@ -1623,7 +1623,7 @@ int CmdHFiClassReadTagFile(const char *Cmd) { endblock = 0; else sscanf(tempnum,"%d",&endblock); - + // file handling and reading f = fopen(filename,"rb"); if(!f) { @@ -1648,7 +1648,7 @@ int CmdHFiClassReadTagFile(const char *Cmd) { } size_t bytes_read = fread(dump, 1, fsize, f); fclose(f); - + uint8_t *csn = dump; PrintAndLogEx(NORMAL, "------+--+-------------------------+\n"); PrintAndLogEx(NORMAL, "CSN |00| %s|\n", sprint_hex(csn, 8) ); @@ -1670,10 +1670,10 @@ void HFiClassCalcDivKey(uint8_t *CSN, uint8_t *KEY, uint8_t *div_key, bool elite //Permute from iclass format to standard format permutekey_rev(key_sel, key_sel_p); - diversifyKey(CSN, key_sel_p, div_key); + diversifyKey(CSN, key_sel_p, div_key); } else { diversifyKey(CSN, KEY, div_key); - } + } } //when told CSN, oldkey, newkey, if new key is elite (elite), and if old key was elite (oldElite) @@ -1686,14 +1686,14 @@ static void HFiClassCalcNewKey(uint8_t *CSN, uint8_t *OLDKEY, uint8_t *NEWKEY, u HFiClassCalcDivKey(CSN, OLDKEY, old_div_key, oldElite); //get new div key HFiClassCalcDivKey(CSN, NEWKEY, new_div_key, elite); - + for (uint8_t i = 0; i < sizeof(old_div_key); i++){ xor_div_key[i] = old_div_key[i] ^ new_div_key[i]; } if (verbose) { PrintAndLogEx(SUCCESS, "Old div key : %s\n",sprint_hex(old_div_key,8)); PrintAndLogEx(SUCCESS, "New div key : %s\n",sprint_hex(new_div_key,8)); - PrintAndLogEx(SUCCESS, "Xor div key : %s\n",sprint_hex(xor_div_key,8)); + PrintAndLogEx(SUCCESS, "Xor div key : %s\n",sprint_hex(xor_div_key,8)); } } @@ -1727,7 +1727,7 @@ int CmdHFiClassCalcNewKey(const char *Cmd) { case 'n': case 'N': dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); - if (dataLen == 16) { + if (dataLen == 16) { errors = param_gethex(tempStr, 0, NEWKEY, dataLen); } else if (dataLen == 1) { keyNbr = param_get8(Cmd, cmdp+1); @@ -1746,7 +1746,7 @@ int CmdHFiClassCalcNewKey(const char *Cmd) { case 'o': case 'O': dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); - if (dataLen == 16) { + if (dataLen == 16) { errors = param_gethex(tempStr, 0, OLDKEY, dataLen); } else if (dataLen == 1) { keyNbr = param_get8(Cmd, cmdp+1); @@ -1776,11 +1776,11 @@ int CmdHFiClassCalcNewKey(const char *Cmd) { } } if (errors || cmdp < 4) return usage_hf_iclass_calc_newkey(); - + if (!givenCSN) if (!select_only(CSN, CCNR, false, true)) return 0; - + HFiClassCalcNewKey(CSN, OLDKEY, NEWKEY, xor_div_key, elite, oldElite, true); return 0; } @@ -1818,7 +1818,7 @@ static int loadKeys(char *filename) { uint8_t i = 0; for (; i < bytes_read/8; i++) memcpy(iClass_Key_Table[i],dump+(i*8),8); - + free(dump); PrintAndLogEx(SUCCESS, "%u keys loaded", i); return 1; @@ -1845,7 +1845,7 @@ static int printKeys(void) { PrintAndLogEx(NORMAL, ""); for (uint8_t i = 0; i < ICLASS_KEYS_MAX; i++) PrintAndLogEx(NORMAL, "%u: %s", i, sprint_hex(iClass_Key_Table[i],8)); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); return 0; } @@ -1867,7 +1867,7 @@ int CmdHFiClassManageKeys(const char *Cmd) { return usage_hf_iclass_managekeys(); case 'f': case 'F': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); if (fileNameLen < 1) { PrintAndLogEx(WARNING, "No filename found after f"); errors = true; @@ -1885,7 +1885,7 @@ int CmdHFiClassManageKeys(const char *Cmd) { break; case 'k': case 'K': - operation += 3; //set key + operation += 3; //set key dataLen = param_getstr(Cmd, cmdp+1, tempStr, sizeof(tempStr)); if (dataLen == 16) { //ul-c or ev1/ntag key length errors = param_gethex(tempStr, 0, KEY, dataLen); @@ -1917,7 +1917,7 @@ int CmdHFiClassManageKeys(const char *Cmd) { } } if (errors) return usage_hf_iclass_managekeys(); - + if (operation == 0){ PrintAndLogEx(WARNING, "no operation specified (load, save, or print)\n"); return usage_hf_iclass_managekeys(); @@ -1945,10 +1945,10 @@ int CmdHFiClassCheckKeys(const char *Cmd) { // empty string if (strlen(Cmd) == 0) return usage_hf_iclass_chk(); - + uint8_t CSN[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t CCNR[12] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; - + // elite key, raw key, standard key bool use_elite = false; bool use_raw = false; @@ -1962,19 +1962,19 @@ int CmdHFiClassCheckKeys(const char *Cmd) { char filename[FILE_PATH_SIZE] = {0}; uint8_t fileNameLen = 0; - uint8_t *keyBlock = NULL; + uint8_t *keyBlock = NULL; iclass_premac_t *pre = NULL; int keycnt = 0; - + // time uint64_t t1 = msclock(); - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch ( tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_hf_iclass_chk(); case 'f': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); if (fileNameLen < 1) { PrintAndLogEx(WARNING, "no filename found after f"); errors = true; @@ -1987,7 +1987,7 @@ int CmdHFiClassCheckKeys(const char *Cmd) { break; case 'c': use_credit_key = true; - cmdp++; + cmdp++; break; case 'r': use_raw = true; @@ -1999,9 +1999,9 @@ int CmdHFiClassCheckKeys(const char *Cmd) { break; } } - if (errors) return usage_hf_iclass_chk(); + if (errors) return usage_hf_iclass_chk(); + - // Get CSN / UID and CCNR PrintAndLogEx(SUCCESS, "Reading tag CSN"); for (uint8_t i=0; i<10 && !got_csn; i++) { @@ -2011,7 +2011,7 @@ int CmdHFiClassCheckKeys(const char *Cmd) { PrintAndLogEx(WARNING, "one more try\n"); } } - + if ( !got_csn ) { PrintAndLogEx(WARNING, "can't select card, aborting..."); return 1; @@ -2023,13 +2023,13 @@ int CmdHFiClassCheckKeys(const char *Cmd) { free(keyBlock); return 1; } - + pre = calloc(keycnt, sizeof(iclass_premac_t)); if ( !pre ) { free(keyBlock); return 1; } - + PrintAndLogEx(SUCCESS, "Generating diversified keys, MAC"); if (use_elite) PrintAndLogEx(SUCCESS, "Using elite algo"); @@ -2046,43 +2046,43 @@ int CmdHFiClassCheckKeys(const char *Cmd) { free(pre); return 1; } - + //PrintPreCalcMac(keyBlock, keycnt, pre); // max 42 keys inside USB_COMMAND. 512/4 = 103 mac uint32_t chunksize = keycnt > (USB_CMD_DATA_SIZE/4) ? (USB_CMD_DATA_SIZE/4) : keycnt; bool lastChunk = false; - // main keychunk loop + // main keychunk loop for (uint32_t i = 0; i < keycnt; i += chunksize) { - + uint64_t t2 = msclock(); uint8_t timeout = 0; - + if (ukbhit()) { int gc = getchar(); (void)gc; PrintAndLogEx(NORMAL, "\n[!] Aborted via keyboard!\n"); goto out; } - + uint32_t keys = ((keycnt - i) > chunksize) ? chunksize : keycnt - i; - + // last chunk? if ( keys == keycnt - i) lastChunk = true; - + UsbCommand c = {CMD_ICLASS_CHECK_KEYS, { (lastChunk << 8), keys, 0}}; - + // bit 16 // - 1 indicates credit key // - 0 indicates debit key (default) c.arg[0] |= (use_credit_key << 16); - + memcpy(c.d.asBytes, pre + i, 4 * keys); clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + while ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { timeout++; printf("."); fflush(stdout); @@ -2092,17 +2092,17 @@ int CmdHFiClassCheckKeys(const char *Cmd) { } } - uint8_t found = resp.arg[1] & 0xFF; + uint8_t found = resp.arg[1] & 0xFF; uint8_t isOK = resp.arg[0] & 0xFF; - + t2 = msclock() - t2; switch ( isOK ) { case 1: { found_debit = true; - + PrintAndLogEx(NORMAL, "\n[-] Chunk [%d/%d]: %.1fs [%s] found key %s (index %u)" , i - , keycnt + , keycnt , (float)(t2/1000.0) , (use_credit_key) ? "credit" : "debit" , sprint_hex(keyBlock + (i+found)*8, 8) @@ -2130,13 +2130,13 @@ int CmdHFiClassCheckKeys(const char *Cmd) { break; } - } // end chunks of keys - -out: + } // end chunks of keys + +out: t1 = msclock() - t1; PrintAndLogEx(SUCCESS, "\nTime in iclass checkkeys: %.0f seconds\n", (float)t1/1000.0); - + DropField(); free(pre); free(keyBlock); @@ -2144,29 +2144,29 @@ out: } static int cmp_uint32( const void *a, const void *b) { - + const iclass_prekey_t* x = (const iclass_prekey_t *)a; const iclass_prekey_t* y = (const iclass_prekey_t *)b; - + uint32_t mx = bytes_to_num( (uint8_t*)x->mac, 4); uint32_t my = bytes_to_num( (uint8_t*)y->mac, 4); - + if (mx < my) return -1; - else + else return mx > my; } // this method tries to identify in which configuration mode a iClass / iClass SE reader is in. // Standard or Elite / HighSecurity mode. It uses a default key dictionary list in order to work. int CmdHFiClassLookUp(const char *Cmd) { - + uint8_t CSN[8]; uint8_t EPURSE[8] = { 0,0,0,0,0,0,0,0 }; uint8_t MACS[8]= { 0,0,0,0,0,0,0,0 }; uint8_t CCNR[12]; uint8_t MAC_TAG[4] = { 0,0,0,0 }; - + // elite key, raw key, standard key bool use_elite = false; bool use_raw = false; @@ -2176,7 +2176,7 @@ int CmdHFiClassLookUp(const char *Cmd) { char filename[FILE_PATH_SIZE] = {0}; uint8_t fileNameLen = 0; - uint8_t *keyBlock = NULL; + uint8_t *keyBlock = NULL; iclass_prekey_t *prekey = NULL; int keycnt = 0, len = 0; @@ -2184,13 +2184,13 @@ int CmdHFiClassLookUp(const char *Cmd) { if (strlen(Cmd) == 0) errors = true; // time uint64_t t1 = msclock(); - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_hf_iclass_lookup(); case 'f': - fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); + fileNameLen = param_getstr(Cmd, cmdp+1, filename, sizeof(filename)); if (fileNameLen < 1) { PrintAndLogEx(WARNING, "No filename found after f"); errors = true; @@ -2203,7 +2203,7 @@ int CmdHFiClassLookUp(const char *Cmd) { PrintAndLogEx(WARNING, "Wrong CSN length, expected %d got [%d]", sizeof(CSN), len>>1); errors = true; } - cmdp += 2; + cmdp += 2; break; case 'm': param_gethex_ex(Cmd, cmdp+1, MACS, &len); @@ -2213,7 +2213,7 @@ int CmdHFiClassLookUp(const char *Cmd) { } else { memcpy(MAC_TAG, MACS+4, 4); } - cmdp += 2; + cmdp += 2; break; case 'p': param_gethex_ex(Cmd, cmdp+1, EPURSE, &len); @@ -2221,7 +2221,7 @@ int CmdHFiClassLookUp(const char *Cmd) { PrintAndLogEx(WARNING, "Wrong EPURSE length, expected %d got [%d] ", sizeof(EPURSE), len>>1); errors = true; } - cmdp += 2; + cmdp += 2; break; break; case 'e': @@ -2239,24 +2239,24 @@ int CmdHFiClassLookUp(const char *Cmd) { } } - if (errors) return usage_hf_iclass_lookup(); + if (errors) return usage_hf_iclass_lookup(); // stupid copy.. CCNR is a combo of epurse and reader nonce memcpy(CCNR, EPURSE, 8); memcpy(CCNR+8, MACS, 4); - + PrintAndLogEx(SUCCESS, "CSN | %s", sprint_hex( CSN, sizeof(CSN) )); PrintAndLogEx(SUCCESS, "Epurse | %s", sprint_hex( EPURSE, sizeof(EPURSE) )); PrintAndLogEx(SUCCESS, "MACS | %s", sprint_hex( MACS, sizeof(MACS) )); PrintAndLogEx(SUCCESS, "CCNR | %s", sprint_hex( CCNR, sizeof(CCNR) )); PrintAndLogEx(SUCCESS, "MAC_TAG | %s", sprint_hex( MAC_TAG, sizeof(MAC_TAG) )); - + int res = LoadDictionaryKeyFile( filename, &keyBlock, &keycnt); if ( res > 0) { free(keyBlock); return 1; } - //iclass_prekey_t + //iclass_prekey_t prekey = calloc(keycnt, sizeof(iclass_prekey_t)); if ( !prekey ) { free(keyBlock); @@ -2269,22 +2269,22 @@ int CmdHFiClassLookUp(const char *Cmd) { free(keyBlock); free(prekey); return 1; - } + } PrintAndLogEx(FAILED, "Sorting"); - + // sort mac list. qsort( prekey, keycnt, sizeof(iclass_prekey_t), cmp_uint32); //PrintPreCalc(prekey, keycnt); - - PrintAndLogEx(FAILED, "Searching"); + + PrintAndLogEx(FAILED, "Searching"); iclass_prekey_t *item; iclass_prekey_t lookup; memcpy(lookup.mac, MAC_TAG, 4); - + // binsearch - item = (iclass_prekey_t*) bsearch(&lookup, prekey, keycnt, sizeof(iclass_prekey_t), cmp_uint32); + item = (iclass_prekey_t*) bsearch(&lookup, prekey, keycnt, sizeof(iclass_prekey_t), cmp_uint32); if( item != NULL ) PrintAndLogEx(SUCCESS, "\n[debit] found key %s", sprint_hex(item->key, 8)); @@ -2292,9 +2292,9 @@ int CmdHFiClassLookUp(const char *Cmd) { PrintAndLogEx(NORMAL, "\nTime in iclass : %.0f seconds\n", (float)t1/1000.0); free(prekey); free(keyBlock); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); return 0; -} +} int LoadDictionaryKeyFile( char* filename, uint8_t **keys, int *keycnt) { @@ -2302,7 +2302,7 @@ int LoadDictionaryKeyFile( char* filename, uint8_t **keys, int *keycnt) { FILE * f; uint8_t *p; int keyitems = 0; - + if ( !(f = fopen( filename , "r")) ) { PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename); return 1; @@ -2311,12 +2311,12 @@ int LoadDictionaryKeyFile( char* filename, uint8_t **keys, int *keycnt) { while( fgets(buf, sizeof(buf), f) ){ if (strlen(buf) < 16 || buf[15] == '\n') continue; - + //goto next line - while (fgetc(f) != '\n' && !feof(f)) {}; - - //The line start with # is comment, skip - if( buf[0]=='#' ) + while (fgetc(f) != '\n' && !feof(f)) {}; + + //The line start with # is comment, skip + if( buf[0]=='#' ) continue; // doesn't this only test first char only? @@ -2324,7 +2324,7 @@ int LoadDictionaryKeyFile( char* filename, uint8_t **keys, int *keycnt) { PrintAndLogEx(ERR, "file content error. '%s' must include 16 HEX symbols", buf); continue; } - + // null terminator (skip the rest of the line) buf[16] = 0; @@ -2353,15 +2353,15 @@ int GenerateMacFromKeyFile( uint8_t* CSN, uint8_t* CCNR, bool use_raw, bool use_ for ( int i=0; i < keycnt; i++) { - memcpy(key, keys + 8 * i , 8); - + memcpy(key, keys + 8 * i , 8); + if (use_raw) memcpy(div_key, key, 8); else HFiClassCalcDivKey(CSN, key, div_key, use_elite); doMAC(CCNR, div_key, list[i].mac); - } + } return 0; } @@ -2370,9 +2370,9 @@ int GenerateFromKeyFile( uint8_t* CSN, uint8_t* CCNR, bool use_raw, bool use_eli uint8_t div_key[8] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; for ( int i=0; i < keycnt; i++) { - - memcpy(list[i].key, keys + 8 * i , 8); - + + memcpy(list[i].key, keys + 8 * i , 8); + // generate diversifed key if (use_raw) memcpy(div_key, list[i].key, 8); @@ -2381,7 +2381,7 @@ int GenerateFromKeyFile( uint8_t* CSN, uint8_t* CCNR, bool use_raw, bool use_eli // generate MAC doMAC(CCNR, div_key, list[i].mac); - } + } return 0; } @@ -2391,9 +2391,9 @@ void PrintPreCalcMac(uint8_t* keys, int keycnt, iclass_premac_t* pre_list) { iclass_prekey_t* b = calloc(keycnt, sizeof(iclass_prekey_t)); if ( !b ) return; - - for ( int i=0; i < keycnt; i++) { - memcpy(b[i].key, keys + 8 * i , 8); + + for ( int i=0; i < keycnt; i++) { + memcpy(b[i].key, keys + 8 * i , 8); memcpy(b[i].mac, pre_list[i].mac, 4); } PrintPreCalc(b, keycnt); @@ -2406,7 +2406,7 @@ void PrintPreCalc(iclass_prekey_t* list, int itemcnt) { PrintAndLogEx(NORMAL, "-----+------------------+---------"); for ( int i=0; i < itemcnt; i++) { - if (i < 10 ) { + if (i < 10 ) { PrintAndLogEx(NORMAL, "[%2d] | %016" PRIx64 " | %08" PRIx32, i, bytes_to_num(list[i].key, 8), bytes_to_num( list[i].mac, 4) ); } else if ( i == 10 ) { PrintAndLogEx(SUCCESS, "... skip printing the rest"); @@ -2414,7 +2414,7 @@ void PrintPreCalc(iclass_prekey_t* list, int itemcnt) { } } -static void permute(uint8_t *data, uint8_t len, uint8_t *output){ +static void permute(uint8_t *data, uint8_t len, uint8_t *output){ #define KEY_SIZE 8 if ( len > KEY_SIZE ) { @@ -2433,7 +2433,7 @@ static void permute(uint8_t *data, uint8_t len, uint8_t *output){ mask = 0x80 >> i; for( j=0; j < KEY_SIZE; ++j){ p >>= 1; - if (data[j] & mask) + if (data[j] & mask) p |= 0x80; } output[i] = p; @@ -2463,17 +2463,17 @@ static void shave(uint8_t *data, uint8_t len){ data[i] &= 0xFE; } static void generate_rev(uint8_t *data, uint8_t len) { - uint8_t *key = calloc(len, sizeof(uint8_t)); + uint8_t *key = calloc(len, sizeof(uint8_t)); PrintAndLogEx(SUCCESS, "input permuted key | %s \n", sprint_hex(data, len)); permute_rev(data, len, key); PrintAndLogEx(SUCCESS, " unpermuted key | %s \n", sprint_hex(key, len)); shave(key, len); PrintAndLogEx(SUCCESS, " key | %s \n", sprint_hex(key, len)); - free(key); + free(key); } static void generate(uint8_t *data, uint8_t len) { uint8_t *key = calloc(len, sizeof(uint8_t)); - uint8_t *pkey = calloc(len, sizeof(uint8_t)); + uint8_t *pkey = calloc(len, sizeof(uint8_t)); PrintAndLogEx(SUCCESS, " input key | %s \n", sprint_hex(data, len)); permute(data, len, pkey); PrintAndLogEx(SUCCESS, "permuted key | %s \n", sprint_hex(pkey, len)); @@ -2483,9 +2483,9 @@ static void generate(uint8_t *data, uint8_t len) { free(pkey); } -int CmdHFiClassPermuteKey(const char *Cmd) { +int CmdHFiClassPermuteKey(const char *Cmd) { - uint8_t key[8] = {0}; + uint8_t key[8] = {0}; uint8_t key_std_format[8] = {0}; uint8_t key_iclass_format[8] = {0}; uint8_t data[16] = {0}; @@ -2493,13 +2493,13 @@ int CmdHFiClassPermuteKey(const char *Cmd) { int len = 0; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0|| cmdp == 'h' || cmdp == 'H') return usage_hf_iclass_permutekey(); - + isReverse = ( cmdp == 'r' || cmdp == 'R' ); - + param_gethex_ex(Cmd, 1, data, &len); if ( len%2 ) return usage_hf_iclass_permutekey(); - len >>= 1; + len >>= 1; memcpy(key, data, 8); @@ -2510,7 +2510,7 @@ int CmdHFiClassPermuteKey(const char *Cmd) { } else { generate(data, len); - permutekey(key, key_iclass_format); + permutekey(key, key_iclass_format); PrintAndLogEx(SUCCESS, "holiman std key | %s \n", sprint_hex(key_iclass_format, 8)); } return 0; diff --git a/client/cmdhflegic.c b/client/cmdhflegic.c index 41df287a9..bf61b570a 100644 --- a/client/cmdhflegic.c +++ b/client/cmdhflegic.c @@ -11,7 +11,7 @@ static int CmdHelp(const char *Cmd); -#define MAX_LENGTH 1024 +#define MAX_LENGTH 1024 int usage_legic_calccrc(void){ PrintAndLogEx(NORMAL, "Calculates the legic crc8/crc16 on the given data."); @@ -28,7 +28,7 @@ int usage_legic_calccrc(void){ PrintAndLogEx(NORMAL, " hf legic crc d deadbeef1122 u 9A c 16"); return 0; } -int usage_legic_rdmem(void){ +int usage_legic_rdmem(void){ PrintAndLogEx(NORMAL, "Read data from a legic tag."); PrintAndLogEx(NORMAL, "Usage: hf legic rdmem [h] "); PrintAndLogEx(NORMAL, "Options:"); @@ -94,7 +94,7 @@ int usage_legic_info(void){ int usage_legic_dump(void){ PrintAndLogEx(NORMAL, "Reads all pages from LEGIC Prime MIM22, MIM256, MIM1024"); PrintAndLogEx(NORMAL, "and saves binary dump into the file `filename.bin` or `cardUID.bin`"); - PrintAndLogEx(NORMAL, "It autodetects card type.\n"); + PrintAndLogEx(NORMAL, "It autodetects card type.\n"); PrintAndLogEx(NORMAL, "Usage: hf legic dump [h] o "); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h : this help"); @@ -121,11 +121,11 @@ int usage_legic_eload(void){ PrintAndLogEx(NORMAL, "It loads binary dump from the file `filename.bin`"); PrintAndLogEx(NORMAL, "Usage: hf legic eload [h] [card memory] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : this help"); + PrintAndLogEx(NORMAL, " h : this help"); PrintAndLogEx(NORMAL, " [card memory] : 0 = MIM22"); PrintAndLogEx(NORMAL, " : 1 = MIM256 (default)"); PrintAndLogEx(NORMAL, " : 2 = MIM1024"); - PrintAndLogEx(NORMAL, " : filename w/o .bin to load"); + PrintAndLogEx(NORMAL, " : filename w/o .bin to load"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf legic eload 2 myfile"); @@ -139,9 +139,9 @@ int usage_legic_esave(void){ PrintAndLogEx(NORMAL, " [card memory] : 0 = MIM22"); PrintAndLogEx(NORMAL, " : 1 = MIM256 (default)"); PrintAndLogEx(NORMAL, " : 2 = MIM1024"); - PrintAndLogEx(NORMAL, " : filename w/o .bin to load"); + PrintAndLogEx(NORMAL, " : filename w/o .bin to load"); PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(NORMAL, "Examples:"); + PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf legic esave 2 myfile"); return 0; } @@ -151,7 +151,7 @@ int usage_legic_wipe(void){ PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h : this help"); PrintAndLogEx(NORMAL, ""); - PrintAndLogEx(NORMAL, "Examples:"); + PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf legic wipe"); return 0; } @@ -181,7 +181,7 @@ int CmdLegicInfo(const char *Cmd) { } PrintAndLogEx(SUCCESS, "Reading tag memory %d b...", card.cardsize); - + // allocate receiver buffer uint8_t *data = calloc(card.cardsize, sizeof(uint8_t)); if (!data) { @@ -195,11 +195,11 @@ int CmdLegicInfo(const char *Cmd) { free(data); return 3; } - + // Output CDF System area (9 bytes) plus remaining header area (12 bytes) crc = data[4]; - uint32_t calc_crc = CRC8Legic(data, 4); - + uint32_t calc_crc = CRC8Legic(data, 4); + PrintAndLogEx(NORMAL, "\nCDF: System Area"); PrintAndLogEx(NORMAL, "------------------------------------------------------"); PrintAndLogEx(NORMAL, "MCD: %02x, MSN: %02x %02x %02x, MCC: %02x %s", @@ -210,7 +210,7 @@ int CmdLegicInfo(const char *Cmd) { data[4], (calc_crc == crc) ? "OK":"Fail" ); - + // MCD = Manufacturer ID (should be list meaning something?) token_type[0] = 0; @@ -224,7 +224,7 @@ int CmdLegicInfo(const char *Cmd) { data[5], data[6] ); - + } else if (dcf > 60000) { // Master token? int fl = 0; @@ -303,7 +303,7 @@ int CmdLegicInfo(const char *Cmd) { } } } - + uint8_t segCrcBytes[8] = {0,0,0,0,0,0,0,0}; uint32_t segCalcCRC = 0; uint32_t segCRC = 0; @@ -311,14 +311,14 @@ int CmdLegicInfo(const char *Cmd) { // Not Data card? if (dcf > 60000) goto out; - + PrintAndLogEx(NORMAL, "\nADF: User Area"); PrintAndLogEx(NORMAL, "------------------------------------------------------"); if(bIsSegmented) { // Data start point on segmented cards - i = 22; + i = 22; // decode segments for (segmentNum=1; segmentNum < 128; segmentNum++ ) @@ -332,7 +332,7 @@ int CmdLegicInfo(const char *Cmd) { bool hasWRP = (wrp > wrc); int wrp_len = (wrp - wrc); int remain_seg_payload_len = (segment_len - wrp - 5); - + // validate segment-crc segCrcBytes[0]=data[0]; //uid0 segCrcBytes[1]=data[1]; //uid1 @@ -352,7 +352,7 @@ int CmdLegicInfo(const char *Cmd) { data[i+1] ^ crc, data[i+2] ^ crc, data[i+3] ^ crc, - segment_len, + segment_len, segment_flag, (segment_flag & 0x4) >> 2, (segment_flag & 0x8) >> 3, @@ -374,7 +374,7 @@ int CmdLegicInfo(const char *Cmd) { data[k] ^= crc; print_hex_break( data+i, wrc, 16); - + i += wrc; } @@ -385,14 +385,14 @@ int CmdLegicInfo(const char *Cmd) { for (k=i; k < (i+wrp_len); ++k) data[k] ^= crc; - + print_hex_break( data+i, wrp_len, 16); - + i += wrp_len; - + // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...) if( wrp_len == 8 ) - PrintAndLogEx(NORMAL, "Card ID: %2X%02X%02X", data[i-4]^crc, data[i-3]^crc, data[i-2]^crc); + PrintAndLogEx(NORMAL, "Card ID: %2X%02X%02X", data[i-4]^crc, data[i-3]^crc, data[i-2]^crc); } PrintAndLogEx(NORMAL, "Remaining segment payload: (I %d | K %d | Remain LEN %d)", i, k, remain_seg_payload_len); @@ -401,19 +401,19 @@ int CmdLegicInfo(const char *Cmd) { for ( k=i; k < (i+remain_seg_payload_len); ++k) data[k] ^= crc; - + print_hex_break( data+i, remain_seg_payload_len, 16); i += remain_seg_payload_len; - + PrintAndLogEx(NORMAL, "-----+------------------------------------------------\n"); // end with last segment - if (segment_flag & 0x8) + if (segment_flag & 0x8) goto out; } // end for loop - + } else { // Data start point on unsegmented cards @@ -447,7 +447,7 @@ int CmdLegicInfo(const char *Cmd) { PrintAndLogEx(NORMAL, "-----+------------------------------------------------"); print_hex_break( data + i, wrp_len, 16); i += wrp_len; - + // does this one work? (Answer: Only if KGH/BGH is used with BCD encoded card number! So maybe this will show just garbage...) if( wrp_len == 8 ) PrintAndLogEx(NORMAL, "Card ID: %2X%02X%02X", data[i-4], data[i-3], data[i-2]); @@ -458,7 +458,7 @@ int CmdLegicInfo(const char *Cmd) { PrintAndLogEx(NORMAL, "-----+------------------------------------------------"); print_hex_break( data + i, remain_seg_payload_len, 16); i += remain_seg_payload_len; - + PrintAndLogEx(NORMAL, "-----+------------------------------------------------\n"); } @@ -474,11 +474,11 @@ int CmdLegicRdmem(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if ( cmdp == 'h' ) return usage_legic_rdmem(); - + uint32_t offset = 0, len = 0, iv = 1; uint16_t datalen = 0; sscanf(Cmd, "%x %x %x", &offset, &len, &iv); - + // sanity checks if ( len + offset >= MAX_LENGTH ) { PrintAndLogEx(WARNING, "Out-of-bounds, Cardsize = %d, [offset+len = %d ]", MAX_LENGTH, len + offset); @@ -486,14 +486,14 @@ int CmdLegicRdmem(const char *Cmd) { } PrintAndLogEx(SUCCESS, "Reading %d bytes, from offset %d", len, offset); - + // allocate receiver buffer uint8_t *data = calloc(len, sizeof(uint8_t)); if ( !data ){ PrintAndLogEx(WARNING, "Cannot allocate memory"); return -2; } - + int status = legic_read_mem(offset, len, iv, data, &datalen); if ( status == 0 ) { PrintAndLogEx(NORMAL, "\n ## | 0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F"); @@ -523,7 +523,7 @@ int CmdLegicRfWrite(const char *Cmd) { bool errors = false; int len = 0, bg, en; uint32_t offset = 0, IV = 0x55; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'd': @@ -542,7 +542,7 @@ int CmdLegicRfWrite(const char *Cmd) { errors = true; break; } - + // limit number of bytes to write. This is not a 'restore' command. if ( (len >> 1) > 100 ){ PrintAndLogEx(WARNING, "Max bound on 100bytes to write a one time."); @@ -554,20 +554,20 @@ int CmdLegicRfWrite(const char *Cmd) { // more than once - we have to clean previous malloc if (data) free(data); - + data = calloc(len >> 1, sizeof(uint8_t)); if ( data == NULL ) { PrintAndLogEx(WARNING, "Can't allocate memory. exiting"); errors = true; break; } - + if (param_gethex(Cmd, cmdp+1, data, len)) { errors = true; break; } - len >>= 1; + len >>= 1; cmdp += 2; break; case 'o': @@ -585,7 +585,7 @@ int CmdLegicRfWrite(const char *Cmd) { } //Validations if (errors || cmdp == 0){ - if (data) + if (data) free(data); return usage_legic_write(); } @@ -598,14 +598,14 @@ int CmdLegicRfWrite(const char *Cmd) { } legic_print_type(card.cardsize, 0); - + // OUT-OF-BOUNDS checks // UID 4+1 bytes can't be written to. if ( offset < 5 ) { PrintAndLogEx(WARNING, "Out-of-bounds, bytes 0-1-2-3-4 can't be written to. Offset = %d", offset); return -2; } - + if ( len + offset >= card.cardsize ) { PrintAndLogEx(WARNING, "Out-of-bounds, Cardsize = %d, [offset+len = %d ]", card.cardsize, len + offset); return -2; @@ -623,17 +623,17 @@ int CmdLegicRfWrite(const char *Cmd) { return 0; } } - + legic_chk_iv(&IV); - + PrintAndLogEx(SUCCESS, "Writing to tag"); UsbCommand c = {CMD_WRITER_LEGIC_RF, {offset, len, IV}}; - memcpy(c.d.asBytes, data, len); + memcpy(c.d.asBytes, data, len); UsbCommand resp; clearCommandBuffer(); SendCommand(&c); - + uint8_t timeout = 0; while (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { @@ -643,9 +643,9 @@ int CmdLegicRfWrite(const char *Cmd) { PrintAndLogEx(WARNING, "\ncommand execution time out"); return 1; } - } + } PrintAndLogEx(NORMAL, "\n"); - + uint8_t isOK = resp.arg[0] & 0xFF; if ( !isOK ) { PrintAndLogEx(WARNING, "Failed writing tag"); @@ -662,7 +662,7 @@ int CmdLegicCalcCrc(const char *Cmd){ bool errors = false; int len = 0; int bg, en; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'd': @@ -691,13 +691,13 @@ int CmdLegicCalcCrc(const char *Cmd){ errors = true; break; } - + if (param_gethex(Cmd, cmdp+1, data, len)) { errors = true; break; } - len >>= 1; + len >>= 1; cmdp += 2; break; case 'u': @@ -722,7 +722,7 @@ int CmdLegicCalcCrc(const char *Cmd){ if (data) free(data); return usage_legic_calccrc(); } - + switch (type){ case 16: init_table(CRC_LEGIC); @@ -732,20 +732,20 @@ int CmdLegicCalcCrc(const char *Cmd){ PrintAndLogEx(SUCCESS, "Legic crc8: %X", CRC8Legic(data, len) ); break; } - + if (data) free(data); return 0; -} +} int legic_read_mem(uint32_t offset, uint32_t len, uint32_t iv, uint8_t *out, uint16_t *outlen) { - + legic_chk_iv(&iv); - + UsbCommand c = {CMD_READER_LEGIC_RF, {offset, len, iv}}; clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + uint8_t timeout = 0; while (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { ++timeout; @@ -754,19 +754,19 @@ int legic_read_mem(uint32_t offset, uint32_t len, uint32_t iv, uint8_t *out, uin PrintAndLogEx(WARNING, "\ncommand execution time out"); return 1; } - } + } PrintAndLogEx(NORMAL, "\n"); - + uint8_t isOK = resp.arg[0] & 0xFF; *outlen = resp.arg[1]; if ( !isOK ) { PrintAndLogEx(WARNING, "Failed reading tag"); return 2; } - + if ( *outlen != len ) PrintAndLogEx(WARNING, "Fail, only managed to read %u bytes", *outlen); - + // copy data from device if ( !GetFromDevice( BIG_BUF_EML, out, *outlen, 0, NULL, 2500, false) ) { PrintAndLogEx(WARNING, "Fail, transfer from device time-out"); @@ -780,7 +780,7 @@ int legic_print_type(uint32_t tagtype, uint8_t spaces){ spc[10]=0x00; char *spacer = spc + (10-spaces); - if ( tagtype == 22 ) + if ( tagtype == 22 ) PrintAndLogEx(SUCCESS, "%sTYPE : MIM%d card (outdated)", spacer, tagtype); else if ( tagtype == 256 ) PrintAndLogEx(SUCCESS, "%sTYPE : MIM%d card (234 bytes)", spacer, tagtype); @@ -800,11 +800,11 @@ int legic_get_type(legic_card_select_t *card){ UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return 2; - + uint8_t isOK = resp.arg[0] & 0xFF; - if ( !isOK ) + if ( !isOK ) return 3; - + memcpy(card, (legic_card_select_t *)resp.d.asBytes, sizeof(legic_card_select_t)); return 0; } @@ -815,20 +815,20 @@ void legic_chk_iv(uint32_t *iv){ } // IV must be odd if ( (*iv & 1) == 0 ){ - *iv |= 0x01; - PrintAndLogEx(INFO, "LSB of IV must be SET %u", *iv); + *iv |= 0x01; + PrintAndLogEx(INFO, "LSB of IV must be SET %u", *iv); } } void legic_seteml(uint8_t *src, uint32_t offset, uint32_t numofbytes) { size_t len = 0; - UsbCommand c = {CMD_LEGIC_ESET, {0, 0, 0}}; + UsbCommand c = {CMD_LEGIC_ESET, {0, 0, 0}}; for(size_t i = offset; i < numofbytes; i += USB_CMD_DATA_SIZE) { - - len = MIN((numofbytes - i), USB_CMD_DATA_SIZE); + + len = MIN((numofbytes - i), USB_CMD_DATA_SIZE); c.arg[0] = i; // offset c.arg[1] = len; // number of bytes - memcpy(c.d.asBytes, src+i, len); + memcpy(c.d.asBytes, src+i, len); clearCommandBuffer(); SendCommand(&c); } @@ -838,15 +838,15 @@ int HFLegicReader(const char *Cmd, bool verbose) { char cmdp = tolower(param_getchar(Cmd, 0)); if ( cmdp == 'h' ) return usage_legic_reader(); - + legic_card_select_t card; switch (legic_get_type(&card)){ - case 1: + case 1: return 2; - case 2: - if ( verbose ) PrintAndLogEx(WARNING, "command execution time out"); + case 2: + if ( verbose ) PrintAndLogEx(WARNING, "command execution time out"); return 1; - case 3: + case 3: if ( verbose ) PrintAndLogEx(WARNING, "legic card select failed"); return 2; default: break; @@ -866,20 +866,20 @@ int CmdLegicDump(const char *Cmd){ char *fnameptr = filename; size_t fileNlen = 0; bool errors = false; - uint16_t dumplen; + uint16_t dumplen; uint8_t cmdp = 0; - + memset(filename, 0, sizeof(filename)); - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_legic_dump(); case 'o': fileNlen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); - if (!fileNlen) - errors = true; - if (fileNlen > FILE_PATH_SIZE-5) + if (!fileNlen) + errors = true; + if (fileNlen > FILE_PATH_SIZE-5) fileNlen = FILE_PATH_SIZE-5; cmdp += 2; break; @@ -891,7 +891,7 @@ int CmdLegicDump(const char *Cmd){ } //Validations if (errors) return usage_legic_dump(); - + // tagtype legic_card_select_t card; if (legic_get_type(&card)) { @@ -899,8 +899,8 @@ int CmdLegicDump(const char *Cmd){ return -1; } dumplen = card.cardsize; - - legic_print_type(dumplen, 0); + + legic_print_type(dumplen, 0); PrintAndLogEx(SUCCESS, "Reading tag memory %d b...", dumplen); UsbCommand c = {CMD_READER_LEGIC_RF, {0x00, dumplen, 0x55}}; @@ -916,9 +916,9 @@ int CmdLegicDump(const char *Cmd){ PrintAndLogEx(WARNING, "\ncommand execution time out"); return 1; } - } + } PrintAndLogEx(NORMAL, "\n"); - + uint8_t isOK = resp.arg[0] & 0xFF; if ( !isOK ) { PrintAndLogEx(WARNING, "Failed dumping tag data"); @@ -931,7 +931,7 @@ int CmdLegicDump(const char *Cmd){ PrintAndLogEx(WARNING, "Fail, cannot allocate memory"); return 3; } - + if ( readlen != dumplen ) PrintAndLogEx(WARNING, "Fail, only managed to read 0x%02X bytes of 0x%02X", readlen, dumplen); @@ -949,7 +949,7 @@ int CmdLegicDump(const char *Cmd){ sprintf(fnameptr + fileNlen,".bin"); f = fopen(filename, "wb"); - if (!f) { + if (!f) { PrintAndLogEx(WARNING, "Could not create file name %s", filename); if (data) free(data); @@ -961,7 +961,7 @@ int CmdLegicDump(const char *Cmd){ free(data); PrintAndLogEx(SUCCESS, "Wrote %d bytes to %s", readlen, filename); return 0; -} +} int CmdLegicRestore(const char *Cmd){ @@ -970,11 +970,11 @@ int CmdLegicRestore(const char *Cmd){ char *fnameptr = filename; size_t fileNlen = 0; bool errors = false; - uint16_t numofbytes; + uint16_t numofbytes; uint8_t cmdp = 0; - + memset(filename, 0, sizeof(filename)); - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -982,12 +982,12 @@ int CmdLegicRestore(const char *Cmd){ break; case 'i': fileNlen = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); - if (!fileNlen) + if (!fileNlen) errors = true; - - if (fileNlen > FILE_PATH_SIZE-5) + + if (fileNlen > FILE_PATH_SIZE-5) fileNlen = FILE_PATH_SIZE-5; - cmdp += 2; + cmdp += 2; break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); @@ -997,23 +997,23 @@ int CmdLegicRestore(const char *Cmd){ } //Validations if (errors || cmdp == 0) return usage_legic_restore(); - + // tagtype legic_card_select_t card; if (legic_get_type(&card)) { PrintAndLogEx(WARNING, "Failed to identify tagtype"); return 1; } - numofbytes = card.cardsize; - + numofbytes = card.cardsize; + // set up buffer uint8_t *data = calloc(numofbytes, sizeof(uint8_t) ); if (!data) { PrintAndLogEx(WARNING, "Fail, cannot allocate memory"); - return 2; + return 2; } - - legic_print_type(numofbytes, 0); + + legic_print_type(numofbytes, 0); // set up file fnameptr += fileNlen; @@ -1024,13 +1024,13 @@ int CmdLegicRestore(const char *Cmd){ PrintAndLogEx(WARNING, "File %s not found or locked", filename); free(data); return 3; - } - - // verify size of dumpfile is the same as card. + } + + // verify size of dumpfile is the same as card. fseek(f, 0, SEEK_END); // seek to end of file size_t filesize = ftell(f); // get current file pointer fseek(f, 0, SEEK_SET); // seek back to beginning of file - + if ( filesize != numofbytes) { PrintAndLogEx(WARNING, "Fail, filesize and cardsize is not equal. [%u != %u]", filesize, numofbytes); free(data); @@ -1041,13 +1041,13 @@ int CmdLegicRestore(const char *Cmd){ // load file size_t bytes_read = fread(data, 1, numofbytes, f); fclose(f); - + if ( bytes_read == 0){ PrintAndLogEx(WARNING, "File reading error"); free(data); return 2; } - + PrintAndLogEx(SUCCESS, "Restoring to card"); // transfer to device @@ -1055,36 +1055,36 @@ int CmdLegicRestore(const char *Cmd){ UsbCommand c = {CMD_WRITER_LEGIC_RF, {0, 0, 0x55}}; UsbCommand resp; for(size_t i = 7; i < numofbytes; i += USB_CMD_DATA_SIZE) { - - len = MIN((numofbytes - i), USB_CMD_DATA_SIZE); + + len = MIN((numofbytes - i), USB_CMD_DATA_SIZE); c.arg[0] = i; // offset c.arg[1] = len; // number of bytes - memcpy(c.d.asBytes, data+i, len); + memcpy(c.d.asBytes, data+i, len); clearCommandBuffer(); SendCommand(&c); - + uint8_t timeout = 0; while (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { ++timeout; printf("."); fflush(stdout); if (timeout > 7) { PrintAndLogEx(WARNING, "\ncommand execution time out"); - free(data); + free(data); return 1; } - } + } PrintAndLogEx(NORMAL, "\n"); - + uint8_t isOK = resp.arg[0] & 0xFF; if ( !isOK ) { PrintAndLogEx(WARNING, "Failed writing tag [msg = %u]", resp.arg[1] & 0xFF); - free(data); + free(data); return 1; } PrintAndLogEx(SUCCESS, "Wrote chunk [offset %d | len %d | total %d", i, len, i+len); - } - - free(data); + } + + free(data); PrintAndLogEx(SUCCESS, "\nWrote %d bytes to card from file %s", numofbytes, filename); return 0; } @@ -1095,14 +1095,14 @@ int CmdLegicELoad(const char *Cmd) { char *fnameptr = filename; int len, numofbytes; int nameParamNo = 1; - + char cmdp = tolower(param_getchar(Cmd, 0)); if ( cmdp == 'h' || cmdp == 0x00) return usage_legic_eload(); switch (cmdp) { case '0' : numofbytes = 22; break; - case '1' : + case '1' : case '\0': numofbytes = 256; break; case '2' : numofbytes = 1024; break; default : numofbytes = 256; nameParamNo = 0;break; @@ -1112,19 +1112,19 @@ int CmdLegicELoad(const char *Cmd) { uint8_t *data = calloc(numofbytes, sizeof(uint8_t)); if (!data) { PrintAndLogEx(WARNING, "Fail, cannot allocate memory"); - return 3; + return 3; } - + // set up file len = param_getstr(Cmd, nameParamNo, filename, FILE_PATH_SIZE); - if (len > FILE_PATH_SIZE - 5) + if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5; fnameptr += len; sprintf(fnameptr, ".bin"); - + // open file f = fopen(filename,"rb"); - if (!f) { + if (!f) { PrintAndLogEx(WARNING, "File %s not found or locked", filename); free(data); return 1; @@ -1136,16 +1136,16 @@ int CmdLegicELoad(const char *Cmd) { PrintAndLogEx(WARNING, "File reading error"); free(data); fclose(f); - f = NULL; + f = NULL; return 2; } fclose(f); f = NULL; - + // transfer to device legic_seteml(data, 0, numofbytes); - - free(data); + + free(data); PrintAndLogEx(SUCCESS, "\nLoaded %d bytes from file: %s to emulator memory", numofbytes, filename); return 0; } @@ -1155,48 +1155,48 @@ int CmdLegicESave(const char *Cmd) { char filename[FILE_PATH_SIZE]; char *fnameptr = filename; int fileNlen, numofbytes, nameParamNo = 1; - + memset(filename, 0, sizeof(filename)); char cmdp = tolower(param_getchar(Cmd, 0)); - + if ( cmdp == 'h' || cmdp == 0x00) return usage_legic_esave(); switch (cmdp) { case '0' : numofbytes = 22; break; - case '1' : + case '1' : case '\0': numofbytes = 256; break; case '2' : numofbytes = 1024; break; default : numofbytes = 256; nameParamNo = 0; break; } fileNlen = param_getstr(Cmd, nameParamNo, filename, FILE_PATH_SIZE); - - if (fileNlen > FILE_PATH_SIZE - 5) + + if (fileNlen > FILE_PATH_SIZE - 5) fileNlen = FILE_PATH_SIZE - 5; // set up buffer uint8_t *data = calloc(numofbytes, sizeof(uint8_t)); if (!data) { PrintAndLogEx(WARNING, "Fail, cannot allocate memory"); - return 3; + return 3; } - + // download emulator memory - PrintAndLogEx(SUCCESS, "Reading emulator memory..."); + PrintAndLogEx(SUCCESS, "Reading emulator memory..."); if (!GetFromDevice( BIG_BUF_EML, data, numofbytes, 0, NULL, 2500, false)) { PrintAndLogEx(WARNING, "Fail, transfer from device time-out"); free(data); return 4; } // user supplied filename? - if (fileNlen < 1) + if (fileNlen < 1) sprintf(fnameptr,"%02X%02X%02X%02X.bin", data[0], data[1], data[2], data[3]); else sprintf(fnameptr + fileNlen,".bin"); - - saveFileEML(filename, "eml", data, numofbytes, 8); + + saveFileEML(filename, "eml", data, numofbytes, 8); saveFile(filename, "bin", data, numofbytes); return 0; } @@ -1204,57 +1204,57 @@ int CmdLegicESave(const char *Cmd) { int CmdLegicWipe(const char *Cmd){ char cmdp = tolower(param_getchar(Cmd, 0)); - + if ( cmdp == 'h') return usage_legic_wipe(); - + // tagtype legic_card_select_t card; if (legic_get_type(&card)) { PrintAndLogEx(WARNING, "Failed to identify tagtype"); return 1; } - + // set up buffer uint8_t *data = calloc(card.cardsize, sizeof(uint8_t)); if (!data) { PrintAndLogEx(WARNING, "Fail, cannot allocate memory"); - return 2; + return 2; } - + legic_print_type(card.cardsize, 0); PrintAndLogEx(SUCCESS, "Erasing"); - + // transfer to device size_t len = 0; UsbCommand c = {CMD_WRITER_LEGIC_RF, {0, 0, 0x55}}; UsbCommand resp; for(size_t i = 7; i < card.cardsize; i += USB_CMD_DATA_SIZE) { - + printf("."); fflush(stdout); - len = MIN((card.cardsize - i), USB_CMD_DATA_SIZE); + len = MIN((card.cardsize - i), USB_CMD_DATA_SIZE); c.arg[0] = i; // offset c.arg[1] = len; // number of bytes - memcpy(c.d.asBytes, data+i, len); + memcpy(c.d.asBytes, data+i, len); clearCommandBuffer(); SendCommand(&c); - + uint8_t timeout = 0; while (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { ++timeout; printf("."); fflush(stdout); if (timeout > 7) { PrintAndLogEx(WARNING, "\ncommand execution time out"); - free(data); + free(data); return 3; } - } - PrintAndLogEx(NORMAL, "\n"); + } + PrintAndLogEx(NORMAL, "\n"); uint8_t isOK = resp.arg[0] & 0xFF; if ( !isOK ) { PrintAndLogEx(WARNING, "Failed writing tag [msg = %u]", resp.arg[1] & 0xFF); - free(data); + free(data); return 4; } } @@ -1276,7 +1276,7 @@ static command_t CommandTable[] = { {"rdmem", CmdLegicRdmem, 0, "Read bytes from a LEGIC Prime tag"}, {"sim", CmdLegicRfSim, 0, "Start tag simulator"}, {"write", CmdLegicRfWrite, 0, "Write data to a LEGIC Prime tag"}, - {"crc", CmdLegicCalcCrc, 1, "Calculate Legic CRC over given bytes"}, + {"crc", CmdLegicCalcCrc, 1, "Calculate Legic CRC over given bytes"}, {"eload", CmdLegicELoad, 1, "Load binary dump to emulator memory"}, {"esave", CmdLegicESave, 1, "Save emulator memory to binary file"}, {"list", CmdLegicList, 1, "[Deprecated] List LEGIC history"}, diff --git a/client/cmdhflist.c b/client/cmdhflist.c index faed275cd..f605008c5 100644 --- a/client/cmdhflist.c +++ b/client/cmdhflist.c @@ -103,7 +103,7 @@ uint8_t iclass_CRC_check(bool isResponse, uint8_t* d, uint8_t n) { return check_crc( CRC_ICLASS, d+1, n-1); } return 2; - } + } /** These tag responses should have CRC. Total length leftmost @@ -154,12 +154,12 @@ int applyIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { case ISO14443A_CMD_REQA: snprintf(exp,size,"REQA"); break; case ISO14443A_CMD_READBLOCK: snprintf(exp,size,"READBLOCK(%d)",cmd[1]); break; case ISO14443A_CMD_WRITEBLOCK: snprintf(exp,size,"WRITEBLOCK(%d)",cmd[1]); break; - case ISO14443A_CMD_HALT: - snprintf(exp,size,"HALT"); + case ISO14443A_CMD_HALT: + snprintf(exp,size,"HALT"); MifareAuthState = masNone; break; case ISO14443A_CMD_RATS: snprintf(exp,size,"RATS"); break; - case ISO14443A_CMD_OPTS: snprintf(exp,size,"OPTIONAL TIMESLOT"); break; + case ISO14443A_CMD_OPTS: snprintf(exp,size,"OPTIONAL TIMESLOT"); break; case MIFARE_CMD_INC: snprintf(exp,size,"INC(%d)",cmd[1]); break; case MIFARE_CMD_DEC: snprintf(exp,size,"DEC(%d)",cmd[1]); break; case MIFARE_CMD_RESTORE: snprintf(exp,size,"RESTORE(%d)",cmd[1]); break; @@ -176,7 +176,7 @@ int applyIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { } case MIFARE_AUTH_KEYB: { MifareAuthState = masNt; - snprintf(exp,size,"AUTH-B(%d)",cmd[1]); + snprintf(exp,size,"AUTH-B(%d)",cmd[1]); break; } case MIFARE_MAGICWUPC1: snprintf(exp,size,"MAGIC WUPC1"); break; @@ -184,7 +184,7 @@ int applyIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { case MIFARE_MAGICWIPEC: snprintf(exp,size,"MAGIC WIPEC"); break; case MIFARE_ULC_AUTH_1 : snprintf(exp,size,"AUTH "); break; case MIFARE_ULC_AUTH_2 : snprintf(exp,size,"AUTH_ANSW"); break; - case MIFARE_ULEV1_AUTH : + case MIFARE_ULEV1_AUTH : if ( cmdsize == 7 ) snprintf(exp,size,"PWD-AUTH KEY: 0x%02x%02x%02x%02x", cmd[1], cmd[2], cmd[3], cmd[4] ); else @@ -192,18 +192,18 @@ int applyIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { break; case MIFARE_ULEV1_FASTREAD : { if ( cmdsize >=3 && cmd[2] <= 0xE6) - snprintf(exp,size,"READ RANGE (%d-%d)",cmd[1],cmd[2]); + snprintf(exp,size,"READ RANGE (%d-%d)",cmd[1],cmd[2]); else // outside limits, useful for some tags... - snprintf(exp,size,"READ RANGE (%d-%d) (?)",cmd[1], cmd[2]); + snprintf(exp,size,"READ RANGE (%d-%d) (?)",cmd[1], cmd[2]); break; } case MIFARE_ULC_WRITE : { if ( cmd[1] < 0x21 ) - snprintf(exp,size,"WRITEBLOCK(%d)",cmd[1]); + snprintf(exp,size,"WRITEBLOCK(%d)",cmd[1]); else - // outside limits, useful for some tags... - snprintf(exp, size, "WRITEBLOCK(%d) (?)", cmd[1]); + // outside limits, useful for some tags... + snprintf(exp, size, "WRITEBLOCK(%d) (?)", cmd[1]); break; } case MIFARE_ULEV1_READ_CNT :{ @@ -278,9 +278,9 @@ void annotateIso15693(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { default: break; } - if ( cmd[1] >= 0x2D && cmd[1] <= 0x9F ) snprintf(exp, size, "Optional RFU"); - else if ( cmd[1] >= 0xA0 && cmd[1] <= 0xDF ) snprintf(exp, size, "Cust IC MFG dependent"); - else if ( cmd[1] >= 0xE0 && cmd[1] <= 0xFF ) snprintf(exp, size, "Proprietary IC MFG dependent"); + if ( cmd[1] >= 0x2D && cmd[1] <= 0x9F ) snprintf(exp, size, "Optional RFU"); + else if ( cmd[1] >= 0xA0 && cmd[1] <= 0xDF ) snprintf(exp, size, "Cust IC MFG dependent"); + else if ( cmd[1] >= 0xE0 && cmd[1] <= 0xFF ) snprintf(exp, size, "Proprietary IC MFG dependent"); else snprintf(exp, size, "?"); } @@ -302,10 +302,10 @@ void annotateTopaz(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ } } -// iso 7816-3 +// iso 7816-3 void annotateIso7816(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ // S-block - if ( (cmd[0] & 0xC0) && (cmdsize == 3) ) { + if ( (cmd[0] & 0xC0) && (cmdsize == 3) ) { switch ( (cmd[0] & 0x3f) ) { case 0x00 : snprintf(exp, size, "S-block RESYNCH req"); break; case 0x20 : snprintf(exp, size, "S-block RESYNCH resp"); break; @@ -316,11 +316,11 @@ void annotateIso7816(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ case 0x03 : snprintf(exp, size, "S-block WTX reqt"); break; case 0x23 : snprintf(exp, size, "S-block WTX resp"); break; default : snprintf(exp, size, "S-block"); break; - } + } } // R-block (ack) else if ( ((cmd[0] & 0xD0) == 0x80) && ( cmdsize > 2) ) { - if ( (cmd[0] & 0x10) == 0 ) + if ( (cmd[0] & 0x10) == 0 ) snprintf(exp, size, "R-block ACK"); else snprintf(exp, size, "R-block NACK"); @@ -365,20 +365,20 @@ void annotateIso7816(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ // MIFARE DESFire void annotateMfDesfire(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ - + // it's basically a ISO14443a tag, so try annotation from there if (!applyIso14443a(exp, size, cmd, cmdsize)){ // S-block 11xxx010 - if ( (cmd[0] & 0xC0) && (cmdsize == 3) ) { + if ( (cmd[0] & 0xC0) && (cmdsize == 3) ) { switch ( (cmd[0] & 0x30) ) { case 0x30 : snprintf(exp, size, "S-block DESELECT"); break; case 0x00 : snprintf(exp, size, "S-block WTX"); break; default : snprintf(exp, size, "S-block"); break; - } + } } // R-block (ack) 101xx01x else if ( ((cmd[0] & 0xB0) == 0xA0) && ( cmdsize > 2) ) { - if ( (cmd[0] & 0x10) == 0 ) + if ( (cmd[0] & 0x10) == 0 ) snprintf(exp, size, "R-block ACK(%d)", (cmd[0] & 0x01)); else snprintf(exp, size, "R-block NACK(%d)", (cmd[0] & 0x01)); @@ -450,14 +450,14 @@ void annotateMfDesfire(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ void annotateIso14443b(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { switch(cmd[0]){ case ISO14443B_REQB : { - + switch ( cmd[2] & 0x07 ) { case 0: snprintf(exp, size,"1 slot ");break; - case 1: snprintf(exp, size,"2 slots ");break; + case 1: snprintf(exp, size,"2 slots ");break; case 2: snprintf(exp, size,"4 slots ");break; case 3: snprintf(exp, size,"8 slots ");break; default: snprintf(exp, size,"16 slots ");break; - } + } if ( (cmd[2] & 0x8) ) snprintf(exp, size,"WUPB"); else @@ -480,12 +480,12 @@ void annotateIso14443b(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) { } } -// LEGIC +// LEGIC // 1 = read // 0 = write // Quite simpel tag -void annotateLegic(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ - uint8_t bitsend = cmd[0]; +void annotateLegic(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ + uint8_t bitsend = cmd[0]; uint8_t cmdBit = (cmd[1] & 1); switch (bitsend){ case 7: @@ -505,11 +505,11 @@ void annotateLegic(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ case 11: { uint16_t address = (cmd[2] << 7) | cmd[1] >> 1; - - if (cmdBit == LEGIC_READ) + + if (cmdBit == LEGIC_READ) snprintf(exp, size, "READ Byte(%d)", address); - - if (cmdBit == LEGIC_WRITE ) + + if (cmdBit == LEGIC_WRITE ) snprintf(exp, size, "WRITE Byte(%d)", address); break; } @@ -535,7 +535,7 @@ void annotateLegic(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ } } -void annotateFelica(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ +void annotateFelica(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ switch(cmd[0]){ case FELICA_POLL_REQ: snprintf(exp,size ,"POLLING");break; @@ -547,7 +547,7 @@ void annotateFelica(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ case FELICA_RDBLK_REQ: snprintf(exp,size ,"READ BLK");break; case FELICA_RDBLK_ACK: snprintf(exp,size ,"READ BLK ACK");break; case FELICA_WRTBLK_REQ: snprintf(exp,size ,"WRITE BLK");break; - case FELICA_WRTBLK_ACK: snprintf(exp,size ,"WRITE BLK ACK");break; + case FELICA_WRTBLK_ACK: snprintf(exp,size ,"WRITE BLK ACK");break; case FELICA_SRCHSYSCODE_REQ: snprintf(exp,size ,"SEARCH SERVICE CODE");break; case FELICA_SRCHSYSCODE_ACK: snprintf(exp,size ,"SSC ACK");break; case FELICA_REQSYSCODE_REQ: snprintf(exp,size ,"REQUEST SYSTEM CODE");break; @@ -555,11 +555,11 @@ void annotateFelica(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ case FELICA_AUTH1_REQ: snprintf(exp,size ,"AUTH 1");break; case FELICA_AUTH1_ACK: snprintf(exp,size ,"AUTH 1 ACK");break; case FELICA_AUTH2_REQ: snprintf(exp,size ,"AUTH 2");break; - case FELICA_AUTH2_ACK: snprintf(exp,size ,"AUTH 2 ACK");break; + case FELICA_AUTH2_ACK: snprintf(exp,size ,"AUTH 2 ACK");break; case FELICA_RDSEC_REQ: snprintf(exp,size ,"READ");break; case FELICA_RDSEC_ACK: snprintf(exp,size ,"READ ACK");break; case FELICA_WRTSEC_REQ: snprintf(exp,size ,"WRITE");break; - case FELICA_WRTSEC_ACK: snprintf(exp,size ,"WRITE ACK");break; + case FELICA_WRTSEC_ACK: snprintf(exp,size ,"WRITE ACK");break; case FELICA_REQSRV2_REQ: snprintf(exp,size ,"REQUEST SERVICE v2");break; case FELICA_REQSRV2_ACK: snprintf(exp,size ,"REQ SERV v2 ACK");break; case FELICA_GETSTATUS_REQ: snprintf(exp,size ,"GET STATUS");break; @@ -567,17 +567,17 @@ void annotateFelica(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ case FELICA_OSVER_REQ: snprintf(exp,size ,"REQUEST SPECIFIC VERSION");break; case FELICA_OSVER_ACK: snprintf(exp,size ,"RSV ACK");break; case FELICA_RESET_MODE_REQ: snprintf(exp,size ,"RESET MODE");break; - case FELICA_RESET_MODE_ACK: snprintf(exp,size ,"RESET MODE ACK");break; + case FELICA_RESET_MODE_ACK: snprintf(exp,size ,"RESET MODE ACK");break; case FELICA_AUTH1V2_REQ: snprintf(exp,size ,"AUTH 1 v2");break; case FELICA_AUTH1V2_ACK: snprintf(exp,size ,"AUTH 1 v2 ACK");break; case FELICA_AUTH2V2_REQ: snprintf(exp,size ,"AUTH 2 v2");break; - case FELICA_AUTH2V2_ACK: snprintf(exp,size ,"AUTH 2 v2 ACK");break; + case FELICA_AUTH2V2_ACK: snprintf(exp,size ,"AUTH 2 v2 ACK");break; case FELICA_RDSECV2_REQ: snprintf(exp,size ,"READ v2");break; case FELICA_RDSECV2_ACK: snprintf(exp,size ,"READ v2 ACK");break; case FELICA_WRTSECV2_REQ: snprintf(exp,size ,"WRITE v2");break; - case FELICA_WRTSECV2_ACK: snprintf(exp,size ,"WRITE v2 ACK");break; + case FELICA_WRTSECV2_ACK: snprintf(exp,size ,"WRITE v2 ACK");break; case FELICA_UPDATE_RNDID_REQ: snprintf(exp,size ,"UPDATE RANDOM ID");break; - case FELICA_UPDATE_RNDID_ACK: snprintf(exp,size ,"URI ACK");break; + case FELICA_UPDATE_RNDID_ACK: snprintf(exp,size ,"URI ACK");break; default : snprintf(exp,size ,"?");break; } } @@ -585,15 +585,15 @@ void annotateFelica(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize){ void annotateMifare(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize, uint8_t* parity, uint8_t paritysize, bool isResponse) { if (!isResponse && cmdsize == 1) { switch(cmd[0]) { - case ISO14443A_CMD_WUPA: - case ISO14443A_CMD_REQA: + case ISO14443A_CMD_WUPA: + case ISO14443A_CMD_REQA: MifareAuthState = masNone; break; default: break; } } - + // get UID if (MifareAuthState == masNone) { if (cmdsize == 9 && cmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT && cmd[1] == 0x70) { @@ -609,7 +609,7 @@ void annotateMifare(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize, uint8 AuthData.uid = bytes_to_num(&cmd[2], 4); } } - + switch(MifareAuthState) { case masNt: if (cmdsize == 4 && isResponse) { @@ -652,18 +652,18 @@ void annotateMifare(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize, uint8 default: break; } - + if (!isResponse && ((MifareAuthState == masNone) || (MifareAuthState == masError))) annotateIso14443a(exp, size, cmd, cmdsize); - + } bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isResponse, uint8_t *mfData, size_t *mfDataLen) { - static struct Crypto1State *traceCrypto1; + static struct Crypto1State *traceCrypto1; static uint64_t mfLastKey; - + *mfDataLen = 0; - + if (MifareAuthState == masAuthComplete) { if (traceCrypto1) { crypto1_destroy(traceCrypto1); @@ -673,21 +673,21 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes MifareAuthState = masFirstData; return false; } - + if (cmdsize > 32) return false; - + if (MifareAuthState == masFirstData) { if (AuthData.first_auth) { AuthData.ks2 = AuthData.ar_enc ^ prng_successor(AuthData.nt, 64); AuthData.ks3 = AuthData.at_enc ^ prng_successor(AuthData.nt, 96); mfLastKey = GetCrypto1ProbableKey(&AuthData); - PrintAndLogEx(NORMAL, " | | * |%49s %012"PRIx64" prng %s | |", - "key", + PrintAndLogEx(NORMAL, " | | * |%49s %012"PRIx64" prng %s | |", + "key", mfLastKey, validate_prng_nonce(AuthData.nt) ? _GREEN_(WEAK): _YELLOW_(HARD)); - + AuthData.first_auth = false; traceCrypto1 = lfsr_recovery64(AuthData.ks2, AuthData.ks3); @@ -704,7 +704,7 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes traceCrypto1 = lfsr_recovery64(AuthData.ks2, AuthData.ks3); }; } - + // check default keys if (!traceCrypto1) { for (int i = 0; i < MIFARE_DEFAULTKEYS_SIZE; i++){ @@ -717,10 +717,10 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes }; } } - + // nested if (!traceCrypto1 && validate_prng_nonce(AuthData.nt)) { - uint32_t ntx = prng_successor(AuthData.nt, 90); + uint32_t ntx = prng_successor(AuthData.nt, 90); for (int i = 0; i < 16383; i++) { ntx = prng_successor(ntx, 1); if (NTParityChk(&AuthData, ntx)){ @@ -729,15 +729,15 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes uint32_t ks3 = AuthData.at_enc ^ prng_successor(ntx, 96); struct Crypto1State *pcs = lfsr_recovery64(ks2, ks3); memcpy(mfData, cmd, cmdsize); - mf_crypto1_decrypt(pcs, mfData, cmdsize, 0); + mf_crypto1_decrypt(pcs, mfData, cmdsize, 0); crypto1_destroy(pcs); - + if (CheckCrypto1Parity(cmd, cmdsize, mfData, parity) && check_crc(CRC_14443_A, mfData, cmdsize)) { AuthData.ks2 = ks2; AuthData.ks3 = ks3; AuthData.nt = ntx; mfLastKey = GetCrypto1ProbableKey(&AuthData); - PrintAndLogEx(NORMAL, " | | * | nested probable key:%012"PRIx64" ks2:%08x ks3:%08x | |", + PrintAndLogEx(NORMAL, " | | * | nested probable key:%012"PRIx64" ks2:%08x ks3:%08x | |", mfLastKey, AuthData.ks2, AuthData.ks3); @@ -745,10 +745,10 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes traceCrypto1 = lfsr_recovery64(AuthData.ks2, AuthData.ks3); break; } - } + } } } - + //hardnested if (!traceCrypto1) { PrintAndLogEx(NORMAL, "hardnested not implemented. uid:%x nt:%x ar_enc:%x at_enc:%x\n", AuthData.uid, AuthData.nt, AuthData.ar_enc, AuthData.at_enc); @@ -780,13 +780,13 @@ bool DecodeMifareData(uint8_t *cmd, uint8_t cmdsize, uint8_t *parity, bool isRes } MifareAuthState = masData; } - + if (MifareAuthState == masData && traceCrypto1) { memcpy(mfData, cmd, cmdsize); mf_crypto1_decrypt(traceCrypto1, mfData, cmdsize, 0); *mfDataLen = cmdsize; } - + return *mfDataLen > 0; } @@ -797,7 +797,7 @@ bool NTParityChk(TAuthData *ad, uint32_t ntx) { (oddparity8(ntx >> 24 & 0xff) ^ (ntx >> 16 & 0x01) ^ ((ad->nt_enc_par >> 7) & 0x01) ^ (ad->nt_enc >> 16 & 0x01)) ) return false; - + uint32_t ar = prng_successor(ntx, 64); if ( (oddparity8(ar >> 8 & 0xff) ^ (ar & 0x01) ^ ((ad->ar_enc_par >> 5) & 0x01) ^ (ad->ar_enc & 0x01)) || @@ -814,14 +814,14 @@ bool NTParityChk(TAuthData *ad, uint32_t ntx) { (oddparity8(at >> 24 & 0xff) ^ (at >> 16 & 0x01) ^ ((ad->at_enc_par >> 7) & 0x01) ^ (ad->at_enc >> 16 & 0x01)) ) return false; - + return true; } bool NestedCheckKey(uint64_t key, TAuthData *ad, uint8_t *cmd, uint8_t cmdsize, uint8_t *parity) { uint8_t buf[32] = {0}; struct Crypto1State *pcs; - + AuthData.ks2 = 0; AuthData.ks3 = 0; @@ -843,13 +843,13 @@ bool NestedCheckKey(uint64_t key, TAuthData *ad, uint8_t *cmd, uint8_t cmdsize, memcpy(buf, cmd, cmdsize); mf_crypto1_decrypt(pcs, buf, cmdsize, 0); crypto1_destroy(pcs); - + if (!CheckCrypto1Parity(cmd, cmdsize, buf, parity)) return false; - if (!check_crc(CRC_14443_A, buf, cmdsize)) + if (!check_crc(CRC_14443_A, buf, cmdsize)) return false; - + AuthData.nt = nt1; AuthData.ks2 = AuthData.ar_enc ^ ar; AuthData.ks3 = AuthData.at_enc ^ at; @@ -865,7 +865,7 @@ bool CheckCrypto1Parity(uint8_t *cmd_enc, uint8_t cmdsize, uint8_t *cmd, uint8_t } // Another implementation of mfkey64 attack, more "valid" than "probable" -// +// uint64_t GetCrypto1ProbableKey(TAuthData *ad) { struct Crypto1State *revstate = lfsr_recovery64(ad->ks2, ad->ks3); lfsr_rollback_word(revstate, 0, 0); diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index da027aad6..fa1f13102 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -17,7 +17,7 @@ #define MFBLOCK_SIZE 16 #define MIFARE_4K_MAXBLOCK 256 -#define MIFARE_2K_MAXBLOCK 128 +#define MIFARE_2K_MAXBLOCK 128 #define MIFARE_1K_MAXBLOCK 64 #define MIFARE_MINI_MAXBLOCK 20 @@ -77,14 +77,14 @@ int usage_hf14_mf1ksim(void){ PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf sim u 0a0a0a0a"); PrintAndLogEx(NORMAL, " hf mf sim u 11223344556677"); - PrintAndLogEx(NORMAL, " hf mf sim u 112233445566778899AA"); - PrintAndLogEx(NORMAL, " hf mf sim u 11223344 i x"); + PrintAndLogEx(NORMAL, " hf mf sim u 112233445566778899AA"); + PrintAndLogEx(NORMAL, " hf mf sim u 11223344 i x"); return 0; } int usage_hf14_dbg(void){ PrintAndLogEx(NORMAL, "Usage: hf mf dbg [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h this help"); + PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, " (Optional) see list for valid levels"); PrintAndLogEx(NORMAL, " 0 - no debug messages"); PrintAndLogEx(NORMAL, " 1 - error messages"); @@ -134,7 +134,7 @@ int usage_hf14_hardnested(void){ PrintAndLogEx(NORMAL, " or hf mf hardnested r [known target key]"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h this help"); + PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, " w acquire nonces and UID, and write them to binary file with default name hf-mf--nonces.bin"); PrintAndLogEx(NORMAL, " s slower acquisition (required by some non standard cards)"); PrintAndLogEx(NORMAL, " r read hf-mf--nonces.bin if tag present, otherwise read nonces.bin, then start attack"); @@ -147,7 +147,7 @@ int usage_hf14_hardnested(void){ PrintAndLogEx(NORMAL, " i a = AVX"); PrintAndLogEx(NORMAL, " i s = SSE2"); PrintAndLogEx(NORMAL, " i m = MMX"); - PrintAndLogEx(NORMAL, " i n = none (use CPU regular instruction set)"); + PrintAndLogEx(NORMAL, " i n = none (use CPU regular instruction set)"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf hardnested 0 A FFFFFFFFFFFF 4 A"); @@ -163,7 +163,7 @@ int usage_hf14_hardnested(void){ int usage_hf14_chk(void){ PrintAndLogEx(NORMAL, "Usage: hf mf chk [h] |<*card memory> [t|d] [] []"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h this help"); + PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, " * all sectors based on card memory, other values then below defaults to 1k"); PrintAndLogEx(NORMAL, " 0 - MINI(320 bytes)"); PrintAndLogEx(NORMAL, " 1 - 1K"); @@ -182,7 +182,7 @@ int usage_hf14_chk_fast(void){ PrintAndLogEx(NORMAL, "This is a improved checkkeys method speedwise. It checks Mifare Classic tags sector keys against a dictionary file with keys"); PrintAndLogEx(NORMAL, "Usage: hf mf fchk [h] [t|d|f] [] []"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h this help"); + PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, " all sectors based on card memory, other values than below defaults to 1k"); PrintAndLogEx(NORMAL, " 0 - MINI(320 bytes)"); PrintAndLogEx(NORMAL, " 1 - 1K "); @@ -204,7 +204,7 @@ int usage_hf14_chk_fast(void){ int usage_hf14_keybrute(void){ PrintAndLogEx(NORMAL, "J_Run's 2nd phase of multiple sector nested authentication key recovery"); PrintAndLogEx(NORMAL, "You have a known 4 last bytes of a key recovered with mf_nonce_brute tool."); - PrintAndLogEx(NORMAL, "First 2 bytes of key will be bruteforced"); + PrintAndLogEx(NORMAL, "First 2 bytes of key will be bruteforced"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " ---[ This attack is obsolete, try hardnested instead ]---"); PrintAndLogEx(NORMAL, ""); @@ -262,7 +262,7 @@ int usage_hf14_eclr(void){ int usage_hf14_eset(void){ PrintAndLogEx(NORMAL, "Usage: hf mf eset "); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " hf mf eset 1 000102030405060708090a0b0c0d0e0f "); + PrintAndLogEx(NORMAL, " hf mf eset 1 000102030405060708090a0b0c0d0e0f "); return 0; } int usage_hf14_eload(void){ @@ -272,7 +272,7 @@ int usage_hf14_eload(void){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf eload filename"); - PrintAndLogEx(NORMAL, " hf mf eload 4 filename"); + PrintAndLogEx(NORMAL, " hf mf eload 4 filename"); return 0; } int usage_hf14_esave(void){ @@ -283,7 +283,7 @@ int usage_hf14_esave(void){ PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf esave "); PrintAndLogEx(NORMAL, " hf mf esave 4"); - PrintAndLogEx(NORMAL, " hf mf esave 4 filename"); + PrintAndLogEx(NORMAL, " hf mf esave 4 filename"); return 0; } int usage_hf14_ecfill(void){ @@ -303,7 +303,7 @@ int usage_hf14_ekeyprn(void){ PrintAndLogEx(NORMAL, " [card memory]: 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " hf mf ekeyprn 1"); + PrintAndLogEx(NORMAL, " hf mf ekeyprn 1"); return 0; } @@ -324,7 +324,7 @@ int usage_hf14_csetuid(void){ } int usage_hf14_csetblk(void){ PrintAndLogEx(NORMAL, "Set block data for magic Chinese card. Only works with magic cards"); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: hf mf csetblk [h] [w]"); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h this help"); @@ -349,7 +349,7 @@ int usage_hf14_cload(void){ PrintAndLogEx(NORMAL, " load card with data from eml file"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf cload mydump"); - PrintAndLogEx(NORMAL, " hf mf cload e"); + PrintAndLogEx(NORMAL, " hf mf cload e"); return 0; } int usage_hf14_cgetblk(void){ @@ -358,9 +358,9 @@ int usage_hf14_cgetblk(void){ PrintAndLogEx(NORMAL, "Usage: hf mf cgetblk [h] "); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h this help"); - PrintAndLogEx(NORMAL, " block number"); + PrintAndLogEx(NORMAL, " block number"); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " hf mf cgetblk 1"); + PrintAndLogEx(NORMAL, " hf mf cgetblk 1"); return 0; } int usage_hf14_cgetsc(void){ @@ -382,7 +382,7 @@ int usage_hf14_csave(void){ PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h this help"); PrintAndLogEx(NORMAL, " e save data to emulator memory"); - PrintAndLogEx(NORMAL, " u save data to file, use carduid as filename"); + PrintAndLogEx(NORMAL, " u save data to file, use carduid as filename"); PrintAndLogEx(NORMAL, " card memory 0 = 320 bytes (Mifare Mini), 1 = 1K (default), 2 = 2K, 4 = 4K"); PrintAndLogEx(NORMAL, " o save data to file"); PrintAndLogEx(NORMAL, ""); @@ -394,7 +394,7 @@ int usage_hf14_csave(void){ } int usage_hf14_nack(void) { PrintAndLogEx(NORMAL, "Test a mifare classic based card for the NACK bug."); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: hf mf nack [h] [v]"); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h this help"); @@ -414,7 +414,7 @@ int GetHFMF14AUID(uint8_t *uid, int *uidlen) { DropField(); return 0; } - + iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); memcpy(uid, card.uid, card.uidlen * sizeof(uint8_t)); @@ -426,15 +426,15 @@ char * GenerateFilename(const char *prefix, const char *suffix){ uint8_t uid[10] = {0,0,0,0,0,0,0,0,0,0}; int uidlen=0; char * fptr = calloc (sizeof (char) * (strlen(prefix) + strlen(suffix)) + sizeof(uid)*2 + 1, sizeof(uint8_t)); - + GetHFMF14AUID(uid, &uidlen); if (!uidlen) { PrintAndLogEx(WARNING, "No tag found."); free(fptr); return NULL; } - - strcpy(fptr, prefix); + + strcpy(fptr, prefix); FillFileNameByUID(fptr, uid, suffix, uidlen); return fptr; } @@ -442,12 +442,12 @@ char * GenerateFilename(const char *prefix, const char *suffix){ int CmdHF14AMfDarkside(const char *Cmd) { uint8_t blockno = 0, key_type = MIFARE_AUTH_KEYA; uint64_t key = 0; - - char cmdp = tolower(param_getchar(Cmd, 0)); + + char cmdp = tolower(param_getchar(Cmd, 0)); if ( cmdp == 'h' ) return usage_hf14_mifare(); - - blockno = param_get8(Cmd, 0); - + + blockno = param_get8(Cmd, 0); + cmdp = tolower(param_getchar(Cmd, 1)); if (cmdp == 'b') key_type = MIFARE_AUTH_KEYB; @@ -479,7 +479,7 @@ int CmdHF14AMfWrBl(const char *Cmd) { PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf wrbl 0 A FFFFFFFFFFFF 000102030405060708090A0B0C0D0E0F"); return 0; - } + } blockNo = param_get8(Cmd, 0); cmdp = tolower(param_getchar(Cmd, 1)); @@ -487,23 +487,23 @@ int CmdHF14AMfWrBl(const char *Cmd) { PrintAndLogEx(NORMAL, "Key type must be A or B"); return 1; } - - if (cmdp != 'a') + + if (cmdp != 'a') keyType = 1; - + if (param_gethex(Cmd, 2, key, 12)) { PrintAndLogEx(NORMAL, "Key must include 12 HEX symbols"); return 1; } - + if (param_gethex(Cmd, 3, bldata, 32)) { PrintAndLogEx(NORMAL, "Block data must include 32 HEX symbols"); return 1; } - + PrintAndLogEx(NORMAL, "--block no:%d, key type:%c, key:%s", blockNo, keyType?'B':'A', sprint_hex(key, 6)); PrintAndLogEx(NORMAL, "--data: %s", sprint_hex(bldata, 16)); - + UsbCommand c = {CMD_MIFARE_WRITEBL, {blockNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); memcpy(c.d.asBytes + 10, bldata, 16); @@ -532,24 +532,24 @@ int CmdHF14AMfRdBl(const char *Cmd) { PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf rdbl 0 A FFFFFFFFFFFF "); return 0; - } - + } + blockNo = param_get8(Cmd, 0); cmdp = tolower(param_getchar(Cmd, 1)); if (cmdp == 0x00) { PrintAndLogEx(NORMAL, "Key type must be A or B"); return 1; } - - if (cmdp != 'a') + + if (cmdp != 'a') keyType = 1; - + if (param_gethex(Cmd, 2, key, 12)) { PrintAndLogEx(NORMAL, "Key must include 12 HEX symbols"); return 1; } PrintAndLogEx(NORMAL, "--block no:%d, key type:%c, key:%s ", blockNo, keyType?'B':'A', sprint_hex(key, 6)); - + UsbCommand c = {CMD_MIFARE_READBL, {blockNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); clearCommandBuffer(); @@ -581,7 +581,7 @@ int CmdHF14AMfRdBl(const char *Cmd) { PrintAndLogEx(WARNING, "Command execute timeout"); return 2; } - + return 0; } @@ -599,29 +599,29 @@ int CmdHF14AMfRdSc(const char *Cmd) { PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mf rdsc 0 A FFFFFFFFFFFF "); return 0; - } - + } + sectorNo = param_get8(Cmd, 0); if (sectorNo > MIFARE_4K_MAXSECTOR ) { PrintAndLogEx(NORMAL, "Sector number must be less than 40"); return 1; } - + cmdp = tolower(param_getchar(Cmd, 1)); if (cmdp != 'a' && cmdp != 'b') { PrintAndLogEx(NORMAL, "Key type must be A or B"); return 1; } - - if (cmdp != 'a') + + if (cmdp != 'a') keyType = 1; - + if (param_gethex(Cmd, 2, key, 12)) { PrintAndLogEx(NORMAL, "Key must include 12 HEX symbols"); return 1; } PrintAndLogEx(NORMAL, "--sector no:%d key type:%c key:%s ", sectorNo, keyType?'B':'A', sprint_hex(key, 6)); - + UsbCommand c = {CMD_MIFARE_READSC, {sectorNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); clearCommandBuffer(); @@ -639,7 +639,7 @@ int CmdHF14AMfRdSc(const char *Cmd) { PrintAndLogEx(NORMAL, "data : %s", sprint_hex(data + i * 16, 16)); } PrintAndLogEx(NORMAL, "trailer: %s", sprint_hex(data + (sectorNo<32?3:15) * 16, 16)); - + PrintAndLogEx(NORMAL, "Trailer decoded:"); int bln = mfFirstBlockOfSector(sectorNo); int blinc = (mfNumBlocksPerSector(sectorNo) > 4) ? 5 : 1; @@ -667,10 +667,10 @@ uint16_t NumOfBlocks(char card){ } uint8_t NumOfSectors(char card){ switch(card){ - case '0' : return MIFARE_MINI_MAXSECTOR; - case '1' : return MIFARE_1K_MAXSECTOR; - case '2' : return MIFARE_2K_MAXSECTOR; - case '4' : return MIFARE_4K_MAXSECTOR; + case '0' : return MIFARE_MINI_MAXSECTOR; + case '1' : return MIFARE_1K_MAXSECTOR; + case '2' : return MIFARE_2K_MAXSECTOR; + case '4' : return MIFARE_4K_MAXSECTOR; default : return MIFARE_1K_MAXSECTOR; } } @@ -700,27 +700,27 @@ int CmdHF14AMfDump(const char *Cmd) { uint8_t carddata[256][16]; uint8_t numSectors = 16; uint8_t cmdp = 0; - + char keyFilename[FILE_PATH_SIZE] = {0}; char dataFilename[FILE_PATH_SIZE]; char * fptr; - + memset(keyFilename, 0, sizeof(keyFilename)); memset(dataFilename, 0, sizeof(dataFilename)); - - FILE *f; + + FILE *f; UsbCommand resp; - + while(param_getchar(Cmd, cmdp) != 0x00) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_hf14_dump(); case 'k': - param_getstr(Cmd, cmdp+1, keyFilename, FILE_PATH_SIZE); + param_getstr(Cmd, cmdp+1, keyFilename, FILE_PATH_SIZE); cmdp += 2; break; case 'f': - param_getstr(Cmd, cmdp+1, dataFilename, FILE_PATH_SIZE); + param_getstr(Cmd, cmdp+1, dataFilename, FILE_PATH_SIZE); cmdp += 2; break; default: @@ -736,9 +736,9 @@ int CmdHF14AMfDump(const char *Cmd) { if ( keyFilename[0] == 0x00 ) { fptr = GenerateFilename("hf-mf-", "-key.bin"); - if (fptr == NULL) + if (fptr == NULL) return 1; - + strcpy(keyFilename, fptr); } @@ -746,7 +746,7 @@ int CmdHF14AMfDump(const char *Cmd) { PrintAndLogEx(WARNING, "Could not find file " _YELLOW_(%s), keyFilename); return 1; } - + // Read keys A from file size_t bytes_read; for (sectorNo=0; sectorNo= FILE_PATH_SIZE ) { PrintAndLogEx(FAILED, "Filename too long"); continue; } - + f = fopen( filename, "r"); if ( !f ){ PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename); continue; } - + // read file while( fgets(buf, sizeof(buf), f) ){ if (strlen(buf) < 12 || buf[11] == '\n') continue; - + while (fgetc(f) != '\n' && !feof(f)) ; //goto next line - + if( buf[0]=='#' ) continue; //The line start with # is comment, skip if (!isxdigit(buf[0])){ PrintAndLogEx(FAILED, "File content error. '" _YELLOW_(%s)"' must include 12 HEX symbols", buf); continue; } - + buf[12] = 0; if ( keyitems - keycnt < 2) { p = realloc(keyBlock, 6 * (keyitems += 64)); @@ -1600,7 +1600,7 @@ int CmdHF14AMfChk_fast(const char *Cmd) { PrintAndLogEx(SUCCESS, "Loaded %2d keys from " _YELLOW_(%s), keycnt, filename); } } - + if (keycnt == 0 && !use_flashmemory) { PrintAndLogEx(SUCCESS, "No key specified, trying default keys"); for (;keycnt < MIFARE_DEFAULTKEYS_SIZE; keycnt++) @@ -1608,17 +1608,17 @@ int CmdHF14AMfChk_fast(const char *Cmd) { (keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2], (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5]); } - + // // initialize storage for found keys e_sector = calloc(sectorsCnt, sizeof(sector_t)); if (e_sector == NULL) { free(keyBlock); return 1; } - + uint32_t chunksize = keycnt > (USB_CMD_DATA_SIZE/6) ? (USB_CMD_DATA_SIZE/6) : keycnt; bool firstChunk = true, lastChunk = false; - + // time uint64_t t1 = msclock(); @@ -1626,31 +1626,31 @@ int CmdHF14AMfChk_fast(const char *Cmd) { PrintAndLogEx(SUCCESS, "Using dictionary in flash memory"); mfCheckKeys_fast( sectorsCnt, true, true, 1, 0, keyBlock, e_sector, use_flashmemory); } else { - + // strategys. 1= deep first on sector 0 AB, 2= width first on all sectors for (uint8_t strategy = 1; strategy < 3; strategy++) { PrintAndLogEx(SUCCESS, "Running strategy %u", strategy); - // main keychunk loop + // main keychunk loop for (uint32_t i = 0; i < keycnt; i += chunksize) { - + if (ukbhit()) { int gc = getchar(); (void)gc; PrintAndLogEx(WARNING, "\naborted via keyboard!\n"); goto out; } - + uint32_t size = ((keycnt - i) > chunksize) ? chunksize : keycnt - i; - + // last chunk? if ( size == keycnt - i) lastChunk = true; - + int res = mfCheckKeys_fast( sectorsCnt, firstChunk, lastChunk, strategy, size, keyBlock + (i * 6), e_sector, false); if ( firstChunk ) firstChunk = false; - + // all keys, aborted if ( res == 0 || res == 2 ) goto out; @@ -1659,25 +1659,25 @@ int CmdHF14AMfChk_fast(const char *Cmd) { lastChunk = false; } // end strategy } -out: +out: t1 = msclock() - t1; PrintAndLogEx(SUCCESS, "Time in checkkeys (fast): %.1fs\n", (float)(t1/1000.0)); // check.. uint8_t found_keys = 0; for (uint8_t i = 0; i < sectorsCnt; ++i) { - - if ( e_sector[i].foundKey[0] ) + + if ( e_sector[i].foundKey[0] ) found_keys++; - + if ( e_sector[i].foundKey[1] ) found_keys++; } - + if ( found_keys == 0 ) { PrintAndLogEx(WARNING, "No keys found"); } else { - + printKeyTable( sectorsCnt, e_sector ); if (transferToEml) { @@ -1692,21 +1692,21 @@ out: } PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); } - + if (createDumpFile) { fptr = GenerateFilename("hf-mf-", "-key.bin"); - if (fptr == NULL) + if (fptr == NULL) return 1; FILE *fkeys = fopen(fptr, "wb"); - if (fkeys == NULL) { + if (fkeys == NULL) { PrintAndLogEx(WARNING, "Could not create file " _YELLOW_(%s), fptr); free(keyBlock); free(e_sector); return 1; } PrintAndLogEx(SUCCESS, "Printing keys to binary file " _YELLOW_(%s)"...", fptr); - + for (i=0; i 0xffffffffffff has been inserted for unknown keys.", fptr); - } + PrintAndLogEx(SUCCESS, "Found keys have been dumped to " _YELLOW_(%s)" --> 0xffffffffffff has been inserted for unknown keys.", fptr); + } } - + free(keyBlock); free(e_sector); PrintAndLogEx(NORMAL, ""); @@ -1743,12 +1743,12 @@ int CmdHF14AMfChk(const char *Cmd) { uint8_t SectorsCnt = 1; uint8_t keyType = 0; uint32_t keyitems = MIFARE_DEFAULTKEYS_SIZE; - uint64_t key64 = 0; + uint64_t key64 = 0; uint8_t tempkey[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; char *fptr; int clen = 0; int transferToEml = 0; - int createDumpFile = 0; + int createDumpFile = 0; int i, res, keycnt = 0; keyBlock = calloc(MIFARE_DEFAULTKEYS_SIZE, 6); @@ -1756,18 +1756,18 @@ int CmdHF14AMfChk(const char *Cmd) { for (int cnt = 0; cnt < MIFARE_DEFAULTKEYS_SIZE; cnt++) num_to_bytes(g_mifare_default_keys[cnt], 6, (uint8_t*)(keyBlock + cnt * 6)); - + if (param_getchar(Cmd, 0)=='*') { blockNo = 3; SectorsCnt = NumOfSectors( param_getchar(Cmd+1, 0) ); } else { blockNo = param_get8(Cmd, 0); } - + ctmp = tolower(param_getchar(Cmd, 1)); clen = param_getlength(Cmd, 1); if (clen == 1) { - switch (ctmp) { + switch (ctmp) { case 'a': keyType = 0; break; @@ -1788,9 +1788,9 @@ int CmdHF14AMfChk(const char *Cmd) { ctmp = tolower(param_getchar(Cmd, i)); clen = param_getlength(Cmd, i); - + if (clen == 12) { - + if ( param_gethex(Cmd, i, keyBlock + 6 * keycnt, 12) ){ PrintAndLogEx(FAILED, "not hex, skipping"); continue; @@ -1816,20 +1816,20 @@ int CmdHF14AMfChk(const char *Cmd) { PrintAndLogEx(FAILED, "File name too long"); continue; } - + f = fopen( filename , "r"); if ( !f ) { PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename); continue; } - + // load keys from dictionary file while( fgets(buf, sizeof(buf), f) ){ if (strlen(buf) < 12 || buf[11] == '\n') continue; - + while (fgetc(f) != '\n' && !feof(f)) ; //goto next line - + if( buf[0]=='#' ) continue; //The line start with # is comment, skip // codesmell, only checks first char? @@ -1837,7 +1837,7 @@ int CmdHF14AMfChk(const char *Cmd) { PrintAndLogEx(FAILED, "File content error. '" _YELLOW_(%s)"' must include 12 HEX symbols",buf); continue; } - + buf[12] = 0; if ( keyitems - keycnt < 2) { @@ -1860,7 +1860,7 @@ int CmdHF14AMfChk(const char *Cmd) { PrintAndLogEx(SUCCESS, "Loaded %2d keys from " _YELLOW_(%s), keycnt, filename); } } - + if (keycnt == 0) { PrintAndLogEx(INFO, "No key specified, trying default keys"); for (;keycnt < MIFARE_DEFAULTKEYS_SIZE; keycnt++) @@ -1868,7 +1868,7 @@ int CmdHF14AMfChk(const char *Cmd) { (keyBlock + 6*keycnt)[0],(keyBlock + 6*keycnt)[1], (keyBlock + 6*keycnt)[2], (keyBlock + 6*keycnt)[3], (keyBlock + 6*keycnt)[4], (keyBlock + 6*keycnt)[5], 6); } - + // initialize storage for found keys e_sector = calloc(SectorsCnt, sizeof(sector_t)); if (e_sector == NULL) { @@ -1883,62 +1883,62 @@ int CmdHF14AMfChk(const char *Cmd) { e_sector[i].foundKey[0] = false; e_sector[i].foundKey[1] = false; } - - + + uint8_t trgKeyType = 0; uint32_t max_keys = keycnt > (USB_CMD_DATA_SIZE/6) ? (USB_CMD_DATA_SIZE/6) : keycnt; - + // time uint64_t t1 = msclock(); - + // check keys. for (trgKeyType = (keyType==2)?0:keyType; trgKeyType < 2; (keyType==2) ? (++trgKeyType) : (trgKeyType=2) ) { int b = blockNo; for (int i = 0; i < SectorsCnt; ++i) { - + // skip already found keys. if (e_sector[i].foundKey[trgKeyType]) continue; - + for (uint32_t c = 0; c < keycnt; c += max_keys) { - + printf("."); fflush(stdout); if (ukbhit()) { int gc = getchar(); (void)gc; PrintAndLogEx(INFO, "\naborted via keyboard!\n"); goto out; } - + uint32_t size = keycnt-c > max_keys ? max_keys : keycnt-c; - + res = mfCheckKeys(b, trgKeyType, true, size, &keyBlock[6*c], &key64); if (!res) { e_sector[i].Key[trgKeyType] = key64; e_sector[i].foundKey[trgKeyType] = true; break; } - + } - b < 127 ? ( b +=4 ) : ( b += 16 ); + b < 127 ? ( b +=4 ) : ( b += 16 ); } } t1 = msclock() - t1; PrintAndLogEx(SUCCESS, "\nTime in checkkeys: %.0f seconds\n", (float)t1/1000.0); - + // 20160116 If Sector A is found, but not Sector B, try just reading it of the tag? if ( keyType != 1 ) { PrintAndLogEx(INFO, "testing to read key B..."); for (i = 0; i < SectorsCnt; i++) { // KEY A but not KEY B if ( e_sector[i].foundKey[0] && !e_sector[i].foundKey[1] ) { - + uint8_t sectrail = (FirstBlockOfSector(i) + NumBlocksPerSector(i) - 1); - + PrintAndLogEx(NORMAL, "Reading block %d", sectrail); - + UsbCommand c = {CMD_MIFARE_READBL, {sectrail, 0, 0}}; num_to_bytes(e_sector[i].Key[0], 6, c.d.asBytes); // KEY A clearCommandBuffer(); @@ -1946,7 +1946,7 @@ int CmdHF14AMfChk(const char *Cmd) { UsbCommand resp; if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500)) continue; - + uint8_t isOK = resp.arg[0] & 0xff; if (!isOK) continue; @@ -1962,10 +1962,10 @@ int CmdHF14AMfChk(const char *Cmd) { } out: - + //print keys printKeyTable( SectorsCnt, e_sector ); - + if (transferToEml) { uint8_t block[16] = {0x00}; for (uint8_t i = 0; i < SectorsCnt; ++i ) { @@ -1978,24 +1978,24 @@ out: } PrintAndLogEx(SUCCESS, "Found keys have been transferred to the emulator memory"); } - + if (createDumpFile) { fptr = GenerateFilename("hf-mf-", "-key.bin"); if (fptr == NULL) { free(keyBlock); - free(e_sector); + free(e_sector); return 1; } FILE *fkeys = fopen(fptr, "wb"); - if (fkeys == NULL) { + if (fkeys == NULL) { PrintAndLogEx(WARNING, "Could not create file " _YELLOW_(%s), fptr); free(keyBlock); free(e_sector); return 1; } PrintAndLogEx(INFO, "Printing keys to binary file " _YELLOW_(%s)"...", fptr); - + for( i=0; i>1) , exitAfterNReads @@ -2141,12 +2141,12 @@ int CmdHF14AMf1kSim(const char *Cmd) { memcpy(c.d.asBytes, uid, sizeof(uid)); clearCommandBuffer(); SendCommand(&c); - UsbCommand resp; + UsbCommand resp; if(flags & FLAG_INTERACTIVE) { PrintAndLogEx(INFO, "Press pm3-button or send another cmd to abort simulation"); - while( !ukbhit() ){ + while( !ukbhit() ){ if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) continue; if ( !(flags & FLAG_NR_AR_ATTACK) ) break; if ( (resp.arg[0] & 0xffff) != CMD_SIMULATE_MIFARE_CARD ) break; @@ -2165,7 +2165,7 @@ int CmdHF14AMfSniff(const char *Cmd){ //bool wantSaveToEml = false; TODO bool wantSaveToEmlFile = false; - //var + //var int res = 0, len = 0, blockLen = 0; int pckNum = 0, num = 0; uint8_t sak = 0; @@ -2177,12 +2177,12 @@ int CmdHF14AMfSniff(const char *Cmd){ uint16_t bufsize = 0; uint8_t *bufPtr = NULL; uint16_t traceLen = 0; - + memset(uid, 0x00, sizeof(uid)); - + char ctmp = tolower(param_getchar(Cmd, 0)); if ( ctmp == 'h') return usage_hf14_sniff(); - + for (int i = 0; i < 4; i++) { ctmp = tolower(param_getchar(Cmd, i)); if (ctmp == 'l') wantLogToFile = true; @@ -2190,7 +2190,7 @@ int CmdHF14AMfSniff(const char *Cmd){ //if (ctmp == 'e') wantSaveToEml = true; TODO if (ctmp == 'f') wantSaveToEmlFile = true; } - + PrintAndLogEx(NORMAL, "-------------------------------------------------------------------------\n"); PrintAndLogEx(NORMAL, "Executing mifare sniffing command. \n"); PrintAndLogEx(NORMAL, "Press the key on the proxmark3 device to abort both proxmark3 and client.\n"); @@ -2202,7 +2202,7 @@ int CmdHF14AMfSniff(const char *Cmd){ SendCommand(&c); UsbCommand resp; - + // wait cycle while (true) { printf("."); fflush(stdout); @@ -2211,11 +2211,11 @@ int CmdHF14AMfSniff(const char *Cmd){ PrintAndLogEx(INFO, "\naborted via keyboard!\n"); break; } - + if ( !WaitForResponseTimeout(CMD_ACK, &resp, 2000) ) { continue; } - + res = resp.arg[0] & 0xff; traceLen = resp.arg[1]; len = resp.arg[2]; @@ -2234,7 +2234,7 @@ int CmdHF14AMfSniff(const char *Cmd){ p = calloc(traceLen, sizeof(uint8_t)); else // need more memory p = realloc(buf, traceLen); - + if (p == NULL) { PrintAndLogEx(FAILED, "Cannot allocate memory for trace"); free(buf); @@ -2268,8 +2268,8 @@ int CmdHF14AMfSniff(const char *Cmd){ isTag = false; } bufPtr += 2; - - // the uid identification package + + // the uid identification package // 0xFF 0xFF xx xx xx xx xx xx xx xx xx xx aa aa cc 0xFF 0xFF // x = uid, a = atqa, c = sak if ((len == 17) && (bufPtr[0] == 0xff) && (bufPtr[1] == 0xff) && (bufPtr[15] == 0xff) && (bufPtr[16] == 0xff)) { @@ -2281,25 +2281,25 @@ int CmdHF14AMfSniff(const char *Cmd){ default: uid_len = 4; break; } sak = bufPtr[14]; - PrintAndLogEx(SUCCESS, "UID %s | ATQA %02x %02x | SAK 0x%02x", + PrintAndLogEx(SUCCESS, "UID %s | ATQA %02x %02x | SAK 0x%02x", sprint_hex(uid, uid_len), - atqa[1], - atqa[0], + atqa[1], + atqa[0], sak); if (wantLogToFile || wantDecrypt) { FillFileNameByUID(logHexFileName, uid, ".log", uid_len); AddLogCurrentDT(logHexFileName); PrintAndLogEx(SUCCESS, "Trace saved to %s", logHexFileName); - } + } if (wantDecrypt) mfTraceInit(uid, uid_len, atqa, sak, wantSaveToEmlFile); } else { PrintAndLogEx(NORMAL, "%03d| %s |%s", num, isTag ? "TAG" : "RDR", sprint_hex(bufPtr, len)); - if (wantLogToFile) + if (wantLogToFile) AddLogHex(logHexFileName, isTag ? "TAG| ":"RDR| ", bufPtr, len); - if (wantDecrypt) + if (wantDecrypt) mfTraceDecode(bufPtr, len, wantSaveToEmlFile); - num++; + num++; } bufPtr += len; bufPtr += ((len-1)/8+1); // ignore parity @@ -2316,7 +2316,7 @@ int CmdHF14AMfDbg(const char *Cmd) { char ctmp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) < 1 || ctmp == 'h' ) return usage_hf14_dbg(); - + uint8_t dbgMode = param_get8ex(Cmd, 0, 0, 10); if (dbgMode > 4) return usage_hf14_dbg(); @@ -2330,50 +2330,50 @@ int CmdHF14AMfKeyBrute(const char *Cmd) { uint8_t blockNo = 0, keytype = 0; uint8_t key[6] = {0, 0, 0, 0, 0, 0}; uint64_t foundkey = 0; - - char cmdp = tolower(param_getchar(Cmd, 0)); + + char cmdp = tolower(param_getchar(Cmd, 0)); if ( cmdp == 'h' ) return usage_hf14_keybrute(); - + // block number - blockNo = param_get8(Cmd, 0); - + blockNo = param_get8(Cmd, 0); + // keytype cmdp = tolower(param_getchar(Cmd, 1)); if ( cmdp == 'b' ) keytype = 1; - + // key if (param_gethex(Cmd, 2, key, 12)) return usage_hf14_keybrute(); - + uint64_t t1 = msclock(); - + if (mfKeyBrute( blockNo, keytype, key, &foundkey)) PrintAndLogEx(SUCCESS, "found valid key: %012" PRIx64 " \n", foundkey); else PrintAndLogEx(FAILED, "key not found"); - + t1 = msclock() - t1; PrintAndLogEx(SUCCESS, "\ntime in keybrute: %.0f seconds\n", (float)t1/1000.0); - return 0; + return 0; } void printKeyTable( uint8_t sectorscnt, sector_t *e_sector ){ char strA[12+1] = {0}; - char strB[12+1] = {0}; + char strB[12+1] = {0}; PrintAndLogEx(NORMAL, "|---|----------------|---|----------------|---|"); PrintAndLogEx(NORMAL, "|sec|key A |res|key B |res|"); PrintAndLogEx(NORMAL, "|---|----------------|---|----------------|---|"); for (uint8_t i = 0; i < sectorscnt; ++i) { - + snprintf(strA, sizeof(strA), "------------"); snprintf(strB, sizeof(strB), "------------"); - + if ( e_sector[i].foundKey[0] ) snprintf(strA, sizeof(strA), "%012" PRIx64, e_sector[i].Key[0]); - + if ( e_sector[i].foundKey[1] ) snprintf(strB, sizeof(strB), "%012" PRIx64, e_sector[i].Key[1]); - + PrintAndLogEx(NORMAL, "|%03d| %s | %d | %s | %d |" , i , strA, e_sector[i].foundKey[0] @@ -2388,9 +2388,9 @@ int CmdHF14AMfEGet(const char *Cmd) { uint8_t blockNo = 0; uint8_t data[16] = {0x00}; char c = tolower(param_getchar(Cmd, 0)); - + if (strlen(Cmd) < 1 || c == 'h') return usage_hf14_eget(); - + blockNo = param_get8(Cmd, 0); PrintAndLogEx(NORMAL, ""); @@ -2405,7 +2405,7 @@ int CmdHF14AMfEGet(const char *Cmd) { int CmdHF14AMfEClear(const char *Cmd) { char c = tolower(param_getchar(Cmd, 0)); if (c == 'h') return usage_hf14_eclr(); - + UsbCommand cmd = {CMD_MIFARE_EML_MEMCLR, {0, 0, 0}}; clearCommandBuffer(); SendCommand(&cmd); @@ -2420,14 +2420,14 @@ int CmdHF14AMfESet(const char *Cmd) { if (strlen(Cmd) < 3 || c == 'h') return usage_hf14_eset(); - + blockNo = param_get8(Cmd, 0); - + if (param_gethex(Cmd, 1, memBlock, 32)) { PrintAndLogEx(WARNING, "block data must include 32 HEX symbols"); return 1; } - + // 1 - blocks count return mfEmlSetMem(memBlock, blockNo, 1); } @@ -2440,12 +2440,12 @@ int CmdHF14AMfELoad(const char *Cmd) { uint8_t blockWidth = 16; char c = tolower(param_getchar(Cmd, 0)); - if ( strlen(Cmd) < 2 && c == 'h' ) + if ( strlen(Cmd) < 2 && c == 'h' ) return usage_hf14_eload(); - + switch (c) { case '0' : numBlocks = MIFARE_MINI_MAXBLOCK; break; - case '1' : + case '1' : case '\0': numBlocks = MIFARE_1K_MAXBLOCK; break; case '2' : numBlocks = MIFARE_2K_MAXBLOCK; break; case '4' : numBlocks = MIFARE_4K_MAXBLOCK; break; @@ -2456,11 +2456,11 @@ int CmdHF14AMfELoad(const char *Cmd) { } } uint32_t numblk2 = param_get32ex(Cmd, 2, 0, 10); - if (numblk2 > 0) + if (numblk2 > 0) numBlocks = numblk2; param_getstr(Cmd, nameParamNo, filename, sizeof(filename)); - + uint8_t *data = calloc(4096, sizeof(uint8_t)); size_t datalen = 0; //int res = loadFile(filename, "bin", data, &datalen); @@ -2469,26 +2469,26 @@ int CmdHF14AMfELoad(const char *Cmd) { free(data); return 1; } - + // 64 or 256 blocks. if ( (datalen % blockWidth) != 0 ) { PrintAndLogEx(FAILED, "File content error. Size doesn't match blockwidth "); - free(data); + free(data); return 2; } - + PrintAndLogEx(INFO, "Copying to emulator memory"); - + blockNum = 0; while ( datalen ) { - + if (mfEmlSetMem_xt(data + counter, blockNum, 1, blockWidth)) { PrintAndLogEx(FAILED, "Cant set emul block: %3d", blockNum); free(data); return 3; } printf("."); fflush(stdout); - + blockNum++; counter += blockWidth; datalen -= blockWidth; @@ -2497,7 +2497,7 @@ int CmdHF14AMfELoad(const char *Cmd) { // Ultralight /Ntag if ( blockWidth == 4 ) { - if ((blockNum != numBlocks)) { + if ((blockNum != numBlocks)) { PrintAndLogEx(FAILED, "Warning, Ultralight/Ntag file content, Loaded %d blocks into emulator memory", blockNum); free(data); return 0; @@ -2524,11 +2524,11 @@ int CmdHF14AMfESave(const char *Cmd) { memset(filename, 0, sizeof(filename)); - char c = tolower(param_getchar(Cmd, 0)); + char c = tolower(param_getchar(Cmd, 0)); if (c == 'h') return usage_hf14_esave(); blocks = NumOfBlocks(c); - bytes = blocks * MFBLOCK_SIZE; + bytes = blocks * MFBLOCK_SIZE; dump = calloc(bytes, sizeof(uint8_t)); if (!dump) { @@ -2536,23 +2536,23 @@ int CmdHF14AMfESave(const char *Cmd) { return 1; } memset(dump, 0, bytes); - + PrintAndLogEx(INFO, "downloading from emulator memory"); if (!GetFromDevice( BIG_BUF_EML, dump, bytes, 0, NULL, 2500, false)) { PrintAndLogEx(WARNING, "Fail, transfer from device time-out"); free(dump); return 2; - } + } len = param_getstr(Cmd, nameParamNo, filename, sizeof(filename)); if (len > FILE_PATH_SIZE - 5) len = FILE_PATH_SIZE - 5; - + // user supplied filename? if (len < 1) { fnameptr += sprintf(fnameptr, "hf-mf-"); FillFileNameByUID(fnameptr, dump, "-dump", 4); } - + saveFile(filename, "bin", dump, bytes); saveFileEML(filename, "eml", dump, bytes, MFBLOCK_SIZE); saveFileJSON(filename, "json", jsfCardMemory, dump, bytes); @@ -2564,7 +2564,7 @@ int CmdHF14AMfECFill(const char *Cmd) { uint8_t keyType = 0; uint8_t numSectors = 16; char c = tolower(param_getchar(Cmd, 0)); - + if (strlen(Cmd) < 1 || c == 'h') return usage_hf14_ecfill(); @@ -2596,7 +2596,7 @@ int CmdHF14AMfEKeyPrn(const char *Cmd) { return usage_hf14_ekeyprn(); numSectors = NumOfSectors(c); - + PrintAndLogEx(NORMAL, "|---|----------------|----------------|"); PrintAndLogEx(NORMAL, "|sec|key A |key B |"); PrintAndLogEx(NORMAL, "|---|----------------|----------------|"); @@ -2613,7 +2613,7 @@ int CmdHF14AMfEKeyPrn(const char *Cmd) { return 0; } -// CHINESE MAGIC COMMANDS +// CHINESE MAGIC COMMANDS int CmdHF14AMfCSetUID(const char *Cmd) { uint8_t wipeCard = 0; uint8_t uid[8] = {0x00}; @@ -2624,7 +2624,7 @@ int CmdHF14AMfCSetUID(const char *Cmd) { int res, argi = 0; char ctmp; - if (strlen(Cmd) < 1 || param_getchar(Cmd, argi) == 'h') + if (strlen(Cmd) < 1 || param_getchar(Cmd, argi) == 'h') return usage_hf14_csetuid(); if (param_getchar(Cmd, argi) && param_gethex(Cmd, argi, uid, 8)) @@ -2668,7 +2668,7 @@ int CmdHF14AMfCSetUID(const char *Cmd) { PrintAndLogEx(WARNING, "Can't set UID. error=%d", res); return 1; } - + PrintAndLogEx(SUCCESS, "old UID:%s", sprint_hex(oldUid, 4)); PrintAndLogEx(SUCCESS, "new UID:%s", sprint_hex(uid, 4)); return 0; @@ -2686,11 +2686,11 @@ int CmdHF14AMfCSetBlk(const char *Cmd) { blockNo = param_get8(Cmd, 0); if (param_gethex(Cmd, 1, block, 32)) return usage_hf14_csetblk(); - + ctmp = tolower(param_getchar(Cmd, 2)); if (ctmp == 'w') params |= MAGIC_WIPE; - + PrintAndLogEx(NORMAL, "--block number:%2d data:%s", blockNo, sprint_hex(block, 16)); res = mfCSetBlock(blockNo, block, NULL, params); @@ -2709,7 +2709,7 @@ int CmdHF14AMfCLoad(const char *Cmd) { bool fillFromJson = false; bool fillFromBin = false; char fileName[50] = {0}; - + char ctmp = tolower(param_getchar(Cmd, 0)); if ( param_getlength(Cmd, 0) == 1 ) { if (ctmp == 'h' || ctmp == 0x00) return usage_hf14_cload(); @@ -2721,7 +2721,7 @@ int CmdHF14AMfCLoad(const char *Cmd) { if (fillFromJson || fillFromBin) param_getstr(Cmd, 1, fileName, sizeof(fileName)); - + if (fillFromEmulator) { for (blockNum = 0; blockNum < 16 * 4; blockNum += 1) { if (mfEmlGetMem(buf8, blockNum, 1)) { @@ -2755,15 +2755,15 @@ int CmdHF14AMfCLoad(const char *Cmd) { res = loadFileEML( Cmd, "eml", data, &datalen); } } - + if ( res ) { if ( data ) free(data); return 1; } - + // PrintAndLogEx(INFO, "DATA | %s", sprint_hex(data+1000, 24) ); - + // 64 or 256blocks. if (datalen != 1024 && datalen != 4096) { @@ -2771,18 +2771,18 @@ int CmdHF14AMfCLoad(const char *Cmd) { free(data); return 2; } - + PrintAndLogEx(INFO, "Copying to magic card"); - + blockNum = 0; while ( datalen ) { - // switch on field and send magic sequence + // switch on field and send magic sequence if (blockNum == 0) flags = MAGIC_INIT + MAGIC_WUPC; - // write + // write if (blockNum == 1) flags = 0; - + // Switch off field. if (blockNum == 16 * 4 - 1) flags = MAGIC_HALT + MAGIC_OFF; @@ -2791,14 +2791,14 @@ int CmdHF14AMfCLoad(const char *Cmd) { free(data); return 3; } - + datalen -= 16; - + printf("."); fflush(stdout); blockNum++; - + // magic card type - mifare 1K - if (blockNum >= MIFARE_1K_MAXBLOCK ) break; + if (blockNum >= MIFARE_1K_MAXBLOCK ) break; } PrintAndLogEx(NORMAL, "\n"); @@ -2808,8 +2808,8 @@ int CmdHF14AMfCLoad(const char *Cmd) { free(data); return 4; } - - PrintAndLogEx(SUCCESS, "Card loaded %d blocks from file", blockNum); + + PrintAndLogEx(SUCCESS, "Card loaded %d blocks from file", blockNum); free(data); return 0; } @@ -2832,9 +2832,9 @@ int CmdHF14AMfCGetBlk(const char *Cmd) { PrintAndLogEx(WARNING, "Can't read block. error=%d", res); return 1; } - + PrintAndLogEx(NORMAL, "data: %s", sprint_hex(data, sizeof(data))); - + if (mfIsSectorTrailer(blockNo)) { PrintAndLogEx(NORMAL, "Trailer decoded:"); PrintAndLogEx(NORMAL, "Key A: %s", sprint_hex_inrow(data, 6)); @@ -2847,7 +2847,7 @@ int CmdHF14AMfCGetBlk(const char *Cmd) { } PrintAndLogEx(NORMAL, "UserData: %s", sprint_hex_inrow(&data[9], 1)); } - + return 0; } @@ -2873,9 +2873,9 @@ int CmdHF14AMfCGetSc(const char *Cmd) { blocks = 16; start = 128 + ( sector - 32 ) * 16; } - + flags = MAGIC_INIT + MAGIC_WUPC; - + for (i = 0; i < blocks; i++) { if (i == 1) flags = 0; if (i == blocks-1) flags = MAGIC_HALT + MAGIC_OFF; @@ -2894,7 +2894,7 @@ int CmdHF14AMfCSave(const char *Cmd) { char filename[FILE_PATH_SIZE]; char * fnameptr = filename; - uint8_t *dump; + uint8_t *dump; bool fillEmulator = false; bool errors = false, hasname = false, useuid = false; int i, len, flags; @@ -2904,7 +2904,7 @@ int CmdHF14AMfCSave(const char *Cmd) { while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { ctmp = tolower(param_getchar(Cmd, cmdp)); - switch (ctmp) { + switch (ctmp) { case 'e': useuid = true; fillEmulator = true; @@ -2924,7 +2924,7 @@ int CmdHF14AMfCSave(const char *Cmd) { case 'u': useuid = true; hasname = true; - cmdp++; + cmdp++; break; case 'o': len = param_getstr(Cmd, cmdp+1, filename, FILE_PATH_SIZE); @@ -2934,9 +2934,9 @@ int CmdHF14AMfCSave(const char *Cmd) { } useuid = false; - hasname = true; + hasname = true; cmdp += 2; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -2945,7 +2945,7 @@ int CmdHF14AMfCSave(const char *Cmd) { } if (!hasname && !fillEmulator) errors = true; - + if (errors || cmdp == 0) return usage_hf14_csave(); dump = calloc(bytes, sizeof(uint8_t)); @@ -2954,27 +2954,27 @@ int CmdHF14AMfCSave(const char *Cmd) { return 1; } memset(dump, 0, bytes); - + flags = MAGIC_INIT + MAGIC_WUPC; for (i = 0; i < numblocks; i++) { if (i == 1) flags = 0; if (i == numblocks - 1) flags = MAGIC_HALT + MAGIC_OFF; - + if (mfCGetBlock(i, dump + (i*MFBLOCK_SIZE), flags)) { PrintAndLogEx(WARNING, "Cant get block: %d", i); free(dump); return 2; } } - + if ( useuid ){ - fnameptr += sprintf(fnameptr, "hf-mf-"); + fnameptr += sprintf(fnameptr, "hf-mf-"); FillFileNameByUID(fnameptr, dump, "-dump", 4); } - + if (fillEmulator) { PrintAndLogEx(INFO, "uploading to emulator memory"); - for (i = 0; i < numblocks; i += 5) { + for (i = 0; i < numblocks; i += 5) { if (mfEmlSetMem(dump + (i*MFBLOCK_SIZE), i, 5)) { PrintAndLogEx(WARNING, "Cant set emul block: %d", i); } @@ -2993,10 +2993,10 @@ int CmdHF14AMfCSave(const char *Cmd) { //needs nt, ar, at, Data to decrypt int CmdHf14AMfDecryptBytes(const char *Cmd){ - + char ctmp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) < 1 || ctmp == 'h') return usage_hf14_decryptbytes(); - + uint32_t nt = param_get32ex(Cmd,0,0,16); uint32_t ar_enc = param_get32ex(Cmd,1,0,16); uint32_t at_enc = param_get32ex(Cmd,2,0,16); @@ -3010,7 +3010,7 @@ int CmdHf14AMfDecryptBytes(const char *Cmd){ PrintAndLogEx(NORMAL, "nt\t%08X", nt); PrintAndLogEx(NORMAL, "ar enc\t%08X", ar_enc); PrintAndLogEx(NORMAL, "at enc\t%08X", at_enc); - + uint8_t *data = calloc(len, sizeof(uint8_t)); param_gethex_ex(Cmd, 3, data, &len); len >>= 1; @@ -3065,7 +3065,7 @@ int CmdHf14AMfNack(const char *Cmd) { if ( verbose ) PrintAndLogEx(INFO, "Started testing card for NACK bug. Press key to abort"); - + detect_classic_nackbug(verbose); return 0; } @@ -3114,14 +3114,14 @@ int CmdHF14AMfice(const char *Cmd) { if(filename[0]=='\0') { fptr = GenerateFilename("hf-mf-","-nonces.bin"); - if (fptr == NULL) + if (fptr == NULL) return 1; strcpy(filename, fptr); } PrintAndLogEx(NORMAL, "Collecting %u nonces \n", limit); - - if ((fnonces = fopen(filename,"wb")) == NULL) { + + if ((fnonces = fopen(filename,"wb")) == NULL) { PrintAndLogEx(WARNING, "Could not create file " _YELLOW_(%s),filename); return 3; } @@ -3129,21 +3129,21 @@ int CmdHF14AMfice(const char *Cmd) { clearCommandBuffer(); uint64_t t1 = msclock(); - + do { if (ukbhit()) { int gc = getchar(); (void)gc; PrintAndLogEx(INFO, "\naborted via keyboard!\n"); break; } - + flags = 0; flags |= initialize ? 0x0001 : 0; flags |= slow ? 0x0002 : 0; UsbCommand c = {CMD_MIFARE_ACQUIRE_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, flags}}; clearCommandBuffer(); - SendCommand(&c); - + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) goto out; if (resp.arg[0]) goto out; @@ -3152,22 +3152,22 @@ int CmdHF14AMfice(const char *Cmd) { fwrite(resp.d.asBytes, 1, items*4, fnonces); fflush(fnonces); } - + total_num_nonces += items; if ( total_num_nonces > part_limit ) { PrintAndLogEx(INFO, "Total nonces %u\n", total_num_nonces); part_limit += 3000; } - - acquisition_completed = ( total_num_nonces > limit); + + acquisition_completed = ( total_num_nonces > limit); initialize = false; - + } while (!acquisition_completed); out: PrintAndLogEx(SUCCESS, "time: %" PRIu64 " seconds\n", (msclock()-t1)/1000); - + if ( fnonces ) { fflush(fnonces); fclose(fnonces); @@ -3185,8 +3185,8 @@ int CmdHF14AMfAuth4(const char *Cmd) { uint8_t key[16] = {0}; int keylen = 0; - CLIParserInit("hf mf auth4", - "Executes AES authentication command in ISO14443-4", + CLIParserInit("hf mf auth4", + "Executes AES authentication command in ISO14443-4", "Usage:\n\thf mf auth4 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n" "\thf mf auth4 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -> executes authentication\n"); @@ -3197,16 +3197,16 @@ int CmdHF14AMfAuth4(const char *Cmd) { arg_param_end }; CLIExecWithReturn(Cmd, argtable, true); - + CLIGetHexWithReturn(1, keyn, &keynlen); CLIGetHexWithReturn(2, key, &keylen); CLIParserFree(); - + if (keynlen != 2) { PrintAndLogEx(ERR, " must be 2 bytes long instead of: %d", keynlen); return 1; } - + if (keylen != 16) { PrintAndLogEx(ERR, " must be 16 bytes long instead of: %d", keylen); return 1; @@ -3218,8 +3218,8 @@ int CmdHF14AMfAuth4(const char *Cmd) { // https://www.nxp.com/docs/en/application-note/AN10787.pdf int CmdHF14AMfMAD(const char *cmd) { - CLIParserInit("hf mf mad", - "Checks and prints Mifare Application Directory (MAD)", + CLIParserInit("hf mf mad", + "Checks and prints Mifare Application Directory (MAD)", "Usage:\n\thf mf mad -> shows MAD if exists\n" "\thf mf mad -a 03e1 -k ffffffffffff -b -> shows NDEF data if exists. read card with custom key and key B\n"); @@ -3240,7 +3240,7 @@ int CmdHF14AMfMAD(const char *cmd) { int keylen; CLIGetHexWithReturn(3, key, &keylen); bool keyB = arg_get_lit(4); - + CLIParserFree(); if (aidlen != 2 && keylen > 0) { @@ -3253,15 +3253,15 @@ int CmdHF14AMfMAD(const char *cmd) { PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys."); return 2; } - + if (verbose) { for(int i = 0; i < 4; i ++) - PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(§or0[i * 16], 16)); + PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(§or0[i * 16], 16)); } bool haveMAD2 = false; MAD1DecodeAndPrint(sector0, verbose, &haveMAD2); - + if (haveMAD2) { if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) { PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys."); @@ -3274,7 +3274,7 @@ int CmdHF14AMfMAD(const char *cmd) { if (aidlen == 2) { uint16_t aaid = (aid[0] << 8) + aid[1]; PrintAndLogEx(NORMAL, "\n-------------- AID 0x%04x ---------------", aaid); - + uint16_t mad[7 + 8 + 8 + 8 + 8] = {0}; size_t madlen = 0; if (MADDecode(sector0, sector10, mad, &madlen)) { @@ -3287,7 +3287,7 @@ int CmdHF14AMfMAD(const char *cmd) { if (keylen == 6) { memcpy(akey, key, 6); } - + for (int i = 0; i < madlen; i++) { if (aaid == mad[i]) { uint8_t vsector[16 * 4] = {0}; @@ -3296,20 +3296,20 @@ int CmdHF14AMfMAD(const char *cmd) { PrintAndLogEx(ERR, "read sector %d error.", i + 1); return 2; } - + for(int j = 0; j < (verbose ? 4 : 3); j ++) - PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16)); + PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16)); } - } + } } - + return 0; } int CmdHFMFNDEF(const char *cmd) { - CLIParserInit("hf mf ndef", - "Prints NFC Data Exchange Format (NDEF)", + CLIParserInit("hf mf ndef", + "Prints NFC Data Exchange Format (NDEF)", "Usage:\n\thf mf ndef -> shows NDEF data\n" "\thf mf ndef -a 03e1 -k ffffffffffff -b -> shows NDEF data with custom AID, key and with key B\n"); @@ -3322,7 +3322,7 @@ int CmdHFMFNDEF(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); bool verbose2 = arg_get_lit(1) > 1; uint8_t aid[2] = {0}; @@ -3332,38 +3332,38 @@ int CmdHFMFNDEF(const char *cmd) { int keylen; CLIGetHexWithReturn(3, key, &keylen); bool keyB = arg_get_lit(4); - + CLIParserFree(); uint16_t ndefAID = 0x03e1; if (aidlen == 2) ndefAID = (aid[0] << 8) + aid[1]; - + uint8_t ndefkey[6] = {0}; memcpy(ndefkey, g_mifare_ndef_key, 6); if (keylen == 6) { memcpy(ndefkey, key, 6); } - + uint8_t sector0[16 * 4] = {0}; uint8_t sector10[16 * 4] = {0}; uint8_t data[4096] = {0}; int datalen = 0; PrintAndLogEx(NORMAL, ""); - + if (mfReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector0)) { PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys."); return 2; } - + bool haveMAD2 = false; int res = MADCheck(sector0, NULL, verbose, &haveMAD2); if (res) { PrintAndLogEx(ERR, "MAD error %d.", res); return res; } - + if (haveMAD2) { if (mfReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifare_mad_key, sector10)) { PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys."); @@ -3386,25 +3386,25 @@ int CmdHFMFNDEF(const char *cmd) { PrintAndLogEx(ERR, "read sector %d error.", i + 1); return 2; } - + memcpy(&data[datalen], vsector, 16 * 3); datalen += 16 * 3; - + printf("."); } } printf(" OK\n"); - + if (!datalen) { PrintAndLogEx(ERR, "no NDEF data."); return 11; } - + if (verbose2) { PrintAndLogEx(NORMAL, "NDEF data:"); dump_buffer(data, datalen, stdout, 1); } - + NDEFDecodeAndPrint(data, datalen, verbose); return 0; @@ -3417,11 +3417,11 @@ int CmdHF14AMfList(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"list", CmdHF14AMfList, 0, "[Deprecated] List ISO 14443-a / Mifare history"}, + {"list", CmdHF14AMfList, 0, "[Deprecated] List ISO 14443-a / Mifare history"}, {"darkside", CmdHF14AMfDarkside, 0, "Darkside attack. read parity error messages."}, {"nested", CmdHF14AMfNested, 0, "Nested attack. Test nested authentication"}, {"hardnested", CmdHF14AMfNestedHard, 0, "Nested attack for hardened Mifare cards"}, - {"keybrute", CmdHF14AMfKeyBrute, 0, "J_Run's 2nd phase of multiple sector nested authentication key recovery"}, + {"keybrute", CmdHF14AMfKeyBrute, 0, "J_Run's 2nd phase of multiple sector nested authentication key recovery"}, {"nack", CmdHf14AMfNack, 0, "Test for Mifare NACK bug"}, {"chk", CmdHF14AMfChk, 0, "Check keys"}, {"fchk", CmdHF14AMfChk_fast, 0, "Check keys fast, targets all keys on card"}, @@ -3433,7 +3433,7 @@ static command_t CommandTable[] = { {"dump", CmdHF14AMfDump, 0, "Dump MIFARE classic tag to binary file"}, {"restore", CmdHF14AMfRestore, 0, "Restore MIFARE classic binary file to BLANK tag"}, {"wrbl", CmdHF14AMfWrBl, 0, "Write MIFARE classic block"}, - {"setmod", CmdHf14AMfSetMod, 0, "Set MIFARE Classic EV1 load modulation strength"}, + {"setmod", CmdHf14AMfSetMod, 0, "Set MIFARE Classic EV1 load modulation strength"}, {"auth4", CmdHF14AMfAuth4, 0, "ISO14443-4 AES authentication"}, // {"sniff", CmdHF14AMfSniff, 0, "Sniff card-reader communication"}, {"-----------", CmdHelp, 1, ""}, diff --git a/client/cmdhfmfdes.c b/client/cmdhfmfdes.c index 0bf5b2443..9ddd23b5f 100644 --- a/client/cmdhfmfdes.c +++ b/client/cmdhfmfdes.c @@ -41,14 +41,14 @@ int CmdHF14ADesWb(const char *Cmd) uint8_t keyType = 0; uint8_t key[6] = {0, 0, 0, 0, 0, 0}; uint8_t bldata[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; - + char cmdp = 0x00; if (strlen(Cmd)<3) { PrintAndLogEx(NORMAL, "Usage: hf mf wrbl "); PrintAndLogEx(NORMAL, " sample: hf mf wrbl 0 A FFFFFFFFFFFF 000102030405060708090A0B0C0D0E0F"); return 0; - } + } blockNo = param_get8(Cmd, 0); cmdp = param_getchar(Cmd, 1); @@ -67,7 +67,7 @@ int CmdHF14ADesWb(const char *Cmd) } PrintAndLogEx(NORMAL, "--block no:%02x key type:%02x key:%s", blockNo, keyType, sprint_hex(key, 6)); PrintAndLogEx(NORMAL, "--data: %s", sprint_hex(bldata, 16)); - + UsbCommand c = {CMD_MIFARE_WRITEBL, {blockNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); memcpy(c.d.asBytes + 10, bldata, 16); @@ -89,7 +89,7 @@ int CmdHF14ADesRb(const char *Cmd) // uint8_t blockNo = 0; // uint8_t keyType = 0; // uint8_t key[6] = {0, 0, 0, 0, 0, 0}; - + // char cmdp = 0x00; @@ -97,8 +97,8 @@ int CmdHF14ADesRb(const char *Cmd) // PrintAndLogEx(NORMAL, "Usage: hf mf rdbl "); // PrintAndLogEx(NORMAL, " sample: hf mf rdbl 0 A FFFFFFFFFFFF "); // return 0; - // } - + // } + // blockNo = param_get8(Cmd, 0); // cmdp = param_getchar(Cmd, 1); // if (cmdp == 0x00) { @@ -111,7 +111,7 @@ int CmdHF14ADesRb(const char *Cmd) // return 1; // } // PrintAndLogEx(NORMAL, "--block no:%02x key type:%02x key:%s ", blockNo, keyType, sprint_hex(key, 6)); - + // UsbCommand c = {CMD_MIFARE_READBL, {blockNo, keyType, 0}}; // memcpy(c.d.asBytes, key, 6); // SendCommand(&c); @@ -137,7 +137,7 @@ int CmdHF14ADesInfo(const char *Cmd){ UsbCommand c = {CMD_MIFARE_DESFIRE_INFO}; SendCommand(&c); UsbCommand resp; - + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { PrintAndLogEx(WARNING, "Command execute timeout"); return 0; @@ -145,16 +145,16 @@ int CmdHF14ADesInfo(const char *Cmd){ uint8_t isOK = resp.arg[0] & 0xff; if ( !isOK ){ switch ( resp.arg[1] ) { - case 1: + case 1: PrintAndLogEx(WARNING, "Can't select card"); break; case 2: PrintAndLogEx(WARNING, "Card is most likely not Desfire. Its UID has wrong size"); break; - case 3: + case 3: default: PrintAndLogEx(WARNING, "Command unsuccessful"); break; } return 0; - } + } PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "-- Desfire Information --------------------------------------"); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); @@ -178,21 +178,21 @@ int CmdHF14ADesInfo(const char *Cmd){ PrintAndLogEx(NORMAL, " storage size : %s", GetCardSizeStr(resp.d.asBytes[19])); PrintAndLogEx(NORMAL, " Protocol : %s", GetProtocolStr(resp.d.asBytes[20])); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); - + // Master Key settings GetKeySettings(NULL); - + // Free memory on card c.cmd = CMD_MIFARE_DESFIRE; c.arg[0] = (INIT | DISCONNECT); c.arg[1] = 0x01; c.d.asBytes[0] = GET_FREE_MEMORY; SendCommand(&c); - if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500)) + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 0; - + uint8_t tmp[3]; - memcpy(tmp, resp.d.asBytes+3,3); + memcpy(tmp, resp.d.asBytes+3,3); PrintAndLogEx(NORMAL, " Available free memory on card : %d bytes", le24toh( tmp )); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); @@ -203,37 +203,37 @@ int CmdHF14ADesInfo(const char *Cmd){ Application keys (APK) 0x01-0x0D Application free 0x0E Application never 0x0F - + ACCESS RIGHTS: keys 0,1,2,3 C keys 4,5,6,7 RW keys 8,9,10,11 W keys 12,13,14,15 R - + */ - + return 1; } /* - The 7 MSBits (= n) code the storage size itself based on 2^n, + The 7 MSBits (= n) code the storage size itself based on 2^n, the LSBit is set to '0' if the size is exactly 2^n - and set to '1' if the storage size is between 2^n and 2^(n+1). + and set to '1' if the storage size is between 2^n and 2^(n+1). For this version of DESFire the 7 MSBits are set to 0x0C (2^12 = 4096) and the LSBit is '0'. */ char * GetCardSizeStr( uint8_t fsize ){ - + static char buf[30] = {0x00}; char *retStr = buf; uint16_t usize = 1 << ((fsize >>1) + 1); uint16_t lsize = 1 << (fsize >>1); - + // is LSB set? if ( fsize & 1 ) sprintf(retStr, "0x%02X (%d - %d bytes)",fsize, usize, lsize); - else - sprintf(retStr, "0x%02X (%d bytes)", fsize, lsize); + else + sprintf(retStr, "0x%02X (%d bytes)", fsize, lsize); return buf; } @@ -245,7 +245,7 @@ char * GetProtocolStr(uint8_t id){ if ( id == 0x05) sprintf(retStr,"0x%02X (ISO 14443-3, 14443-4)", id); else - sprintf(retStr,"0x%02X (Unknown)", id); + sprintf(retStr,"0x%02X (Unknown)", id); return buf; } @@ -255,7 +255,7 @@ char * GetVersionStr(uint8_t major, uint8_t minor){ char *retStr = buf; if ( major == 0x00) - sprintf(retStr,"%d.%d (Desfire MF3ICD40)", major, minor); + sprintf(retStr,"%d.%d (Desfire MF3ICD40)", major, minor); else if ( major == 0x01 && minor == 0x00) sprintf(retStr,"%d.%d (Desfire EV1)", major, minor); else if ( major == 0x12 && minor == 0x00) @@ -266,7 +266,7 @@ char * GetVersionStr(uint8_t major, uint8_t minor){ } void GetKeySettings( uint8_t *aid){ - + char messStr[512] = {0x00}; char *str = messStr; uint8_t isOK = 0; @@ -275,7 +275,7 @@ void GetKeySettings( uint8_t *aid){ UsbCommand resp; //memset(messStr, 0x00, 512); - + if ( aid == NULL ){ PrintAndLogEx(NORMAL, " CMK - PICC, Card Master Key settings "); PrintAndLogEx(NORMAL, ""); @@ -283,14 +283,14 @@ void GetKeySettings( uint8_t *aid){ c.arg[LENPOS] = 0x01; c.d.asBytes[0] = GET_KEY_SETTINGS; // 0x45 SendCommand(&c); - if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} isOK = resp.arg[0] & 0xff; if ( !isOK ){ - PrintAndLogEx(WARNING, " Can't select master application"); + PrintAndLogEx(WARNING, " Can't select master application"); return; - } + } - str = (resp.d.asBytes[3] & (1 << 3 )) ? "YES":"NO"; + str = (resp.d.asBytes[3] & (1 << 3 )) ? "YES":"NO"; PrintAndLogEx(NORMAL, " [0x08] Configuration changeable : %s", str); str = (resp.d.asBytes[3] & (1 << 2 )) ? "NO":"YES"; PrintAndLogEx(NORMAL, " [0x04] CMK required for create/delete : %s",str); @@ -298,7 +298,7 @@ void GetKeySettings( uint8_t *aid){ PrintAndLogEx(NORMAL, " [0x02] Directory list access with CMK : %s",str); str = (resp.d.asBytes[3] & (1 << 0 )) ? "YES" : "NO"; PrintAndLogEx(NORMAL, " [0x01] CMK is changeable : %s", str); - + c.arg[LENPOS] = 0x02; //LEN c.d.asBytes[0] = GET_KEY_VERSION; //0x64 c.d.asBytes[1] = 0x00; @@ -313,7 +313,7 @@ void GetKeySettings( uint8_t *aid){ PrintAndLogEx(NORMAL, " Max number of keys : %d", resp.d.asBytes[4]); PrintAndLogEx(NORMAL, " Master key Version : %d (0x%02x)", resp.d.asBytes[3], resp.d.asBytes[3]); PrintAndLogEx(NORMAL, " ----------------------------------------------------------"); - + c.arg[LENPOS] = 0x02; //LEN c.d.asBytes[0] = AUTHENTICATE; //0x0A c.d.asBytes[1] = 0x00; // KEY 0 @@ -327,7 +327,7 @@ void GetKeySettings( uint8_t *aid){ if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} isOK = resp.d.asBytes[2] & 0xff; PrintAndLogEx(NORMAL, " [0x1A] Authenticate ISO : %s", ( isOK==0xAE ) ? "NO":"YES"); - + c.d.asBytes[0] = AUTHENTICATE_AES; //0xAA SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK,&resp,1000) ) {return;} @@ -335,32 +335,32 @@ void GetKeySettings( uint8_t *aid){ PrintAndLogEx(NORMAL, " [0xAA] Authenticate AES : %s", ( isOK==0xAE ) ? "NO":"YES"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " ----------------------------------------------------------"); - + } else { PrintAndLogEx(NORMAL, " AMK - Application Master Key settings"); - + // SELECT AID c.arg[0] = (INIT | CLEARTRACE); c.arg[LENPOS] = 0x04; c.d.asBytes[0] = SELECT_APPLICATION; // 0x5a memcpy(c.d.asBytes+1, aid, 3); SendCommand(&c); - + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { PrintAndLogEx(WARNING, " Timed-out"); return; - } + } isOK = resp.arg[0] & 0xff; if ( !isOK ){ - PrintAndLogEx(WARNING, " Can't select AID: %s",sprint_hex(aid,3)); + PrintAndLogEx(WARNING, " Can't select AID: %s",sprint_hex(aid,3)); return; - } - + } + // KEY SETTINGS options = NONE; c.arg[0] = options; c.arg[LENPOS] = 0x01; - c.d.asBytes[0] = GET_KEY_SETTINGS; // 0x45 + c.d.asBytes[0] = GET_KEY_SETTINGS; // 0x45 SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { return; @@ -387,9 +387,9 @@ void GetKeySettings( uint8_t *aid){ } PrintAndLogEx(NORMAL, "Changekey Access rights"); PrintAndLogEx(NORMAL, "-- %s",str); - PrintAndLogEx(NORMAL, ""); + PrintAndLogEx(NORMAL, ""); // same as CMK - str = (resp.d.asBytes[3] & (1 << 3 )) ? "YES":"NO"; + str = (resp.d.asBytes[3] & (1 << 3 )) ? "YES":"NO"; PrintAndLogEx(NORMAL, " 0x08 Configuration changeable : %s", str); str = (resp.d.asBytes[3] & (1 << 2 )) ? "NO":"YES"; PrintAndLogEx(NORMAL, " 0x04 AMK required for create/delete : %s",str); @@ -398,8 +398,8 @@ void GetKeySettings( uint8_t *aid){ str = (resp.d.asBytes[3] & (1 << 0 )) ? "YES" : "NO"; PrintAndLogEx(NORMAL, " 0x01 AMK is changeable : %s", str); } - - // KEY VERSION - AMK + + // KEY VERSION - AMK c.arg[0] = NONE; c.arg[LENPOS] = 0x02; c.d.asBytes[0] = GET_KEY_VERSION; //0x64 @@ -409,9 +409,9 @@ void GetKeySettings( uint8_t *aid){ PrintAndLogEx(WARNING, " Timed-out"); return; } - + int numOfKeys; - + isOK = resp.arg[0] & 0xff; if ( !isOK ){ PrintAndLogEx(WARNING, " Can't read Application Master key version. Trying all keys"); @@ -422,83 +422,83 @@ void GetKeySettings( uint8_t *aid){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " Max number of keys : %d", numOfKeys ); PrintAndLogEx(NORMAL, " Application Master key Version : %d (0x%02x)", resp.d.asBytes[3], resp.d.asBytes[3]); - PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); + PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); } - - // LOOP over numOfKeys that we got before. + + // LOOP over numOfKeys that we got before. // From 0x01 to numOfKeys. We already got 0x00. (AMK) for(int i=0x01; i<=0x0f; ++i){ - + } - - + + } } int CmdHF14ADesEnumApplications(const char *Cmd){ - + uint8_t isOK = 0x00; uint8_t aid[3]; uint32_t options = (INIT | DISCONNECT); - + UsbCommand c = {CMD_MIFARE_DESFIRE, {options , 0x01 }}; c.d.asBytes[0] = GET_APPLICATION_IDS; //0x6a - + SendCommand(&c); UsbCommand resp; - + if ( !WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { return 0; - } + } isOK = resp.arg[0] & 0xff; if ( !isOK ){ PrintAndLogEx(NORMAL, "Command unsuccessful"); return 0; - } - PrintAndLogEx(NORMAL, ""); + } + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "-- Desfire Enumerate Applications ---------------------------"); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); UsbCommand respAid; UsbCommand respFiles; - + uint8_t num = 0; int max = resp.arg[1] -3 -2; - + for(int i=3; i<=max; i+=3){ PrintAndLogEx(NORMAL, " Aid %d : %02X %02X %02X ",num ,resp.d.asBytes[i],resp.d.asBytes[i+1],resp.d.asBytes[i+2]); num++; - + aid[0] = resp.d.asBytes[i]; aid[1] = resp.d.asBytes[i+1]; aid[2] = resp.d.asBytes[i+2]; GetKeySettings(aid); - + // Select Application c.arg[CMDPOS] = INIT; - c.arg[LENPOS] = 0x04; + c.arg[LENPOS] = 0x04; c.d.asBytes[0] = SELECT_APPLICATION; // 0x5a c.d.asBytes[1] = resp.d.asBytes[i]; - c.d.asBytes[2] = resp.d.asBytes[i+1]; + c.d.asBytes[2] = resp.d.asBytes[i+1]; c.d.asBytes[3] = resp.d.asBytes[i+2]; SendCommand(&c); - + if (!WaitForResponseTimeout(CMD_ACK,&respAid,1500) ) { PrintAndLogEx(WARNING, " Timed-out"); continue; - } + } isOK = respAid.d.asBytes[2] & 0xff; if ( isOK != 0x00 ){ - PrintAndLogEx(WARNING, " Can't select AID: %s",sprint_hex(resp.d.asBytes+i,3)); + PrintAndLogEx(WARNING, " Can't select AID: %s",sprint_hex(resp.d.asBytes+i,3)); continue; } - + // Get File IDs c.arg[CMDPOS] = NONE; c.arg[LENPOS] = 0x01; c.d.asBytes[0] = GET_FILE_IDS; // 0x6f SendCommand(&c); - + if ( !WaitForResponseTimeout(CMD_ACK,&respFiles,1500) ) { PrintAndLogEx(WARNING, " Timed-out"); continue; @@ -506,20 +506,20 @@ int CmdHF14ADesEnumApplications(const char *Cmd){ isOK = respFiles.d.asBytes[2] & 0xff; if ( !isOK ){ PrintAndLogEx(WARNING, " Can't get file ids "); - } else { - int respfileLen = resp.arg[1]-3-2; + } else { + int respfileLen = resp.arg[1]-3-2; for (int j=0; j< respfileLen; ++j){ PrintAndLogEx(NORMAL, " Fileid %d :", resp.d.asBytes[j+3]); } } } - + // Get ISO File IDs c.arg[CMDPOS] = DISCONNECT; c.arg[LENPOS] = 0x01; c.d.asBytes[0] = GET_ISOFILE_IDS; // 0x61 SendCommand(&c); - + if ( !WaitForResponseTimeout(CMD_ACK,&respFiles,1500) ) { PrintAndLogEx(WARNING, " Timed-out"); continue; @@ -527,27 +527,27 @@ int CmdHF14ADesEnumApplications(const char *Cmd){ isOK = respFiles.d.asBytes[2] & 0xff; if ( !isOK ){ PrintAndLogEx(WARNING, " Can't get ISO file ids "); - } else { - int respfileLen = resp.arg[1]-3-2; + } else { + int respfileLen = resp.arg[1]-3-2; for (int j=0; j< respfileLen; ++j){ PrintAndLogEx(NORMAL, " ISO Fileid %d :", resp.d.asBytes[j+3]); } } } - - + + } PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); - - + + return 1; } // MIAFRE DesFire Authentication // -#define BUFSIZE 256 +#define BUFSIZE 256 int CmdHF14ADesAuth(const char *Cmd){ - + // NR DESC KEYLENGHT // ------------------------ // 1 = DES 8 @@ -556,8 +556,8 @@ int CmdHF14ADesAuth(const char *Cmd){ // 4 = AES 16 uint8_t keylength = 8; - unsigned char key[24]; - + unsigned char key[24]; + if (strlen(Cmd)<3) { PrintAndLogEx(NORMAL, "Usage: hf mfdes auth <1|2|3> <1|2|3|4> "); PrintAndLogEx(NORMAL, " Auth modes"); @@ -569,14 +569,14 @@ int CmdHF14ADesAuth(const char *Cmd){ PrintAndLogEx(NORMAL, " hf mfdes auth 1 1 0 11223344"); PrintAndLogEx(NORMAL, " hf mfdes auth 3 4 0 404142434445464748494a4b4c4d4e4f"); return 0; - } + } uint8_t cmdAuthMode = param_get8(Cmd,0); uint8_t cmdAuthAlgo = param_get8(Cmd,1); uint8_t cmdKeyNo = param_get8(Cmd,2); - + switch (cmdAuthMode) { - case 1: + case 1: if ( cmdAuthAlgo != 1 && cmdAuthAlgo != 2) { PrintAndLogEx(NORMAL, "Crypto algo not valid for the auth mode"); return 1; @@ -599,13 +599,13 @@ int CmdHF14ADesAuth(const char *Cmd){ return 1; break; } - + switch (cmdAuthAlgo){ - case 2: + case 2: keylength = 16; PrintAndLogEx(NORMAL, "3DES selected"); break; - case 3: + case 3: keylength = 24; PrintAndLogEx(NORMAL, "3 key 3DES selected"); break; @@ -625,24 +625,24 @@ int CmdHF14ADesAuth(const char *Cmd){ PrintAndLogEx(WARNING, "Key must include %d HEX symbols", keylength); return 1; } - // algo, nyckell�ngd, + // algo, nyckell�ngd, UsbCommand c = {CMD_MIFARE_DESFIRE_AUTH1, { cmdAuthMode, cmdAuthAlgo, cmdKeyNo }}; - + c.d.asBytes[0] = keylength; memcpy(c.d.asBytes+1, key, keylength); clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + if (!WaitForResponseTimeout(CMD_ACK,&resp,3000)) { PrintAndLogEx(WARNING, "Client command execute timeout"); return 0; - } + } uint8_t isOK = resp.arg[0] & 0xff; if ( isOK) { uint8_t * data= resp.d.asBytes; - + PrintAndLogEx(NORMAL, " Key :%s",sprint_hex(key, keylength)); PrintAndLogEx(NORMAL, " SESSION :%s",sprint_hex(data, keylength)); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); @@ -650,7 +650,7 @@ int CmdHF14ADesAuth(const char *Cmd){ } else{ PrintAndLogEx(NORMAL, "Client command failed."); } - PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); + PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); return 1; } diff --git a/client/cmdhfmfdes.h b/client/cmdhfmfdes.h index 18594075c..01ca471c9 100644 --- a/client/cmdhfmfdes.h +++ b/client/cmdhfmfdes.h @@ -82,7 +82,7 @@ enum { #define NO_CHANGES 0x0C // No changes done to backup files // ,CommitTransaction/ // AbortTransaction not necessary -#define OUT_OF_EEPROM_ERROR 0x0E // Insufficient NV-Memory to +#define OUT_OF_EEPROM_ERROR 0x0E // Insufficient NV-Memory to // complete command #define ILLEGAL_COMMAND_CODE 0x1C // Command code not supported #define INTEGRITY_ERROR 0x1E // CRC or MAC does not match data @@ -119,7 +119,7 @@ enum { // with same number already exists #define EEPROM_ERROR 0xEE // [1] // Could not complete NV-write // operation due to loss of power, - // internal backup/rollback + // internal backup/rollback // mechanism activated #define FILE_NOT_FOUND_ERROR 0xF0 // Specified file number does not // exist diff --git a/client/cmdhfmfdesfire.c b/client/cmdhfmfdesfire.c index a7452eb27..91b9bc645 100644 --- a/client/cmdhfmfdesfire.c +++ b/client/cmdhfmfdesfire.c @@ -30,7 +30,7 @@ static int CmdHelp(const char *Cmd); //verify n'r=nr int CmdHF14AMfDESAuth(const char *Cmd){ - + uint8_t blockNo = 0; //keyNo=0; uint32_t cuid = 0; @@ -39,8 +39,8 @@ int CmdHF14AMfDESAuth(const char *Cmd){ uint8_t b1[8]={ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t b2[8]={ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; DES_cblock nr, b0, r1, r0; - - + + uint8_t key[8]={ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; //DES_cblock iv={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; DES_key_schedule ks1; @@ -51,15 +51,15 @@ int CmdHF14AMfDESAuth(const char *Cmd){ PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf desfire des-auth k 0"); return 0; - } - + } + //Change key to user defined one - + memcpy(key1,key,8); //memcpy(key2,key+8,8); DES_set_key((DES_cblock *)key1,&ks1); //DES_set_key((DES_cblock *)key2,&ks2); - + //Auth1 UsbCommand c = {CMD_MIFARE_DES_AUTH1, {blockNo}}; SendCommand(&c); @@ -76,7 +76,7 @@ int CmdHF14AMfDESAuth(const char *Cmd){ } else { PrintAndLogEx(WARNING, "Command execute timeout"); } - + //Do crypto magic DES_random_key(&nr); //b1=dec(nr) @@ -89,7 +89,7 @@ int CmdHF14AMfDESAuth(const char *Cmd){ memcpy(r1,r0,8); rol(r1,8); PrintAndLogEx(NORMAL, "r1:%s",sprint_hex(r1, 8)); - for(int i=0;i<8;i++){ + for(int i=0;i<8;i++){ b2[i]=(r1[i] ^ b1[i]); } DES_ecb_encrypt(&b2,&b2,&ks1,0); @@ -110,10 +110,10 @@ int CmdHF14AMfDESAuth(const char *Cmd){ if (isOK) PrintAndLogEx(NORMAL, "b3:%s", sprint_hex(data2+2, 8)); - + } else { PrintAndLogEx(WARNING, "Command execute timeout"); - } + } return 1; } @@ -123,14 +123,14 @@ int CmdHF14AMfDESAuth(const char *Cmd){ // Reader 2 Card : 03AF, 16 Bytes(b1),16Bytes(b2) CRC1 CRC2 // Card 2 Reader : 0300, 16 bytes(b3), CRC1 CRC2 ; success int CmdHF14AMfAESAuth(const char *Cmd){ - + uint8_t blockNo = 0; //keyNo=0; uint32_t cuid = 0; uint8_t reply[32] = {0x00}; //DES_cblock r1_b1; //unsigned char * b1, b2, nr, b0, r0, r1; - + uint8_t b1[16]={ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t b2[16]={ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; uint8_t nr[16]={ 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; @@ -148,8 +148,8 @@ int CmdHF14AMfAESAuth(const char *Cmd){ PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf desfire aes-auth k 0"); return 0; - } - + } + //Change key to user defined one // // int private_AES_set_encrypt_key(const unsigned char *userKey, const int bits,AES_KEY *key); @@ -159,7 +159,7 @@ int CmdHF14AMfAESAuth(const char *Cmd){ //memcpy(key2,key+8,8); AES_set_encrypt_key(key,128,&key_e); AES_set_decrypt_key(key,128,&key_d); - + //Auth1 UsbCommand c = {CMD_MIFARE_DES_AUTH1, {blockNo}}; SendCommand(&c); @@ -180,7 +180,7 @@ int CmdHF14AMfAESAuth(const char *Cmd){ // void AES_cbc_encrypt(const unsigned char *in, unsigned char *out, //size_t length, const AES_KEY *key, //unsigned char *ivec, const int enc); - + //Do crypto magic //DES_random_key(&nr); //b1=dec(nr) @@ -217,10 +217,10 @@ int CmdHF14AMfAESAuth(const char *Cmd){ if (isOK) PrintAndLogEx(NORMAL, "b3:%s", sprint_hex(data2+2, 16)); - + } else { PrintAndLogEx(WARNING, "Command execute timeout"); - } + } return 1; } diff --git a/client/cmdhfmfhard.c b/client/cmdhfmfhard.c index 1ebf2131d..d5c8c9403 100644 --- a/client/cmdhfmfhard.c +++ b/client/cmdhfmfhard.c @@ -11,7 +11,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- @@ -92,8 +92,8 @@ static void get_SIMD_instruction_set(char* instruction_set) { default: strcpy(instruction_set, "no"); break; - } -} + } +} static void print_progress_header(void) { @@ -222,7 +222,7 @@ static void inflate_free(voidpf opaque, voidpf address) #define INPUT_BUFFER_LEN 80 //---------------------------------------------------------------------------- -// Initialize decompression of the respective (HF or LF) FPGA stream +// Initialize decompression of the respective (HF or LF) FPGA stream //---------------------------------------------------------------------------- static void init_inflate(z_streamp compressed_stream, uint8_t *input_buffer, uint32_t insize, uint8_t *output_buffer, uint32_t outsize) { @@ -236,7 +236,7 @@ static void init_inflate(z_streamp compressed_stream, uint8_t *input_buffer, uin compressed_stream->zfree = &inflate_free; inflateInit2(compressed_stream, 0); - + } @@ -244,14 +244,14 @@ static void init_bitflip_bitarrays(void) { #if defined (DEBUG_REDUCTION) uint8_t line = 0; -#endif +#endif z_stream compressed_stream; - + char state_files_path[strlen(get_my_executable_directory()) + strlen(STATE_FILES_DIRECTORY) + strlen(STATE_FILE_TEMPLATE) + 1]; char state_file_name[strlen(STATE_FILE_TEMPLATE)+1]; - + for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { num_effective_bitflips[odd_even] = 0; for (uint16_t bitflip = 0x001; bitflip < 0x400; bitflip++) { @@ -339,14 +339,14 @@ static void init_bitflip_bitarrays(void) for(uint16_t i = 0; i < num_1st_byte_effective_bitflips; i++) { PrintAndLogEx(NORMAL, "%03x ", all_effective_bitflip[i]); } -#endif +#endif qsort(all_effective_bitflip+num_1st_byte_effective_bitflips, num_all_effective_bitflips - num_1st_byte_effective_bitflips, sizeof(uint16_t), compare_count_bitflip_bitarrays); #if defined (DEBUG_REDUCTION) PrintAndLogEx(NORMAL, "\n2nd byte effective bitflips (%d): \n", num_all_effective_bitflips - num_1st_byte_effective_bitflips); for(uint16_t i = num_1st_byte_effective_bitflips; i < num_all_effective_bitflips; i++) { PrintAndLogEx(NORMAL, "%03x ", all_effective_bitflip[i]); } -#endif +#endif char progress_text[80]; sprintf(progress_text, "Using %d precalculated bitflip state tables", num_all_effective_bitflips); hardnested_print_progress(0, progress_text, (float)(1LL<<47), 0); @@ -369,10 +369,10 @@ static void free_bitflip_bitarrays(void) static uint32_t *part_sum_a0_bitarrays[2][NUM_PART_SUMS]; static uint32_t *part_sum_a8_bitarrays[2][NUM_PART_SUMS]; -static uint32_t *sum_a0_bitarrays[2][NUM_SUMS]; +static uint32_t *sum_a0_bitarrays[2][NUM_SUMS]; static uint16_t PartialSumProperty(uint32_t state, odd_even_t odd_even) -{ +{ uint16_t sum = 0; for (uint16_t j = 0; j < 16; j++) { uint32_t st = state; @@ -408,7 +408,7 @@ static void init_part_sum_bitarrays(void) } } for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { - //PrintAndLogEx(NORMAL, "(%d, %" PRIu16 ")...", odd_even, part_sum_a0); + //PrintAndLogEx(NORMAL, "(%d, %" PRIu16 ")...", odd_even, part_sum_a0); for (uint32_t state = 0; state < (1<<20); state++) { uint16_t part_sum_a0 = PartialSumProperty(state, odd_even) / 2; for (uint16_t low_bits = 0; low_bits < 1<<4; low_bits++) { @@ -428,7 +428,7 @@ static void init_part_sum_bitarrays(void) } } for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { - //PrintAndLogEx(NORMAL, "(%d, %" PRIu16 ")...", odd_even, part_sum_a8); + //PrintAndLogEx(NORMAL, "(%d, %" PRIu16 ")...", odd_even, part_sum_a8); for (uint32_t state = 0; state < (1<<20); state++) { uint16_t part_sum_a8 = PartialSumProperty(state, odd_even) / 2; for (uint16_t high_bits = 0; high_bits < 1<<4; high_bits++) { @@ -439,7 +439,7 @@ static void init_part_sum_bitarrays(void) } -static void free_part_sum_bitarrays(void) +static void free_part_sum_bitarrays(void) { for (int16_t part_sum_a8 = (NUM_PART_SUMS-1); part_sum_a8 >= 0; part_sum_a8--) { free_bitarray(part_sum_a8_bitarrays[ODD_STATE][part_sum_a8]); @@ -494,14 +494,14 @@ static void free_sum_bitarrays(void) char failstr[250] = ""; #endif -static const float p_K0[NUM_SUMS] = { // the probability that a random nonce has a Sum Property K - 0.0290, 0.0083, 0.0006, 0.0339, 0.0048, 0.0934, 0.0119, 0.0489, 0.0602, 0.4180, 0.0602, 0.0489, 0.0119, 0.0934, 0.0048, 0.0339, 0.0006, 0.0083, 0.0290 +static const float p_K0[NUM_SUMS] = { // the probability that a random nonce has a Sum Property K + 0.0290, 0.0083, 0.0006, 0.0339, 0.0048, 0.0934, 0.0119, 0.0489, 0.0602, 0.4180, 0.0602, 0.0489, 0.0119, 0.0934, 0.0048, 0.0339, 0.0006, 0.0083, 0.0290 }; -static float my_p_K[NUM_SUMS]; +static float my_p_K[NUM_SUMS]; static const float *p_K; - + static uint32_t cuid; static noncelist_t nonces[256]; static uint8_t best_first_bytes[256]; @@ -520,7 +520,7 @@ static uint64_t num_keys_tested = 0; static statelist_t *candidates = NULL; -static int add_nonce(uint32_t nonce_enc, uint8_t par_enc) +static int add_nonce(uint32_t nonce_enc, uint8_t par_enc) { uint8_t first_byte = nonce_enc >> 24; noncelistentry_t *p1 = nonces[first_byte].first; @@ -535,7 +535,7 @@ static int add_nonce(uint32_t nonce_enc, uint8_t par_enc) p2 = p1; p1 = p1->next; } - + if (p1 == NULL) { // need to add at the end of the list if (p2 == NULL) { // list is empty yet. Add first entry. p2 = nonces[first_byte].first = malloc(sizeof(noncelistentry_t)); @@ -548,7 +548,7 @@ static int add_nonce(uint32_t nonce_enc, uint8_t par_enc) } else { p2 = p2->next = malloc(sizeof(noncelistentry_t)); } - } else { // we have seen this 2nd byte before. Nothing to add or insert. + } else { // we have seen this 2nd byte before. Nothing to add or insert. return (0); } @@ -626,7 +626,7 @@ static void free_nonces_memory(void) -static double p_hypergeometric(uint16_t i_K, uint16_t n, uint16_t k) +static double p_hypergeometric(uint16_t i_K, uint16_t n, uint16_t k) { // for efficient computation we are using the recursive definition // (K-k+1) * (n-k+1) @@ -637,19 +637,19 @@ static double p_hypergeometric(uint16_t i_K, uint16_t n, uint16_t k) // P(X=0) = ----------------------------- // N*(N-1)*...*(N-n+1) - + uint16_t const N = 256; uint16_t K = sums[i_K]; - + if (n-k > N-K || k > K) return 0.0; // avoids log(x<=0) in calculation below if (k == 0) { // use logarithms to avoid overflow with huge factorials (double type can only hold 170!) double log_result = 0.0; for (int16_t i = N-K; i >= N-K-n+1; i--) { log_result += log(i); - } + } for (int16_t i = N; i >= N-n+1; i--) { log_result -= log(i); } @@ -669,8 +669,8 @@ static double p_hypergeometric(uint16_t i_K, uint16_t n, uint16_t k) } } } - - + + static float sum_probability(uint16_t i_K, uint16_t n, uint16_t k) { if (k > sums[i_K]) return 0.0; @@ -703,7 +703,7 @@ static void init_allbitflips_array(void) static void update_allbitflips_array(void) -{ +{ if (hardnested_stage & CHECK_2ND_BYTES) { for (uint16_t i = 0; i < 256; i++) { for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { @@ -720,22 +720,22 @@ static void update_allbitflips_array(void) } } - -static uint32_t estimated_num_states_part_sum_coarse(uint16_t part_sum_a0_idx, uint16_t part_sum_a8_idx, odd_even_t odd_even) + +static uint32_t estimated_num_states_part_sum_coarse(uint16_t part_sum_a0_idx, uint16_t part_sum_a8_idx, odd_even_t odd_even) { return part_sum_count[odd_even][part_sum_a0_idx][part_sum_a8_idx]; } -static uint32_t estimated_num_states_part_sum(uint8_t first_byte, uint16_t part_sum_a0_idx, uint16_t part_sum_a8_idx, odd_even_t odd_even) +static uint32_t estimated_num_states_part_sum(uint8_t first_byte, uint16_t part_sum_a0_idx, uint16_t part_sum_a8_idx, odd_even_t odd_even) { if (odd_even == ODD_STATE) { - return count_bitarray_AND3(part_sum_a0_bitarrays[odd_even][part_sum_a0_idx], - part_sum_a8_bitarrays[odd_even][part_sum_a8_idx], + return count_bitarray_AND3(part_sum_a0_bitarrays[odd_even][part_sum_a0_idx], + part_sum_a8_bitarrays[odd_even][part_sum_a8_idx], nonces[first_byte].states_bitarray[odd_even]); } else { - return count_bitarray_AND4(part_sum_a0_bitarrays[odd_even][part_sum_a0_idx], - part_sum_a8_bitarrays[odd_even][part_sum_a8_idx], + return count_bitarray_AND4(part_sum_a0_bitarrays[odd_even][part_sum_a0_idx], + part_sum_a8_bitarrays[odd_even][part_sum_a8_idx], nonces[first_byte].states_bitarray[odd_even], nonces[first_byte^0x80].states_bitarray[odd_even]); } @@ -759,7 +759,7 @@ static uint64_t estimated_num_states(uint8_t first_byte, uint16_t sum_a0, uint16 for (uint8_t r = 0; r < NUM_PART_SUMS; r++) { for (uint8_t s = 0; s < NUM_PART_SUMS; s++) { if (2*r*(16-2*s) + (16-2*r)*2*s == sum_a8) { - num_states += (uint64_t)estimated_num_states_part_sum(first_byte, p, r, ODD_STATE) + num_states += (uint64_t)estimated_num_states_part_sum(first_byte, p, r, ODD_STATE) * estimated_num_states_part_sum(first_byte, q, s, EVEN_STATE); } } @@ -780,7 +780,7 @@ static uint64_t estimated_num_states_coarse(uint16_t sum_a0, uint16_t sum_a8) for (uint8_t r = 0; r < NUM_PART_SUMS; r++) { for (uint8_t s = 0; s < NUM_PART_SUMS; s++) { if (2*r*(16-2*s) + (16-2*r)*2*s == sum_a8) { - num_states += (uint64_t)estimated_num_states_part_sum_coarse(p, r, ODD_STATE) + num_states += (uint64_t)estimated_num_states_part_sum_coarse(p, r, ODD_STATE) * estimated_num_states_part_sum_coarse(q, s, EVEN_STATE); } } @@ -826,7 +826,7 @@ static void update_sum_bitarrays(odd_even_t odd_even) } for (uint8_t part_sum_a0 = 0; part_sum_a0 < NUM_PART_SUMS; part_sum_a0++) { for (uint8_t part_sum_a8 = 0; part_sum_a8 < NUM_PART_SUMS; part_sum_a8++) { - part_sum_count[odd_even][part_sum_a0][part_sum_a8] + part_sum_count[odd_even][part_sum_a0][part_sum_a8] += count_bitarray_AND2(part_sum_a0_bitarrays[odd_even][part_sum_a0], part_sum_a8_bitarrays[odd_even][part_sum_a8]); } } @@ -854,7 +854,7 @@ static int compare_sum_a8_guess(const void *b1, const void *b2) } -static float check_smallest_bitflip_bitarrays(void) +static float check_smallest_bitflip_bitarrays(void) { uint32_t num_odd, num_even; uint64_t smallest = 1LL << 48; @@ -900,7 +900,7 @@ static void update_expected_brute_force(uint8_t best_byte) { static float sort_best_first_bytes(void) { - + // initialize best_first_bytes, do a rough estimation on remaining states for each Sum_a8 property // and the expected number of states to brute force for (uint16_t i = 0; i < 256; i++) { @@ -914,7 +914,7 @@ static float sort_best_first_bytes(void) nonces[i].expected_num_brute_force += prob_all_failed * (float)nonces[i].sum_a8_guess[j].num_states / 2.0; } } - + // sort based on expected number of states to brute force qsort(best_first_bytes, 256, 1, compare_expected_num_brute_force); @@ -988,11 +988,11 @@ static float sort_best_first_bytes(void) } -static float update_reduction_rate(float last, bool init) +static float update_reduction_rate(float last, bool init) { #define QUEUE_LEN 4 static float queue[QUEUE_LEN]; - + for (uint16_t i = 0; i < QUEUE_LEN-1; i++) { if (init) { queue[i] = (float)(1LL << 48); @@ -1005,7 +1005,7 @@ static float update_reduction_rate(float last, bool init) } else { queue[QUEUE_LEN-1] = last; } - + // linear regression float avg_y = 0.0; float avg_x = 0.0; @@ -1015,7 +1015,7 @@ static float update_reduction_rate(float last, bool init) } avg_x /= QUEUE_LEN; avg_y /= QUEUE_LEN; - + float dev_xy = 0.0; float dev_x2 = 0.0; for (uint16_t i = 0; i < QUEUE_LEN; i++) { @@ -1025,9 +1025,9 @@ static float update_reduction_rate(float last, bool init) float reduction_rate = -1.0 * dev_xy / dev_x2; // the negative slope of the linear regression -#if defined (DEBUG_REDUCTION) +#if defined (DEBUG_REDUCTION) PrintAndLogEx(NORMAL, "update_reduction_rate(%1.0f) = %1.0f per sample, brute_force_per_sample = %1.0f\n", last, reduction_rate, brute_force_per_second * (float)sample_period / 1000.0); -#endif +#endif return reduction_rate; } @@ -1047,12 +1047,12 @@ static bool shrink_key_space(float *brute_forces) //iceman 2018 return ((hardnested_stage & CHECK_2ND_BYTES) && - reduction_rate >= 0.0 && + reduction_rate >= 0.0 && ( reduction_rate < brute_force_per_second * (float)sample_period / 1000.0 || *brute_forces < 0x1F00000000)); } - -static void estimate_sum_a8(void) + +static void estimate_sum_a8(void) { if (first_byte_num == 256) { for (uint16_t i = 0; i < 256; i++) { @@ -1066,7 +1066,7 @@ static void estimate_sum_a8(void) } } } -} +} static int read_nonce_file(char *filename) @@ -1079,9 +1079,9 @@ static int read_nonce_file(char *filename) uint8_t read_buf[9]; uint32_t nt_enc1, nt_enc2; uint8_t par_enc; - + num_acquired_nonces = 0; - if ((fnonces = fopen(filename,"rb")) == NULL) { + if ((fnonces = fopen(filename,"rb")) == NULL) { PrintAndLogEx(WARNING, "Could not open file %s",filename); return 1; } @@ -1108,9 +1108,9 @@ static int read_nonce_file(char *filename) bytes_read = fread(read_buf, 1, 9, fnonces); } fclose(fnonces); - + char progress_string[80]; - sprintf(progress_string, "Read %d nonces from file. cuid=%08x", num_acquired_nonces, cuid); + sprintf(progress_string, "Read %d nonces from file. cuid=%08x", num_acquired_nonces, cuid); hardnested_print_progress(num_acquired_nonces, progress_string, (float)(1LL<<47), 0); sprintf(progress_string, "Target Block=%d, Keytype=%c", trgBlockNo, trgKeyType==0?'A':'B'); hardnested_print_progress(num_acquired_nonces, progress_string, (float)(1LL<<47), 0); @@ -1121,7 +1121,7 @@ static int read_nonce_file(char *filename) break; } } - + return 0; } @@ -1145,10 +1145,10 @@ static bool timeout(void) } -static void +static void #ifdef __has_attribute #if __has_attribute(force_align_arg_pointer) -__attribute__((force_align_arg_pointer)) +__attribute__((force_align_arg_pointer)) #endif #endif *check_for_BitFlipProperties_thread(void *args) @@ -1156,15 +1156,15 @@ __attribute__((force_align_arg_pointer)) uint8_t first_byte = ((uint8_t *)args)[0]; uint8_t last_byte = ((uint8_t *)args)[1]; uint8_t time_budget = ((uint8_t *)args)[2]; - + if (hardnested_stage & CHECK_1ST_BYTES) { // for (uint16_t bitflip = 0x001; bitflip < 0x200; bitflip++) { for (uint16_t bitflip_idx = 0; bitflip_idx < num_1st_byte_effective_bitflips; bitflip_idx++) { uint16_t bitflip = all_effective_bitflip[bitflip_idx]; if (time_budget & timeout()) { -#if defined (DEBUG_REDUCTION) +#if defined (DEBUG_REDUCTION) PrintAndLogEx(NORMAL, "break at bitflip_idx %d...", bitflip_idx); -#endif +#endif return NULL; } for (uint16_t i = first_byte; i <= last_byte; i++) { @@ -1243,26 +1243,26 @@ static void check_for_BitFlipProperties(bool time_budget) { // create and run worker threads pthread_t thread_id[NUM_CHECK_BITFLIPS_THREADS]; - + uint8_t args[NUM_CHECK_BITFLIPS_THREADS][3]; - uint16_t bytes_per_thread = (256 + (NUM_CHECK_BITFLIPS_THREADS/2)) / NUM_CHECK_BITFLIPS_THREADS; + uint16_t bytes_per_thread = (256 + (NUM_CHECK_BITFLIPS_THREADS/2)) / NUM_CHECK_BITFLIPS_THREADS; for (uint8_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) { args[i][0] = i * bytes_per_thread; args[i][1] = MIN(args[i][0]+bytes_per_thread-1, 255); args[i][2] = time_budget; } args[NUM_CHECK_BITFLIPS_THREADS-1][1] = MAX(args[NUM_CHECK_BITFLIPS_THREADS-1][1], 255); - + // start threads for (uint8_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) { pthread_create(&thread_id[i], NULL, check_for_BitFlipProperties_thread, args[i]); } - + // wait for threads to terminate: for (uint8_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) { pthread_join(thread_id[i], NULL); } - + if (hardnested_stage & CHECK_2ND_BYTES) { hardnested_stage &= ~CHECK_1ST_BYTES; // we are done with 1st stage, except... for (uint16_t i = 0; i < NUM_CHECK_BITFLIPS_THREADS; i++) { @@ -1272,7 +1272,7 @@ static void check_for_BitFlipProperties(bool time_budget) } } } -#if defined (DEBUG_REDUCTION) +#if defined (DEBUG_REDUCTION) if (hardnested_stage & CHECK_1ST_BYTES) PrintAndLogEx(NORMAL, "stage 1 not completed yet\n"); #endif } @@ -1319,12 +1319,12 @@ static void simulate_MFplus_RNG(uint32_t test_cuid, uint64_t test_key, uint32_t for (int8_t byte_pos = 3; byte_pos >= 0; byte_pos--) { uint8_t nt_byte_dec = (nt >> (8*byte_pos)) & 0xff; uint8_t nt_byte_enc = crypto1_byte(&sim_cs, nt_byte_dec ^ (test_cuid >> (8*byte_pos)), false) ^ nt_byte_dec; // encode the nonce byte - *nt_enc = (*nt_enc << 8) | nt_byte_enc; + *nt_enc = (*nt_enc << 8) | nt_byte_enc; uint8_t ks_par = filter(sim_cs.odd); // the keystream bit to encode/decode the parity bit uint8_t nt_byte_par_enc = ks_par ^ oddparity8(nt_byte_dec); // determine the nt byte's parity and encode it *par_enc = (*par_enc << 1) | nt_byte_par_enc; } - + } @@ -1338,7 +1338,7 @@ static void simulate_acquire_nonces() uint32_t total_num_nonces = 0; float brute_force; bool reported_suma8 = false; - + cuid = (rand() & 0xff) << 24 | (rand() & 0xff) << 16 | (rand() & 0xff) << 8 | (rand() & 0xff); if (known_target_key == -1) { known_target_key = ((uint64_t)rand() & 0xfff) << 36 | ((uint64_t)rand() & 0xfff) << 24 | ((uint64_t)rand() & 0xfff) << 12 | ((uint64_t)rand() & 0xfff); @@ -1350,7 +1350,7 @@ static void simulate_acquire_nonces() fprintf(fstats, "%012" PRIx64 ";%" PRIx32 ";", known_target_key, cuid); num_acquired_nonces = 0; - + do { uint32_t nt_enc = 0; uint8_t par_enc = 0; @@ -1362,7 +1362,7 @@ static void simulate_acquire_nonces() } last_sample_clock = msclock(); - + if (first_byte_num == 256 ) { if (hardnested_stage == CHECK_1ST_BYTES) { for (uint16_t i = 0; i < NUM_SUMS; i++) { @@ -1373,7 +1373,7 @@ static void simulate_acquire_nonces() } hardnested_stage |= CHECK_2ND_BYTES; apply_sum_a0(); - } + } update_nonce_data(true); acquisition_completed = shrink_key_space(&brute_force); if (!reported_suma8) { @@ -1392,14 +1392,14 @@ static void simulate_acquire_nonces() } while (!acquisition_completed); time_t end_time = time(NULL); - // PrintAndLogEx(NORMAL, "Acquired a total of %" PRId32" nonces in %1.0f seconds (%1.0f nonces/minute)", - // num_acquired_nonces, - // difftime(end_time, time1), + // PrintAndLogEx(NORMAL, "Acquired a total of %" PRId32" nonces in %1.0f seconds (%1.0f nonces/minute)", + // num_acquired_nonces, + // difftime(end_time, time1), // difftime(end_time, time1)!=0.0?(float)total_num_nonces*60.0/difftime(end_time, time1):INFINITY // ); fprintf(fstats, "%" PRId32 ";%" PRId32 ";%1.0f;", total_num_nonces, num_acquired_nonces, difftime(end_time,time1)); - + } @@ -1421,7 +1421,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ UsbCommand resp; num_acquired_nonces = 0; - + clearCommandBuffer(); do { @@ -1434,9 +1434,9 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ clearCommandBuffer(); SendCommand(&c); - + if (field_off) break; - + if (initialize) { if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) { //strange second call (iceman) @@ -1449,7 +1449,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ cuid = resp.arg[1]; if (nonce_file_write && fnonces == NULL) { - if ((fnonces = fopen(filename,"wb")) == NULL) { + if ((fnonces = fopen(filename,"wb")) == NULL) { PrintAndLogEx(WARNING, "Could not create file %s", filename); return 3; } @@ -1472,7 +1472,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ nt_enc1 = bytes_to_num(bufp, 4); nt_enc2 = bytes_to_num(bufp+4, 4); par_enc = bytes_to_num(bufp+8, 1); - + //PrintAndLogEx(NORMAL, "Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc1, par_enc >> 4); num_acquired_nonces += add_nonce(nt_enc1, par_enc >> 4); //PrintAndLogEx(NORMAL, "Encrypted nonce: %08x, encrypted_parity: %02x\n", nt_enc2, par_enc & 0x0f); @@ -1485,7 +1485,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ bufp += 9; } total_num_nonces += num_sampled_nonces; - + if (first_byte_num == 256 ) { if (hardnested_stage == CHECK_1ST_BYTES) { for (uint16_t i = 0; i < NUM_SUMS; i++) { @@ -1513,7 +1513,7 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ hardnested_print_progress(num_acquired_nonces, "Apply bit flip properties", brute_force, 0); } } - + if (acquisition_completed) { field_off = true; // switch off field with next SendCommand and then finish } @@ -1545,12 +1545,12 @@ static int acquire_nonces(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_ if (nonce_file_write) { fclose(fnonces); } - - // PrintAndLogEx(NORMAL, "Sampled a total of %d nonces in %d seconds (%0.0f nonces/minute)", - // total_num_nonces, - // time(NULL)-time1, + + // PrintAndLogEx(NORMAL, "Sampled a total of %d nonces in %d seconds (%0.0f nonces/minute)", + // total_num_nonces, + // time(NULL)-time1, // (float)total_num_nonces*60.0/(time(NULL)-time1)); - + return 0; } @@ -1594,7 +1594,7 @@ static inline bool remaining_bits_match(uint_fast8_t num_common_bits, uint_fast8 } } else { // even bits - switch (num_common_bits) { + switch (num_common_bits) { case 0: if (invalid_state(byte_diff, state1, state2, 0, 0)) return false; case 1: if (!invariant_holds(byte_diff, state1, state2, 2, 1)) return true; case 2: if (invalid_state(byte_diff, state1, state2, 2, 1)) return false; @@ -1604,7 +1604,7 @@ static inline bool remaining_bits_match(uint_fast8_t num_common_bits, uint_fast8 case 6: if (invalid_state(byte_diff, state1, state2, 6, 3)) return false; } } - + return true; // valid state } @@ -1637,7 +1637,7 @@ static void init_statelist_cache(void) sl_cache[i][j][k].cache_status = TO_BE_DONE; } } - } + } pthread_mutex_unlock(&statelist_cache_mutex); } @@ -1651,7 +1651,7 @@ static void free_statelist_cache(void) free(sl_cache[i][j][k].sl); } } - } + } pthread_mutex_unlock(&statelist_cache_mutex); } @@ -1660,7 +1660,7 @@ static void free_statelist_cache(void) static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even, bool quiet) #else static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even) -#endif +#endif { uint32_t *bitset = nonces[byte].states_bitarray[odd_even]; bool possible = test_bit24(bitset, state); @@ -1673,11 +1673,11 @@ static inline bool bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_e #endif return false; } - + return true; } - - + + static uint_fast8_t reverse(uint_fast8_t b) { b = (b & 0xF0) >> 4 | (b & 0x0F) << 4; @@ -1687,11 +1687,11 @@ static uint_fast8_t reverse(uint_fast8_t b) } -static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even) +static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even) { uint32_t masks[2][8] = {{0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe, 0x00ffffff}, {0x00fffff0, 0x00fffff0, 0x00fffff8, 0x00fffff8, 0x00fffffc, 0x00fffffc, 0x00fffffe, 0x00fffffe} }; - + for (uint16_t i = 1; i < 256; i++) { uint_fast8_t bytes_diff = reverse(i); // start with most common bits uint_fast8_t byte2 = byte ^ bytes_diff; @@ -1704,16 +1704,16 @@ static bool all_bitflips_match(uint8_t byte, uint32_t state, odd_even_t odd_even if (bitflips_match(byte2, (state & mask) | remaining_bits, odd_even, true)) { #else if (bitflips_match(byte2, (state & mask) | remaining_bits, odd_even)) { -#endif +#endif found_match = true; break; } } } if (!found_match) { -#ifdef DEBUG_KEY_ELIMINATION +#ifdef DEBUG_KEY_ELIMINATION if (known_target_key != -1 && state == test_state[odd_even]) { - PrintAndLogEx(NORMAL, "all_bitflips_match() 1st Byte: %s test state (0x%06x): Eliminated. Bytes = %02x, %02x, Common Bits = %d\n", + PrintAndLogEx(NORMAL, "all_bitflips_match() 1st Byte: %s test state (0x%06x): Eliminated. Bytes = %02x, %02x, Common Bits = %d\n", odd_even == ODD_STATE ? "odd" : "even", test_state[odd_even], byte, @@ -1767,15 +1767,15 @@ static void add_matching_states(statelist_t *candidates, uint8_t part_sum_a0, ui free(candidates->states[odd_even]); exit(4); } - + uint32_t *bitarray_a0 = part_sum_a0_bitarrays[odd_even][part_sum_a0/2]; uint32_t *bitarray_a8 = part_sum_a8_bitarrays[odd_even][part_sum_a8/2]; uint32_t *bitarray_bitflips = nonces[best_first_bytes[0]].states_bitarray[odd_even]; bitarray_AND4(candidates_bitarray, bitarray_a0, bitarray_a8, bitarray_bitflips); - + bitarray_to_list(best_first_bytes[0], candidates_bitarray, candidates->states[odd_even], &(candidates->len[odd_even]), odd_even); - + if (candidates->len[odd_even] == 0) { free(candidates->states[odd_even]); candidates->states[odd_even] = NULL; @@ -1825,7 +1825,7 @@ static void add_bitflip_candidates(uint8_t byte) PrintAndLogEx(WARNING, "Out of memory error in add_bitflip_candidates().\n"); exit(4); } - + bitarray_to_list(byte, nonces[byte].states_bitarray[odd_even], candidates->states[odd_even], &(candidates->len[odd_even]), odd_even); if (candidates->len[odd_even] + 1 < worstcase_size) { @@ -1844,7 +1844,7 @@ static bool TestIfKeyExists(uint64_t key) uint32_t state_odd = pcs->odd & 0x00ffffff; uint32_t state_even = pcs->even & 0x00ffffff; - + uint64_t count = 0; for (statelist_t *p = candidates; p != NULL; p = p->next) { bool found_odd = false; @@ -1898,10 +1898,10 @@ static void init_book_of_work(void) } } -static void +static void #ifdef __has_attribute #if __has_attribute(force_align_arg_pointer) -__attribute__((force_align_arg_pointer)) +__attribute__((force_align_arg_pointer)) #endif #endif *generate_candidates_worker_thread(void *args) @@ -1910,14 +1910,14 @@ __attribute__((force_align_arg_pointer)) uint16_t sum_a0 = sums[sum_args[0]]; uint16_t sum_a8 = sums[sum_args[1]]; // uint16_t my_thread_number = sums[2]; - + bool there_might_be_more_work = true; do { there_might_be_more_work = false; for (uint8_t p = 0; p < NUM_PART_SUMS; p++) { for (uint8_t q = 0; q < NUM_PART_SUMS; q++) { if (2*p*(16-2*q) + (16-2*p)*2*q == sum_a0) { - // PrintAndLogEx(NORMAL, "Reducing Partial Statelists (p,q) = (%d,%d) with lengths %d, %d\n", + // PrintAndLogEx(NORMAL, "Reducing Partial Statelists (p,q) = (%d,%d) with lengths %d, %d\n", // p, q, partial_statelist[p].len[ODD_STATE], partial_statelist[q].len[EVEN_STATE]); for (uint8_t r = 0; r < NUM_PART_SUMS; r++) { for (uint8_t s = 0; s < NUM_PART_SUMS; s++) { @@ -1952,13 +1952,13 @@ __attribute__((force_align_arg_pointer)) add_cached_states(current_candidates, 2*q, 2*s, EVEN_STATE); even_completed = true; } - + bool work_required = true; // if there had been two cached results, there is no more work to do if (even_completed && odd_completed) { work_required = false; - } + } // if there had been one cached empty result, there is no need to calculate the other part: if (work_required) { @@ -1966,7 +1966,7 @@ __attribute__((force_align_arg_pointer)) current_candidates->len[ODD_STATE] = 0; current_candidates->states[ODD_STATE] = NULL; work_required = false; - } + } if (odd_completed && !current_candidates->len[ODD_STATE]) { current_candidates->len[EVEN_STATE] = 0; current_candidates->states[EVEN_STATE] = NULL; @@ -1995,7 +1995,7 @@ __attribute__((force_align_arg_pointer)) work_required = false; } } - + if (work_required) { // we had no cached result. Need to calculate both odd and even sl_cache[p][r][ODD_STATE].cache_status = WORK_IN_PROGRESS; sl_cache[q][s][EVEN_STATE].cache_status = WORK_IN_PROGRESS; @@ -2027,10 +2027,10 @@ __attribute__((force_align_arg_pointer)) // log((uint64_t)current_candidates->len[ODD_STATE] * current_candidates->len[EVEN_STATE])/log(2)); // uint32_t estimated_odd = estimated_num_states_part_sum(best_first_bytes[0], p, r, ODD_STATE); // uint32_t estimated_even= estimated_num_states_part_sum(best_first_bytes[0], q, s, EVEN_STATE); - // uint64_t estimated_total = (uint64_t)estimated_odd * estimated_even; + // uint64_t estimated_total = (uint64_t)estimated_odd * estimated_even; // PrintAndLogEx(NORMAL, "Estimated: %" PRIu32 " * %" PRIu32 " = %" PRIu64 " (2^%0.1f)\n", estimated_odd, estimated_even, estimated_total, log(estimated_total) / log(2)); // if (estimated_odd < current_candidates->len[ODD_STATE] || estimated_even < current_candidates->len[EVEN_STATE]) { - // PrintAndLogEx(NORMAL, "############################################################################ERROR! ESTIMATED < REAL !!!\n"); + // PrintAndLogEx(NORMAL, "############################################################################ERROR! ESTIMATED < REAL !!!\n"); // //exit(2); // } // } @@ -2041,14 +2041,14 @@ __attribute__((force_align_arg_pointer)) } } } while (there_might_be_more_work); - + return NULL; } static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx) { - + init_statelist_cache(); init_book_of_work(); @@ -2058,7 +2058,7 @@ static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx) // create and run worker threads pthread_t thread_id[NUM_REDUCTION_WORKING_THREADS]; - + uint16_t sums[NUM_REDUCTION_WORKING_THREADS][3]; for (uint16_t i = 0; i < NUM_REDUCTION_WORKING_THREADS; i++) { sums[i][0] = sum_a0_idx; @@ -2066,7 +2066,7 @@ static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx) sums[i][2] = i+1; pthread_create(thread_id + i, NULL, generate_candidates_worker_thread, sums[i]); } - + // wait for threads to terminate: for (uint16_t i = 0; i < NUM_REDUCTION_WORKING_THREADS; i++) { pthread_join(thread_id[i], NULL); @@ -2074,7 +2074,7 @@ static void generate_candidates(uint8_t sum_a0_idx, uint8_t sum_a8_idx) // clean up mutex pthread_mutex_destroy(&statelist_cache_mutex); - + maximum_states = 0; for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) { maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE]; @@ -2104,8 +2104,8 @@ static void free_candidates_memory(statelist_t *sl) static void pre_XOR_nonces(void) { - // prepare acquired nonces for faster brute forcing. - + // prepare acquired nonces for faster brute forcing. + // XOR the cryptoUID and its parity for (uint16_t i = 0; i < 256; i++) { noncelistentry_t *test_nonce = nonces[i].first; @@ -2142,8 +2142,8 @@ static void Tests() for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { uint32_t *bitset = nonces[best_first_bytes[0]].states_bitarray[odd_even]; if (!test_bit24(bitset, test_state[odd_even])) { - PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n", - odd_even==EVEN_STATE?"even":"odd ", + PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n", + odd_even==EVEN_STATE?"even":"odd ", best_first_bytes[0]); } } @@ -2153,43 +2153,43 @@ static void Tests() for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { uint32_t *bitset = all_bitflips_bitarray[odd_even]; if (!test_bit24(bitset, test_state[odd_even])) { - PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n", + PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n", odd_even==EVEN_STATE?"even":"odd "); } } - } + } } -static void Tests2(void) +static void Tests2(void) { if (known_target_key != -1) { for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { uint32_t *bitset = nonces[best_first_byte_smallest_bitarray].states_bitarray[odd_even]; if (!test_bit24(bitset, test_state[odd_even])) { PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of first nonce byte's (0x%02x) states_bitarray!\n", - odd_even==EVEN_STATE?"even":"odd ", + odd_even==EVEN_STATE?"even":"odd ", best_first_byte_smallest_bitarray); } } - } + } if (known_target_key != -1) { for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { uint32_t *bitset = all_bitflips_bitarray[odd_even]; if (!test_bit24(bitset, test_state[odd_even])) { - PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n", + PrintAndLogEx(NORMAL, "\nBUG: known target key's %s state is not member of all_bitflips_bitarray!\n", odd_even==EVEN_STATE?"even":"odd "); } } - } - + } + } static uint16_t real_sum_a8 = 0; -static void set_test_state(uint8_t byte) +static void set_test_state(uint8_t byte) { struct Crypto1State *pcs; pcs = crypto1_create(known_target_key); @@ -2201,11 +2201,11 @@ static void set_test_state(uint8_t byte) } -int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests, uint64_t *foundkey, char *filename) +int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t *trgkey, bool nonce_file_read, bool nonce_file_write, bool slow, int tests, uint64_t *foundkey, char *filename) { - char progress_text[80]; + char progress_text[80]; char instr_set[12] = {0}; - + get_SIMD_instruction_set(instr_set); PrintAndLogEx(SUCCESS,"Using %s SIMD core.", instr_set); @@ -2217,11 +2217,11 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc // set the correct locale for the stats printing write_stats = true; setlocale(LC_NUMERIC, ""); - if ((fstats = fopen("hardnested_stats.txt","a")) == NULL) { + if ((fstats = fopen("hardnested_stats.txt","a")) == NULL) { PrintAndLogEx(WARNING, "Could not create/open file hardnested_stats.txt"); return 3; } - + for (uint32_t i = 0; i < tests; i++) { start_time = msclock(); print_progress_header(); @@ -2241,7 +2241,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc init_allbitflips_array(); init_nonce_memory(); update_reduction_rate(0.0, true); - + simulate_acquire_nonces(); set_test_state(best_first_bytes[0]); @@ -2252,7 +2252,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc fprintf(fstats, "%" PRIu16 ";%1.1f;", sums[first_byte_Sum], log(p_K0[first_byte_Sum])/log(2.0)); fprintf(fstats, "%" PRIu16 ";%1.1f;", sums[nonces[best_first_bytes[0]].sum_a8_guess[0].sum_a8_idx], log(p_K[nonces[best_first_bytes[0]].sum_a8_guess[0].sum_a8_idx])/log(2.0)); fprintf(fstats, "%" PRIu16 ";", real_sum_a8); - + #ifdef DEBUG_KEY_ELIMINATION failstr[0] = '\0'; #endif @@ -2263,7 +2263,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc float expected_brute_force1 = (float)num_odd * num_even / 2.0; float expected_brute_force2 = nonces[best_first_bytes[0]].expected_num_brute_force; fprintf(fstats, "%1.1f;%1.1f;", log(expected_brute_force1)/log(2.0), log(expected_brute_force2)/log(2.0)); - + if (expected_brute_force1 < expected_brute_force2) { hardnested_print_progress(num_acquired_nonces, "(Ignoring Sum(a8) properties)", expected_brute_force1, 0); set_test_state(best_first_byte_smallest_bitarray); @@ -2289,7 +2289,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc for (uint8_t j = 0; j < NUM_SUMS && !key_found; j++) { float expected_brute_force = nonces[best_first_bytes[0]].expected_num_brute_force; sprintf(progress_text, "(%d. guess: Sum(a8) = %" PRIu16 ")", j+1, sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx]); - hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0); + hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0); if (sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx] != real_sum_a8) { sprintf(progress_text, "(Estimated Sum(a8) is WRONG! Correct Sum(a8) = %" PRIu16 ")", real_sum_a8); hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0); @@ -2314,7 +2314,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc #else fprintf(fstats, "%1.0f;%d\n", log(num_keys_tested)/log(2.0), (float)num_keys_tested/brute_force_per_second, key_found); #endif - + free_nonces_memory(); free_bitarray(all_bitflips_bitarray[ODD_STATE]); free_bitarray(all_bitflips_bitarray[EVEN_STATE]); @@ -2357,7 +2357,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc free_bitarray(all_bitflips_bitarray[EVEN_STATE]); free_sum_bitarrays(); free_part_sum_bitarrays(); - + return is_OK; } } @@ -2368,7 +2368,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc } else { known_target_key = -1; } - + Tests(); free_bitflip_bitarrays(); @@ -2378,14 +2378,14 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc uint32_t num_even = nonces[best_first_byte_smallest_bitarray].num_states_bitarray[EVEN_STATE]; float expected_brute_force1 = (float)num_odd * num_even / 2.0; float expected_brute_force2 = nonces[best_first_bytes[0]].expected_num_brute_force; - + if (expected_brute_force1 < expected_brute_force2) { hardnested_print_progress(num_acquired_nonces, "(Ignoring Sum(a8) properties)", expected_brute_force1, 0); set_test_state(best_first_byte_smallest_bitarray); add_bitflip_candidates(best_first_byte_smallest_bitarray); Tests2(); maximum_states = 0; - + for (statelist_t *sl = candidates; sl != NULL; sl = sl->next) { maximum_states += (uint64_t)sl->len[ODD_STATE] * sl->len[EVEN_STATE]; } @@ -2400,20 +2400,20 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc free_candidates_memory(candidates); candidates = NULL; } else { - + pre_XOR_nonces(); prepare_bf_test_nonces(nonces, best_first_bytes[0]); - + for (uint8_t j = 0; j < NUM_SUMS && !key_found; j++) { float expected_brute_force = nonces[best_first_bytes[0]].expected_num_brute_force; sprintf(progress_text, "(%d. guess: Sum(a8) = %" PRIu16 ")", j+1, sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx]); - hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0); - + hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0); + if (trgkey != NULL && sums[nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx] != real_sum_a8) { sprintf(progress_text, "(Estimated Sum(a8) is WRONG! Correct Sum(a8) = %" PRIu16 ")", real_sum_a8); hardnested_print_progress(num_acquired_nonces, progress_text, expected_brute_force, 0); } - + generate_candidates(first_byte_Sum, nonces[best_first_bytes[0]].sum_a8_guess[j].sum_a8_idx); key_found = brute_force(foundkey); free_statelist_cache(); @@ -2429,7 +2429,7 @@ int mfnestedhard(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint8_t trgBloc } } - + free_nonces_memory(); free_bitarray(all_bitflips_bitarray[ODD_STATE]); free_bitarray(all_bitflips_bitarray[EVEN_STATE]); diff --git a/client/cmdhfmfp.c b/client/cmdhfmfp.c index 348a4a9c9..ade39b9bc 100644 --- a/client/cmdhfmfp.c +++ b/client/cmdhfmfp.c @@ -34,10 +34,10 @@ static const uint8_t DefaultKey[16] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, static int CmdHelp(const char *Cmd); int CmdHFMFPInfo(const char *cmd) { - + if (cmd && strlen(cmd) > 0) PrintAndLogEx(WARNING, "command don't have any parameters.\n"); - + // info about 14a part CmdHF14AInfo(""); @@ -47,16 +47,16 @@ int CmdHFMFPInfo(const char *cmd) { UsbCommand resp; WaitForResponse(CMD_ACK,&resp); - + iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision - + if (select_status == 1 || select_status == 2) { PrintAndLogEx(NORMAL, "----------------------------------------------"); PrintAndLogEx(NORMAL, "Mifare Plus info:"); - + // MIFARE Type Identification Procedure // https://www.nxp.com/docs/en/application-note/AN10833.pdf uint16_t ATQA = card.atqa[0] + (card.atqa[1] << 8); @@ -64,7 +64,7 @@ int CmdHFMFPInfo(const char *cmd) { if (ATQA == 0x0002) PrintAndLogEx(INFO, "ATQA: Mifare Plus 4k 4bUID"); if (ATQA == 0x0044) PrintAndLogEx(INFO, "ATQA: Mifare Plus 2k 7bUID"); if (ATQA == 0x0042) PrintAndLogEx(INFO, "ATQA: Mifare Plus 4k 7bUID"); - + uint8_t SLmode = 0xff; if (card.sak == 0x08) { PrintAndLogEx(INFO, "SAK: Mifare Plus 2k 7bUID"); @@ -98,7 +98,7 @@ int CmdHFMFPInfo(const char *cmd) { } } } - + if (SLmode != 0xff) PrintAndLogEx(INFO, "Mifare Plus SL mode: SL%d", SLmode); else @@ -106,9 +106,9 @@ int CmdHFMFPInfo(const char *cmd) { } else { PrintAndLogEx(INFO, "Mifare Plus info not available."); } - + DropField(); - + return 0; } @@ -118,8 +118,8 @@ int CmdHFMFPWritePerso(const char *cmd) { uint8_t key[64] = {0}; int keyLen = 0; - CLIParserInit("hf mfp wrp", - "Executes Write Perso command. Can be used in SL0 mode only.", + CLIParserInit("hf mfp wrp", + "Executes Write Perso command. Can be used in SL0 mode only.", "Usage:\n\thf mfp wrp 4000 000102030405060708090a0b0c0d0e0f -> write key (00..0f) to key number 4000 \n" "\thf mfp wrp 4000 -> write default key(0xff..0xff) to key number 4000"); @@ -131,19 +131,19 @@ int CmdHFMFPWritePerso(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); CLIGetHexWithReturn(2, keyNum, &keyNumLen); CLIGetHexWithReturn(3, key, &keyLen); CLIParserFree(); - + mfpSetVerboseMode(verbose); - + if (!keyLen) { memmove(key, DefaultKey, 16); keyLen = 16; } - + if (keyNumLen != 2) { PrintAndLogEx(ERR, "Key number length must be 2 bytes instead of: %d", keyNumLen); return 1; @@ -161,7 +161,7 @@ int CmdHFMFPWritePerso(const char *cmd) { PrintAndLogEx(ERR, "Exchange error: %d", res); return res; } - + if (datalen != 3) { PrintAndLogEx(ERR, "Command must return 3 bytes instead of: %d", datalen); return 1; @@ -172,7 +172,7 @@ int CmdHFMFPWritePerso(const char *cmd) { return 1; } PrintAndLogEx(INFO, "Write OK."); - + return 0; } @@ -186,8 +186,8 @@ int CmdHFMFPInitPerso(const char *cmd) { uint8_t data[250] = {0}; int datalen = 0; - CLIParserInit("hf mfp initp", - "Executes Write Perso command for all card's keys. Can be used in SL0 mode only.", + CLIParserInit("hf mfp initp", + "Executes Write Perso command for all card's keys. Can be used in SL0 mode only.", "Usage:\n\thf mfp initp 000102030405060708090a0b0c0d0e0f -> fill all the keys with key (00..0f)\n" "\thf mfp initp -vv -> fill all the keys with default key(0xff..0xff) and show all the data exchange"); @@ -198,7 +198,7 @@ int CmdHFMFPInitPerso(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); bool verbose2 = arg_get_lit(1) > 1; CLIGetHexWithReturn(2, key, &keyLen); @@ -208,7 +208,7 @@ int CmdHFMFPInitPerso(const char *cmd) { PrintAndLogEx(ERR, "Key length must be 16 bytes instead of: %d", keyLen); return 1; } - + if (!keyLen) memmove(key, DefaultKey, 16); @@ -226,7 +226,7 @@ int CmdHFMFPInitPerso(const char *cmd) { break; } } - + mfpSetVerboseMode(verbose); for (int i = 0; i < sizeof(CardAddresses) / 2; i++) { keyNum[0] = CardAddresses[i] >> 8; @@ -241,20 +241,20 @@ int CmdHFMFPInitPerso(const char *cmd) { } } } - + DropField(); - + if (res) return res; - + PrintAndLogEx(INFO, "Done."); - + return 0; } int CmdHFMFPCommitPerso(const char *cmd) { - CLIParserInit("hf mfp commitp", - "Executes Commit Perso command. Can be used in SL0 mode only.", + CLIParserInit("hf mfp commitp", + "Executes Commit Perso command. Can be used in SL0 mode only.", "Usage:\n\thf mfp commitp -> \n"); void* argtable[] = { @@ -264,12 +264,12 @@ int CmdHFMFPCommitPerso(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); CLIParserFree(); - + mfpSetVerboseMode(verbose); - + uint8_t data[250] = {0}; int datalen = 0; @@ -278,7 +278,7 @@ int CmdHFMFPCommitPerso(const char *cmd) { PrintAndLogEx(ERR, "Exchange error: %d", res); return res; } - + if (datalen != 3) { PrintAndLogEx(ERR, "Command must return 3 bytes instead of: %d", datalen); return 1; @@ -298,9 +298,9 @@ int CmdHFMFPAuth(const char *cmd) { int keynlen = 0; uint8_t key[250] = {0}; int keylen = 0; - - CLIParserInit("hf mfp auth", - "Executes AES authentication command for Mifare Plus card", + + CLIParserInit("hf mfp auth", + "Executes AES authentication command for Mifare Plus card", "Usage:\n\thf mfp auth 4000 000102030405060708090a0b0c0d0e0f -> executes authentication\n" "\thf mfp auth 9003 FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF -v -> executes authentication and shows all the system data\n"); @@ -312,17 +312,17 @@ int CmdHFMFPAuth(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); CLIGetHexWithReturn(2, keyn, &keynlen); CLIGetHexWithReturn(3, key, &keylen); CLIParserFree(); - + if (keynlen != 2) { PrintAndLogEx(ERR, "ERROR: must be 2 bytes long instead of: %d", keynlen); return 1; } - + if (keylen != 16) { PrintAndLogEx(ERR, "ERROR: must be 16 bytes long instead of: %d", keylen); return 1; @@ -335,9 +335,9 @@ int CmdHFMFPRdbl(const char *cmd) { uint8_t keyn[2] = {0}; uint8_t key[250] = {0}; int keylen = 0; - - CLIParserInit("hf mfp rdbl", - "Reads several blocks from Mifare Plus card.", + + CLIParserInit("hf mfp rdbl", + "Reads several blocks from Mifare Plus card.", "Usage:\n\thf mfp rdbl 0 000102030405060708090a0b0c0d0e0f -> executes authentication and read block 0 data\n" "\thf mfp rdbl 1 -v -> executes authentication and shows sector 1 data with default key 0xFF..0xFF and some additional data\n"); @@ -352,7 +352,7 @@ int CmdHFMFPRdbl(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, false); - + bool verbose = arg_get_lit(1); int blocksCount = arg_get_int_def(2, 1); bool keyB = arg_get_lit(3); @@ -360,19 +360,19 @@ int CmdHFMFPRdbl(const char *cmd) { uint32_t blockn = arg_get_int(5); CLIGetHexWithReturn(6, key, &keylen); CLIParserFree(); - + mfpSetVerboseMode(verbose); if (!keylen) { memmove(key, DefaultKey, 16); keylen = 16; } - + if (blockn > 255) { PrintAndLogEx(ERR, " must be in range [0..255] instead of: %d", blockn); return 1; } - + if (keylen != 16) { PrintAndLogEx(ERR, " must be 16 bytes long instead of: %d", keylen); return 1; @@ -383,25 +383,25 @@ int CmdHFMFPRdbl(const char *cmd) { PrintAndLogEx(ERR, "blocks count must be less than 3 instead of: %d", blocksCount); return 1; } - + if (blocksCount > 1 && mfIsSectorTrailer(blockn)) { PrintAndLog("WARNING: trailer!"); } - + uint8_t sectorNum = mfSectorNum(blockn & 0xff); uint16_t uKeyNum = 0x4000 + sectorNum * 2 + (keyB ? 1 : 0); keyn[0] = uKeyNum >> 8; keyn[1] = uKeyNum & 0xff; if (verbose) PrintAndLogEx(INFO, "--block:%d sector[%d]:%02x key:%04x", blockn, mfNumBlocksPerSector(sectorNum), sectorNum, uKeyNum); - + mf4Session session; int res = MifareAuth4(&session, keyn, key, true, true, verbose); if (res) { PrintAndLogEx(ERR, "Authentication error: %d", res); return res; } - + uint8_t data[250] = {0}; int datalen = 0; uint8_t mac[8] = {0}; @@ -410,12 +410,12 @@ int CmdHFMFPRdbl(const char *cmd) { PrintAndLogEx(ERR, "Read error: %d", res); return res; } - + if (datalen && data[0] != 0x90) { PrintAndLogEx(ERR, "Card read error: %02x %s", data[0], mfpGetErrorDescription(data[0])); return 6; } - + if (datalen != 1 + blocksCount * 16 + 8 + 2) { PrintAndLogEx(ERR, "Error return length:%d", datalen); return 5; @@ -435,11 +435,11 @@ int CmdHFMFPRdbl(const char *cmd) { PrintAndLogEx(WARNING, "WARNING: mac not equal..."); PrintAndLogEx(WARNING, "MAC card: %s", sprint_hex(&data[blocksCount * 16 + 1], 8)); PrintAndLogEx(WARNING, "MAC reader: %s", sprint_hex(mac, 8)); - } else { + } else { if(verbose) PrintAndLogEx(INFO, "MAC: %s", sprint_hex(&data[blocksCount * 16 + 1], 8)); } - + return 0; } @@ -447,9 +447,9 @@ int CmdHFMFPRdsc(const char *cmd) { uint8_t keyn[2] = {0}; uint8_t key[250] = {0}; int keylen = 0; - - CLIParserInit("hf mfp rdsc", - "Reads one sector from Mifare Plus card.", + + CLIParserInit("hf mfp rdsc", + "Reads one sector from Mifare Plus card.", "Usage:\n\thf mfp rdsc 0 000102030405060708090a0b0c0d0e0f -> executes authentication and read sector 0 data\n" "\thf mfp rdsc 1 -v -> executes authentication and shows sector 1 data with default key 0xFF..0xFF and some additional data\n"); @@ -463,44 +463,44 @@ int CmdHFMFPRdsc(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, false); - + bool verbose = arg_get_lit(1); bool keyB = arg_get_lit(2); bool plain = arg_get_lit(3); uint32_t sectorNum = arg_get_int(4); CLIGetHexWithReturn(5, key, &keylen); CLIParserFree(); - + mfpSetVerboseMode(verbose); if (!keylen) { memmove(key, DefaultKey, 16); keylen = 16; } - + if (sectorNum > 39) { PrintAndLogEx(ERR, " must be in range [0..39] instead of: %d", sectorNum); return 1; } - + if (keylen != 16) { PrintAndLogEx(ERR, " must be 16 bytes long instead of: %d", keylen); return 1; } - + uint16_t uKeyNum = 0x4000 + sectorNum * 2 + (keyB ? 1 : 0); keyn[0] = uKeyNum >> 8; keyn[1] = uKeyNum & 0xff; if (verbose) PrintAndLogEx(INFO, "--sector[%d]:%02x key:%04x", mfNumBlocksPerSector(sectorNum), sectorNum, uKeyNum); - + mf4Session session; int res = MifareAuth4(&session, keyn, key, true, true, verbose); if (res) { PrintAndLogEx(ERR, "Authentication error: %d", res); return res; } - + uint8_t data[250] = {0}; int datalen = 0; uint8_t mac[8] = {0}; @@ -511,7 +511,7 @@ int CmdHFMFPRdsc(const char *cmd) { DropField(); return res; } - + if (datalen && data[0] != 0x90) { PrintAndLogEx(ERR, "Card read error: %02x %s", data[0], mfpGetErrorDescription(data[0])); DropField(); @@ -524,18 +524,18 @@ int CmdHFMFPRdsc(const char *cmd) { } PrintAndLogEx(INFO, "data[%03d]: %s", n, sprint_hex(&data[1], 16)); - + if (memcmp(&data[1 + 16], mac, 8)) { PrintAndLogEx(WARNING, "WARNING: mac on block %d not equal...", n); PrintAndLogEx(WARNING, "MAC card: %s", sprint_hex(&data[1 + 16], 8)); PrintAndLogEx(WARNING, "MAC reader: %s", sprint_hex(mac, 8)); - } else { + } else { if(verbose) PrintAndLogEx(INFO, "MAC: %s", sprint_hex(&data[1 + 16], 8)); } } DropField(); - + return 0; } @@ -545,9 +545,9 @@ int CmdHFMFPWrbl(const char *cmd) { int keylen = 0; uint8_t datain[250] = {0}; int datainlen = 0; - - CLIParserInit("hf mfp wrbl", - "Writes one block to Mifare Plus card.", + + CLIParserInit("hf mfp wrbl", + "Writes one block to Mifare Plus card.", "Usage:\n\thf mfp wrbl 1 ff0000000000000000000000000000ff 000102030405060708090a0b0c0d0e0f -> writes block 1 data\n" "\thf mfp wrbl 2 ff0000000000000000000000000000ff -v -> writes block 2 data with default key 0xFF..0xFF and some additional data\n"); @@ -561,26 +561,26 @@ int CmdHFMFPWrbl(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, false); - + bool verbose = arg_get_lit(1); bool keyB = arg_get_lit(2); uint32_t blockNum = arg_get_int(3); CLIGetHexWithReturn(4, datain, &datainlen); CLIGetHexWithReturn(5, key, &keylen); CLIParserFree(); - + mfpSetVerboseMode(verbose); if (!keylen) { memmove(key, DefaultKey, 16); keylen = 16; } - + if (blockNum > 39) { PrintAndLogEx(ERR, " must be in range [0..255] instead of: %d", blockNum); return 1; } - + if (keylen != 16) { PrintAndLogEx(ERR, " must be 16 bytes long instead of: %d", keylen); return 1; @@ -590,14 +590,14 @@ int CmdHFMFPWrbl(const char *cmd) { PrintAndLogEx(ERR, " must be 16 bytes long instead of: %d", datainlen); return 1; } - + uint8_t sectorNum = mfSectorNum(blockNum & 0xff); uint16_t uKeyNum = 0x4000 + sectorNum * 2 + (keyB ? 1 : 0); keyn[0] = uKeyNum >> 8; keyn[1] = uKeyNum & 0xff; if (verbose) PrintAndLogEx(INFO, "--block:%d sector[%d]:%02x key:%04x", blockNum & 0xff, mfNumBlocksPerSector(sectorNum), sectorNum, uKeyNum); - + mf4Session session; int res = MifareAuth4(&session, keyn, key, true, true, verbose); if (res) { @@ -614,37 +614,37 @@ int CmdHFMFPWrbl(const char *cmd) { DropField(); return res; } - + if (datalen != 3 && (datalen != 3 + 8)) { PrintAndLogEx(ERR, "Error return length:%d", datalen); DropField(); return 5; } - + if (datalen && data[0] != 0x90) { PrintAndLogEx(ERR, "Card write error: %02x %s", data[0], mfpGetErrorDescription(data[0])); DropField(); return 6; } - + if (memcmp(&data[1], mac, 8)) { PrintAndLogEx(WARNING, "WARNING: mac not equal..."); PrintAndLogEx(WARNING, "MAC card: %s", sprint_hex(&data[1], 8)); PrintAndLogEx(WARNING, "MAC reader: %s", sprint_hex(mac, 8)); - } else { + } else { if(verbose) PrintAndLogEx(INFO, "MAC: %s", sprint_hex(&data[1], 8)); } - + DropField(); - PrintAndLogEx(INFO, "Write OK."); + PrintAndLogEx(INFO, "Write OK."); return 0; } int CmdHFMFPMAD(const char *cmd) { - CLIParserInit("hf mfp mad", - "Checks and prints Mifare Application Directory (MAD)", + CLIParserInit("hf mfp mad", + "Checks and prints Mifare Application Directory (MAD)", "Usage:\n\thf mfp mad -> shows MAD if exists\n" "\thf mfp mad -a 03e1 -k d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7 -> shows NDEF data if exists\n"); @@ -657,7 +657,7 @@ int CmdHFMFPMAD(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); uint8_t aid[2] = {0}; int aidlen; @@ -666,30 +666,30 @@ int CmdHFMFPMAD(const char *cmd) { int keylen; CLIGetHexWithReturn(3, key, &keylen); bool keyB = arg_get_lit(4); - + CLIParserFree(); - + if (aidlen != 2 && keylen > 0) { PrintAndLogEx(WARNING, "do not need a key without aid."); } uint8_t sector0[16 * 4] = {0}; uint8_t sector10[16 * 4] = {0}; - + if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector0, verbose)) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys."); return 2; } - + if (verbose) { for(int i = 0; i < 4; i ++) - PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(§or0[i * 16], 16)); + PrintAndLogEx(NORMAL, "[%d] %s", i, sprint_hex(§or0[i * 16], 16)); } bool haveMAD2 = false; MAD1DecodeAndPrint(sector0, verbose, &haveMAD2); - + if (haveMAD2) { if (mfpReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector10, verbose)) { PrintAndLogEx(NORMAL, ""); @@ -703,7 +703,7 @@ int CmdHFMFPMAD(const char *cmd) { if (aidlen == 2) { uint16_t aaid = (aid[0] << 8) + aid[1]; PrintAndLogEx(NORMAL, "\n-------------- AID 0x%04x ---------------", aaid); - + uint16_t mad[7 + 8 + 8 + 8 + 8] = {0}; size_t madlen = 0; if (MADDecode(sector0, sector10, mad, &madlen)) { @@ -716,7 +716,7 @@ int CmdHFMFPMAD(const char *cmd) { if (keylen == 16) { memcpy(akey, key, 16); } - + for (int i = 0; i < madlen; i++) { if (aaid == mad[i]) { uint8_t vsector[16 * 4] = {0}; @@ -725,20 +725,20 @@ int CmdHFMFPMAD(const char *cmd) { PrintAndLogEx(ERR, "read sector %d error.", i + 1); return 2; } - + for(int j = 0; j < (verbose ? 4 : 3); j ++) - PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16)); + PrintAndLogEx(NORMAL, " [%03d] %s", (i + 1) * 4 + j, sprint_hex(&vsector[j * 16], 16)); } - } + } } - + return 0; } int CmdHFMFPNDEF(const char *cmd) { - CLIParserInit("hf mfp ndef", - "Prints NFC Data Exchange Format (NDEF)", + CLIParserInit("hf mfp ndef", + "Prints NFC Data Exchange Format (NDEF)", "Usage:\n\thf mfp ndef -> shows NDEF data\n" "\thf mfp ndef -a 03e1 -k d3f7d3f7d3f7d3f7d3f7d3f7d3f7d3f7 -> shows NDEF data with custom AID and key\n"); @@ -751,7 +751,7 @@ int CmdHFMFPNDEF(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool verbose = arg_get_lit(1); bool verbose2 = arg_get_lit(1) > 1; uint8_t aid[2] = {0}; @@ -761,38 +761,38 @@ int CmdHFMFPNDEF(const char *cmd) { int keylen; CLIGetHexWithReturn(3, key, &keylen); bool keyB = arg_get_lit(4); - + CLIParserFree(); uint16_t ndefAID = 0x03e1; if (aidlen == 2) ndefAID = (aid[0] << 8) + aid[1]; - + uint8_t ndefkey[16] = {0}; memcpy(ndefkey, g_mifarep_ndef_key, 16); if (keylen == 16) { memcpy(ndefkey, key, 16); } - + uint8_t sector0[16 * 4] = {0}; uint8_t sector10[16 * 4] = {0}; uint8_t data[4096] = {0}; int datalen = 0; PrintAndLogEx(NORMAL, ""); - + if (mfpReadSector(MF_MAD1_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector0, verbose)) { PrintAndLogEx(ERR, "read sector 0 error. card don't have MAD or don't have MAD on default keys."); return 2; } - + bool haveMAD2 = false; int res = MADCheck(sector0, NULL, verbose, &haveMAD2); if (res) { PrintAndLogEx(ERR, "MAD error %d.", res); return res; } - + if (haveMAD2) { if (mfpReadSector(MF_MAD2_SECTOR, MF_KEY_A, (uint8_t *)g_mifarep_mad_key, sector10, verbose)) { PrintAndLogEx(ERR, "read sector 0x10 error. card don't have MAD or don't have MAD on default keys."); @@ -815,25 +815,25 @@ int CmdHFMFPNDEF(const char *cmd) { PrintAndLogEx(ERR, "read sector %d error.", i + 1); return 2; } - + memcpy(&data[datalen], vsector, 16 * 3); datalen += 16 * 3; - + printf("."); } } printf(" OK\n"); - + if (!datalen) { PrintAndLogEx(ERR, "no NDEF data."); return 11; } - + if (verbose2) { PrintAndLogEx(NORMAL, "NDEF data:"); dump_buffer(data, datalen, stdout, 1); } - + NDEFDecodeAndPrint(data, datalen, verbose); return 0; diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 8b27d9b22..c24ba6407 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -61,7 +61,7 @@ uint32_t UL_TYPES_ARRAY[MAX_UL_TYPES] = { uint8_t UL_MEMORY_ARRAY[MAX_UL_TYPES] = { MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_ULC_BLOCKS, MAX_ULEV1a_BLOCKS, MAX_ULEV1b_BLOCKS, MAX_NTAG_203, - MAX_NTAG_203, MAX_NTAG_210, MAX_NTAG_212, MAX_NTAG_213, MAX_NTAG_215, MAX_NTAG_216, + MAX_NTAG_203, MAX_NTAG_210, MAX_NTAG_212, MAX_NTAG_213, MAX_NTAG_215, MAX_NTAG_216, MAX_UL_BLOCKS, MAX_MY_D_NFC, MAX_MY_D_MOVE, MAX_MY_D_MOVE, MAX_MY_D_MOVE_LEAN, MAX_UL_BLOCKS, MAX_ULEV1a_BLOCKS, MAX_NTAG_213, MAX_NTAG_216, MAX_UL_NANO_40 }; @@ -69,13 +69,13 @@ uint8_t UL_MEMORY_ARRAY[MAX_UL_TYPES] = { //------------------------------------ // Pwd & Pack generation Stuff //------------------------------------ -const uint32_t c_D[] = { - 0x6D835AFC, 0x7D15CD97, 0x0942B409, 0x32F9C923, 0xA811FB02, 0x64F121E8, - 0xD1CC8B4E, 0xE8873E6F, 0x61399BBB, 0xF1B91926, 0xAC661520, 0xA21A31C9, - 0xD424808D, 0xFE118E07, 0xD18E728D, 0xABAC9E17, 0x18066433, 0x00E18E79, - 0x65A77305, 0x5AE9E297, 0x11FC628C, 0x7BB3431F, 0x942A8308, 0xB2F8FD20, +const uint32_t c_D[] = { + 0x6D835AFC, 0x7D15CD97, 0x0942B409, 0x32F9C923, 0xA811FB02, 0x64F121E8, + 0xD1CC8B4E, 0xE8873E6F, 0x61399BBB, 0xF1B91926, 0xAC661520, 0xA21A31C9, + 0xD424808D, 0xFE118E07, 0xD18E728D, 0xABAC9E17, 0x18066433, 0x00E18E79, + 0x65A77305, 0x5AE9E297, 0x11FC628C, 0x7BB3431F, 0x942A8308, 0xB2F8FD20, 0x5728B869, 0x30726D5A -}; +}; void transform_D(uint8_t* ru) { //Transform @@ -101,12 +101,12 @@ void transform_D(uint8_t* ru) { ru[6] = (v2 >> 16) & 0xFF; ru[7] = (v2 >> 24) & 0xFF; } - + // Certain pwd generation algo nickname A. -uint32_t ul_ev1_pwdgenA(uint8_t* uid) { +uint32_t ul_ev1_pwdgenA(uint8_t* uid) { uint8_t pos = (uid[3] ^ uid[4] ^ uid[5] ^ uid[6]) % 32; - + uint32_t xortable[] = { 0x4f2711c1, 0x07D7BB83, 0x9636EF07, 0xB5F4460E, 0xF271141C, 0x7D7BB038, 0x636EF871, 0x5F4468E3, 0x271149C7, 0xD7BB0B8F, 0x36EF8F1E, 0xF446863D, 0x7114947A, 0x7BB0B0F5, 0x6EF8F9EB, 0x44686BD7, @@ -116,7 +116,7 @@ uint32_t ul_ev1_pwdgenA(uint8_t* uid) { uint8_t entry[] = {0x00,0x00,0x00,0x00}; uint8_t pwd[] = {0x00,0x00,0x00,0x00}; - + num_to_bytes( xortable[pos], 4, entry); pwd[0] = entry[0] ^ uid[1] ^ uid[2] ^ uid[3]; @@ -131,7 +131,7 @@ uint32_t ul_ev1_pwdgenA(uint8_t* uid) { uint32_t ul_ev1_pwdgenB(uint8_t* uid) { uint8_t pwd[] = {0x00,0x00,0x00,0x00}; - + pwd[0] = uid[1] ^ uid[3] ^ 0xAA; pwd[1] = uid[2] ^ uid[4] ^ 0x55; pwd[2] = uid[3] ^ uid[5] ^ 0xAA; @@ -157,8 +157,8 @@ uint32_t ul_ev1_pwdgenC(uint8_t* uid){ } return BSWAP_32(pwd); } -// Certain pwd generation algo nickname D. -// a.k.a xzy +// Certain pwd generation algo nickname D. +// a.k.a xzy uint32_t ul_ev1_pwdgenD(uint8_t* uid){ uint8_t i; //Rotate @@ -166,9 +166,9 @@ uint32_t ul_ev1_pwdgenD(uint8_t* uid){ uint8_t ru[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //Rotated UID for (i = 0; i < 7; i++) ru[(i + r) & 7] = uid[i]; - + transform_D(ru); - + //Calc key uint32_t pwd = 0; //Key as int r = (ru[0] + ru[2] + ru[4] + ru[6]) & 3; //Offset @@ -195,11 +195,11 @@ uint16_t ul_ev1_packgenD(uint8_t* uid){ uint8_t ru[8] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; //Rotated UID for (i = 0; i < 7; i++) ru[(i + r) & 7] = uid[i]; - + transform_D(ru); - + //Calc pack - uint32_t p = 0; + uint32_t p = 0; for (i = 0; i < 8; i++) p += ru[i] * 13; @@ -208,12 +208,12 @@ uint16_t ul_ev1_packgenD(uint8_t* uid){ } int ul_ev1_pwdgen_selftest(){ - + uint8_t uid1[] = {0x04, 0x11, 0x12, 0x11, 0x12, 0x11, 0x10}; uint32_t pwd1 = ul_ev1_pwdgenA(uid1); PrintAndLogEx(NORMAL, "UID | %s | %08X | %s", sprint_hex(uid1,7), pwd1, (pwd1 == 0x8432EB17)?"OK":"->8432EB17<-"); - uint8_t uid2[] = {0x04, 0x1f, 0x98, 0xea, 0x1e, 0x3e, 0x81}; + uint8_t uid2[] = {0x04, 0x1f, 0x98, 0xea, 0x1e, 0x3e, 0x81}; uint32_t pwd2 = ul_ev1_pwdgenB(uid2); PrintAndLogEx(NORMAL, "UID | %s | %08X | %s", sprint_hex(uid2,7), pwd2, (pwd2 == 0x5fd37eca)?"OK":"->5fd37eca<--"); @@ -228,7 +228,7 @@ int ul_ev1_pwdgen_selftest(){ } //------------------------------------ -// get version nxp product type +// get version nxp product type char *getProductTypeStr( uint8_t id){ static char buf[20]; @@ -243,9 +243,9 @@ char *getProductTypeStr( uint8_t id){ } /* - The 7 MSBits (=n) code the storage size itself based on 2^n, + The 7 MSBits (=n) code the storage size itself based on 2^n, the LSBit is set to '0' if the size is exactly 2^n - and set to '1' if the storage size is between 2^n and 2^(n+1). + and set to '1' if the storage size is between 2^n and 2^(n+1). */ char *getUlev1CardSizeStr( uint8_t fsize ){ @@ -259,8 +259,8 @@ char *getUlev1CardSizeStr( uint8_t fsize ){ // is LSB set? if ( fsize & 1 ) sprintf(retStr, "%02X, (%u <-> %u bytes)",fsize, usize, lsize); - else - sprintf(retStr, "%02X, (%u bytes)", fsize, lsize); + else + sprintf(retStr, "%02X, (%u bytes)", fsize, lsize); return buf; } @@ -291,7 +291,7 @@ static int ul_select( iso14a_card_select_t *card ){ UsbCommand resp; bool ans = false; ans = WaitForResponseTimeout(CMD_ACK, &resp, 1500); - + if (!ans || resp.arg[0] < 1) { PrintAndLogEx(WARNING, "iso14443a card select failed"); DropField(); @@ -354,7 +354,7 @@ static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t pa int len = ul_send_cmd_raw(cmd, sizeof(cmd), pack, packLength); // NACK tables different tags, but between 0-9 is a NEGATIVE response. // ACK == 0xA - if ( len == 1 && pack[0] <= 0x09 ) + if ( len == 1 && pack[0] <= 0x09 ) return -1; return len; } @@ -381,7 +381,7 @@ static int ul_auth_select( iso14a_card_select_t *card, TagTypeUL_t tagtype, bool } static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ - uint8_t cmd[] = {MIFARE_ULEV1_VERSION}; + uint8_t cmd[] = {MIFARE_ULEV1_VERSION}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); return len; } @@ -410,7 +410,7 @@ static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ // Fudan check checks for which error is given for a command with incorrect crc // NXP UL chip responds with 01, fudan 00. // other possible checks: -// send a0 + crc +// send a0 + crc // UL responds with 00, fudan doesn't respond // or // send a200 + crc @@ -422,7 +422,7 @@ static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ // make sure field is off before calling this function static int ul_fudan_check( void ){ iso14a_card_select_t card; - if ( !ul_select(&card) ) + if ( !ul_select(&card) ) return UL_ERROR; UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_NO_RATS, 4, 0}}; @@ -459,7 +459,7 @@ static int ul_print_default( uint8_t *data){ case 0xc6: PrintAndLogEx(NORMAL, " IC type : SLE 66R32P 5120 Bytes"); break; //512 pages /2 sectors } } - // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 + // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; if ( data[3] == crc0 ) PrintAndLogEx(NORMAL, " BCC0 : %02X, Ok", data[3]); @@ -494,7 +494,7 @@ static int ndef_print_CC(uint8_t *data) { PrintAndLogEx(NORMAL, "--- NDEF Message"); PrintAndLogEx(NORMAL, "Capability Container: %s", sprint_hex(data,4) ); - PrintAndLogEx(NORMAL, " %02X : NDEF Magic Number", data[0]); + PrintAndLogEx(NORMAL, " %02X : NDEF Magic Number", data[0]); PrintAndLogEx(NORMAL, " %02X : version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0F); PrintAndLogEx(NORMAL, " %02X : Physical Memory Size: %d bytes", data[2], (data[2] + 1) * 8); if ( data[2] == 0x96 ) @@ -506,8 +506,8 @@ static int ndef_print_CC(uint8_t *data) { else if ( data[2] == 0x6D ) PrintAndLogEx(NORMAL, " %02X : NDEF Memory Size: %d bytes", data[2], 872); - PrintAndLogEx(NORMAL, " %02X : %s / %s", data[3], - (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", + PrintAndLogEx(NORMAL, " %02X : %s / %s", data[3], + (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", (data[3] & 0x0F)==0 ? "Write access granted without any security" : (data[3] & 0x0F)==0x0F ? "No write access granted at all" : "(RFU)"); return 0; } @@ -517,15 +517,15 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ spc[10]=0x00; char *spacer = spc + (10-spaces); - if ( tagtype & UL ) + if ( tagtype & UL ) PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight (MF0ICU1) %s", spacer, (tagtype & MAGIC) ? "" : "" ); else if ( tagtype & UL_C) PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight C (MF0ULC) %s", spacer, (tagtype & MAGIC) ? "" : "" ); else if ( tagtype & UL_NANO_40) - PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight Nano 40bytes (MF0UNH00)", spacer); + PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight Nano 40bytes (MF0UNH00)", spacer); else if ( tagtype & UL_EV1_48) - PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)", spacer); - else if ( tagtype & UL_EV1_128) + PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)", spacer); + else if ( tagtype & UL_EV1_128) PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)", spacer); else if ( tagtype & UL_EV1 ) PrintAndLogEx(NORMAL, "%sTYPE : MIFARE Ultralight EV1 UNKNOWN", spacer); @@ -546,14 +546,14 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ else if ( tagtype & NTAG_216 ) PrintAndLogEx(NORMAL, "%sTYPE : NTAG 216 888bytes (NT2H1611G0DU)", spacer); else if ( tagtype & NTAG_216_F ) - PrintAndLogEx(NORMAL, "%sTYPE : NTAG 216F 888bytes (NT2H1611F0DTL)", spacer); + PrintAndLogEx(NORMAL, "%sTYPE : NTAG 216F 888bytes (NT2H1611F0DTL)", spacer); else if ( tagtype & NTAG_I2C_1K ) PrintAndLogEx(NORMAL, "%sTYPE : NTAG I%sC 888bytes (NT3H1101FHK)", spacer, "\xFD"); - else if ( tagtype & NTAG_I2C_2K ) + else if ( tagtype & NTAG_I2C_2K ) PrintAndLogEx(NORMAL, "%sTYPE : NTAG I%sC 1904bytes (NT3H1201FHK)", spacer, "\xFD"); else if ( tagtype & NTAG_I2C_1K_PLUS ) PrintAndLogEx(NORMAL, "%sTYPE : NTAG I%sC plus 888bytes (NT3H2111FHK)", spacer, "\xFD"); - else if ( tagtype & NTAG_I2C_2K_PLUS ) + else if ( tagtype & NTAG_I2C_2K_PLUS ) PrintAndLogEx(NORMAL, "%sTYPE : NTAG I%sC plus 1912bytes (NT3H2211FHK)", spacer, "\xFD"); else if ( tagtype & MY_D ) PrintAndLogEx(NORMAL, "%sTYPE : INFINEON my-d\x99 (SLE 66RxxS)", spacer); @@ -617,29 +617,29 @@ static int ulev1_print_configuration(uint32_t tagtype, uint8_t *data, uint8_t st uint8_t vctid = data[5]; PrintAndLogEx(NORMAL, " cfg0 [%u/0x%02X] : %s", startPage, startPage, sprint_hex(data, 4)); - + if ( (tagtype & (NTAG_213_F | NTAG_216_F)) ) { uint8_t mirror_conf = (data[0] & 0xC0); uint8_t mirror_byte = (data[0] & 0x30); bool sleep_en = (data[0] & 0x08); strg_mod_en = (data[0] & 0x04); uint8_t fdp_conf = (data[0] & 0x03); - + switch (mirror_conf) { case 0: PrintAndLogEx(NORMAL, " - no ASCII mirror"); break; case 1: PrintAndLogEx(NORMAL, " - UID ASCII mirror"); break; case 2: PrintAndLogEx(NORMAL, " - NFC counter ASCII mirror"); break; - case 3: PrintAndLogEx(NORMAL, " - UID and NFC counter ASCII mirror"); break; + case 3: PrintAndLogEx(NORMAL, " - UID and NFC counter ASCII mirror"); break; default: break; } - - PrintAndLogEx(NORMAL, " - SLEEP mode %s", (sleep_en) ? "enabled":"disabled"); - + + PrintAndLogEx(NORMAL, " - SLEEP mode %s", (sleep_en) ? "enabled":"disabled"); + switch (fdp_conf) { case 0: PrintAndLogEx(NORMAL, " - no field detect"); break; case 1: PrintAndLogEx(NORMAL, " - enabled by first State-of-Frame (start of communication)"); break; case 2: PrintAndLogEx(NORMAL, " - enabled by selection of the tag"); break; - case 3: PrintAndLogEx(NORMAL, " - enabled by field presence"); break; + case 3: PrintAndLogEx(NORMAL, " - enabled by field presence"); break; default: break; } // valid mirror start page and byte position within start page. @@ -656,14 +656,14 @@ static int ulev1_print_configuration(uint32_t tagtype, uint8_t *data, uint8_t st case 2: { PrintAndLogEx(NORMAL, " mirror start block %02X | byte pos %02X - %s", data[2], mirror_byte, ( data[2]>= 0x4 && data[2] <= 0xE0) ? "OK":"Invalid value"); break;} case 3: { PrintAndLogEx(NORMAL, " mirror start block %02X | byte pos %02X - %s", data[2], mirror_byte, ( data[2]>= 0x4 && data[2] <= 0xDC) ? "OK":"Invalid value"); break;} default: break; - } + } } } PrintAndLogEx(NORMAL, " - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); - + if ( data[3] < 0xff ) PrintAndLogEx(NORMAL, " - page %d and above need authentication",data[3]); - else + else PrintAndLogEx(NORMAL, " - pages don't need authentication"); PrintAndLogEx(NORMAL, " cfg1 [%u/0x%02X] : %s", startPage + 1, startPage + 1, sprint_hex(data+4, 4) ); @@ -671,10 +671,10 @@ static int ulev1_print_configuration(uint32_t tagtype, uint8_t *data, uint8_t st PrintAndLogEx(NORMAL, " - Unlimited password attempts"); else PrintAndLogEx(NORMAL, " - Max number of password attempts is %d", authlim); - + PrintAndLogEx(NORMAL, " - NFC counter %s", (nfc_cnf_en) ? "enabled":"disabled"); PrintAndLogEx(NORMAL, " - NFC counter %s", (nfc_cnf_prot_pwd) ? "not protected":"password protection enabled"); - + PrintAndLogEx(NORMAL, " - user configuration %s", cfglck ? "permanently locked":"writeable"); PrintAndLogEx(NORMAL, " - %s access is protected with password", prot ? "read and write":"write"); PrintAndLogEx(NORMAL, " - %02X, Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); @@ -701,8 +701,8 @@ static int ulev1_print_counters(){ } static int ulev1_print_signature( uint8_t *data, uint8_t len){ - PrintAndLogEx(NORMAL, "\n--- Tag Signature"); - PrintAndLogEx(NORMAL, "IC signature public key name : NXP NTAG21x (2013)"); + PrintAndLogEx(NORMAL, "\n--- Tag Signature"); + PrintAndLogEx(NORMAL, "IC signature public key name : NXP NTAG21x (2013)"); PrintAndLogEx(NORMAL, "IC signature public key value : %s", sprint_hex(public_ecda_key, PUBLIC_ECDA_KEYLEN) ); PrintAndLogEx(NORMAL, " Elliptic curve parameters : secp128r1"); PrintAndLogEx(NORMAL, " Tag ECC Signature : %s", sprint_hex(data, len)); @@ -747,22 +747,22 @@ static int ulc_magic_test(){ returnValue = ( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; } else { returnValue = UL; - } + } DropField(); return returnValue; } */ static int ul_magic_test(){ // Magic Ultralight tests - // 1) take present UID, and try to write it back. OBSOLETE + // 1) take present UID, and try to write it back. OBSOLETE // 2) make a wrong length write to page0, and see if tag answers with ACK/NACK: iso14a_card_select_t card; - if ( !ul_select(&card) ) + if ( !ul_select(&card) ) return UL_ERROR; int status = ul_comp_write(0, NULL, 0); DropField(); - if ( status == 0 ) + if ( status == 0 ) return MAGIC; return 0; } @@ -777,7 +777,7 @@ uint32_t GetHF14AMfU_Type(void){ if (!ul_select(&card)) return UL_ERROR; - // Ultralight - ATQA / SAK + // Ultralight - ATQA / SAK if ( card.atqa[1] != 0x00 || card.atqa[0] != 0x44 || card.sak != 0x00 ) { //PrintAndLogEx(NORMAL, "Tag is not Ultralight | NTAG | MY-D [ATQA: %02X %02X SAK: %02X]\n", card.atqa[1], card.atqa[0], card.sak); DropField(); @@ -828,7 +828,7 @@ uint32_t GetHF14AMfU_Type(void){ DropField(); if (status > 1) { tagtype = UL_C; - } else { + } else { // need to re-select after authentication error if ( !ul_select(&card) ) return UL_ERROR; @@ -850,12 +850,12 @@ uint32_t GetHF14AMfU_Type(void){ } } if (tagtype & UL) { - tagtype = ul_fudan_check(); + tagtype = ul_fudan_check(); DropField(); } } else { DropField(); - // Infinition MY-D tests Exam high nibble + // Infinition MY-D tests Exam high nibble uint8_t nib = (card.uid[1] & 0xf0) >> 4; switch ( nib ){ // case 0: tagtype = SLE66R35E7; break; //or SLE 66R35E7 - mifare compat... should have different sak/atqa for mf 1k @@ -929,7 +929,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); ul_print_type(tagtype, 6); - // Swap endianness + // Swap endianness if (swapEndian && hasAuthKey) authkeyptr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4 ); if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; @@ -957,10 +957,10 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLogEx(WARNING, "Error: tag didn't answer to READ UL-C"); DropField(); return status; - } - if (status == 16) + } + if (status == 16) ulc_print_configuration(ulc_conf); - else + else locked = true; if ((tagtype & MAGIC)) { @@ -976,7 +976,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } else { DropField(); - // if we called info with key, just return + // if we called info with key, just return if ( hasAuthKey ) return 1; // also try to diversify default keys.. look into CmdHF14AMfuGenDiverseKeys @@ -989,13 +989,13 @@ int CmdHF14AMfUInfo(const char *Cmd){ memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); return 1; - } + } } return 1; } } - // do counters and signature first (don't neet auth) + // do counters and signature first (don't neet auth) // ul counters are different than ntag counters if ((tagtype & (UL_EV1_48 | UL_EV1_128 | UL_EV1))) { @@ -1006,7 +1006,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } // NTAG counters? - + // Read signature if ((tagtype & (UL_EV1_48 | UL_EV1_128 | UL_EV1 | UL_NANO_40 | NTAG_213 | NTAG_213_F | NTAG_215 | NTAG_216 | NTAG_216_F | NTAG_I2C_1K | NTAG_I2C_2K | NTAG_I2C_1K_PLUS | NTAG_I2C_2K_PLUS))) { uint8_t ulev1_signature[32] = {0x00}; @@ -1040,7 +1040,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t startconfigblock = 0; uint8_t ulev1_conf[16] = {0x00}; - + // config blocks always are last 4 pages for (uint8_t i = 0; i < MAX_UL_TYPES; i++) { if (tagtype & UL_TYPES_ARRAY[i]) { @@ -1048,7 +1048,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ break; } } - + if (startconfigblock){ // if we know where the config block is... status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); if ( status == -1 ) { @@ -1074,7 +1074,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( !authlim && !hasAuthKey ) { PrintAndLogEx(NORMAL, "\n--- Known EV1/NTAG passwords."); len = 0; - + // test pwd gen A num_to_bytes( ul_ev1_pwdgenA(card.uid), 4, key); len = ulev1_requestAuthentication(key, pack, sizeof(pack)); @@ -1084,7 +1084,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; - + // test pwd gen B num_to_bytes( ul_ev1_pwdgenB(card.uid), 4, key); len = ulev1_requestAuthentication(key, pack, sizeof(pack)); @@ -1102,9 +1102,9 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLogEx(SUCCESS, "Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); goto out; } - + if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; - + // test pwd gen D num_to_bytes( ul_ev1_pwdgenD(card.uid), 4, key); len = ulev1_requestAuthentication(key, pack, sizeof(pack)); @@ -1112,9 +1112,9 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLogEx(SUCCESS, "Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); goto out; } - - if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; - + + if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; + for (uint8_t i = 0; i < KEYS_PWD_COUNT; ++i ) { key = default_pwd_pack[i]; len = ulev1_requestAuthentication(key, pack, sizeof(pack)); @@ -1140,7 +1140,7 @@ out: // int CmdHF14AMfUWrBl(const char *Cmd){ - int blockNo = -1; + int blockNo = -1; bool errors = false; bool hasAuthKey = false; bool hasPwdKey = false; @@ -1166,7 +1166,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ hasPwdKey = true; break; } - // UL-C size key + // UL-C size key keylen = param_gethex(Cmd, cmdp+1, data, 32); if (!keylen){ memcpy(authenticationkey, data, 16); @@ -1175,19 +1175,19 @@ int CmdHF14AMfUWrBl(const char *Cmd){ break; } PrintAndLogEx(WARNING, "ERROR: Key is incorrect length\n"); - errors = true; + errors = true; break; case 'b': blockNo = param_get8(Cmd, cmdp+1); if (blockNo < 0) { PrintAndLogEx(WARNING, "Wrong block number"); - errors = true; + errors = true; } cmdp += 2; break; case 'l': swapEndian = true; - cmdp++; + cmdp++; break; case 'd': if ( param_gethex(Cmd, cmdp+1, blockdata, 8) ) { @@ -1205,7 +1205,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ } //Validations if (errors || cmdp == 0) return usage_hf_mfu_wrbl(); - + if ( blockNo == -1 ) return usage_hf_mfu_wrbl(); // starting with getting tagtype TagTypeUL_t tagtype = GetHF14AMfU_Type(); @@ -1223,15 +1223,15 @@ int CmdHF14AMfUWrBl(const char *Cmd){ return usage_hf_mfu_wrbl(); } - // Swap endianness + // Swap endianness if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, 16, 8); if (swapEndian && hasPwdKey) authKeyPtr = SwapEndian64(authenticationkey, 4, 4); - if ( blockNo <= 3) + if ( blockNo <= 3) PrintAndLogEx(NORMAL, "Special Block: %0d (0x%02X) [ %s]", blockNo, blockNo, sprint_hex(blockdata, 4)); else PrintAndLogEx(NORMAL, "Block: %0d (0x%02X) [ %s]", blockNo, blockNo, sprint_hex(blockdata, 4)); - + //Send write Block UsbCommand c = {CMD_MIFAREU_WRITEBL, {blockNo}}; memcpy(c.d.asBytes, blockdata, 4); @@ -1244,7 +1244,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ c.arg[1] = 2; memcpy(c.d.asBytes+4, authKeyPtr, 4); } - + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; @@ -1254,7 +1254,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ } else { PrintAndLogEx(WARNING, "Command execute timeout"); } - + return 0; } // @@ -1262,7 +1262,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ // int CmdHF14AMfURdBl(const char *Cmd){ - int blockNo = -1; + int blockNo = -1; bool errors = false; bool hasAuthKey = false; bool hasPwdKey = false; @@ -1286,7 +1286,7 @@ int CmdHF14AMfURdBl(const char *Cmd){ hasPwdKey = true; break; } - // UL-C size key + // UL-C size key keylen = param_gethex(Cmd, cmdp+1, data, 32); if (!keylen){ memcpy(authenticationkey, data, 16); @@ -1295,20 +1295,20 @@ int CmdHF14AMfURdBl(const char *Cmd){ break; } PrintAndLogEx(WARNING, "ERROR: Key is incorrect length\n"); - errors = true; + errors = true; break; case 'b': blockNo = param_get8(Cmd, cmdp+1); if (blockNo < 0) { PrintAndLogEx(WARNING, "Wrong block number"); - errors = true; + errors = true; } cmdp += 2; break; case 'l': swapEndian = true; - cmdp++; - break; + cmdp++; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -1317,7 +1317,7 @@ int CmdHF14AMfURdBl(const char *Cmd){ } //Validations if (errors || cmdp == 0) return usage_hf_mfu_rdbl(); - + if ( blockNo == -1 ) return usage_hf_mfu_rdbl(); // start with getting tagtype TagTypeUL_t tagtype = GetHF14AMfU_Type(); @@ -1335,10 +1335,10 @@ int CmdHF14AMfURdBl(const char *Cmd){ return usage_hf_mfu_rdbl(); } - // Swap endianness + // Swap endianness if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, 16, 8); if (swapEndian && hasPwdKey) authKeyPtr = SwapEndian64(authenticationkey, 4, 4); - + //Read Block UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; if ( hasAuthKey ){ @@ -1349,7 +1349,7 @@ int CmdHF14AMfURdBl(const char *Cmd){ c.arg[1] = 2; memcpy(c.d.asBytes,authKeyPtr,4); } - + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; @@ -1393,14 +1393,14 @@ int usage_hf_mfu_dump(void) { PrintAndLogEx(NORMAL, "Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); PrintAndLogEx(NORMAL, "NTAG 203, NTAG 210, NTAG 212, NTAG 213, NTAG 215, NTAG 216"); PrintAndLogEx(NORMAL, "and saves binary dump into the file `filename.bin` or `cardUID.bin`"); - PrintAndLogEx(NORMAL, "It autodetects card type.\n"); + PrintAndLogEx(NORMAL, "It autodetects card type.\n"); PrintAndLogEx(NORMAL, "Usage: hf mfu dump k l f p q <#pages>"); PrintAndLogEx(NORMAL, " Options :"); PrintAndLogEx(NORMAL, " k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); PrintAndLogEx(NORMAL, " l : (optional) swap entered key's endianness"); - PrintAndLogEx(NORMAL, " f : filename w/o .bin to save the dump as"); - PrintAndLogEx(NORMAL, " p : starting Page number to manually set a page to start the dump at"); - PrintAndLogEx(NORMAL, " q : number of Pages to manually set how many pages to dump"); + PrintAndLogEx(NORMAL, " f : filename w/o .bin to save the dump as"); + PrintAndLogEx(NORMAL, " p : starting Page number to manually set a page to start the dump at"); + PrintAndLogEx(NORMAL, " q : number of Pages to manually set how many pages to dump"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mfu dump"); @@ -1419,7 +1419,7 @@ int usage_hf_mfu_restore(void){ PrintAndLogEx(NORMAL, " s : (optional) enable special write UID -MAGIC TAG ONLY-"); PrintAndLogEx(NORMAL, " e : (optional) enable special write version/signature -MAGIC NTAG 21* ONLY-"); PrintAndLogEx(NORMAL, " r : (optional) use the password found in dumpfile to configure tag. requires 'e' parameter to work"); - PrintAndLogEx(NORMAL, " f : filename w/o .bin to restore"); + PrintAndLogEx(NORMAL, " f : filename w/o .bin to restore"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mfu restore s f myfile"); @@ -1429,12 +1429,12 @@ int usage_hf_mfu_restore(void){ } int usage_hf_mfu_rdbl(void) { - PrintAndLogEx(NORMAL, "Read a block and print. It autodetects card type.\n"); + PrintAndLogEx(NORMAL, "Read a block and print. It autodetects card type.\n"); PrintAndLogEx(NORMAL, "Usage: hf mfu rdbl b k l\n"); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " b : block to read"); PrintAndLogEx(NORMAL, " k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); - PrintAndLogEx(NORMAL, " l : (optional) swap entered key's endianness"); + PrintAndLogEx(NORMAL, " l : (optional) swap entered key's endianness"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mfu rdbl b 0"); @@ -1444,13 +1444,13 @@ int usage_hf_mfu_rdbl(void) { } int usage_hf_mfu_wrbl(void) { - PrintAndLogEx(NORMAL, "Write a block. It autodetects card type.\n"); + PrintAndLogEx(NORMAL, "Write a block. It autodetects card type.\n"); PrintAndLogEx(NORMAL, "Usage: hf mfu wrbl b d k l\n"); - PrintAndLogEx(NORMAL, "Options:"); + PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " b : block to write"); PrintAndLogEx(NORMAL, " d : block data - (8 hex symbols)"); PrintAndLogEx(NORMAL, " k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); - PrintAndLogEx(NORMAL, " l : (optional) swap entered key's endianness"); + PrintAndLogEx(NORMAL, " l : (optional) swap entered key's endianness"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mfu wrbl b 0 d 01234567"); @@ -1463,9 +1463,9 @@ int usage_hf_mfu_eload(void) { PrintAndLogEx(NORMAL, "Hint: See script dumptoemul-mfu.lua to convert the .bin to the eml"); PrintAndLogEx(NORMAL, "Usage: hf mfu eload u [numblocks]"); PrintAndLogEx(NORMAL, " Options:"); - PrintAndLogEx(NORMAL, " h : this help"); + PrintAndLogEx(NORMAL, " h : this help"); PrintAndLogEx(NORMAL, " u : UL (required)"); - PrintAndLogEx(NORMAL, " [filename] : without `.eml` (required)"); + PrintAndLogEx(NORMAL, " [filename] : without `.eml` (required)"); PrintAndLogEx(NORMAL, " numblocks : number of blocks to load from eml file (optional)"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " sample: hf mfu eload u filename"); @@ -1485,7 +1485,7 @@ int usage_hf_mfu_sim(void) { PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mfu sim t 7"); PrintAndLogEx(NORMAL, " hf mfu sim t 7 u 1122344556677\n"); - + return 0; } @@ -1497,7 +1497,7 @@ int usage_hf_mfu_ucauth(void) { PrintAndLogEx(NORMAL, " 3 : nfc key"); PrintAndLogEx(NORMAL, " 4 : all 0x01 key"); PrintAndLogEx(NORMAL, " 5 : all 0xff key"); - PrintAndLogEx(NORMAL, " 6 : 0x00-0xFF key"); + PrintAndLogEx(NORMAL, " 6 : 0x00-0xFF key"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " hf mfu cauth k"); PrintAndLogEx(NORMAL, " hf mfu cauth k 3"); @@ -1575,18 +1575,18 @@ void printMFUdumpEx(mfu_dump_t* card, uint16_t pages, uint8_t startpage) { uint8_t j = 0; bool lckbit = false; uint8_t *data = card->data; - + uint8_t lockbytes_sta[] = {0,0}; uint8_t lockbytes_dyn[] = {0,0,0}; bool bit_stat[16] = {0}; bool bit_dyn[16] = {0}; - - // Load static lock bytes. + + // Load static lock bytes. memcpy(lockbytes_sta, data+10, sizeof(lockbytes_sta)); for(j = 0; j < 16; j++){ bit_stat[j] = lockbytes_sta[j/8] & ( 1 <<(7-j%8)); } - + // Load dynamic lockbytes if available // TODO -- FIGURE OUT LOCK BYTES FOR TO EV1 and/or NTAG if ( pages == 44 ) { @@ -1598,7 +1598,7 @@ void printMFUdumpEx(mfu_dump_t* card, uint16_t pages, uint8_t startpage) { } PrintAndLogEx(NORMAL, "DYNAMIC LOCK: %s\n", sprint_hex(lockbytes_dyn,3)); } - + for (uint8_t i = 0; i < pages; ++i) { if ( i < 3 ) { PrintAndLogEx(NORMAL, "%3d/0x%02X | %s| | %s", i+startpage, i+startpage, sprint_hex(data + i * 4, 4), sprint_ascii(data + i * 4,4) ); @@ -1625,7 +1625,7 @@ void printMFUdumpEx(mfu_dump_t* card, uint16_t pages, uint8_t startpage) { case 20: case 21: case 22: - case 23: lckbit = bit_dyn[5]; break; + case 23: lckbit = bit_dyn[5]; break; case 24: case 25: case 26: @@ -1637,11 +1637,11 @@ void printMFUdumpEx(mfu_dump_t* card, uint16_t pages, uint8_t startpage) { case 32: case 33: case 34: - case 35: lckbit = bit_dyn[1]; break; + case 35: lckbit = bit_dyn[1]; break; case 36: case 37: case 38: - case 39: lckbit = bit_dyn[0]; break; + case 39: lckbit = bit_dyn[0]; break; case 40: lckbit = bit_dyn[12]; break; case 41: lckbit = bit_dyn[11]; break; case 42: lckbit = bit_dyn[10]; break; //auth0 @@ -1664,7 +1664,7 @@ int CmdHF14AMfUDump(const char *Cmd){ uint8_t data[1024] = {0x00}; memset(data, 0x00, sizeof(data)); - + bool hasAuthKey = false; int i = 0; int pages = 16; @@ -1726,12 +1726,12 @@ int CmdHF14AMfUDump(const char *Cmd){ if (errors) return usage_hf_mfu_dump(); //if we entered a key in little endian and set the swapEndian switch - switch it... - if (swapEndian && hasAuthKey) + if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4); TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; - + //get number of pages to read if (!manualPages) { for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++) { @@ -1772,16 +1772,16 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLogEx(FAILED, "Data exceeded Buffer size!"); bufferSize = sizeof(data); } - + if ( !GetFromDevice(BIG_BUF, data, bufferSize, startindex, NULL, 2500, false) ) { PrintAndLogEx(WARNING, "command execution time out"); return 1; } bool is_partial = (pages != bufferSize/4); - + pages = bufferSize/4; - + iso14a_card_select_t card; mfu_dump_t dump_file_data; uint8_t get_pack[] = {0,0}; @@ -1793,7 +1793,7 @@ int CmdHF14AMfUDump(const char *Cmd){ memset( get_signature, 0, sizeof(get_signature) ); // not ul_c and not std ul then attempt to collect info like - // VERSION, SIGNATURE, COUNTERS, TEARING, PACK, + // VERSION, SIGNATURE, COUNTERS, TEARING, PACK, if (!(tagtype & UL_C || tagtype & UL)) { //attempt to read pack if (!ul_auth_select( &card, tagtype, true, authKeyPtr, get_pack, sizeof(get_pack))) { @@ -1802,14 +1802,14 @@ int CmdHF14AMfUDump(const char *Cmd){ get_pack[1] = 0; } DropField(); - + // only add pack if not partial read, and complete pages read. if ( !is_partial && pages == card_mem_size) { - - // add pack to block read + + // add pack to block read memcpy(data + (pages*4) - 4, get_pack, sizeof(get_pack)); } - + if ( hasAuthKey ) ul_auth_select( &card, tagtype, hasAuthKey, authKeyPtr, dummy_pack, sizeof(dummy_pack)); else @@ -1820,13 +1820,13 @@ int CmdHF14AMfUDump(const char *Cmd){ ulev1_readTearing(i, get_tearing+i, 1); ulev1_readCounter(i, get_counter, sizeof(get_counter) ); } - + DropField(); if ( hasAuthKey ) ul_auth_select( &card, tagtype, hasAuthKey, authKeyPtr, dummy_pack, sizeof(dummy_pack)); else ul_select(&card); - + ulev1_readSignature( get_signature, sizeof(get_signature)); DropField(); } @@ -1844,7 +1844,7 @@ int CmdHF14AMfUDump(const char *Cmd){ if (tagtype & UL_C){ //add 4 pages memcpy(data + pages*4, authKeyPtr, dataLen); - pages += dataLen/4; + pages += dataLen/4; } else { // 2nd page from end memcpy(data + (pages*4) - 8, authenticationkey, dataLen); } @@ -1859,22 +1859,22 @@ int CmdHF14AMfUDump(const char *Cmd){ memcpy(dump_file_data.data, data, pages*4); printMFUdumpEx(&dump_file_data, pages, startPage); - + // user supplied filename? if (fileNameLen < 1) { PrintAndLogEx(INFO, "Using UID as filename"); - - fptr += sprintf(fptr, "hf-mfu-"); + + fptr += sprintf(fptr, "hf-mfu-"); FillFileNameByUID(fptr, card.uid, "-dump", card.uidlen); - } + } uint16_t datalen = pages*4 + DUMP_PREFIX_LENGTH; saveFile(filename, "bin", (uint8_t*)&dump_file_data, datalen); saveFileJSON(filename, "json", jsfMfuMemory, (uint8_t*)&dump_file_data, datalen); - - if ( is_partial ) + + if ( is_partial ) PrintAndLogEx(WARNING, "Partial dump created. (%d of %d blocks)", pages, card_mem_size); - + return 0; } @@ -1896,7 +1896,7 @@ int CmdHF14AMfURestore(const char *Cmd){ char tempStr[50] = {0}; char filename[FILE_PATH_SIZE] = {0}; - uint8_t authkey[16] = {0}; + uint8_t authkey[16] = {0}; uint8_t *p_authkey = authkey; uint8_t cmdp = 0, keylen = 0; bool hasKey = false; @@ -1910,7 +1910,7 @@ int CmdHF14AMfURestore(const char *Cmd){ UsbCommand c = {CMD_MIFAREU_WRITEBL, {0,0,0}}; memset(authkey, 0x00, sizeof(authkey)); - + while(param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -1936,7 +1936,7 @@ int CmdHF14AMfURestore(const char *Cmd){ if (filelen > FILE_PATH_SIZE-5) filelen = FILE_PATH_SIZE-5; - + if (filelen < 1) sprintf(filename, "dumpdata.bin"); @@ -1963,11 +1963,11 @@ int CmdHF14AMfURestore(const char *Cmd){ //Validations if (errors || cmdp == 0) return usage_hf_mfu_restore(); - + if ((f = fopen(filename,"rb")) == NULL) { PrintAndLogEx(WARNING, "Could not find file " _YELLOW_(%s), filename); return 1; - } + } // get filesize to know how memory to allocate fseek(f, 0, SEEK_END); @@ -1994,16 +1994,16 @@ int CmdHF14AMfURestore(const char *Cmd){ free(dump); return 1; } - + PrintAndLogEx(INFO, "Restoring " _YELLOW_(%s)" to card", filename); - + mfu_dump_t *mem = (mfu_dump_t*)dump; uint8_t pages = (bytes_read-48)/4; - + // print dump printMFUdumpEx(mem, pages, 0); - - // Swap endianness + + // Swap endianness if (swapEndian && hasKey) { if ( keylen == 16 ) p_authkey = SwapEndian64(authkey, keylen, 8); @@ -2016,11 +2016,11 @@ int CmdHF14AMfURestore(const char *Cmd){ c.arg[1] = (keylen == 16) ? 1 : 2; memcpy(c.d.asBytes+4, p_authkey, keylen); } - + // write version, signature, pack // only magic NTAG cards if ( write_extra ) { - + #define MFU_NTAG_SPECIAL_PWD 0xF0 #define MFU_NTAG_SPECIAL_PACK 0xF1 #define MFU_NTAG_SPECIAL_VERSION 0xFA @@ -2040,13 +2040,13 @@ int CmdHF14AMfURestore(const char *Cmd){ clearCommandBuffer(); SendCommand(&c); wait4response(MFU_NTAG_SPECIAL_PWD); - + // copy the new key c.arg[1] = 2; memcpy(authkey, c.d.asBytes, 4); memcpy(c.d.asBytes+4, authkey, 4); } - + // pack c.arg[0] = MFU_NTAG_SPECIAL_PACK; c.d.asBytes[0] = mem->pack[0]; @@ -2057,7 +2057,7 @@ int CmdHF14AMfURestore(const char *Cmd){ clearCommandBuffer(); SendCommand(&c); wait4response(MFU_NTAG_SPECIAL_PACK); - + // Signature for (uint8_t s = MFU_NTAG_SPECIAL_SIGNATURE, i=0; s < MFU_NTAG_SPECIAL_SIGNATURE+8; s++, i += 4){ c.arg[0] = s; @@ -2065,26 +2065,26 @@ int CmdHF14AMfURestore(const char *Cmd){ PrintAndLogEx(NORMAL, "special SIG block written 0x%X - %s\n", s, sprint_hex(c.d.asBytes, 4) ); clearCommandBuffer(); SendCommand(&c); - wait4response(s); + wait4response(s); } - + // Version - for (uint8_t s = MFU_NTAG_SPECIAL_VERSION, i=0; s < MFU_NTAG_SPECIAL_VERSION+2; s++, i += 4){ + for (uint8_t s = MFU_NTAG_SPECIAL_VERSION, i=0; s < MFU_NTAG_SPECIAL_VERSION+2; s++, i += 4){ c.arg[0] = s; - memcpy(c.d.asBytes, mem->version+i, 4 ); + memcpy(c.d.asBytes, mem->version+i, 4 ); PrintAndLogEx(NORMAL, "special VERSION block written 0x%X - %s\n", s, sprint_hex(c.d.asBytes, 4) ); clearCommandBuffer(); SendCommand(&c); wait4response(s); } } - + PrintAndLogEx(INFO, "Restoring data blocks."); - // write all other data + // write all other data // Skip block 0,1,2,3 (only magic tags can write to them) // Skip last 5 blocks usually is configuration for (uint8_t b = 4; b < pages-5; b++) { - + //Send write Block c.arg[0] = b; memcpy(c.d.asBytes, mem->data + (b*4), 4); @@ -2094,14 +2094,14 @@ int CmdHF14AMfURestore(const char *Cmd){ printf("."); fflush(stdout); } PrintAndLogEx(NORMAL, "\n"); - + // write special data last if (write_special) { - + PrintAndLogEx(INFO, "Restoring configuration blocks.\n"); - + PrintAndLogEx(NORMAL, "authentication with keytype[%x] %s\n", (uint8_t)(c.arg[1] & 0xff), sprint_hex(p_authkey,4)); - + // otp, uid, lock, cfg1, cfg0, dynlockbits uint8_t blocks[] = {3, 0, 1, 2, pages-5, pages-4, pages-3}; for ( uint8_t i = 0; i < sizeof(blocks); i++){ @@ -2114,10 +2114,10 @@ int CmdHF14AMfURestore(const char *Cmd){ PrintAndLogEx(NORMAL, "special block written %u - %s\n", b, sprint_hex(c.d.asBytes, 4) ); } } - + DropField(); free(dump); - return 0; + return 0; } // // Load emulator with dump file @@ -2153,33 +2153,33 @@ int CmdHF14AMfucAuth(const char *Cmd){ //Change key to user defined one if (cmdp == 'k'){ keyNo = param_get8(Cmd, 1); - if(keyNo >= KEYS_3DES_COUNT) + if(keyNo >= KEYS_3DES_COUNT) errors = true; } if (cmdp == 'h') errors = true; - - if (errors) return usage_hf_mfu_ucauth(); + + if (errors) return usage_hf_mfu_ucauth(); uint8_t *key = default_3des_keys[keyNo]; if (ulc_authentication(key, true)) PrintAndLogEx(SUCCESS, "Authentication successful. 3des key: %s",sprint_hex(key, 16)); else PrintAndLogEx(WARNING, "Authentication failed"); - + return 0; } /** -A test function to validate that the polarssl-function works the same -was as the openssl-implementation. -Commented out, since it requires openssl +A test function to validate that the polarssl-function works the same +was as the openssl-implementation. +Commented out, since it requires openssl int CmdTestDES(const char * cmd) { - uint8_t key[16] = {0x00}; - - memcpy(key,key3_3des_data,16); + uint8_t key[16] = {0x00}; + + memcpy(key,key3_3des_data,16); DES_cblock RndA, RndB; PrintAndLogEx(NORMAL, "----------OpenSSL DES implementation----------"); @@ -2191,7 +2191,7 @@ int CmdTestDES(const char * cmd) DES_key_schedule ks1,ks2; DES_cblock key1,key2; - memcpy(key,key3_3des_data,16); + memcpy(key,key3_3des_data,16); memcpy(key1,key,8); memcpy(key2,key+8,8); @@ -2248,7 +2248,7 @@ int CmdTestDES(const char * cmd) rol(random_b,8); memcpy(random_a_and_b ,random_a,8); memcpy(random_a_and_b+8,random_b,8); - + PrintAndLogEx(NORMAL, " RA+B:%s",sprint_hex(random_a_and_b, 16)); des3_set2key_enc(&ctx, key); @@ -2263,26 +2263,26 @@ int CmdTestDES(const char * cmd) PrintAndLogEx(NORMAL, "enc(RA+B):%s",sprint_hex(random_a_and_b, 16)); } - return 0; + return 0; } **/ -// +// // Mifare Ultralight C - Set password // int CmdHF14AMfucSetPwd(const char *Cmd){ - uint8_t pwd[16] = {0x00}; + uint8_t pwd[16] = {0x00}; char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_hf_mfu_ucsetpwd(); - + if (param_gethex(Cmd, 0, pwd, 32)) { PrintAndLogEx(WARNING, "Password must include 32 HEX symbols"); return 1; } - - UsbCommand c = {CMD_MIFAREUC_SETPWD}; + + UsbCommand c = {CMD_MIFAREUC_SETPWD}; memcpy( c.d.asBytes, pwd, 16); clearCommandBuffer(); SendCommand(&c); @@ -2298,7 +2298,7 @@ int CmdHF14AMfucSetPwd(const char *Cmd){ } else { PrintAndLogEx(WARNING, "command execution time out"); return 1; - } + } return 0; } @@ -2311,7 +2311,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ UsbCommand resp; uint8_t uid[7] = {0x00}; char cmdp = tolower(param_getchar(Cmd, 0)); - + if (strlen(Cmd) == 0 || cmdp == 'h') return usage_hf_mfu_ucsetuid(); if (param_gethex(Cmd, 0, uid, 14)) { @@ -2319,7 +2319,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ return 1; } - // read block2. + // read block2. c.arg[0] = 2; clearCommandBuffer(); SendCommand(&c); @@ -2331,7 +2331,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ // save old block2. uint8_t oldblock2[4] = {0x00}; memcpy(resp.d.asBytes, oldblock2, 4); - + // block 0. c.cmd = CMD_MIFAREU_WRITEBL; c.arg[0] = 0; @@ -2370,13 +2370,13 @@ int CmdHF14AMfucSetUid(const char *Cmd){ if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { PrintAndLogEx(WARNING, "Command execute timeout"); return 5; - } + } return 0; } int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ - uint8_t uid[4]; + uint8_t uid[4]; char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_hf_mfu_gendiverse(); @@ -2389,13 +2389,13 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ WaitForResponse(CMD_ACK, &resp); iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); - - uint64_t select_status = resp.arg[0]; + + uint64_t select_status = resp.arg[0]; // 0: couldn't read, // 1: OK, with ATS // 2: OK, no ATS // 3: proprietary Anticollision - + if ( select_status == 0 ) { PrintAndLogEx(WARNING, "iso14443a card select failed"); return 1; @@ -2404,33 +2404,33 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ PrintAndLogEx(WARNING, "Wrong sized UID, expected 4bytes got %d", card.uidlen); return 1; } - memcpy(uid, card.uid, sizeof(uid)); + memcpy(uid, card.uid, sizeof(uid)); } else { if (param_gethex(Cmd, 0, uid, 8)) return usage_hf_mfu_gendiverse(); } - - + + uint8_t iv[8] = { 0x00 }; uint8_t block = 0x01; - + uint8_t mifarekeyA[] = { 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5 }; uint8_t mifarekeyB[] = { 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5 }; uint8_t dkeyA[8] = { 0x00 }; uint8_t dkeyB[8] = { 0x00 }; - + uint8_t masterkey[] = { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff }; - + uint8_t mix[8] = { 0x00 }; uint8_t divkey[8] = { 0x00 }; - + memcpy(mix, mifarekeyA, 4); - + mix[4] = mifarekeyA[4] ^ uid[0]; mix[5] = mifarekeyA[5] ^ uid[1]; mix[6] = block ^ uid[2]; mix[7] = uid[3]; - + mbedtls_des3_context ctx; mbedtls_des3_set2key_enc(&ctx, masterkey); @@ -2449,17 +2449,17 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ PrintAndLogEx(NORMAL, "Mifare key :\t %s", sprint_hex(mifarekeyA, sizeof(mifarekeyA))); PrintAndLogEx(NORMAL, "Message :\t %s", sprint_hex(mix, sizeof(mix))); PrintAndLogEx(NORMAL, "Diversified key: %s", sprint_hex(divkey+1, 6)); - + for (int i=0; i < sizeof(mifarekeyA); ++i){ dkeyA[i] = (mifarekeyA[i] << 1) & 0xff; dkeyA[6] |= ((mifarekeyA[i] >> 7) & 1) << (i+1); } - + for (int i=0; i < sizeof(mifarekeyB); ++i){ dkeyB[1] |= ((mifarekeyB[i] >> 7) & 1) << (i+1); dkeyB[2+i] = (mifarekeyB[i] << 1) & 0xff; } - + uint8_t zeros[8] = {0x00}; uint8_t newpwd[8] = {0x00}; uint8_t dmkey[24] = {0x00}; @@ -2467,7 +2467,7 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ memcpy(dmkey+8, dkeyB, 8); memcpy(dmkey+16, dkeyA, 8); memset(iv, 0x00, 8); - + mbedtls_des3_set3key_enc(&ctx, dmkey); mbedtls_des3_crypt_cbc(&ctx // des3_context @@ -2477,25 +2477,25 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ , zeros // input , newpwd // output ); - + PrintAndLogEx(NORMAL, "\n-- DES version"); PrintAndLogEx(NORMAL, "Mifare dkeyA :\t %s", sprint_hex(dkeyA, sizeof(dkeyA))); PrintAndLogEx(NORMAL, "Mifare dkeyB :\t %s", sprint_hex(dkeyB, sizeof(dkeyB))); PrintAndLogEx(NORMAL, "Mifare ABA :\t %s", sprint_hex(dmkey, sizeof(dmkey))); PrintAndLogEx(NORMAL, "Mifare Pwd :\t %s", sprint_hex(newpwd, sizeof(newpwd))); - - // next. from the diversify_key method. + + // next. from the diversify_key method. return 0; } int CmdHF14AMfuPwdGen(const char *Cmd){ - - uint8_t uid[7] = {0x00}; + + uint8_t uid[7] = {0x00}; char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_hf_mfu_pwdgen(); - + if (cmdp == 't') return ul_ev1_pwdgen_selftest(); - + if ( cmdp == 'r') { // read uid from tag UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_RATS, 0, 0}}; @@ -2505,7 +2505,7 @@ int CmdHF14AMfuPwdGen(const char *Cmd){ WaitForResponse(CMD_ACK, &resp); iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); - + uint64_t select_status = resp.arg[0]; // 0: couldn't read // 1: OK with ATS @@ -2519,12 +2519,12 @@ int CmdHF14AMfuPwdGen(const char *Cmd){ PrintAndLogEx(WARNING, "Wrong sized UID, expected 7bytes got %d", card.uidlen); return 1; } - memcpy(uid, card.uid, sizeof(uid)); + memcpy(uid, card.uid, sizeof(uid)); } else { if (param_gethex(Cmd, 0, uid, 14)) return usage_hf_mfu_pwdgen(); } - + PrintAndLogEx(NORMAL, "---------------------------------"); PrintAndLogEx(NORMAL, " Using UID : %s", sprint_hex(uid, 7)); PrintAndLogEx(NORMAL, "---------------------------------"); @@ -2548,13 +2548,13 @@ static command_t CommandTable[] = { {"info", CmdHF14AMfUInfo, 0, "Tag information"}, {"dump", CmdHF14AMfUDump, 0, "Dump Ultralight / Ultralight-C / NTAG tag to binary file"}, {"restore", CmdHF14AMfURestore, 0, "Restore a dump onto a MFU MAGIC tag"}, - {"eload", CmdHF14AMfUeLoad, 0, "load Ultralight .eml dump file into emulator memory"}, + {"eload", CmdHF14AMfUeLoad, 0, "load Ultralight .eml dump file into emulator memory"}, {"rdbl", CmdHF14AMfURdBl, 0, "Read block"}, {"wrbl", CmdHF14AMfUWrBl, 0, "Write block"}, {"cauth", CmdHF14AMfucAuth, 0, "Authentication - Ultralight C"}, {"setpwd", CmdHF14AMfucSetPwd, 0, "Set 3des password - Ultralight-C"}, {"setuid", CmdHF14AMfucSetUid, 0, "Set UID - MAGIC tags only"}, - {"sim", CmdHF14AMfUSim, 0, "Simulate Ultralight from emulator memory"}, + {"sim", CmdHF14AMfUSim, 0, "Simulate Ultralight from emulator memory"}, {"gen", CmdHF14AMfuGenDiverseKeys , 1, "Generate 3des mifare diversified keys"}, {"pwdgen", CmdHF14AMfuPwdGen, 1, "Generate pwd from known algos"}, {NULL, NULL, 0, NULL} diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index b03444839..4a5528b83 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -12,7 +12,7 @@ #include "comms.h" #include "loclass/fileutils.h" -#define DUMP_PREFIX_LENGTH 48 +#define DUMP_PREFIX_LENGTH 48 typedef struct { uint8_t version[8]; @@ -20,7 +20,7 @@ typedef struct { uint8_t tearing[3]; uint8_t pack[2]; uint8_t tbo1[1]; - uint8_t signature[32]; + uint8_t signature[32]; //uint8_t counter[3]; uint8_t data[1024]; } mfu_dump_t; diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c index 2f80b054c..64d4a6f5b 100644 --- a/client/cmdhftopaz.c +++ b/client/cmdhftopaz.c @@ -52,12 +52,12 @@ static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) { if (resp.arg[0] > 0) { memcpy(response, resp.d.asBytes, resp.arg[0]); } - + return resp.arg[0]; } -// calculate CRC bytes and send topaz command, returns the length of the response (0 in case of error) +// calculate CRC bytes and send topaz command, returns the length of the response (0 in case of error) static int topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) { if (len > 1) { uint8_t b1, b2; @@ -88,7 +88,7 @@ static int topaz_select(uint8_t *atqa, uint8_t *rid_response) { topaz_switch_off_field(); return -2; // RID failed } - + return 0; // OK } @@ -102,7 +102,7 @@ static int topaz_rall(uint8_t *uid, uint8_t *response) { topaz_switch_off_field(); return -1; // RALL failed } - + return 0; } @@ -112,7 +112,7 @@ static int topaz_read_block(uint8_t *uid, uint8_t blockno, uint8_t *block_data) { uint8_t read8_cmd[] = {TOPAZ_READ8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t read8_response[11]; - + read8_cmd[1] = blockno; memcpy(&read8_cmd[10], uid, 4); if (!topaz_send_cmd(read8_cmd, sizeof(read8_cmd), read8_response)) { @@ -127,7 +127,7 @@ static int topaz_read_block(uint8_t *uid, uint8_t blockno, uint8_t *block_data) static int topaz_read_segment(uint8_t *uid, uint8_t segno, uint8_t *segment_data) { uint8_t rseg_cmd[] = {TOPAZ_RSEG, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; uint8_t rseg_response[131]; - + rseg_cmd[1] = segno << 4; memcpy(&rseg_cmd[10], uid, 4); if (!topaz_send_cmd(rseg_cmd, sizeof(rseg_cmd), rseg_response)) { @@ -138,11 +138,11 @@ static int topaz_read_segment(uint8_t *uid, uint8_t segno, uint8_t *segment_data return 0; } -// search for the lock area descriptor for the lockable area including byteno +// search for the lock area descriptor for the lockable area including byteno static dynamic_lock_area_t *get_dynamic_lock_area(uint16_t byteno) { - dynamic_lock_area_t *lock_area; + dynamic_lock_area_t *lock_area; lock_area = topaz_tag.dynamic_lock_areas; - + while (lock_area != NULL) { if (byteno < lock_area->first_locked_byte) { lock_area = lock_area->next; @@ -158,7 +158,7 @@ static bool topaz_byte_is_locked(uint16_t byteno) { uint8_t *lockbits; uint16_t locked_bytes_per_bit; dynamic_lock_area_t *lock_area; - + if (byteno < TOPAZ_STATIC_MEMORY) { lockbits = &topaz_tag.data_blocks[0x0e][0]; locked_bytes_per_bit = 8; @@ -190,20 +190,20 @@ static int topaz_print_CC(uint8_t *data) { } PrintAndLogEx(NORMAL, "Capability Container: %02x %02x %02x %02x", data[0], data[1], data[2], data[3]); - PrintAndLogEx(NORMAL, " %02x: NDEF Magic Number", data[0]); + PrintAndLogEx(NORMAL, " %02x: NDEF Magic Number", data[0]); PrintAndLogEx(NORMAL, " %02x: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); uint16_t memsize = (data[2] + 1) * 8; topaz_tag.size = memsize; topaz_tag.dynamic_memory = calloc(memsize - TOPAZ_STATIC_MEMORY, sizeof(uint8_t)); PrintAndLogEx(NORMAL, " %02x: Physical Memory Size of this tag: %d bytes", data[2], memsize); - PrintAndLogEx(NORMAL, " %02x: %s / %s", data[3], - (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", + PrintAndLogEx(NORMAL, " %02x: %s / %s", data[3], + (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", (data[3] & 0x0F)==0 ? "Write access granted without any security" : (data[3] & 0x0F)==0x0F ? "No write access granted at all" : "(RFU)"); - return 0; + return 0; } -// return type, length and value of a TLV, starting at memory position *TLV_ptr +// return type, length and value of a TLV, starting at memory position *TLV_ptr static void get_TLV(uint8_t **TLV_ptr, uint8_t *TLV_type, uint16_t *TLV_length, uint8_t **TLV_value) { *TLV_length = 0; *TLV_value = NULL; @@ -236,7 +236,7 @@ static void get_TLV(uint8_t **TLV_ptr, uint8_t *TLV_type, uint16_t *TLV_length, // lock area TLVs contain no information on the start of the respective lockable area. Lockable areas -// do not include the lock bits and reserved memory. We therefore need to adjust the start of the +// do not include the lock bits and reserved memory. We therefore need to adjust the start of the // respective lockable areas accordingly static void adjust_lock_areas(uint16_t block_start, uint16_t block_size) { dynamic_lock_area_t *lock_area = topaz_tag.dynamic_lock_areas; @@ -258,8 +258,8 @@ static void topaz_print_control_TLVs(uint8_t *memory) { bool lock_TLV_present = false; bool reserved_memory_control_TLV_present = false; uint16_t next_lockable_byte = 0x0f * 8; // first byte after static memory area - - while (*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { + + while (*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { // all Lock Control TLVs shall be present before the NDEF message TLV, the proprietary TLV (and the Terminator TLV) get_TLV(&TLV_ptr, &TLV_type, &TLV_length, &TLV_value); if (TLV_type == 0x01) { // a Lock Control TLV @@ -270,7 +270,7 @@ static void topaz_print_control_TLVs(uint8_t *memory) { uint16_t bytes_per_page = 1 << (TLV_value[2] & 0x0f); uint16_t bytes_locked_per_bit = 1 << (TLV_value[2] >> 4); uint16_t area_start = pages_addr * bytes_per_page + byte_offset; - PrintAndLogEx(NORMAL, "Lock Area of %d bits at byte offset 0x%04x. Each Lock Bit locks %d bytes.", + PrintAndLogEx(NORMAL, "Lock Area of %d bits at byte offset 0x%04x. Each Lock Bit locks %d bytes.", size_in_bits, area_start, bytes_locked_per_bit); @@ -294,7 +294,7 @@ static void topaz_print_control_TLVs(uint8_t *memory) { new->byte_offset = area_start; new->size_in_bits = size_in_bits; new->bytes_locked_per_bit = bytes_locked_per_bit; - next_lockable_byte += size_in_bits * bytes_locked_per_bit; + next_lockable_byte += size_in_bits * bytes_locked_per_bit; } if (TLV_type == 0x02) { // a Reserved Memory Control TLV uint8_t pages_addr = TLV_value[0] >> 4; @@ -302,7 +302,7 @@ static void topaz_print_control_TLVs(uint8_t *memory) { uint16_t size_in_bytes = TLV_value[1] ? TLV_value[1] : 256; uint8_t bytes_per_page = 1 << (TLV_value[2] & 0x0f); uint16_t area_start = pages_addr * bytes_per_page + byte_offset; - PrintAndLogEx(NORMAL, "Reserved Memory of %d bytes at byte offset 0x%02x.", + PrintAndLogEx(NORMAL, "Reserved Memory of %d bytes at byte offset 0x%02x.", size_in_bytes, area_start); reserved_memory_control_TLV_present = true; @@ -312,14 +312,14 @@ static void topaz_print_control_TLVs(uint8_t *memory) { } } } - + if (!lock_TLV_present) { PrintAndLogEx(NORMAL, "(No Lock Control TLV present)"); } - + if (!reserved_memory_control_TLV_present) { PrintAndLogEx(NORMAL, "(No Reserved Memory Control TLV present)"); - } + } } // read all of the dynamic memory @@ -329,7 +329,7 @@ static int topaz_read_dynamic_data(void){ PrintAndLogEx(WARNING, "Error while reading dynamic memory block %02x. Aborting...", 0x0f); return -1; } - + // read the remaining segments uint8_t max_segment = topaz_tag.size / 128 - 1; for (uint8_t segment = 1; segment <= max_segment; segment++) { @@ -337,10 +337,10 @@ static int topaz_read_dynamic_data(void){ PrintAndLogEx(WARNING, "Error while reading dynamic memory block %02x. Aborting...", 0x0f); return -1; } - } + } return 0; } - + // read and print the dynamic memory static void topaz_print_dynamic_data(void) { @@ -368,10 +368,10 @@ static void topaz_print_lifecycle_state(uint8_t *data) { } static void topaz_print_NDEF(uint8_t *data) { - // to be done. + // to be done. } - -// read a Topaz tag and print some useful information + +// read a Topaz tag and print some useful information int CmdHFTopazReader(const char *Cmd) { int status; uint8_t atqa[2]; @@ -382,7 +382,7 @@ int CmdHFTopazReader(const char *Cmd) { char ctmp = param_getchar(Cmd, 0); if ( ctmp == 'S' || ctmp == 's') verbose = false; - + status = topaz_select(atqa, rid_response); if (status == -1) { @@ -396,7 +396,7 @@ int CmdHFTopazReader(const char *Cmd) { topaz_switch_off_field(); return -1; } - + if (status == -2) { PrintAndLogEx(WARNING, "Error: tag didn't answer to RID"); topaz_switch_off_field(); @@ -405,14 +405,14 @@ int CmdHFTopazReader(const char *Cmd) { topaz_tag.HR01[0] = rid_response[0]; topaz_tag.HR01[1] = rid_response[1]; - + // ToDo: CRC check - PrintAndLogEx(NORMAL, "HR0 : %02x (%sa Topaz tag (%scapable of carrying a NDEF message), %s memory map)", rid_response[0], + PrintAndLogEx(NORMAL, "HR0 : %02x (%sa Topaz tag (%scapable of carrying a NDEF message), %s memory map)", rid_response[0], (rid_response[0] & 0xF0) == 0x10 ? "" : "not ", (rid_response[0] & 0xF0) == 0x10 ? "" : "not ", (rid_response[0] & 0x0F) == 0x01 ? "static" : "dynamic"); PrintAndLogEx(NORMAL, "HR1 : %02x", rid_response[1]); - + status = topaz_rall(uid_echo, rall_response); if (status == -1) { @@ -422,19 +422,19 @@ int CmdHFTopazReader(const char *Cmd) { } memcpy(topaz_tag.uid, rall_response+2, 7); - PrintAndLogEx(NORMAL, "UID : %02x %02x %02x %02x %02x %02x %02x", - topaz_tag.uid[6], - topaz_tag.uid[5], - topaz_tag.uid[4], - topaz_tag.uid[3], - topaz_tag.uid[2], - topaz_tag.uid[1], + PrintAndLogEx(NORMAL, "UID : %02x %02x %02x %02x %02x %02x %02x", + topaz_tag.uid[6], + topaz_tag.uid[5], + topaz_tag.uid[4], + topaz_tag.uid[3], + topaz_tag.uid[2], + topaz_tag.uid[1], topaz_tag.uid[0]); - - PrintAndLogEx(NORMAL, " UID[6] (Manufacturer Byte) = %02x, Manufacturer: %s", - topaz_tag.uid[6], + + PrintAndLogEx(NORMAL, " UID[6] (Manufacturer Byte) = %02x, Manufacturer: %s", + topaz_tag.uid[6], getTagInfo(topaz_tag.uid[6])); - + memcpy(topaz_tag.data_blocks, rall_response+2, 0x0f*8); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Static Data blocks 00 to 0c:"); @@ -449,14 +449,14 @@ int CmdHFTopazReader(const char *Cmd) { lockbits[8] = '\0'; PrintAndLogEx(NORMAL, " 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, lockbits); } - + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Static Reserved block 0d:"); for (uint16_t j = 0; j < 8; j++) { sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0d][j]); } PrintAndLogEx(NORMAL, " 0x%02x | 0x%02x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); - + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Static Lockbits and OTP Bytes:"); for (uint16_t j = 0; j < 8; j++) { @@ -467,7 +467,7 @@ int CmdHFTopazReader(const char *Cmd) { PrintAndLogEx(NORMAL, ""); status = topaz_print_CC(&topaz_tag.data_blocks[1][0]); - + if (status == -1) { PrintAndLogEx(NORMAL, "No NDEF message data present"); topaz_switch_off_field(); @@ -476,14 +476,14 @@ int CmdHFTopazReader(const char *Cmd) { PrintAndLogEx(NORMAL, ""); topaz_print_control_TLVs(&topaz_tag.data_blocks[1][4]); - + PrintAndLogEx(NORMAL, ""); topaz_print_dynamic_data(); - + topaz_print_lifecycle_state(&topaz_tag.data_blocks[1][0]); topaz_print_NDEF(&topaz_tag.data_blocks[1][0]); - + topaz_switch_off_field(); return 0; } diff --git a/client/cmdhw.c b/client/cmdhw.c index ec7b42a1a..640729306 100644 --- a/client/cmdhw.c +++ b/client/cmdhw.c @@ -26,9 +26,9 @@ static int CmdHelp(const char *Cmd); static void lookupChipID(uint32_t iChipID, uint32_t mem_used) { char asBuff[120]; memset(asBuff, 0, sizeof(asBuff)); - uint32_t mem_avail = 0; + uint32_t mem_avail = 0; PrintAndLogEx(NORMAL, "\n [ Hardware ] "); - + switch(iChipID) { case 0x270B0A40: sprintf(asBuff,"AT91SAM7S512 Rev A"); break; case 0x270B0A4F: sprintf(asBuff,"AT91SAM7S512 Rev B"); break; @@ -69,19 +69,19 @@ static void lookupChipID(uint32_t iChipID, uint32_t mem_used) { case 12: mem_avail = 1024; break; case 14: mem_avail = 2048; break; } - + uint32_t mem_left = 0; - if ( mem_avail > 0 ) + if ( mem_avail > 0 ) mem_left = (mem_avail * 1024) - mem_used; - - PrintAndLogEx(NORMAL, " --= Nonvolatile Program Memory Size: %uK bytes, Used: %u bytes (%2.0f%%) Free: %u bytes (%2.0f%%)", - mem_avail, - mem_used, + + PrintAndLogEx(NORMAL, " --= Nonvolatile Program Memory Size: %uK bytes, Used: %u bytes (%2.0f%%) Free: %u bytes (%2.0f%%)", + mem_avail, + mem_used, mem_avail == 0 ? 0.0f : (float)mem_used/(mem_avail*1024)*100, mem_left, mem_avail == 0 ? 0.0f : (float)mem_left/(mem_avail*1024)*100 ); - + switch( (iChipID & 0xF000) >> 12 ) { case 0: sprintf(asBuff,"None"); break; case 1: sprintf(asBuff,"8K bytes"); break; @@ -140,7 +140,7 @@ static void lookupChipID(uint32_t iChipID, uint32_t mem_used) { case 1: sprintf(asBuff,"ROMless or on-chip Flash"); break; case 2: sprintf(asBuff,"Embedded Flash Memory"); break; case 3: sprintf(asBuff,"ROM and Embedded Flash Memory\nNVPSIZ is ROM size\nNVPSIZ2 is Flash size"); break; - case 4: sprintf(asBuff,"SRAM emulating ROM"); break; + case 4: sprintf(asBuff,"SRAM emulating ROM"); break; } PrintAndLogEx(NORMAL, " --= Nonvolatile Program Memory Type: %s",asBuff); } @@ -156,7 +156,7 @@ int CmdDetectReader(const char *Cmd) { PrintAndLogEx(NORMAL, "use 'detectreader' or 'detectreader l' or 'detectreader h'"); return 0; } - clearCommandBuffer(); + clearCommandBuffer(); SendCommand(&c); return 0; } @@ -211,11 +211,11 @@ int CmdReset(const char *Cmd) { */ int CmdSetDivisor(const char *Cmd) { UsbCommand c = {CMD_SET_LF_DIVISOR, {strtol(Cmd, NULL, 0), 0, 0}}; - + if (c.arg[0] < 19 || c.arg[0] > 255) { PrintAndLogEx(NORMAL, "divisor must be between 19 and 255"); return 1; - } + } // 12 000 000 (12Mhz) clearCommandBuffer(); SendCommand(&c); @@ -224,12 +224,12 @@ int CmdSetDivisor(const char *Cmd) { } int CmdSetMux(const char *Cmd) { - + if (strlen(Cmd) < 5) { PrintAndLogEx(NORMAL, "expected: lopkd | loraw | hipkd | hiraw"); return 1; } - + UsbCommand c = {CMD_SET_ADC_MUX}; if (strcmp(Cmd, "lopkd") == 0) c.arg[0] = 0; @@ -246,9 +246,9 @@ int CmdTune(const char *Cmd) { } int CmdVersion(const char *Cmd) { - + bool silent = (Cmd[0] == 's' || Cmd[0] == 'S'); - if ( silent ) + if ( silent ) return 0; UsbCommand c = {CMD_VERSION, {0, 0, 0}}; @@ -259,15 +259,15 @@ int CmdVersion(const char *Cmd) { #ifdef __WIN32 PrintAndLogEx(NORMAL, "\n [ Proxmark3 RFID instrument ]\n"); #else - PrintAndLogEx(NORMAL, "\n\e[34m [ Proxmark3 RFID instrument ]\e[0m\n"); -#endif + PrintAndLogEx(NORMAL, "\n\e[34m [ Proxmark3 RFID instrument ]\e[0m\n"); +#endif char s[50] = {0}; #if defined(WITH_FLASH) || defined(WITH_SMARTCARD) || defined(WITH_FPC) strncat(s, "build for RDV40 with ", sizeof(s) - strlen(s) - 1); #endif #ifdef WITH_FLASH strncat(s, "flashmem; ", sizeof(s) - strlen(s) - 1); -#endif +#endif #ifdef WITH_SMARTCARD strncat(s, "smartcard; ", sizeof(s) - strlen(s) - 1); #endif @@ -276,10 +276,10 @@ int CmdVersion(const char *Cmd) { #endif PrintAndLogEx(NORMAL, "\n [ CLIENT ]"); PrintAndLogEx(NORMAL, " client: iceman %s \n", s); - + PrintAndLogEx(NORMAL, (char*)resp.d.asBytes); - lookupChipID(resp.arg[0], resp.arg[1]); - } + lookupChipID(resp.arg[0], resp.arg[1]); + } PrintAndLogEx(NORMAL, "\n"); return 0; } @@ -301,7 +301,7 @@ int CmdPing(const char *Cmd) { if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) PrintAndLogEx(NORMAL, "Ping successful"); else - PrintAndLogEx(NORMAL, "Ping failed"); + PrintAndLogEx(NORMAL, "Ping failed"); return 0; } @@ -312,7 +312,7 @@ static command_t CommandTable[] = { #ifdef WITH_LCD {"lcd", CmdLCD, 0, " -- Send command/data to LCD"}, {"lcdreset", CmdLCDReset, 0, "Hardware reset LCD"}, -#endif +#endif {"readmem", CmdReadmem, 0, "[address] -- Read memory at decimal address from flash"}, {"reset", CmdReset, 0, "Reset the Proxmark3"}, {"setlfdivisor", CmdSetDivisor, 0, "<19 - 255> -- Drive LF antenna at 12Mhz/(divisor+1)"}, diff --git a/client/cmdlf.c b/client/cmdlf.c index 240a1d402..59dc12654 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -23,7 +23,7 @@ int usage_lf_cmdread(void) { PrintAndLogEx(NORMAL, " c Command bytes (in ones and zeros)"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " ************* All periods in microseconds (ms)"); - PrintAndLogEx(NORMAL, " ************* Use lf config to configure options."); + PrintAndLogEx(NORMAL, " ************* Use lf config to configure options."); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf cmdread d 80 z 100 o 200 c 11000"); return 0; @@ -33,7 +33,7 @@ int usage_lf_read(void){ PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h This help"); PrintAndLogEx(NORMAL, " s silent run no printout"); - PrintAndLogEx(NORMAL, " d #samples # samples to collect (optional)"); + PrintAndLogEx(NORMAL, " d #samples # samples to collect (optional)"); PrintAndLogEx(NORMAL, "Use 'lf config' to set parameters."); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); @@ -79,7 +79,7 @@ int usage_lf_simfsk(void) { PrintAndLogEx(NORMAL, "FSK1 - where fc/8 = high and fc/5 = low"); PrintAndLogEx(NORMAL, "FSK1a - is inverted FSK1, ie: fc/5 = high and fc/8 = low"); PrintAndLogEx(NORMAL, "FSK2 - where fc/10 = high and fc/8 = low"); - PrintAndLogEx(NORMAL, "FSK2a - is inverted FSK2, ie: fc/10 = high and fc/8 = low"); + PrintAndLogEx(NORMAL, "FSK2a - is inverted FSK2, ie: fc/10 = high and fc/8 = low"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h This help"); @@ -176,10 +176,10 @@ int CmdLFCommandRead(const char *Cmd) { //Validations if (errors || cmdp == 0) return usage_lf_cmdread(); - + clearCommandBuffer(); SendCommand(&c); - + WaitForResponse(CMD_ACK, NULL); getSamples(0, true); return 0; @@ -197,9 +197,9 @@ int CmdFlexdemod(const char *Cmd) { int data[GraphTraceLen]; memcpy(data, GraphBuffer, GraphTraceLen); - + size_t size = GraphTraceLen; - + for (i = 0; i < GraphTraceLen; ++i) data[i] = (data[i] < 0) ? -1 : 1; @@ -213,7 +213,7 @@ int CmdFlexdemod(const char *Cmd) { if (i == (start + LONG_WAIT)) break; } - + if (start == size - LONG_WAIT) { PrintAndLogEx(NORMAL, "nothing to wait for"); return 0; @@ -221,7 +221,7 @@ int CmdFlexdemod(const char *Cmd) { data[start] = 4; data[start+1] = 0; - + uint8_t bits[64] = {0x00}; i = start; @@ -250,9 +250,9 @@ int CmdFlexdemod(const char *Cmd) { GraphTraceLen = 32 * 64; i = 0; for (bit = 0; bit < 64; bit++) { - + phase = (bits[bit] == 0) ? 0 : 1; - + for (j = 0; j < 32; j++) { GraphBuffer[i++] = phase; phase = !phase; @@ -317,7 +317,7 @@ int CmdLFSetConfig(const char *Cmd) { //Validations if (errors || cmdp == 0) return usage_lf_config(); - + //Bps is limited to 8 if (bps >> 4) bps = 8; @@ -352,9 +352,9 @@ bool lf_read(bool silent, uint32_t samples) { } int CmdLFRead(const char *Cmd) { - + if ( IsOffline() ) return 0; - + bool errors = false; bool silent = false; uint32_t samples = 0; @@ -387,9 +387,9 @@ int CmdLFRead(const char *Cmd) { int CmdLFSnoop(const char *Cmd) { uint8_t cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_lf_snoop(); - + UsbCommand c = {CMD_LF_SNOOP_RAW_ADC_SAMPLES,{0,0,0}}; - clearCommandBuffer(); + clearCommandBuffer(); SendCommand(&c); WaitForResponse(CMD_ACK, NULL); getSamples(0, false); @@ -414,11 +414,11 @@ int CmdLFSim(const char *Cmd) { int gap = 0; sscanf(Cmd, "%i", &gap); - // convert to bitstream if necessary + // convert to bitstream if necessary ChkBitstream(Cmd); PrintAndLogEx(DEBUG, "DEBUG: Sending [%d bytes]\n", GraphTraceLen); - + //can send only 512 bits at a time (1 byte sent per bit...) for (uint16_t i = 0; i < GraphTraceLen; i += USB_CMD_DATA_SIZE) { UsbCommand c = {CMD_UPLOAD_SIM_SAMPLES_125K, {i, FPGA_LF, 0}}; @@ -440,7 +440,7 @@ int CmdLFSim(const char *Cmd) { return 0; } -// by marshmellow - sim fsk data given clock, fcHigh, fcLow, invert +// by marshmellow - sim fsk data given clock, fcHigh, fcLow, invert // - allow pull data from DemodBuffer int CmdLFfskSim(const char *Cmd) { //might be able to autodetect FCs and clock from Graphbuffer if using demod buffer @@ -448,10 +448,10 @@ int CmdLFfskSim(const char *Cmd) { uint8_t fcHigh = 0, fcLow = 0, clk = 0; bool errors = false, separator = false; char hexData[64] = {0x00}; // store entered hex data - uint8_t data[255] = {0x00}; + uint8_t data[255] = {0x00}; int dataLen = 0; - uint8_t cmdp = 0; - + uint8_t cmdp = 0; + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (param_getchar(Cmd, cmdp)){ case 'h': @@ -475,11 +475,11 @@ int CmdLFfskSim(const char *Cmd) { case 'd': dataLen = param_getstr(Cmd, cmdp+1, hexData, sizeof(hexData)); if (dataLen == 0) - errors = true; + errors = true; else dataLen = hextobinarray((char *)data, hexData); - - if (dataLen == 0) errors = true; + + if (dataLen == 0) errors = true; if (errors) PrintAndLogEx(WARNING, "Error getting hex data"); cmdp += 2; break; @@ -489,7 +489,7 @@ int CmdLFfskSim(const char *Cmd) { break; } } - + // No args if (cmdp == 0 && DemodBufferLen == 0) return usage_lf_simfsk(); @@ -497,7 +497,7 @@ int CmdLFfskSim(const char *Cmd) { if (errors) return usage_lf_simfsk(); int firstClockEdge = 0; - if (dataLen == 0){ //using DemodBuffer + if (dataLen == 0){ //using DemodBuffer if (clk == 0 || fcHigh == 0 || fcLow == 0){ //manual settings must set them all uint8_t ans = fskClocks(&fcHigh, &fcLow, &clk, &firstClockEdge); if (ans==0){ @@ -522,29 +522,29 @@ int CmdLFfskSim(const char *Cmd) { if (size > USB_CMD_DATA_SIZE) { PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); size = USB_CMD_DATA_SIZE; - } + } UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, DemodBuffer, size); clearCommandBuffer(); SendCommand(&c); - + setClockGrid(clk, 0); return 0; } -// by marshmellow - sim ask data given clock, invert, manchester or raw, separator +// by marshmellow - sim ask data given clock, invert, manchester or raw, separator // - allow pull data from DemodBuffer int CmdLFaskSim(const char *Cmd) { // autodetect clock from Graphbuffer if using demod buffer // needs clock, invert, manchester/raw as m or r, separator as s, and bitstream uint8_t encoding = 1, separator = 0, clk = 0, invert = 0; bool errors = false; - char hexData[64] = {0x00}; + char hexData[64] = {0x00}; uint8_t data[255] = {0x00}; // store entered hex data int dataLen = 0; uint8_t cmdp = 0; - + while(param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_lf_simask(); @@ -575,11 +575,11 @@ int CmdLFaskSim(const char *Cmd) { case 'd': dataLen = param_getstr(Cmd, cmdp+1, hexData, sizeof(hexData)); if (dataLen == 0) - errors = true; + errors = true; else dataLen = hextobinarray((char *)data, hexData); - - if (dataLen == 0) errors = true; + + if (dataLen == 0) errors = true; if (errors) PrintAndLogEx(WARNING, "Error getting hex data, datalen: %d", dataLen); cmdp += 2; break; @@ -595,26 +595,26 @@ int CmdLFaskSim(const char *Cmd) { //Validations if (errors) return usage_lf_simask(); - + if (dataLen == 0){ //using DemodBuffer - if (clk == 0) + if (clk == 0) clk = GetAskClock("0", false); } else { setDemodBuf(data, dataLen, 0); } if (clk == 0) clk = 64; if (encoding == 0) clk /= 2; //askraw needs to double the clock speed - + size_t size = DemodBufferLen; if (size > USB_CMD_DATA_SIZE) { PrintAndLogEx(NORMAL, "DemodBuffer too long for current implementation - length: %d - max: %d", size, USB_CMD_DATA_SIZE); size = USB_CMD_DATA_SIZE; } - - PrintAndLogEx(NORMAL, "preparing to sim ask data: %d bits", size); - uint16_t arg1, arg2; + PrintAndLogEx(NORMAL, "preparing to sim ask data: %d bits", size); + + uint16_t arg1, arg2; arg1 = clk << 8 | encoding; arg2 = invert << 8 | separator; @@ -625,7 +625,7 @@ int CmdLFaskSim(const char *Cmd) { return 0; } -// by marshmellow - sim psk data given carrier, clock, invert +// by marshmellow - sim psk data given carrier, clock, invert // - allow pull data from DemodBuffer or parameters int CmdLFpskSim(const char *Cmd) { //might be able to autodetect FC and clock from Graphbuffer if using demod buffer @@ -634,11 +634,11 @@ int CmdLFpskSim(const char *Cmd) { uint8_t invert=0; bool errors = false; char hexData[64] = {0x00}; // store entered hex data - uint8_t data[255] = {0x00}; + uint8_t data[255] = {0x00}; int dataLen = 0; uint8_t cmdp = 0; uint8_t pskType = 1; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -670,11 +670,11 @@ int CmdLFpskSim(const char *Cmd) { case 'd': dataLen = param_getstr(Cmd, cmdp+1, hexData, sizeof(hexData)); if (dataLen == 0) - errors = true; + errors = true; else dataLen = hextobinarray((char *)data, hexData); - - if (dataLen == 0) errors = true; + + if (dataLen == 0) errors = true; if (errors) PrintAndLogEx(WARNING, "Error getting hex data"); cmdp+=2; break; @@ -693,13 +693,13 @@ int CmdLFpskSim(const char *Cmd) { if (dataLen == 0){ //using DemodBuffer PrintAndLogEx(NORMAL, "Getting Clocks"); - + if (clk==0) clk = GetPskClock("", false); PrintAndLogEx(NORMAL, "clk: %d",clk); - - if (!carrier) carrier = GetPskCarrier("", false); + + if (!carrier) carrier = GetPskCarrier("", false); PrintAndLogEx(NORMAL, "carrier: %d", carrier); - + } else { setDemodBuf(data, dataLen, 0); } @@ -708,7 +708,7 @@ int CmdLFpskSim(const char *Cmd) { if (carrier != 2 && carrier != 4 && carrier != 8 ) carrier = 2; - + if (pskType != 1){ if (pskType == 2){ //need to convert psk2 to psk1 data before sim @@ -784,14 +784,14 @@ int CmdVchDemod(const char *Cmd) { for (i = 0; i < 2048; i += 8) { sum = 0; - for (j = 0; j < 8; j++) + for (j = 0; j < 8; j++) sum += GraphBuffer[bestPos+i+j]; - + if (sum < 0) bits[i/8] = '.'; else bits[i/8] = '1'; - + if(abs(sum) < worst) { worst = abs(sum); worstPos = i; @@ -819,7 +819,7 @@ int CmdVchDemod(const char *Cmd) { int CheckChipType(bool getDeviceData) { if (!getDeviceData) return 0; - + save_restoreDB(GRAPH_SAVE); //check for em4x05/em4x69 chips first @@ -836,7 +836,7 @@ int CheckChipType(bool getDeviceData) { PrintAndLogEx(SUCCESS, "\nValid T55xx Chip Found"); PrintAndLogEx(SUCCESS, "Try " _YELLOW_(`lf t55xx`)" commands"); save_restoreGB(GRAPH_RESTORE); - return 1; + return 1; } save_restoreDB(GRAPH_RESTORE); @@ -849,16 +849,16 @@ int CmdLFfind(const char *Cmd) { size_t minLength = 2000; char cmdp = tolower(param_getchar(Cmd, 0)); char testRaw = param_getchar(Cmd, 1); - + if (strlen(Cmd) > 3 || cmdp == 'h') return usage_lf_find(); - + if (cmdp == 'u') testRaw = 'u'; - + bool isOnline = (!IsOffline() && (cmdp != '1') ); - + if (isOnline) lf_read(true, 30000); - + if (GraphTraceLen < minLength) { PrintAndLogEx(FAILED, "Data in Graphbuffer was too small."); return 0; @@ -866,9 +866,9 @@ int CmdLFfind(const char *Cmd) { PrintAndLogEx(INFO, "NOTE: some demods output possible binary"); PrintAndLogEx(INFO, "if it finds something that looks like a tag"); - PrintAndLogEx(INFO, "False Positives " _YELLOW_(ARE) "possible\n"); + PrintAndLogEx(INFO, "False Positives " _YELLOW_(ARE) "possible\n"); PrintAndLogEx(INFO, "\nChecking for known tags:\n"); - + // only run these tests if device is online if (isOnline) { // only run if graphbuffer is just noise as it should be for hitag @@ -876,21 +876,21 @@ int CmdLFfind(const char *Cmd) { signal_t *sp = getSignalProperties(); if (sp->isnoise) { - PrintAndLogEx(INFO, "Signal looks just like noise. Looking for Hitag signal now."); + PrintAndLogEx(INFO, "Signal looks just like noise. Looking for Hitag signal now."); // 26 === RHT2F_UID_ONLY if (CmdLFHitagReader("26") == 0) { PrintAndLogEx(SUCCESS, "\nValid Hitag Found!"); return 1;} if (CmdCOTAGRead("") > 0) { PrintAndLogEx(SUCCESS, "\nValid COTAG ID Found!"); return 1;} - + PrintAndLogEx(FAILED, "\nNo Data Found! - maybe not an LF tag?"); return 0; } } - + if (EM4x50Read("", false)) { PrintAndLogEx(SUCCESS, "\nValid EM4x50 ID Found!"); return 1;} if (CmdAWIDDemod("")) { PrintAndLogEx(SUCCESS, "\nValid AWID ID Found!"); goto out;} if (CmdEM410xDemod("")) { PrintAndLogEx(SUCCESS, "\nValid EM410x ID Found!"); goto out;} - if (CmdFdxDemod("")) { PrintAndLogEx(SUCCESS, "\nValid FDX-B ID Found!"); goto out;} + if (CmdFdxDemod("")) { PrintAndLogEx(SUCCESS, "\nValid FDX-B ID Found!"); goto out;} if (CmdGuardDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Guardall G-Prox II ID Found!"); goto out; } if (CmdHIDDemod("")) { PrintAndLogEx(SUCCESS, "\nValid HID Prox ID Found!"); goto out;} if (CmdPSKIdteck("")) { PrintAndLogEx(SUCCESS, "\nValid Idteck ID Found!"); goto out;} @@ -901,19 +901,19 @@ int CmdLFfind(const char *Cmd) { if (CmdNexWatchDemod("")) { PrintAndLogEx(SUCCESS, "\nValid NexWatch ID Found!"); goto out;} if (CmdNoralsyDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Noralsy ID Found!"); goto out;} if (CmdKeriDemod("")) { PrintAndLogEx(SUCCESS, "\nValid KERI ID Found!"); goto out;} - if (CmdPacDemod("")) { PrintAndLogEx(SUCCESS, "\nValid PAC/Stanley ID Found!"); goto out;} + if (CmdPacDemod("")) { PrintAndLogEx(SUCCESS, "\nValid PAC/Stanley ID Found!"); goto out;} if (CmdParadoxDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Paradox ID Found!"); goto out;} - if (CmdPrescoDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Presco ID Found!"); goto out;} + if (CmdPrescoDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Presco ID Found!"); goto out;} if (CmdPyramidDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Pyramid ID Found!"); goto out;} if (CmdSecurakeyDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Securakey ID Found!"); goto out;} - if (CmdVikingDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Viking ID Found!"); goto out;} + if (CmdVikingDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Viking ID Found!"); goto out;} if (CmdVisa2kDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Visa2000 ID Found!"); goto out;} //if (CmdFermaxDemod("")) { PrintAndLogEx(SUCCESS, "\nValid Fermax ID Found!"); goto out;} // TIdemod? flexdemod? - + PrintAndLogEx(FAILED, "\nNo known 125/134 KHz tags Found!\n"); - + if (testRaw == 'u'){ //test unknown tag formats (raw mode) PrintAndLogEx(INFO, "\nChecking for Unknown tags:\n"); @@ -922,31 +922,31 @@ int CmdLFfind(const char *Cmd) { PrintAndLogEx(INFO, "Possible Auto Correlation of %d repeating samples",ans); - if ( ans % 8 == 0) + if ( ans % 8 == 0) PrintAndLogEx(INFO, "Possible %d bytes", (ans / 8)); } //fsk if ( GetFskClock("", false) ) { - if ( FSKrawDemod("", true) ) { + if ( FSKrawDemod("", true) ) { PrintAndLogEx(NORMAL, "\nUnknown FSK Modulated Tag Found!"); goto out; } } - + bool st = true; if ( ASKDemod_ext("0 0 0", true, false, 1, &st) ) { PrintAndLogEx(NORMAL, "\nUnknown ASK Modulated and Manchester encoded Tag Found!"); PrintAndLogEx(NORMAL, "\nif it does not look right it could instead be ASK/Biphase - try 'data rawdemod ab'"); goto out; } - + if ( CmdPSK1rawDemod("") ) { PrintAndLogEx(NORMAL, "Possible unknown PSK1 Modulated Tag Found above!\n\nCould also be PSK2 - try 'data rawdemod p2'"); PrintAndLogEx(NORMAL, "\nCould also be PSK3 - [currently not supported]"); PrintAndLogEx(NORMAL, "\nCould also be NRZ - try 'data nrzrawdemod"); goto out; } - + PrintAndLogEx(FAILED, "\nNo Data Found!\n"); } out: @@ -970,12 +970,12 @@ static command_t CommandTable[] = { {"keri", CmdLFKeri, 1, "{ KERI RFIDs... }"}, {"nedap", CmdLFNedap, 1, "{ Nedap RFIDs... }"}, {"nexwatch", CmdLFNEXWATCH, 1, "{ NexWatch RFIDs... }"}, - {"noralsy", CmdLFNoralsy, 1, "{ Noralsy RFIDs... }"}, + {"noralsy", CmdLFNoralsy, 1, "{ Noralsy RFIDs... }"}, {"pac", CmdLFPac, 1, "{ PAC/Stanley RFIDs... }"}, {"paradox", CmdLFParadox, 1, "{ Paradox RFIDs... }"}, {"pcf7931", CmdLFPCF7931, 1, "{ PCF7931 CHIPs... }"}, {"presco", CmdLFPresco, 1, "{ Presco RFIDs... }"}, - {"pyramid", CmdLFPyramid, 1, "{ Farpointe/Pyramid RFIDs... }"}, + {"pyramid", CmdLFPyramid, 1, "{ Farpointe/Pyramid RFIDs... }"}, {"securakey", CmdLFSecurakey, 1, "{ Securakey RFIDs... }"}, {"ti", CmdLFTI, 1, "{ TI CHIPs... }"}, {"t55xx", CmdLFT55XX, 1, "{ T55xx CHIPs... }"}, @@ -999,7 +999,7 @@ static command_t CommandTable[] = { int CmdLF(const char *Cmd) { clearCommandBuffer(); CmdsParse(CommandTable, Cmd); - return 0; + return 0; } int CmdHelp(const char *Cmd) { diff --git a/client/cmdlf.h b/client/cmdlf.h index 04c7317a1..be0313528 100644 --- a/client/cmdlf.h +++ b/client/cmdlf.h @@ -17,7 +17,7 @@ #include #include #include "proxmark3.h" -#include "lfdemod.h" // device/client demods of LF signals +#include "lfdemod.h" // device/client demods of LF signals #include "util.h" // for parsing cli command utils #include "ui.h" // for show graph controls #include "graph.h" // for graph data diff --git a/client/cmdlfawid.c b/client/cmdlfawid.c index 3cc56f56c..6e181aa34 100644 --- a/client/cmdlfawid.c +++ b/client/cmdlfawid.c @@ -11,7 +11,7 @@ // FSK2a, RF/50, 96 bits (complete) //----------------------------------------------------------------------------- #include "cmdlfawid.h" // AWID function declarations - + static int CmdHelp(const char *Cmd); int usage_lf_awid_read(void) { @@ -21,7 +21,7 @@ int usage_lf_awid_read(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf awid read [h] [1]"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " 1 : (optional) stop after reading a single card"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); @@ -36,7 +36,7 @@ int usage_lf_awid_sim(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf awid sim [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " : format length 26|34|37|50"); PrintAndLogEx(NORMAL, " : 8|16bit value facility code"); PrintAndLogEx(NORMAL, " : 16|32-bit value card number"); @@ -53,7 +53,7 @@ int usage_lf_awid_clone(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf awid clone [h] [Q5]"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " : format length 26|34|37|50"); PrintAndLogEx(NORMAL, " : 8|16bit value facility code"); PrintAndLogEx(NORMAL, " : 16|32-bit value card number"); @@ -77,7 +77,7 @@ int usage_lf_awid_brute(void){ PrintAndLogEx(NORMAL, " f : 8|16bit value facility code"); PrintAndLogEx(NORMAL, " c : (optional) cardnumber to start with, max 65535"); PrintAndLogEx(NORMAL, " d : delay betweens attempts in ms. Default 1000ms"); - PrintAndLogEx(NORMAL, " v : verbose logging, show all tries"); + PrintAndLogEx(NORMAL, " v : verbose logging, show all tries"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf awid brute a 26 f 224"); @@ -89,8 +89,8 @@ int usage_lf_awid_brute(void){ static bool sendPing(void){ UsbCommand ping = {CMD_PING, {1, 2, 3}}; SendCommand(&ping); - SendCommand(&ping); - SendCommand(&ping); + SendCommand(&ping); + SendCommand(&ping); clearCommandBuffer(); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) @@ -99,10 +99,10 @@ static bool sendPing(void){ } static bool sendTry(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint32_t delay, uint8_t *bits, size_t bs_len, bool verbose){ - + if ( verbose ) - PrintAndLogEx(INFO, "Trying FC: %u; CN: %u", fc, cn); - + PrintAndLogEx(INFO, "Trying FC: %u; CN: %u", fc, cn); + if ( !getAWIDBits(fmtlen, fc, cn, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return false; @@ -116,7 +116,7 @@ static bool sendTry(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint32_t delay, ui memcpy(c.d.asBytes, bits, bs_len); clearCommandBuffer(); SendCommand(&c); - + msleep(delay); sendPing(); return true; @@ -125,15 +125,15 @@ static bool sendTry(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint32_t delay, ui //refactored by marshmellow int getAWIDBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *bits) { - // the return bits, preamble 0000 0001 - bits[7] = 1; - + // the return bits, preamble 0000 0001 + bits[7] = 1; + uint8_t pre[66]; memset(pre, 0, sizeof(pre)); // add formatlength num_to_bytebits(fmtlen, 8, pre); - + // add facilitycode, cardnumber and wiegand parity bits switch (fmtlen) { case 26:{ @@ -165,14 +165,14 @@ int getAWIDBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *bits) { break; } } - - // add AWID 4bit parity + + // add AWID 4bit parity size_t bitLen = addParity(pre, bits+8, 66, 4, 1); if (bitLen != 88) return 0; - + PrintAndLogEx(SUCCESS, "awid raw bits:\n %s \n", sprint_bin(bits, bitLen)); - + return 1; } @@ -192,7 +192,7 @@ static void verify_values(uint8_t *fmtlen, uint32_t *fc, uint32_t *cn){ if ((*cn & 0x3FFFF) != *cn) { *cn &= 0x3FFFF; PrintAndLogEx(INFO, "Card Number Truncated to 18-bits (AWID37): %u", *cn); - } + } break; case 34: if ((*fc & 0xFF) != *fc) { @@ -233,7 +233,7 @@ int CmdAWIDRead_device(const char *Cmd) { UsbCommand c = {CMD_AWID_DEMOD_FSK, {findone, 0, 0}}; clearCommandBuffer(); SendCommand(&c); - return 0; + return 0; } //by marshmellow @@ -283,7 +283,7 @@ int CmdAWIDDemod(const char *Cmd) { // f = facility code, c = card number // w = wiegand parity // (26 bit format shown) - + //get raw ID before removing parities uint32_t rawLo = bytebits_to_byte(bits + idx + 64, 32); uint32_t rawHi = bytebits_to_byte(bits + idx + 32, 32); @@ -305,9 +305,9 @@ int CmdAWIDDemod(const char *Cmd) { // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // |26 bit| |-117--| |-----142------| // - // 00110010 0 0000111110100000 00000000000100010010100010000111 1 000000000 + // 00110010 0 0000111110100000 00000000000100010010100010000111 1 000000000 // bbbbbbbb w ffffffffffffffff cccccccccccccccccccccccccccccccc w xxxxxxxxx - // |50 bit| |----4000------| |-----------2248975------------| + // |50 bit| |----4000------| |-----------2248975------------| // b = format bit len, o = odd parity of last 3 bits // f = facility code, c = card number // w = wiegand parity @@ -319,7 +319,7 @@ int CmdAWIDDemod(const char *Cmd) { uint8_t fmtLen = bytebits_to_byte(bits, 8); switch(fmtLen) { - case 26: + case 26: fc = bytebits_to_byte(bits + 9, 8); cardnum = bytebits_to_byte(bits + 17, 16); code1 = bytebits_to_byte(bits + 8,fmtLen); @@ -329,18 +329,18 @@ int CmdAWIDDemod(const char *Cmd) { fc = bytebits_to_byte(bits + 9, 8); cardnum = bytebits_to_byte(bits + 17, 24); code1 = bytebits_to_byte(bits + 8, (fmtLen-32) ); - code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32); - PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo); + code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32); + PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo); break; case 37: fc = bytebits_to_byte(bits + 9, 13); cardnum = bytebits_to_byte(bits + 22, 18); code1 = bytebits_to_byte(bits + 8, (fmtLen-32) ); - code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32); + code2 = bytebits_to_byte(bits + 8 + (fmtLen-32), 32); PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d, FC: %d, Card: %u - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, code2, rawHi2, rawHi, rawLo); break; // case 40: - // break; + // break; case 50: fc = bytebits_to_byte(bits + 9, 16); cardnum = bytebits_to_byte(bits + 25, 32); @@ -359,7 +359,7 @@ int CmdAWIDDemod(const char *Cmd) { code1 = bytebits_to_byte(bits + 8, fmtLen); PrintAndLogEx(SUCCESS, "AWID Found - BitLength: %d -unknown BitLength- (%u) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo); } - break; + break; } PrintAndLogEx(DEBUG, "DEBUG: AWID idx: %d, Len: %d Printing Demod Buffer:", idx, size); @@ -378,22 +378,22 @@ int CmdAWIDSim(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_awid_sim(); - + fmtlen = param_get8(Cmd, 0); - fc = param_get32ex(Cmd, 1, 0, 10); + fc = param_get32ex(Cmd, 1, 0, 10); cn = param_get32ex(Cmd, 2, 0, 10); if ( !fc || !cn) return usage_lf_awid_sim(); - + verify_values(&fmtlen, &fc, &cn); - + PrintAndLogEx(SUCCESS, "Simulating AWID %u -- FC: %u; CN: %u\n", fmtlen, fc, cn); PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or run another command"); - + if (!getAWIDBits(fmtlen, fc, cn, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; } - + uint8_t clk = 50, high = 10, low = 8, invert = 1; uint64_t arg1 = (high << 8) + low; uint64_t arg2 = (invert << 8) + clk; @@ -402,7 +402,7 @@ int CmdAWIDSim(const char *Cmd) { // arg1 --- fcHigh<<8 + fcLow // arg2 --- Inversion and clk setting // 96 --- Bitstream length: 96-bits == 12 bytes - UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; + UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bits, size); clearCommandBuffer(); SendCommand(&c); @@ -416,7 +416,7 @@ int CmdAWIDClone(const char *Cmd) { uint8_t bits[96]; uint8_t *bs=bits; memset(bs,0,sizeof(bits)); - + char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_awid_clone(); @@ -425,17 +425,17 @@ int CmdAWIDClone(const char *Cmd) { cn = param_get32ex(Cmd, 2, 0, 10); if ( !fc || !cn) return usage_lf_awid_clone(); - + if (tolower(param_getchar(Cmd, 3)) == 'q') //t5555 (Q5) BITRATE = (RF-2)/2 (iceman) blocks[0] = T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | T5555_SET_BITRATE(50) | 3< 1 ) if ( down > 1 ) diff --git a/client/cmdlfcotag.c b/client/cmdlfcotag.c index ff0167938..208355ad8 100644 --- a/client/cmdlfcotag.c +++ b/client/cmdlfcotag.c @@ -32,7 +32,7 @@ int CmdCOTAGDemod(const char *Cmd) { uint8_t bits[COTAG_BITS] = {0}; size_t bitlen = COTAG_BITS; memcpy(bits, DemodBuffer, COTAG_BITS); - + uint8_t alignPos = 0; int err = manrawdecode(bits, &bitlen, 1, &alignPos); if (err){ @@ -45,18 +45,18 @@ int CmdCOTAGDemod(const char *Cmd) { //got a good demod uint16_t cn = bytebits_to_byteLSBF(bits+1, 16); uint32_t fc = bytebits_to_byteLSBF(bits+1+16, 8); - + uint32_t raw1 = bytebits_to_byteLSBF(bits, 32); uint32_t raw2 = bytebits_to_byteLSBF(bits+32, 32); uint32_t raw3 = bytebits_to_byteLSBF(bits+64, 32); uint32_t raw4 = bytebits_to_byteLSBF(bits+96, 32); - + /* fc 161: 1010 0001 -> LSB 1000 0101 cn 33593 1000 0011 0011 1001 -> LSB 1001 1100 1100 0001 cccc cccc cccc cccc ffffffff 0 1001 1100 1100 0001 1000 0101 0000 0000 100001010000000001111011100000011010000010000000000000000000000000000000000000000000000000000000100111001100000110000101000 - 1001 1100 1100 0001 10000101 + 1001 1100 1100 0001 10000101 */ PrintAndLogEx(SUCCESS, "COTAG Found: FC %u, CN: %u Raw: %08X%08X%08X%08X", fc, cn, raw1 ,raw2, raw3, raw4); return 1; @@ -65,32 +65,32 @@ int CmdCOTAGDemod(const char *Cmd) { // When reading a COTAG. // 0 = HIGH/LOW signal - maxlength bigbuff // 1 = translation for HI/LO into bytes with manchester 0,1 - length 300 -// 2 = raw signal - maxlength bigbuff +// 2 = raw signal - maxlength bigbuff int CmdCOTAGRead(const char *Cmd) { - + if (Cmd[0] == 'h' || Cmd[0] == 'H') return usage_lf_cotag_read(); - + uint32_t rawsignal = 1; sscanf(Cmd, "%u", &rawsignal); - + UsbCommand c = {CMD_COTAG, {rawsignal, 0, 0}}; clearCommandBuffer(); SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK, NULL, 7000) ) { PrintAndLogEx(WARNING, "command execution time out"); - return -1; + return -1; } - + switch ( rawsignal ){ - case 0: + case 0: case 2: { CmdPlot(""); CmdGrid("384"); - getSamples(0, true); + getSamples(0, true); break; } case 1: { - + if ( !GetFromDevice(BIG_BUF, DemodBuffer, COTAG_BITS, 0, NULL, 1000, false)) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return -1; @@ -98,7 +98,7 @@ int CmdCOTAGRead(const char *Cmd) { DemodBufferLen = COTAG_BITS; return CmdCOTAGDemod(""); } - } + } return 0; } diff --git a/client/cmdlfcotag.h b/client/cmdlfcotag.h index e03f7d5f5..9270ccbb7 100644 --- a/client/cmdlfcotag.h +++ b/client/cmdlfcotag.h @@ -17,7 +17,7 @@ #include "cmdparser.h" // CmdsParse, CmdsHelp #include "comms.h" #include "ui.h" // PrintAndLog -#include "cmdlf.h" // Setconfig +#include "cmdlf.h" // Setconfig #ifndef COTAG_BITS #define COTAG_BITS 264 diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index 8b9530957..3024470de 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -130,7 +130,7 @@ int usage_lf_em4x50_write(void) { PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h - this help"); PrintAndLogEx(NORMAL, " address - memory address to write to. (0-15)"); - PrintAndLogEx(NORMAL, " data - data to write (hex)"); + PrintAndLogEx(NORMAL, " data - data to write (hex)"); PrintAndLogEx(NORMAL, " pwd - password (hex) (optional)"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf em 4x50_write 1 deadc0de"); @@ -171,7 +171,7 @@ int usage_lf_em4x05_write(void) { PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h - this help"); PrintAndLogEx(NORMAL, " address - memory address to write to. (0-15)"); - PrintAndLogEx(NORMAL, " data - data to write (hex)"); + PrintAndLogEx(NORMAL, " data - data to write (hex)"); PrintAndLogEx(NORMAL, " pwd - password (hex) (optional)"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf em 4x05_write 1 deadc0de"); @@ -251,7 +251,7 @@ void ConstructEM410xEmulGraph(const char *uid,const uint8_t clock) { void printEM410x(uint32_t hi, uint64_t id) { if (!id && !hi) return; - + PrintAndLogEx(NORMAL, "EM410x %s pattern found", (hi) ? "XL" : "" ); uint64_t iii=1; @@ -263,7 +263,7 @@ void printEM410x(uint32_t hi, uint64_t id) { id2lo=(id2lo<<1LL) | ((id & (iii << (i+((ii-1)*8)))) >> (i+((ii-1)*8))); } } - + if (hi){ //output 88 bit em id PrintAndLogEx(NORMAL, "\nEM TAG ID : %06X%016" PRIX64, hi, id); @@ -294,12 +294,12 @@ void printEM410x(uint32_t hi, uint64_t id) { (id2lo & 0x000000000f) ); uint64_t paxton = (((id>>32) << 24) | (id & 0xffffff)) + 0x143e00; - PrintAndLogEx(NORMAL, "}\nOther : %05" PRIu64 "_%03" PRIu64 "_%08" PRIu64, (id&0xFFFF), ((id>>16LL) & 0xFF), (id & 0xFFFFFF)); + PrintAndLogEx(NORMAL, "}\nOther : %05" PRIu64 "_%03" PRIu64 "_%08" PRIu64, (id&0xFFFF), ((id>>16LL) & 0xFF), (id & 0xFFFFFF)); PrintAndLogEx(NORMAL, "Pattern Paxton : %" PRIu64 " [0x%" PRIX64 "]", paxton, paxton); uint32_t p1id = (id & 0xFFFFFF); uint8_t arr[32] = {0x00}; - int i =0; + int i =0; int j = 23; for (; i < 24; ++i, --j ){ arr[i] = (p1id >> i) & 1; @@ -311,12 +311,12 @@ void printEM410x(uint32_t hi, uint64_t id) { p1 |= arr[22] << 23; p1 |= arr[21] << 20; p1 |= arr[20] << 22; - + p1 |= arr[19] << 18; p1 |= arr[18] << 16; p1 |= arr[17] << 19; p1 |= arr[16] << 17; - + p1 |= arr[15] << 13; p1 |= arr[14] << 15; p1 |= arr[13] << 12; @@ -355,12 +355,12 @@ void printEM410x(uint32_t hi, uint64_t id) { int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) { size_t idx = 0; uint8_t bits[512] = {0}; - size_t size = sizeof(bits); + size_t size = sizeof(bits); if ( !getDemodBuf(bits, &size) ) { PrintAndLogEx(DEBUG, "DEBUG: Error - Em410x problem during copy from ASK demod"); return 0; } - + int ans = Em410xDecode(bits, &size, &idx, hi, lo); if ( ans < 0){ @@ -379,13 +379,13 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) { PrintAndLogEx(DEBUG, "DEBUG: Error - Em410x decoded to all zeros"); return 0; } - + //set GraphBuffer for clone or sim command setDemodBuf(DemodBuffer, (size==40) ? 64 : 128, idx+1); setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx+1)*g_DemodClock)); - + PrintAndLogEx(DEBUG, "DEBUG: Em410x idx: %d, Len: %d, Printing Demod Buffer:", idx, size); - if (g_debugMode) + if (g_debugMode) printDemodBuff(); if (verbose) @@ -422,12 +422,12 @@ int CmdEM410xRead_device(const char *Cmd) { int CmdEM410xDemod(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) > 10 || cmdp == 'h') return usage_lf_em410x_demod(); - + uint32_t hi = 0; uint64_t lo = 0; if (AskEm410xDemod(Cmd, &hi, &lo, true) != 1) return 0; - + g_em410xid = lo; return 1; } @@ -446,14 +446,14 @@ int CmdEM410xSim(const char *Cmd) { PrintAndLogEx(FAILED, "UID must include 10 HEX symbols"); return 0; } - + param_getdec(Cmd, 1, &clock); - + PrintAndLogEx(SUCCESS, "Starting simulating UID %02X%02X%02X%02X%02X clock: %d", uid[0],uid[1],uid[2],uid[3],uid[4],clock); PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation"); ConstructEM410xEmulGraph(Cmd, clock); - + CmdLFSim("0"); //240 start_gap. return 0; } @@ -470,10 +470,10 @@ int CmdEM410xBrute(const char *Cmd) { uint8_t clock = 64; /* default pause time: 1 second */ uint32_t delay = 1000; - + char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_lf_em410x_brute(); - + cmdp = tolower(param_getchar(Cmd, 1)); if (cmdp == 'd') { delay = param_get32ex(Cmd, 2, 1000, 10); @@ -483,12 +483,12 @@ int CmdEM410xBrute(const char *Cmd) { delay = param_get32ex(Cmd, 4, 1000, 10); } - int filelen = param_getstr(Cmd, 0, filename, FILE_PATH_SIZE); + int filelen = param_getstr(Cmd, 0, filename, FILE_PATH_SIZE); if (filelen == 0) { PrintAndLogEx(WARNING, "Error: Please specify a filename"); - return 1; + return 1; } - + if ((f = fopen(filename, "r")) == NULL) { PrintAndLogEx(WARNING, "Error: Could not open UIDs file [%s]", filename); return 1; @@ -499,23 +499,23 @@ int CmdEM410xBrute(const char *Cmd) { fclose(f); return 1; } - + while( fgets(buf, sizeof(buf), f) ) { if (strlen(buf) < 10 || buf[9] == '\n') continue; while (fgetc(f) != '\n' && !feof(f)); //goto next line //The line start with # is comment, skip if( buf[0]=='#' ) continue; - + if (param_gethex(buf, 0, uid, 10)) { PrintAndLogEx(FAILED, "UIDs must include 10 HEX symbols"); free(uidBlock); fclose(f); return 1; } - + buf[10] = 0; - + if ( stUidBlock - uidcnt < 2) { p = realloc(uidBlock, 5 * (stUidBlock += 10) ); if (!p) { @@ -531,50 +531,50 @@ int CmdEM410xBrute(const char *Cmd) { uidcnt++; memset(buf, 0, sizeof(buf)); } - + fclose(f); - + if (uidcnt == 0) { PrintAndLogEx(FAILED, "No UIDs found in file"); free(uidBlock); return 1; } - + PrintAndLogEx(SUCCESS, "Loaded %d UIDs from %s, pause delay: %d ms", uidcnt, filename, delay); - + // loop for(uint32_t c = 0; c < uidcnt; ++c ) { char testuid[11]; testuid[10] = 0; - + if (ukbhit()) { int gc = getchar(); (void)gc; PrintAndLogEx(NORMAL, "\nAborted via keyboard!\n"); free(uidBlock); return 0; } - + sprintf(testuid, "%010" PRIX64, bytes_to_num(uidBlock + 5*c, 5)); PrintAndLogEx(NORMAL, "Bruteforce %d / %d: simulating UID %s, clock %d", c + 1, uidcnt, testuid, clock); - + ConstructEM410xEmulGraph(testuid, clock); - + CmdLFSim("0"); //240 start_gap. msleep(delay); } - + free(uidBlock); return 0; } /* Function is equivalent of lf read + data samples + em410xread - * looped until an EM410x tag is detected - * + * looped until an EM410x tag is detected + * * Why is CmdSamples("16000")? * TBD: Auto-grow sample size based on detected sample rate. IE: If the * rate gets lower, then grow the number of samples - * Changed by martin, 4000 x 4 = 16000, + * Changed by martin, 4000 x 4 = 16000, * see http://www.proxmark.org/forum/viewtopic.php?pid=7235#p7235 * * EDIT -- capture enough to get 2 complete preambles at the slowest data rate known to be used (rf/64) (64*64*2+9 = 8201) marshmellow @@ -585,19 +585,19 @@ int CmdEM410xWatch(const char *Cmd) { int gc = getchar(); (void)gc; PrintAndLogEx(NORMAL, "\naborted via keyboard!\n"); break; - } + } lf_read(true, 8201); - + } while (!CmdEM410xRead("")); return 0; } //currently only supports manchester modulations int CmdEM410xWatchnSpoof(const char *Cmd) { - + char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_lf_em410x_ws(); - + // loops if the captured ID was in XL-format. CmdEM410xWatch(Cmd); PrintAndLogEx(SUCCESS, "# Replaying captured ID: %010" PRIx64 , g_em410xid); @@ -608,7 +608,7 @@ int CmdEM410xWatchnSpoof(const char *Cmd) { int CmdEM410xWrite(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (cmdp == 'h' || cmdp == 'H') return usage_lf_em410x_write(); - + uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value int card = 0xFF; // invalid card value uint32_t clock = 0; // invalid clock value @@ -699,14 +699,14 @@ bool EM_ByteParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t co // 012345678|r3 // 012345678|r4 // ------------ -//c012345678| 0 +//c012345678| 0 // |- must be zero bool EMwordparitytest(uint8_t *bits){ // last row/col parity must be 0 if (bits[44] != 0 ) return false; - + // col parity check uint8_t c1 = bytebits_to_byte(bits, 8) ^ bytebits_to_byte(bits+9, 8) ^ bytebits_to_byte(bits+18, 8) ^ bytebits_to_byte(bits+27, 8); uint8_t c2 = bytebits_to_byte(bits+36, 8); @@ -718,8 +718,8 @@ bool EMwordparitytest(uint8_t *bits){ rowP ^= bits[i]; if ( i>0 && (i % 9) == 0) { - - if ( rowP != EVEN ) + + if ( rowP != EVEN ) return false; rowP = 0; @@ -733,12 +733,12 @@ bool EMwordparitytest(uint8_t *bits){ uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool pTest) { if (size<45) return 0; - + uint32_t code = bytebits_to_byte(BitStream,8); code = code<<8 | bytebits_to_byte(BitStream+9,8); code = code<<8 | bytebits_to_byte(BitStream+18,8); code = code<<8 | bytebits_to_byte(BitStream+27,8); - + if (verbose || g_debugMode){ for (uint8_t i = 0; i<5; i++){ if (i == 4) PrintAndLogEx(NORMAL, ""); //parity byte spacer @@ -797,11 +797,11 @@ int EM4x50Read(const char *Cmd, bool verbose) { // get user entry if any sscanf(Cmd, "%i %i", &clk, &invert); - + uint8_t bits[MAX_GRAPH_TRACE_LEN] = {0}; size_t size = getFromGraphBuf(bits); computeSignalProperties(bits, size); - + signal_t *sp = getSignalProperties(); high = sp->high; low = sp->low; @@ -835,7 +835,7 @@ int EM4x50Read(const char *Cmd, bool verbose) { if (!clk) { for (uint8_t clkCnt = 0; clkCnt < 7; clkCnt++) { tol = fndClk[clkCnt] / 8; - if (minClk >= fndClk[clkCnt] - tol && minClk <= fndClk[clkCnt] + 1) { + if (minClk >= fndClk[clkCnt] - tol && minClk <= fndClk[clkCnt] + 1) { clk = fndClk[clkCnt]; break; } @@ -863,12 +863,12 @@ int EM4x50Read(const char *Cmd, bool verbose) { // skip over the remainder of LW skip += (tmpbuff[i+1] + tmpbuff[i+2] + clk); - - if (tmpbuff[i+3] > clk) + + if (tmpbuff[i+3] > clk) phaseoff = tmpbuff[i+3] - clk; else phaseoff = 0; - + // now do it again to find the end end = skip; for (i += 3; i < j - 4 ; ++i) { @@ -894,12 +894,12 @@ int EM4x50Read(const char *Cmd, bool verbose) { return 0; } } else if (start < 0) return 0; - + start = skip; snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk * 47); - // save GraphBuffer - to restore it later + // save GraphBuffer - to restore it later save_restoreGB(GRAPH_SAVE); - // get rid of leading crap + // get rid of leading crap snprintf(tmp, sizeof(tmp), "%i", skip); CmdLtrim(tmp); bool pTest; @@ -910,7 +910,7 @@ int EM4x50Read(const char *Cmd, bool verbose) { while (block < 6) { if (verbose || g_debugMode) PrintAndLogEx(NORMAL, "\nBlock %i:", block); skip = phaseoff; - + // look for LW before start of next block for ( ; i < j - 4 ; ++i) { skip += tmpbuff[i]; @@ -924,9 +924,9 @@ int EM4x50Read(const char *Cmd, bool verbose) { phaseoff = tmpbuff[i+1] - clk; else phaseoff = 0; - + i += 2; - + if (ASKDemod(tmp2, false, false, 1) < 1) { save_restoreGB(GRAPH_RESTORE); return 0; @@ -934,7 +934,7 @@ int EM4x50Read(const char *Cmd, bool verbose) { //set DemodBufferLen to just one block DemodBufferLen = skip/clk; //test parities - pTest = EM_ByteParityTest(DemodBuffer,DemodBufferLen, 5, 9, 0); + pTest = EM_ByteParityTest(DemodBuffer,DemodBufferLen, 5, 9, 0); pTest &= EM_EndParityTest(DemodBuffer,DemodBufferLen, 5, 9, 0); AllPTest &= pTest; //get output @@ -953,7 +953,7 @@ int EM4x50Read(const char *Cmd, bool verbose) { PrintAndLogEx(NORMAL, "Partial data - no end found!"); PrintAndLogEx(NORMAL, "Try again with more samples."); } - PrintAndLogEx(NORMAL, "Found data at sample: %i - using clock: %i", start, clk); + PrintAndLogEx(NORMAL, "Found data at sample: %i - using clock: %i", start, clk); end = block; for (block=0; block < end; block++){ PrintAndLogEx(NORMAL, "Block %d: %08x", block, Code[block]); @@ -973,7 +973,7 @@ int EM4x50Read(const char *Cmd, bool verbose) { int CmdEM4x50Read(const char *Cmd) { uint8_t ctmp = tolower(param_getchar(Cmd, 0)); - if ( ctmp == 'h' ) return usage_lf_em4x50_read(); + if ( ctmp == 'h' ) return usage_lf_em4x50_read(); return EM4x50Read(Cmd, true); } int CmdEM4x50Write(const char *Cmd){ @@ -992,7 +992,7 @@ int CmdEM4x50Dump(const char *Cmd){ #define EM_PREAMBLE_LEN 6 // download samples from device and copy to Graphbuffer bool downloadSamplesEM(){ - + // 8 bit preamble + 32 bit word response (max clock (128) * 40bits = 5120 samples) uint8_t got[6000]; if ( !GetFromDevice(BIG_BUF, got, sizeof(got), 0, NULL, 2500, false)) { @@ -1011,9 +1011,9 @@ bool downloadSamplesEM(){ return true; } -// em_demod +// em_demod bool doPreambleSearch(size_t *startIdx){ - + // sanity check if ( DemodBufferLen < EM_PREAMBLE_LEN) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 demodbuffer too small"); @@ -1022,14 +1022,14 @@ bool doPreambleSearch(size_t *startIdx){ // set size to 20 to only test first 14 positions for the preamble size_t size = (20 > DemodBufferLen) ? DemodBufferLen : 20; - *startIdx = 0; + *startIdx = 0; // skip first two 0 bits as they might have been missed in the demod uint8_t preamble[EM_PREAMBLE_LEN] = {0,0,1,0,1,0}; - + if ( !preambleSearchEx(DemodBuffer, preamble, EM_PREAMBLE_LEN, &size, startIdx, true)) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM4305 preamble not found :: %d", *startIdx); return false; - } + } return true; } @@ -1048,7 +1048,7 @@ bool detectFSK(){ return true; } // PSK clocks should be easy to detect ( but difficult to demod a non-repeating pattern... ) -bool detectPSK(){ +bool detectPSK(){ int ans = GetPskClock("", false); if (ans <= 0) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM: PSK clock failed"); @@ -1077,14 +1077,14 @@ bool detectASK_MAN(){ if ( !ASKDemod_ext("0 0 0", false, false, 1, &stcheck) ) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/Manchester Demod failed"); return false; - } + } return true; } bool detectASK_BI(){ int ans = ASKbiphaseDemod("0 0 1", false); - if (!ans) { + if (!ans) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/biphase normal demod failed"); - + ans = ASKbiphaseDemod("0 1 1", false); if (!ans) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM: ASK/biphase inverted demod failed"); @@ -1104,8 +1104,8 @@ bool setDemodBufferEM(uint32_t *word, size_t idx){ PrintAndLogEx(DEBUG, "DEBUG: Error - EM Parity tests failed"); return false; } - - // test for even parity bits and remove them. (leave out the end row of parities so 36 bits) + + // test for even parity bits and remove them. (leave out the end row of parities so 36 bits) if (!removeParity(DemodBuffer, idx + EM_PREAMBLE_LEN, 9, 0, 36)) { PrintAndLogEx(DEBUG, "DEBUG: Error - EM, failed removing parity"); return false; @@ -1115,25 +1115,25 @@ bool setDemodBufferEM(uint32_t *word, size_t idx){ return true; } -// FSK, PSK, ASK/MANCHESTER, ASK/BIPHASE, ASK/DIPHASE +// FSK, PSK, ASK/MANCHESTER, ASK/BIPHASE, ASK/DIPHASE // should cover 90% of known used configs // the rest will need to be manually demoded for now... bool demodEM4x05resp(uint32_t *word) { - size_t idx = 0; + size_t idx = 0; *word = 0; if (detectASK_MAN() && doPreambleSearch( &idx )) return setDemodBufferEM(word, idx); - + if (detectASK_BI() && doPreambleSearch( &idx )) return setDemodBufferEM(word, idx); - + if (detectFSK() && doPreambleSearch( &idx )) return setDemodBufferEM(word, idx); - + if (detectPSK()) { if (doPreambleSearch( &idx )) return setDemodBufferEM(word, idx); - + psk1TOpsk2(DemodBuffer, DemodBufferLen); if (doPreambleSearch( &idx )) return setDemodBufferEM(word, idx); @@ -1146,7 +1146,7 @@ int EM4x05ReadWord_ext(uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *word) UsbCommand c = {CMD_EM4X_READ_WORD, {addr, pwd, usePwd}}; clearCommandBuffer(); SendCommand(&c); - UsbCommand resp; + UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 2500)){ PrintAndLogEx(DEBUG, "Command timed out"); return -1; @@ -1154,7 +1154,7 @@ int EM4x05ReadWord_ext(uint8_t addr, uint32_t pwd, bool usePwd, uint32_t *word) if ( !downloadSamplesEM() ) { return -1; } - + return demodEM4x05resp(word); } @@ -1167,7 +1167,7 @@ int CmdEM4x05Dump(const char *Cmd) { // for now use default input of 1 as invalid (unlikely 1 will be a valid password...) pwd = param_get32ex(Cmd, 0, 1, 16); - + if ( pwd != 1 ) usePwd = true; @@ -1176,7 +1176,7 @@ int CmdEM4x05Dump(const char *Cmd) { PrintAndLogEx(NORMAL, "Addr | data | ascii"); PrintAndLogEx(NORMAL, "-----+--------+------"); for (; addr < 16; addr++) { - + if (addr == 2) { if (usePwd) { PrintAndLogEx(NORMAL, " %02u | %08X", addr, pwd, word ); @@ -1200,7 +1200,7 @@ int CmdEM4x05Read(const char *Cmd) { addr = param_get8ex(Cmd, 0, 50, 10); pwd = param_get32ex(Cmd, 1, 1, 16); - + if (addr > 15) { PrintAndLogEx(NORMAL, "Address must be between 0 and 15"); return 1; @@ -1211,7 +1211,7 @@ int CmdEM4x05Read(const char *Cmd) { usePwd = true; PrintAndLogEx(NORMAL, "Reading address %02u | password %08X", addr, pwd); } - + uint32_t word = 0; int isOk = EM4x05ReadWord_ext(addr, pwd, usePwd, &word); if (isOk) @@ -1224,38 +1224,38 @@ int CmdEM4x05Read(const char *Cmd) { int CmdEM4x05Write(const char *Cmd) { uint8_t ctmp = param_getchar(Cmd, 0); if ( strlen(Cmd) == 0 || ctmp == 'H' || ctmp == 'h' ) return usage_lf_em4x05_write(); - - bool usePwd = false; + + bool usePwd = false; uint8_t addr = 50; // default to invalid address uint32_t data = 0; // default to blank data uint32_t pwd = 1; // default to blank password - + addr = param_get8ex(Cmd, 0, 50, 10); data = param_get32ex(Cmd, 1, 0, 16); pwd = param_get32ex(Cmd, 2, 1, 16); - + if ( addr > 15 ) { PrintAndLogEx(NORMAL, "Address must be between 0 and 15"); return 1; } if ( pwd == 1 ) - PrintAndLogEx(NORMAL, "Writing address %d data %08X", addr, data); + PrintAndLogEx(NORMAL, "Writing address %d data %08X", addr, data); else { usePwd = true; - PrintAndLogEx(NORMAL, "Writing address %d data %08X using password %08X", addr, data, pwd); + PrintAndLogEx(NORMAL, "Writing address %d data %08X using password %08X", addr, data, pwd); } - + uint16_t flag = (addr << 8 ) | usePwd; - + UsbCommand c = {CMD_EM4X_WRITE_WORD, {flag, data, pwd}}; clearCommandBuffer(); SendCommand(&c); - UsbCommand resp; + UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)){ PrintAndLogEx(WARNING, "Error occurred, device did not respond during write operation."); return -1; } - + if (!downloadSamplesEM()) return -1; @@ -1265,7 +1265,7 @@ int CmdEM4x05Write(const char *Cmd) { if (isOk) PrintAndLogEx(NORMAL, "Write Verified"); else - PrintAndLogEx(NORMAL, "Write could not be verified"); + PrintAndLogEx(NORMAL, "Write could not be verified"); return isOk; } @@ -1325,10 +1325,10 @@ void printEM4x05config(uint32_t wordData) { PrintAndLogEx(NORMAL, " PSK CF: %u | %s", PSKcf, cf); PrintAndLogEx(NORMAL, " Delay: %u | %s", delay, cdelay); PrintAndLogEx(NORMAL, " LastWordR: %02u | Address of last word for default read - meaning %u blocks are output", LWR, numblks); - PrintAndLogEx(NORMAL, " ReadLogin: %u | Read Login is %s", readLogin, readLogin ? "Required" : "Not Required"); - PrintAndLogEx(NORMAL, " ReadHKL: %u | Read Housekeeping Words Login is %s", readHKL, readHKL ? "Required" : "Not Required"); - PrintAndLogEx(NORMAL, "WriteLogin: %u | Write Login is %s", writeLogin, writeLogin ? "Required" : "Not Required"); - PrintAndLogEx(NORMAL, " WriteHKL: %u | Write Housekeeping Words Login is %s", writeHKL, writeHKL ? "Required" : "Not Required"); + PrintAndLogEx(NORMAL, " ReadLogin: %u | Read Login is %s", readLogin, readLogin ? "Required" : "Not Required"); + PrintAndLogEx(NORMAL, " ReadHKL: %u | Read Housekeeping Words Login is %s", readHKL, readHKL ? "Required" : "Not Required"); + PrintAndLogEx(NORMAL, "WriteLogin: %u | Write Login is %s", writeLogin, writeLogin ? "Required" : "Not Required"); + PrintAndLogEx(NORMAL, " WriteHKL: %u | Write Housekeeping Words Login is %s", writeHKL, writeHKL ? "Required" : "Not Required"); PrintAndLogEx(NORMAL, " R.A.W.: %u | Read After Write is %s", raw, raw ? "On" : "Off"); PrintAndLogEx(NORMAL, " Disable: %u | Disable Command is %s", disable, disable ? "Accepted" : "Not Accepted"); PrintAndLogEx(NORMAL, " R.T.F.: %u | Reader Talk First is %s", rtf, rtf ? "Enabled" : "Disabled"); @@ -1336,11 +1336,11 @@ void printEM4x05config(uint32_t wordData) { } void printEM4x05info(uint32_t block0, uint32_t serial) { - + uint8_t chipType = (block0 >> 1) & 0xF; uint8_t cap = (block0 >> 5) & 3; uint16_t custCode = (block0 >> 9) & 0x3FF; - + switch (chipType) { case 9: PrintAndLogEx(NORMAL, "\n Chip Type: %u | EM4305", chipType); break; case 8: PrintAndLogEx(NORMAL, "\n Chip Type: %u | EM4205", chipType); break; @@ -1366,7 +1366,7 @@ void printEM4x05info(uint32_t block0, uint32_t serial) { void printEM4x05ProtectionBits(uint32_t word) { for (uint8_t i = 0; i < 15; i++) { PrintAndLogEx(NORMAL, " Word: %02u | %s", i, (((1 << i) & word ) || i < 2) ? "Is Write Locked" : "Is Not Write Locked"); - if (i==14) + if (i==14) PrintAndLogEx(NORMAL, " Word: %02u | %s", i+1, (((1 << i) & word ) || i < 2) ? "Is Write Locked" : "Is Not Write Locked"); } } @@ -1390,25 +1390,25 @@ int CmdEM4x05Info(const char *Cmd) { // for now use default input of 1 as invalid (unlikely 1 will be a valid password...) pwd = param_get32ex(Cmd, 0, 1, 16); - + if ( pwd != 1 ) usePwd = true; // read word 0 (chip info) // block 0 can be read even without a password. - if ( !EM4x05IsBlock0(&block0) ) + if ( !EM4x05IsBlock0(&block0) ) return -1; - + // read word 1 (serial #) doesn't need pwd // continue if failed, .. non blocking fail. EM4x05ReadWord_ext(EM_SERIAL_BLOCK, 0, false, &serial); printEM4x05info(block0, serial); - // read word 4 (config block) + // read word 4 (config block) // needs password if one is set if ( EM4x05ReadWord_ext(EM_CONFIG_BLOCK, pwd, usePwd, &word) != 1 ) return 0; - + printEM4x05config(word); // read word 14 and 15 to see which is being used for the protection bits @@ -1428,8 +1428,8 @@ int CmdEM4x05Info(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - //{"410x_demod", CmdEMdemodASK, 0, "Extract ID from EM410x tag on antenna)"}, - {"410x_demod", CmdEM410xDemod, 0, "demodulate a EM410x tag from the GraphBuffer"}, + //{"410x_demod", CmdEMdemodASK, 0, "Extract ID from EM410x tag on antenna)"}, + {"410x_demod", CmdEM410xDemod, 0, "demodulate a EM410x tag from the GraphBuffer"}, {"410x_read", CmdEM410xRead, 1, "attempt to read and extract tag data"}, {"410x_sim", CmdEM410xSim, 0, "simulate EM410x tag"}, {"410x_brute", CmdEM410xBrute, 0, "reader bruteforce attack by simulating EM410x tags"}, diff --git a/client/cmdlfem4x.h b/client/cmdlfem4x.h index 676c6fd6b..7a8186e6a 100644 --- a/client/cmdlfem4x.h +++ b/client/cmdlfem4x.h @@ -50,7 +50,7 @@ extern void printEM410x(uint32_t hi, uint64_t id); extern int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ); extern int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose); -extern int usage_lf_em410x_sim(void); +extern int usage_lf_em410x_sim(void); extern int usage_lf_em410x_ws(void); extern int usage_lf_em410x_clone(void); extern int usage_lf_em410x_sim(void); diff --git a/client/cmdlffdx.c b/client/cmdlffdx.c index 4f867b038..c87f40ba4 100644 --- a/client/cmdlffdx.c +++ b/client/cmdlffdx.c @@ -18,8 +18,8 @@ COUNTRY CODE (ISO3166) or http://cms.abvma.ca/uploads/ManufacturersISOsandCountryCodes.pdf FLAG (animal/non-animal) - 38 IDbits - 10 country code + 38 IDbits + 10 country code 1 extra app bit 14 reserved bits 1 animal bit @@ -78,12 +78,12 @@ int detectFDXB(uint8_t *dest, size_t *size) { return (int)startIdx; } -// clearing the topbit needed for the preambl detection. +// clearing the topbit needed for the preambl detection. static void verify_values(uint32_t countryid, uint64_t animalid){ if ((animalid & 0x3FFFFFFFFF) != animalid) { animalid &= 0x3FFFFFFFFF; PrintAndLogEx(INFO, "Animal ID Truncated to 38bits: %"PRIx64, animalid); - } + } if ( (countryid & 0x3ff) != countryid ) { countryid &= 0x3ff; PrintAndLogEx(INFO, "Country ID Truncated to 10bits: %03d", countryid); @@ -95,31 +95,31 @@ int getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t // add preamble ten 0x00 and one 0x01 memset(bits, 0x00, 10); bits[10] = 1; - + // 128bits // every 9th bit is 0x01, but we can just fill the rest with 0x01 and overwrite memset(bits, 0x01, 128); - + // add preamble ten 0x00 and one 0x01 memset(bits, 0x00, 10); - // add reserved + // add reserved num_to_bytebitsLSBF(0x00, 7, bits + 66); num_to_bytebitsLSBF(0x00 >> 7, 7, bits + 74); // add animal flag - OK bits[65] = isanimal; - + // add extended flag - OK bits[81] = isextended; - + // add national code 40bits - OK num_to_bytebitsLSBF(national_id >> 0, 8, bits+11); num_to_bytebitsLSBF(national_id >> 8, 8, bits+20); num_to_bytebitsLSBF(national_id >> 16, 8, bits+29); num_to_bytebitsLSBF(national_id >> 24, 8, bits+38); num_to_bytebitsLSBF(national_id >> 32, 6, bits+47); - + // add country code - OK num_to_bytebitsLSBF(country >> 0, 2, bits+53); num_to_bytebitsLSBF(country >> 2, 8, bits+56); @@ -128,11 +128,11 @@ int getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t uint8_t raw[8]; for (uint8_t i=0; i<8; ++i) raw[i] = bytebits_to_byte(bits + 11 + i * 9, 8); - + uint16_t crc = crc16_kermit(raw, 8); num_to_bytebitsLSBF(crc >> 0, 8, bits+83); num_to_bytebitsLSBF(crc >> 8, 8, bits+92); - + // extended data - OK num_to_bytebitsLSBF( extended >> 0 , 8, bits+101); num_to_bytebitsLSBF( extended >> 8 , 8, bits+110); @@ -147,8 +147,8 @@ int getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t // COUNTRY CODE (ISO3166) or http://cms.abvma.ca/uploads/ManufacturersISOsandCountryCodes.pdf // FLAG (animal/non-animal) /* -38 IDbits -10 country code +38 IDbits +10 country code 1 extra app bit 14 reserved bits 1 animal bit @@ -161,11 +161,11 @@ int CmdFDXBdemodBI(const char *Cmd){ int clk = 32; int invert = 1, errCnt = 0, offset = 0, maxErr = 0; - uint8_t bs[MAX_DEMOD_BUF_LEN]; - size_t size = getFromGraphBuf(bs); - + uint8_t bs[MAX_DEMOD_BUF_LEN]; + size_t size = getFromGraphBuf(bs); + errCnt = askdemod(bs, &size, &clk, &invert, maxErr, 0, 0); - if ( errCnt < 0 || errCnt > maxErr ) { + if ( errCnt < 0 || errCnt > maxErr ) { PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB no data or error found %d, clock: %d", errCnt, clk); return 0; } @@ -174,8 +174,8 @@ int CmdFDXBdemodBI(const char *Cmd){ if (errCnt < 0 || errCnt > maxErr ) { PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB BiphaseRawDecode: %d", errCnt); return 0; - } - + } + int preambleIndex = detectFDXB(bs, &size); if (preambleIndex < 0){ PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB preamble not found :: %d",preambleIndex); @@ -185,7 +185,7 @@ int CmdFDXBdemodBI(const char *Cmd){ PrintAndLogEx(DEBUG, "DEBUG: Error - FDXB incorrect data length found"); return 0; } - + setDemodBuf(bs, 128, preambleIndex); // remove marker bits (1's every 9th digit after preamble) (pType = 2) @@ -231,7 +231,7 @@ int CmdFDXBdemodBI(const char *Cmd){ //see ASKDemod for what args are accepted -//almost the same demod as cmddata.c/CmdFDXBdemodBI +//almost the same demod as cmddata.c/CmdFDXBdemodBI int CmdFdxDemod(const char *Cmd) { //Differential Biphase / di-phase (inverted biphase) @@ -279,25 +279,25 @@ int CmdFdxDemod(const char *Cmd) { uint16_t calcCrc = crc16_kermit(raw, 8); - + PrintAndLogEx(SUCCESS, "\nFDX-B / ISO 11784/5 Animal Tag ID Found: Raw : %s", sprint_hex(raw, 8)); PrintAndLogEx(SUCCESS, "Animal ID %04u-%012" PRIu64, countryCode, NationalCode); PrintAndLogEx(SUCCESS, "National Code %012" PRIu64 " (0x%" PRIx64 ")", NationalCode, NationalCode); PrintAndLogEx(SUCCESS, "Country Code %04u", countryCode); PrintAndLogEx(SUCCESS, "Reserved/RFU %u (0x04%X)", reservedCode, reservedCode); - PrintAndLogEx(SUCCESS, "Animal Tag %s", animalBit ? _YELLOW_(True) : "False"); - PrintAndLogEx(SUCCESS, "Has extended data %s [0x%X]", dataBlockBit ? _YELLOW_(True) : "False", extended); + PrintAndLogEx(SUCCESS, "Animal Tag %s", animalBit ? _YELLOW_(True) : "False"); + PrintAndLogEx(SUCCESS, "Has extended data %s [0x%X]", dataBlockBit ? _YELLOW_(True) : "False", extended); PrintAndLogEx(SUCCESS, "CRC-16 0x%04X - 0x%04X [%s]", crc16, calcCrc, (calcCrc == crc16) ? _GREEN_(Ok) : "Failed"); if (g_debugMode) { - PrintAndLogEx(DEBUG, "Start marker %d; Size %d", preambleIndex, size); + PrintAndLogEx(DEBUG, "Start marker %d; Size %d", preambleIndex, size); char *bin = sprint_bin_break(DemodBuffer, size, 16); PrintAndLogEx(DEBUG, "DEBUG bin stream:\n%s", bin); } // set block 0 for later //g_DemodConfig = T55x7_MODULATION_DIPHASE | T55x7_BITRATE_RF_32 | 4 << T55x7_MAXBLOCK_SHIFT; - + return 1; } @@ -314,20 +314,20 @@ int CmdFdxClone(const char *Cmd) { uint8_t bits[128]; uint8_t *bs = bits; memset(bs, 0, sizeof(bits)); - + char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_fdx_clone(); countryid = param_get32ex(Cmd, 0, 0, 10); animalid = param_get64ex(Cmd, 1, 0, 10); - + verify_values(countryid, animalid); - - // getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t isextended, uint32_t extended, uint8_t *bits) + + // getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t isextended, uint32_t extended, uint8_t *bits) if ( !getFDXBits(animalid, countryid, 1, 0, 0, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } //Q5 if (param_getchar(Cmd, 2) == 'Q' || param_getchar(Cmd, 2) == 'q') @@ -341,7 +341,7 @@ int CmdFdxClone(const char *Cmd) { PrintAndLogEx(INFO, "Preparing to clone FDX-B to T55x7 with animal ID: %04u-%"PRIu64, countryid, animalid); print_blocks(blocks, 5); - + UsbCommand resp; UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}}; @@ -367,9 +367,9 @@ int CmdFdxSim(const char *Cmd) { countryid = param_get32ex(Cmd, 0, 0, 10); animalid = param_get64ex(Cmd, 1, 0, 10); - + verify_values(countryid, animalid); - + // 32, no STT, BIPHASE INVERTED == diphase uint8_t clk = 32, encoding = 2, separator = 0, invert = 1; uint16_t arg1, arg2; @@ -381,7 +381,7 @@ int CmdFdxSim(const char *Cmd) { UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; - //getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t isextended, uint32_t extended, uint8_t *bits) + //getFDXBits(uint64_t national_id, uint16_t country, uint8_t isanimal, uint8_t isextended, uint32_t extended, uint8_t *bits) getFDXBits(animalid, countryid, 1, 0, 0, c.d.asBytes); clearCommandBuffer(); SendCommand(&c); diff --git a/client/cmdlffdx.h b/client/cmdlffdx.h index b7b019909..107bb83ec 100644 --- a/client/cmdlffdx.h +++ b/client/cmdlffdx.h @@ -17,7 +17,7 @@ #include "cmdlf.h" // lf read #include "crc16.h" // for checksum crc-16_ccitt #include "protocols.h" // for T55xx config register definitions -#include "lfdemod.h" // parityTest +#include "lfdemod.h" // parityTest extern int CmdLFFdx(const char *Cmd); extern int CmdFdxClone(const char *Cmd); diff --git a/client/cmdlfguard.c b/client/cmdlfguard.c index 5707c78fb..3e3642766 100644 --- a/client/cmdlfguard.c +++ b/client/cmdlfguard.c @@ -18,7 +18,7 @@ int usage_lf_guard_clone(void){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf gprox clone [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " : format length 26|32|36|40"); + PrintAndLogEx(NORMAL, " : format length 26|32|36|40"); PrintAndLogEx(NORMAL, " : 8-bit value facility code"); PrintAndLogEx(NORMAL, " : 16-bit value card number"); PrintAndLogEx(NORMAL, ""); @@ -35,7 +35,7 @@ int usage_lf_guard_sim(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf gprox sim [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " : format length 26|32|36|40"); + PrintAndLogEx(NORMAL, " : format length 26|32|36|40"); PrintAndLogEx(NORMAL, " : 8-bit value facility code"); PrintAndLogEx(NORMAL, " : 16-bit value card number"); PrintAndLogEx(NORMAL, ""); @@ -46,33 +46,33 @@ int usage_lf_guard_sim(void) { // Works for 26bits. int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) { - + uint8_t xorKey = 0x66; uint8_t i; uint8_t pre[96]; uint8_t rawbytes[12]; memset(pre, 0x00, sizeof(pre)); - memset(rawbytes, 0x00, sizeof(rawbytes)); + memset(rawbytes, 0x00, sizeof(rawbytes)); // add format length (decimal) switch (fmtlen) { case 32: { rawbytes[1] = (32 << 2); - + break; } case 36: { // FC = ((ByteStream[3] & 0x7F)<<7) | (ByteStream[4]>>1); // Card = ((ByteStream[4]&1)<<19) | (ByteStream[5]<<11) | (ByteStream[6]<<3) | (ByteStream[7]>>5); rawbytes[1] = (36 << 2); - // Get 26 wiegand from FacilityCode, CardNumber + // Get 26 wiegand from FacilityCode, CardNumber uint8_t wiegand[34]; memset(wiegand, 0x00, sizeof(wiegand)); num_to_bytebits(fc, 8, wiegand); num_to_bytebits(cn, 26, wiegand+8); // add wiegand parity bits (dest, source, len) - wiegand_add_parity(pre, wiegand, 34); + wiegand_add_parity(pre, wiegand, 34); break; } case 40: { @@ -82,7 +82,7 @@ int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) { case 26: default: { rawbytes[1] = (26 << 2); - // Get 26 wiegand from FacilityCode, CardNumber + // Get 26 wiegand from FacilityCode, CardNumber uint8_t wiegand[24]; memset(wiegand, 0x00, sizeof(wiegand)); num_to_bytebits(fc, 8, wiegand); @@ -93,27 +93,27 @@ int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) { break; } } - // 2bit checksum, unknown today, + // 2bit checksum, unknown today, // these two bits are the last ones of rawbyte[1], hence the LSHIFT above. - + // xor key rawbytes[0] = xorKey; - + rawbytes[2] = 1; rawbytes[3] = 0; - + // add wiegand to rawbytes for (i = 0; i < 4; ++i) rawbytes[i+4] = bytebits_to_byte( pre + (i*8), 8); - - PrintAndLogEx(DEBUG, " WIE | %s\n", sprint_hex(rawbytes, sizeof(rawbytes))); - - + + PrintAndLogEx(DEBUG, " WIE | %s\n", sprint_hex(rawbytes, sizeof(rawbytes))); + + // XOR (only works on wiegand stuff) for (i = 1; i < 12; ++i) rawbytes[i] ^= xorKey ; - + PrintAndLogEx(DEBUG, " XOR | %s \n", sprint_hex(rawbytes, sizeof(rawbytes))); // convert rawbytes to bits in pre @@ -122,7 +122,7 @@ int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) { PrintAndLogEx(DEBUG, "\n Raw | %s \n", sprint_hex(rawbytes, sizeof(rawbytes))); PrintAndLogEx(DEBUG, " Raw | %s\n", sprint_bin(pre, 64) ); - + // add spacer bit 0 every 4 bits, starting with index 0, // 12 bytes, 24 nibbles. 24+1 extra bites. 3bytes. ie 9bytes | 1byte xorkey, 8bytes rawdata (64bits, should be enough for a 40bit wiegand) addParity(pre, guardBits+6, 64, 5, 3); @@ -134,30 +134,30 @@ int GetGuardBits(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint8_t *guardBits) { guardBits[3] = 1; guardBits[4] = 1; guardBits[5] = 0; - + PrintAndLogEx(DEBUG, " FIN | %s\n", sprint_bin(guardBits, 96) ); return 1; } // by marshmellow -// demod gProxIIDemod -// error returns as -x +// demod gProxIIDemod +// error returns as -x // success returns start position in bitstream // Bitstream must contain previously askrawdemod and biphasedemoded data int detectGProxII(uint8_t *bits, size_t *size) { - + size_t startIdx = 0; uint8_t preamble[] = {1,1,1,1,1,0}; // sanity check if ( *size < sizeof(preamble) ) return -1; - - if (!preambleSearch(bits, preamble, sizeof(preamble), size, &startIdx)) + + if (!preambleSearch(bits, preamble, sizeof(preamble), size, &startIdx)) return -2; //preamble not found //gProxII should be 96 bits - if (*size != 96) return -3; - + if (*size != 96) return -3; + //check first 6 spacer bits to verify format if (!bits[startIdx+5] && !bits[startIdx+10] && !bits[startIdx+15] && !bits[startIdx+20] && !bits[startIdx+25] && !bits[startIdx+30]){ //confirmed proper separator bits found @@ -180,7 +180,7 @@ int CmdGuardDemod(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII ASKbiphaseDemod failed"); return 0; } - + size_t size = DemodBufferLen; int preambleIndex = detectGProxII(DemodBuffer, &size); @@ -194,11 +194,11 @@ int CmdGuardDemod(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII size not correct: %d", size); else if (preambleIndex == -5) PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII wrong spacerbits"); - else + else PrintAndLogEx(DEBUG, "DEBUG: Error - gProxII ans: %d", preambleIndex); return 0; } - + //got a good demod of 96 bits uint8_t ByteStream[8] = {0x00}; uint8_t xorKey = 0; @@ -221,8 +221,8 @@ int CmdGuardDemod(const char *Cmd) { } setDemodBuf(DemodBuffer, 96, preambleIndex); - setClockGrid(g_DemodClock, g_DemodStartIdx + (preambleIndex*g_DemodClock)); - + setClockGrid(g_DemodClock, g_DemodStartIdx + (preambleIndex*g_DemodClock)); + //ByteStream contains 8 Bytes (64 bits) of decrypted raw tag data uint8_t fmtLen = ByteStream[0] >> 2; uint32_t FC = 0; @@ -237,7 +237,7 @@ int CmdGuardDemod(const char *Cmd) { FC = ((ByteStream[3] & 0x7F)<<7) | (ByteStream[4]>>1); Card = ((ByteStream[4]&1)<<19) | (ByteStream[5]<<11) | (ByteStream[6]<<3) | (ByteStream[7]>>5); break; - case 26: + case 26: FC = ((ByteStream[3] & 0x7F)<<1) | (ByteStream[4]>>7); Card = ((ByteStream[4]&0x7F)<<9) | (ByteStream[5]<<1) | (ByteStream[6]>>7); break; @@ -267,20 +267,20 @@ int CmdGuardClone(const char *Cmd) { uint8_t i; uint8_t bs[96]; memset(bs, 0x00, sizeof(bs)); - + //GuardProxII - compat mode, ASK/Biphase, data rate 64, 3 data blocks uint32_t blocks[4] = {T55x7_MODULATION_BIPHASE | T55x7_BITRATE_RF_64 | 3 << T55x7_MAXBLOCK_SHIFT, 0, 0, 0}; - + if (sscanf(Cmd, "%u %u %u", &fmtlen, &fc, &cn ) != 3) return usage_lf_guard_clone(); fmtlen &= 0x7f; facilitycode = (fc & 0x000000FF); cardnumber = (cn & 0x0000FFFF); - + if ( !GetGuardBits(fmtlen, facilitycode, cardnumber, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } // Q5 if (param_getchar(Cmd, 3) == 'Q' || param_getchar(Cmd, 3) == 'q') @@ -321,17 +321,17 @@ int CmdGuardSim(const char *Cmd) { if (sscanf(Cmd, "%u %u %u", &fmtlen, &fc, &cn ) != 3) return usage_lf_guard_sim(); uint8_t bs[96]; - size_t size = sizeof(bs); + size_t size = sizeof(bs); memset(bs, 0x00, size); fmtlen &= 0x7F; facilitycode = (fc & 0x000000FF); cardnumber = (cn & 0x0000FFFF); - + if ( !GetGuardBits(fmtlen, facilitycode, cardnumber, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } PrintAndLogEx(SUCCESS, "Simulating Guardall - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber ); diff --git a/client/cmdlfhid.c b/client/cmdlfhid.c index 7d1bda95c..87cb8d160 100644 --- a/client/cmdlfhid.c +++ b/client/cmdlfhid.c @@ -23,12 +23,12 @@ int usage_lf_hid_read(void){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf hid read [h] [1]"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " 1 : (optional) stop after reading a single card"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf hid read"); - PrintAndLogEx(NORMAL, " lf hid read 1"); + PrintAndLogEx(NORMAL, " lf hid read 1"); return 0; } int usage_lf_hid_wiegand(void){ @@ -76,7 +76,7 @@ int usage_lf_hid_brute(void){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf hid brute [h] [v] a f c d "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " a : 26|33|34|35|37|40|44|84"); PrintAndLogEx(NORMAL, " f : 8-bit value HID facility code"); PrintAndLogEx(NORMAL, " c : (optional) cardnumber to start with, max 65535"); @@ -94,8 +94,8 @@ int usage_lf_hid_brute(void){ static bool sendPing(void){ UsbCommand ping = {CMD_PING, {1, 2, 3}}; SendCommand(&ping); - SendCommand(&ping); - SendCommand(&ping); + SendCommand(&ping); + SendCommand(&ping); clearCommandBuffer(); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)) @@ -107,12 +107,12 @@ static bool sendTry(uint8_t fmtlen, uint32_t fc, uint32_t cn, uint32_t delay, ui // this should be optional. if ( verbose ) PrintAndLogEx(INFO, "Trying FC: %u; CN: %u", fc, cn); - + calcWiegand( fmtlen, fc, cn, bits); uint64_t arg1 = bytebits_to_byte(bits, 32); uint64_t arg2 = bytebits_to_byte(bits + 32, 32); - UsbCommand c = {CMD_HID_SIM_TAG, {arg1, arg2, 0}}; + UsbCommand c = {CMD_HID_SIM_TAG, {arg1, arg2, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -157,12 +157,12 @@ int CmdHIDDemod(const char *Cmd) { setDemodBuf(bits, size, idx); setClockGrid(50, waveIdx + (idx*50)); - + if (hi2==0 && hi==0 && lo==0) { PrintAndLogEx(DEBUG, "DEBUG: Error - HID no values found"); return 0; } - + if (hi2 != 0){ //extra large HID tags PrintAndLogEx(SUCCESS, "HID Prox TAG ID: %x%08x%08x (%u)", hi2, hi, lo, (lo>>1) & 0xFFFF); } else { //standard HID tags <38 bits @@ -216,9 +216,9 @@ int CmdHIDDemod(const char *Cmd) { } PrintAndLogEx(DEBUG, "DEBUG: HID idx: %d, Len: %d, Printing Demod Buffer:", idx, size); - if (g_debugMode) + if (g_debugMode) printDemodBuff(); - + return 1; } @@ -231,7 +231,7 @@ int CmdHIDRead(const char *Cmd) { // this read loops on device side. // uses the demod in lfops.c int CmdHIDRead_device(const char *Cmd) { - + if (Cmd[0] == 'h' || Cmd[0] == 'H') return usage_lf_hid_read(); uint8_t findone = ( Cmd[0] == '1' ) ? 1 : 0; UsbCommand c = {CMD_HID_DEMOD_FSK, {findone, 0 , 0}}; @@ -246,7 +246,7 @@ int CmdHIDSim(const char *Cmd) { uint8_t ctmp = tolower(param_getchar(Cmd, 0)); if ( strlen(Cmd) == 0 || ctmp == 'h' ) return usage_lf_hid_sim(); - + while (sscanf(&Cmd[i++], "%1x", &n ) == 1) { hi = (hi << 4) | (lo >> 28); lo = (lo << 4) | (n & 0xf); @@ -262,7 +262,7 @@ int CmdHIDSim(const char *Cmd) { } int CmdHIDClone(const char *Cmd) { - + uint32_t hi2 = 0, hi = 0, lo = 0; uint32_t n = 0, i = 0; UsbCommand c = {CMD_HID_CLONE_TAG}; @@ -308,7 +308,7 @@ typedef struct { size_t Wiegand_n; } wiegand_t; -static void addHIDMarker(uint8_t fmtlen, uint8_t *out) { +static void addHIDMarker(uint8_t fmtlen, uint8_t *out) { // temp array uint8_t arr[BITS]; memset(arr, 0, BITS); @@ -316,7 +316,7 @@ static void addHIDMarker(uint8_t fmtlen, uint8_t *out) { // copy inpu uint8_t pos = sizeof(arr)-fmtlen; memcpy(arr+pos, out, fmtlen); - + switch(fmtlen) { case 26:{ // start sentinel, BITS-bit 27 = 1 @@ -329,7 +329,7 @@ static void addHIDMarker(uint8_t fmtlen, uint8_t *out) { case 34: // start sentinel, BITS-bit 27 = 1 arr[BITS-35] = 1; - + // fmt smaller than 37 used, bit37 = 1 arr[BITS-38] = 1; memcpy(out, arr, BITS); @@ -342,13 +342,13 @@ static void addHIDMarker(uint8_t fmtlen, uint8_t *out) { // uint32_t result = 0; // int i; - // // even parity + // // even parity // for (i = 7;i >= 0;i--) // result ^= (*hi >> i) & i; // for (i = 31;i >= 24;i--) // result ^= (*lo >> i) & 1; - // *hi |= result << 2; + // *hi |= result << 2; // // odd parity bit // result = 0; @@ -388,14 +388,14 @@ static void calc34(uint16_t fc, uint32_t cardno, uint8_t *out){ uint8_t wiegand[32]; num_to_bytebits(fc, 16, wiegand); num_to_bytebits(cardno, 16, wiegand + 16); - wiegand_add_parity(out, wiegand, sizeof(wiegand) ); + wiegand_add_parity(out, wiegand, sizeof(wiegand) ); } // static void calc35(uint16_t fc, uint32_t cardno, uint8_t *out){ - // *lo = ((cardno & 0xFFFFF) << 1) | fc << 21; - // *hi = (1 << 5) | ((fc >> 11) & 1); + // *lo = ((cardno & 0xFFFFF) << 1) | fc << 21; + // *hi = (1 << 5) | ((fc >> 11) & 1); // } static void calc37S(uint16_t fc, uint32_t cardno, uint8_t *out){ - // FC 2 - 17 - 16 bit + // FC 2 - 17 - 16 bit // cardno 18 - 36 - 19 bit // Even P1 1 - 19 // Odd P37 19 - 36 @@ -406,20 +406,20 @@ static void calc37S(uint16_t fc, uint32_t cardno, uint8_t *out){ } static void calc37H(uint64_t cardno, uint8_t *out){ // SC NONE - // cardno 1-35 34 bits + // cardno 1-35 34 bits // Even Parity 0th bit 1-18 // Odd Parity 36th bit 19-35 uint8_t wiegand[37]; num_to_bytebits( (uint32_t)(cardno >> 32), 2, wiegand); num_to_bytebits( (uint32_t)(cardno >> 0), 32, wiegand + 2); wiegand_add_parity(out, wiegand, sizeof(wiegand) ); - + PrintAndLogEx(NORMAL, "%x %x\n", (uint32_t)(cardno >> 32), (uint32_t)cardno ); } // static void calc40(uint64_t cardno, uint8_t *out){ // cardno = (cardno & 0xFFFFFFFFFF); - // *lo = ((cardno & 0xFFFFFFFF) << 1 ); - // *hi = (cardno >> 31); + // *lo = ((cardno & 0xFFFFFFFF) << 1 ); + // *hi = (cardno >> 31); // } void calcWiegand(uint8_t fmtlen, uint16_t fc, uint64_t cardno, uint8_t *bits){ @@ -436,17 +436,17 @@ void calcWiegand(uint8_t fmtlen, uint16_t fc, uint64_t cardno, uint8_t *bits){ // case 84 : { break; } default: break; } -} +} int CmdHIDWiegand(const char *Cmd) { uint32_t oem = 0, fc = 0; uint64_t cardnum = 0; - uint64_t blocks = 0, wiegand = 0; + uint64_t blocks = 0, wiegand = 0; uint8_t bits[BITS]; uint8_t *bs = bits; memset(bs, 0, sizeof(bits)); - + uint8_t ctmp = param_getchar(Cmd, 0); if ( strlen(Cmd) == 0 || strlen(Cmd) < 3 || ctmp == 'H' || ctmp == 'h' ) return usage_lf_hid_wiegand(); @@ -455,7 +455,7 @@ int CmdHIDWiegand(const char *Cmd) { cardnum = param_get64ex(Cmd, 2, 0, 10); uint8_t fmtlen[] = {26,33,34,35,37,38,40}; - + PrintAndLogEx(NORMAL, "HID | OEM | FC | CN | Wiegand | HID Formatted"); PrintAndLogEx(NORMAL, "----+-----+------+---------+-----------+--------------------"); for (uint8_t i = 0; i < sizeof(fmtlen); i++){ @@ -463,13 +463,13 @@ int CmdHIDWiegand(const char *Cmd) { calcWiegand( fmtlen[i], fc, cardnum, bs); PrintAndLogEx(NORMAL, "ice:: %s \n", sprint_bin(bs, fmtlen[i])); wiegand = (uint64_t)bytebits_to_byte(bs, 32) << 32 | bytebits_to_byte(bs+32, 32); - - addHIDMarker(fmtlen[i], bs); + + addHIDMarker(fmtlen[i], bs); PrintAndLogEx(NORMAL, "ice:: %s\n", sprint_bin(bs, BITS)); blocks = (uint64_t)bytebits_to_byte(bs+32, 32) << 32 | bytebits_to_byte(bs+64, 32); - uint8_t shifts = 64-fmtlen[i]; + uint8_t shifts = 64-fmtlen[i]; wiegand >>= shifts; - + PrintAndLogEx(NORMAL, " %u | %03u | %03u | %" PRIu64 " | %" PRIX64 " | %" PRIX64 , fmtlen[i], oem, @@ -484,14 +484,14 @@ int CmdHIDWiegand(const char *Cmd) { } int CmdHIDBrute(const char *Cmd){ - + bool errors = false, verbose = false; uint32_t fc = 0, cn = 0, delay = 1000; uint8_t fmtlen = 0; uint8_t bits[96]; memset(bits, 0, sizeof(bits)); uint8_t cmdp = 0; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -503,7 +503,7 @@ int CmdHIDBrute(const char *Cmd){ cmdp += 2; break; case 'd': - // delay between attemps, defaults to 1000ms. + // delay between attemps, defaults to 1000ms. delay = param_get32ex(Cmd, cmdp+1, 1000, 10); cmdp += 2; break; @@ -526,7 +526,7 @@ int CmdHIDBrute(const char *Cmd){ // negated errors = !is_ftm_ok; break; - case 'v': + case 'v': verbose = true; cmdp++; break; @@ -538,31 +538,31 @@ int CmdHIDBrute(const char *Cmd){ } if ( fc == 0 ) errors = true; if ( errors ) return usage_lf_hid_brute(); - + PrintAndLogEx(INFO, "Brute-forcing HID reader"); PrintAndLogEx(INFO, "Press pm3-button to abort simulation or run another command"); - + uint16_t up = cn; uint16_t down = cn; - + // main loop for (;;){ - + if ( IsOffline() ) { PrintAndLogEx(WARNING, "Device offline\n"); return 2; } - + if (ukbhit()) { int gc = getchar(); (void)gc; PrintAndLogEx(INFO, "aborted via keyboard!"); return sendPing(); } - + // Do one up if ( up < 0xFFFF ) if ( !sendTry(fmtlen, fc, up++, delay, bits, verbose)) return 1; - + // Do one down (if cardnumber is given) if ( cn > 1 ) if ( down > 1 ) diff --git a/client/cmdlfhid.h b/client/cmdlfhid.h index c34a48406..895117960 100644 --- a/client/cmdlfhid.h +++ b/client/cmdlfhid.h @@ -20,7 +20,7 @@ #include "util.h" // wiegand_add_parity etc #include "cmddata.h" //for g_debugMode, demodbuff cmds #include "cmdlf.h" // lf_read -#include "cmdmain.h" +#include "cmdmain.h" #include "util_posix.h" #include "lfdemod.h" diff --git a/client/cmdlfhitag.c b/client/cmdlfhitag.c index 69bae1b38..45aeea317 100644 --- a/client/cmdlfhitag.c +++ b/client/cmdlfhitag.c @@ -43,7 +43,7 @@ int CmdLFHitagList(const char *Cmd) { free(got); return 2; } - + uint16_t traceLen = response.arg[2]; if (traceLen > USB_CMD_DATA_SIZE) { uint8_t *p = realloc(got, traceLen); @@ -59,7 +59,7 @@ int CmdLFHitagList(const char *Cmd) { return 2; } } - + PrintAndLogEx(NORMAL, "recorded activity (TraceLen = %d bytes):"); PrintAndLogEx(NORMAL, " ETU :nbits: who bytes"); PrintAndLogEx(NORMAL, "---------+-----+----+-----------"); @@ -70,11 +70,11 @@ int CmdLFHitagList(const char *Cmd) { char filename[FILE_PATH_SIZE] = { 0x00 }; FILE* f = NULL; - + if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; - + memcpy(filename, Cmd, len); - + if (strlen(filename) > 0) { f = fopen(filename,"wb"); if (!f) { @@ -84,7 +84,7 @@ int CmdLFHitagList(const char *Cmd) { } for (;;) { - + if(i >= traceLen) { break; } bool isResponse; @@ -143,11 +143,11 @@ int CmdLFHitagList(const char *Cmd) { (isResponse ? "TAG" : " "), line); } - + prev = timestamp; i += (len + 9); } - + if (f) { fclose(f); PrintAndLogEx(NORMAL, "Recorded activity succesfully written to file: %s", filename); @@ -165,12 +165,12 @@ int CmdLFHitagSnoop(const char *Cmd) { } int CmdLFHitagSim(const char *Cmd) { - + UsbCommand c = {CMD_SIMULATE_HITAG}; char filename[FILE_PATH_SIZE] = { 0x00 }; FILE* f; bool tag_mem_supplied; - + int len = strlen(Cmd); if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, Cmd, len); @@ -201,11 +201,11 @@ int CmdLFHitagSim(const char *Cmd) { } int CmdLFHitagReader(const char *Cmd) { - + UsbCommand c = {CMD_READER_HITAG, {0,0,0} };//, {param_get32ex(Cmd,0,0,10),param_get32ex(Cmd,1,0,16),param_get32ex(Cmd,2,0,16),param_get32ex(Cmd,3,0,16)}}; hitag_data* htd = (hitag_data*)c.d.asBytes; hitag_function htf = param_get32ex(Cmd, 0, 0, 10); - + switch (htf) { case 01: { //RHTSF_CHALLENGE c.cmd = CMD_READ_HITAG_S; @@ -255,7 +255,7 @@ int CmdLFHitagReader(const char *Cmd) { c.arg[0] = htf; clearCommandBuffer(); SendCommand(&c); - UsbCommand resp; + UsbCommand resp; if ( !WaitForResponseTimeout(CMD_ACK, &resp, 4000) ) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return 1; @@ -333,7 +333,7 @@ int CmdLFHitagCheckChallenges(const char *Cmd) { if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, Cmd, len); - + if (strlen(filename) > 0) { f = fopen(filename,"rb+"); if ( !f ) { @@ -351,7 +351,7 @@ int CmdLFHitagCheckChallenges(const char *Cmd) { } else { file_given = false; } - + //file with all the challenges to try c.arg[0] = (uint32_t)file_given; clearCommandBuffer(); @@ -406,7 +406,7 @@ static command_t CommandTable[] = { {"list", CmdLFHitagList, 1, " List Hitag trace history"}, {"reader", CmdLFHitagReader, 1, "Act like a Hitag Reader"}, {"sim", CmdLFHitagSim, 1, " Simulate Hitag transponder"}, - {"simS", CmdLFHitagSimS, 1, " Simulate HitagS transponder" }, + {"simS", CmdLFHitagSimS, 1, " Simulate HitagS transponder" }, {"snoop", CmdLFHitagSnoop, 1, "Eavesdrop Hitag communication"}, {"writer", CmdLFHitagWP, 1, "Act like a Hitag Writer" }, {"check_challenges", CmdLFHitagCheckChallenges, 1, " test all challenges" }, diff --git a/client/cmdlfindala.c b/client/cmdlfindala.c index 1707895b0..17e3455d9 100644 --- a/client/cmdlfindala.c +++ b/client/cmdlfindala.c @@ -31,7 +31,7 @@ int usage_lf_indala_sim(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf indala sim [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " : 64/224 UID"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); @@ -45,7 +45,7 @@ int usage_lf_indala_clone(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf indala clone [h] [Q5]"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " : 64/224 UID"); PrintAndLogEx(NORMAL, " Q5 : optional - clone to Q5 (T5555) instead of T55x7 chip"); PrintAndLogEx(NORMAL, ""); @@ -70,10 +70,10 @@ int indala64decode(uint8_t *dest, size_t *size, uint8_t *invert) { if (found_size != 64) return -2; if (*invert == 1) - for (size_t i = idx; i < found_size + idx; i++) + for (size_t i = idx; i < found_size + idx; i++) dest[i] ^= 1; - // note: don't change *size until we are sure we got it... + // note: don't change *size until we are sure we got it... *size = found_size; return (int) idx; } @@ -90,9 +90,9 @@ int indala224decode(uint8_t *dest, size_t *size, uint8_t *invert) { *invert ^= 1; } if (found_size != 224) return -2; - + if (*invert==1 && idx > 0) - for (size_t i = idx-1; i < found_size + idx + 2; i++) + for (size_t i = idx-1; i < found_size + idx + 2; i++) dest[i] ^= 1; // 224 formats are typically PSK2 (afaik 2017 Marshmellow) @@ -139,14 +139,14 @@ int CmdIndalaDemod(const char *Cmd) { return 0; } } - + setDemodBuf(DemodBuffer, size, (size_t)idx); setClockGrid(g_DemodClock, g_DemodStartIdx + (idx * g_DemodClock)); if (invert) { - PrintAndLogEx(DEBUG, "DEBUG: Error - Indala had to invert bits"); - for (size_t i = 0; i < size; i++) + PrintAndLogEx(DEBUG, "DEBUG: Error - Indala had to invert bits"); + for (size_t i = 0; i < size; i++) DemodBuffer[i] ^= 1; - } + } //convert UID to HEX uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7; @@ -162,7 +162,7 @@ int CmdIndalaDemod(const char *Cmd) { uid5 = bytebits_to_byte(DemodBuffer+128,32); uid6 = bytebits_to_byte(DemodBuffer+160,32); uid7 = bytebits_to_byte(DemodBuffer+192,32); - PrintAndLogEx(SUCCESS, "Indala Found - bitlength %d, UID = (0x%x%08x%08x%08x%08x%08x%08x)\n%s", + PrintAndLogEx(SUCCESS, "Indala Found - bitlength %d, UID = (0x%x%08x%08x%08x%08x%08x%08x)\n%s", DemodBufferLen, uid1, uid2, uid3, uid4, uid5, uid6, uid7, sprint_bin_break(DemodBuffer, DemodBufferLen, 32) ); @@ -188,7 +188,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { // under normal conditions it's < 2048 uint8_t data[MAX_GRAPH_TRACE_LEN] = {0}; size_t datasize = getFromGraphBuf(data); - + uint8_t rawbits[4096]; int rawbit = 0; int worst = 0, worstPos = 0; @@ -196,7 +196,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { //clear clock grid and demod plot setClockGrid(0, 0); DemodBufferLen = 0; - + // PrintAndLogEx(NORMAL, "Expecting a bit less than %d raw bits", GraphTraceLen / 32); // loop through raw signal - since we know it is psk1 rf/32 fc/2 skip every other value (+=2) for (i = 0; i < datasize-1; i += 2) { @@ -229,7 +229,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { count = 0; } } - + if (rawbit > 0){ PrintAndLogEx(INFO, "Recovered %d raw bits, expected: %d", rawbit, GraphTraceLen/32); PrintAndLogEx(INFO, "worst metric (0=best..7=worst): %d at pos %d", worst, worstPos); @@ -260,7 +260,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { break; } } - + if (start == rawbit - uidlen + 1) { PrintAndLogEx(FAILED, "nothing to wait for"); return 0; @@ -279,7 +279,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { int bit; i = start; int times = 0; - + if (uidlen > rawbit) { PrintAndLogEx(WARNING, "Warning: not enough raw bits to get a full UID"); for (bit = 0; bit < rawbit; bit++) { @@ -297,12 +297,12 @@ int CmdIndalaDemodAlt(const char *Cmd) { } times = 1; } - + //convert UID to HEX uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7; int idx; uid1 = uid2 = 0; - + if (uidlen == 64){ for( idx=0; idx < 64; idx++) { if (showbits[idx] == '0') { @@ -311,7 +311,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { } else { uid1 = (uid1<<1) | (uid2>>31); uid2 = (uid2<<1) | 1; - } + } } PrintAndLogEx(SUCCESS, "UID | %s (%x%08x)", showbits, uid1, uid2); } @@ -325,10 +325,10 @@ int CmdIndalaDemodAlt(const char *Cmd) { uid4 = (uid4<<1) | (uid5>>31); uid5 = (uid5<<1) | (uid6>>31); uid6 = (uid6<<1) | (uid7>>31); - - if (showbits[idx] == '0') + + if (showbits[idx] == '0') uid7 = (uid7<<1) | 0; - else + else uid7 = (uid7<<1) | 1; } PrintAndLogEx(SUCCESS, "UID | %s (%x%08x%08x%08x%08x%08x%08x)", showbits, uid1, uid2, uid3, uid4, uid5, uid6, uid7); @@ -353,7 +353,7 @@ int CmdIndalaDemodAlt(const char *Cmd) { PrintAndLogEx(DEBUG, "Occurrences: %d (expected %d)", times, (rawbit - start) / uidlen); // Remodulating for tag cloning - // HACK: 2015-01-04 this will have an impact on our new way of seening lf commands (demod) + // HACK: 2015-01-04 this will have an impact on our new way of seening lf commands (demod) // since this changes graphbuffer data. GraphTraceLen = 32 * uidlen; i = 0; @@ -388,9 +388,9 @@ int CmdIndalaSim(const char *Cmd) { uint8_t hexuid[100]; int len = 0; param_gethex_ex(Cmd, 0, hexuid, &len); - if ( len > 28 ) + if ( len > 28 ) return usage_lf_indala_sim(); - + // convert to binarray uint8_t counter = 223; for (uint8_t i = 0; i < len; i++) { @@ -399,27 +399,27 @@ int CmdIndalaSim(const char *Cmd) { hexuid[i] >>= 1; } } - - // indala PSK + + // indala PSK uint8_t clk = 32, carrier = 2, invert = 0; uint16_t arg1, arg2; arg1 = clk << 8 | carrier; arg2 = invert; - + // It has to send either 64bits (8bytes) or 224bits (28bytes). Zero padding needed if not. // lf simpsk 1 c 32 r 2 d 0102030405060708 - + PrintAndLogEx(SUCCESS, "Simulating Indala UID: %s", sprint_hex(hexuid, len)); PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or run another command"); - - UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}}; + + UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bits, size); clearCommandBuffer(); SendCommand(&c); return 0; } -// iceman - needs refactoring +// iceman - needs refactoring int CmdIndalaClone(const char *Cmd) { UsbCommand c = {0}; uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7; @@ -427,7 +427,7 @@ int CmdIndalaClone(const char *Cmd) { uint32_t n = 0, i = 0; if (strchr(Cmd,'l') != 0) { - + while (sscanf(&Cmd[i++], "%1x", &n ) == 1) { uid1 = (uid1 << 4) | (uid2 >> 28); uid2 = (uid2 << 4) | (uid3 >> 28); @@ -437,7 +437,7 @@ int CmdIndalaClone(const char *Cmd) { uid6 = (uid6 << 4) | (uid7 >> 28); uid7 = (uid7 << 4) | (n & 0xf); } - + PrintAndLogEx(INFO, "Preparing to clone Indala 224bit tag with UID %x%08x%08x%08x%08x%08x%08x", uid1, uid2, uid3, uid4, uid5, uid6, uid7); c.cmd = CMD_INDALA_CLONE_TAG_L; c.d.asDwords[0] = uid1; @@ -476,7 +476,7 @@ static command_t CommandTable[] = { int CmdLFINDALA(const char *Cmd){ clearCommandBuffer(); CmdsParse(CommandTable, Cmd); - return 0; + return 0; } int CmdHelp(const char *Cmd) { diff --git a/client/cmdlfio.c b/client/cmdlfio.c index 61fe9d00d..53ad90ec7 100644 --- a/client/cmdlfio.c +++ b/client/cmdlfio.c @@ -34,7 +34,7 @@ int usage_lf_io_sim(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf io sim [h] "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " : 8bit version"); PrintAndLogEx(NORMAL, " : 8bit value facility code"); PrintAndLogEx(NORMAL, " : 16bit value card number"); @@ -50,7 +50,7 @@ int usage_lf_io_clone(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf io clone [h] [Q5]"); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : This help"); + PrintAndLogEx(NORMAL, " h : This help"); PrintAndLogEx(NORMAL, " : 8bit version"); PrintAndLogEx(NORMAL, " : 8bit value facility code"); PrintAndLogEx(NORMAL, " : 16bit value card number"); @@ -88,18 +88,18 @@ int CmdIOProxDemod(const char *Cmd) { if (size < 65) { PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples in GraphBuffer"); return 0; - } - //get binary from fsk wave + } + //get binary from fsk wave int waveIdx = 0; idx = detectIOProx(bits, &size, &waveIdx); if (idx < 0) { if (g_debugMode) { if (idx == -1) { - PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples"); + PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox not enough samples"); } else if (idx == -2) { PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox just noise detected"); } else if (idx == -3) { - PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox error during fskdemod"); + PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox error during fskdemod"); } else if (idx == -4) { PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox preamble not found"); } else if (idx == -5) { @@ -114,15 +114,15 @@ int CmdIOProxDemod(const char *Cmd) { } setDemodBuf(bits, size, idx); setClockGrid(64, waveIdx + (idx*64)); - + if (idx == 0) { if (g_debugMode) { PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox data not found - FSK Bits: %d", size); if (size > 92) PrintAndLogEx(DEBUG, "%s", sprint_bin_break(bits, 92, 16)); - } + } return retval; } - + //Index map //0 10 20 30 40 50 60 //| | | | | | | @@ -131,7 +131,7 @@ int CmdIOProxDemod(const char *Cmd) { //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11 // //XSF(version)facility:codeone+codetwo (raw) - + PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d", bits[idx], bits[idx+1], bits[idx+2], bits[idx+3], bits[idx+4], bits[idx+5], bits[idx+6], bits[idx+7], bits[idx+8]); PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d", bits[idx+9], bits[idx+10], bits[idx+11],bits[idx+12],bits[idx+13],bits[idx+14],bits[idx+15],bits[idx+16],bits[idx+17]); PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d facility", bits[idx+18], bits[idx+19], bits[idx+20],bits[idx+21],bits[idx+22],bits[idx+23],bits[idx+24],bits[idx+25],bits[idx+26]); @@ -139,7 +139,7 @@ int CmdIOProxDemod(const char *Cmd) { PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d code1", bits[idx+36], bits[idx+37], bits[idx+38],bits[idx+39],bits[idx+40],bits[idx+41],bits[idx+42],bits[idx+43],bits[idx+44]); PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d code2", bits[idx+45], bits[idx+46], bits[idx+47],bits[idx+48],bits[idx+49],bits[idx+50],bits[idx+51],bits[idx+52],bits[idx+53]); PrintAndLogEx(DEBUG, "%d%d%d%d%d%d%d%d %d%d checksum", bits[idx+54],bits[idx+55],bits[idx+56],bits[idx+57],bits[idx+58],bits[idx+59],bits[idx+60],bits[idx+61],bits[idx+62],bits[idx+63]); - + uint32_t code = bytebits_to_byte(bits+idx,32); uint32_t code2 = bytebits_to_byte(bits+idx+32,32); uint8_t version = bytebits_to_byte(bits+idx+27,8); //14,4 @@ -156,13 +156,13 @@ int CmdIOProxDemod(const char *Cmd) { char crcStr[30]; memset(crcStr, 0x00, sizeof(crcStr) ); - + if (crc == calccrc) { snprintf(crcStr, 3, "ok"); retval = 1; } else { PrintAndLogEx(DEBUG, "DEBUG: Error - IO prox crc failed"); - + snprintf(crcStr, sizeof(crcStr), "failed 0x%02X != 0x%02X", crc, calccrc); retval = 0; } @@ -172,7 +172,7 @@ int CmdIOProxDemod(const char *Cmd) { if (g_debugMode){ PrintAndLogEx(DEBUG, "DEBUG: IO prox idx: %d, Len: %d, Printing demod buffer:", idx, size); printDemodBuff(); - } + } return retval; } @@ -184,7 +184,7 @@ int CmdIOProxDemod(const char *Cmd) { //00000000 0 11110000 1 facility 1 version* 1 code*one 1 code*two 1 ???????? 11 //XSF(version)facility:codeone+codetwo (raw) int getIOProxBits(uint8_t version, uint8_t fc, uint16_t cn, uint8_t *bits) { - #define SEPARATOR 1 + #define SEPARATOR 1 uint8_t pos=0; // the return bits, preamble 0000 0000 0 uint8_t pre[64]; @@ -192,31 +192,31 @@ int getIOProxBits(uint8_t version, uint8_t fc, uint16_t cn, uint8_t *bits) { // skip 9 zeros as preamble pos = 9; - + // another fixed byte 11110000 = 0xF0 num_to_bytebits(0xF0, 8, pre+pos); pos += 8; pre[pos] = SEPARATOR; - pos++; - + pos++; + // add facilitycode num_to_bytebits(fc, 8, pre+pos); pos += 8; pre[pos] = SEPARATOR; pos++; - + // add version num_to_bytebits(version, 8, pre+pos); pos += 8; pre[pos] = SEPARATOR; pos++; - + // cardnumber high byte num_to_bytebits( ((cn & 0xFF00)>>8), 8, pre+pos); pos += 8; pre[pos] = SEPARATOR; pos++; - + // cardnumber low byte num_to_bytebits( (cn & 0xFF), 8, pre+pos); pos += 8; @@ -227,18 +227,18 @@ int getIOProxBits(uint8_t version, uint8_t fc, uint16_t cn, uint8_t *bits) { uint16_t crc = 0; for (uint8_t i=1; i<6; ++i) crc += bytebits_to_byte(pre+9*i, 8); - + crc &= 0xFF; crc = 0xff - crc; num_to_bytebits(crc, 8, pre+pos); pos += 8; - + // Final two ONES pre[pos] = SEPARATOR; pre[++pos] = SEPARATOR; memcpy(bits, pre, sizeof(pre)); - + PrintAndLogEx(SUCCESS, "IO raw bits:\n %s \n", sprint_bin(bits, 64)); return 1; } @@ -249,30 +249,30 @@ int CmdIOProxSim(const char *Cmd) { uint8_t bits[64]; size_t size = sizeof(bits); memset(bits, 0x00, size); - + char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_io_sim(); - + version = param_get8(Cmd, 0); fc = param_get8(Cmd, 1); cn = param_get32ex(Cmd, 2, 0, 10); if ( !version | !fc || !cn) return usage_lf_io_sim(); - + if ((cn & 0xFFFF) != cn) { cn &= 0xFFFF; PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (IOProx): %u", cn); } - + // clock 64, FSK2a fcHIGH 10 | fcLOW 8 uint8_t clk = 64, invert = 1, high = 10, low = 8; - uint16_t arg1, arg2; + uint16_t arg1, arg2; arg1 = high << 8 | low; arg2 = invert << 8 | clk; PrintAndLogEx(SUCCESS, "Simulating IOProx version: %u FC: %u; CN: %u\n", version, fc, cn); PrintAndLogEx(SUCCESS, "Press pm3-button to abort simulation or run another command"); - + if ( !getIOProxBits(version, fc, cn, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; @@ -281,7 +281,7 @@ int CmdIOProxSim(const char *Cmd) { // arg1 --- fcHigh<<8 + fcLow // arg2 --- Invert and clk setting // size --- 64 bits == 8 bytes - UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; + UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bits, size); clearCommandBuffer(); SendCommand(&c); @@ -289,13 +289,13 @@ int CmdIOProxSim(const char *Cmd) { } int CmdIOProxClone(const char *Cmd) { - + uint32_t blocks[3] = {T55x7_MODULATION_FSK2a | T55x7_BITRATE_RF_64 | 2 << T55x7_MAXBLOCK_SHIFT, 0, 0}; uint16_t cn = 0; uint8_t version = 0, fc = 0; uint8_t bits[64]; memset(bits,0,sizeof(bits)); - + char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_io_clone(); @@ -304,17 +304,17 @@ int CmdIOProxClone(const char *Cmd) { cn = param_get32ex(Cmd, 2, 0, 10); if ( !version | !fc || !cn) return usage_lf_io_clone(); - + if ((cn & 0xFFFF) != cn) { cn &= 0xFFFF; PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (IOProx): %u", cn); } - + if ( !getIOProxBits(version, fc, cn, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; } - + if (param_getchar(Cmd, 3) == 'Q' || param_getchar(Cmd, 3) == 'q') blocks[0] = T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | T5555_SET_BITRATE(64) | 2 << T5555_MAXBLOCK_SHIFT; @@ -323,7 +323,7 @@ int CmdIOProxClone(const char *Cmd) { PrintAndLogEx(INFO, "Preparing to clone IOProx to T55x7 with Version: %u FC: %u, CN: %u", version, fc, cn); print_blocks(blocks, 3); - + //UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}}; UsbCommand c = {CMD_IO_CLONE_TAG, {blocks[1],blocks[2],0}}; clearCommandBuffer(); @@ -343,7 +343,7 @@ static command_t CommandTable[] = { int CmdLFIO(const char *Cmd){ clearCommandBuffer(); CmdsParse(CommandTable, Cmd); - return 0; + return 0; } int CmdHelp(const char *Cmd) { diff --git a/client/cmdlfjablotron.c b/client/cmdlfjablotron.c index 541e7b31b..339752202 100644 --- a/client/cmdlfjablotron.c +++ b/client/cmdlfjablotron.c @@ -44,11 +44,11 @@ static uint8_t jablontron_chksum(uint8_t *bits){ for (int i=16; i < 56; i += 8) { chksum += bytebits_to_byte(bits+i,8); } - chksum ^= 0x3A; + chksum ^= 0x3A; return chksum; } -int getJablotronBits(uint64_t fullcode, uint8_t *bits) { +int getJablotronBits(uint64_t fullcode, uint8_t *bits) { //preamp num_to_bytebits(0xFFFF, 16, bits); @@ -72,7 +72,7 @@ int detectJablotron(uint8_t *bits, size_t *size) { if (preambleSearch(bits, preamble, sizeof(preamble), size, &startIdx) == 0) return -2; //preamble not found if (*size != 64) return -3; // wrong demoded size - + uint8_t checkchksum = jablontron_chksum(bits+startIdx); uint8_t crc = bytebits_to_byte(bits+startIdx+56, 8); if ( checkchksum != crc ) return -5; @@ -119,7 +119,7 @@ int CmdJablotronDemod(const char *Cmd) { setDemodBuf(DemodBuffer, 64, ans); setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); - + //got a good demod uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); @@ -136,7 +136,7 @@ int CmdJablotronDemod(const char *Cmd) { ); id = DEC2BCD(id); - // Printed format: 1410-nn-nnnn-nnnn + // Printed format: 1410-nn-nnnn-nnnn PrintAndLogEx(SUCCESS, "Printed: 1410-%02X-%04X-%04X", (uint8_t)(id >> 32) & 0xFF, (uint16_t)(id >> 16) & 0xFFFF, @@ -157,33 +157,33 @@ int CmdJablotronClone(const char *Cmd) { uint8_t bits[64]; memset(bits, 0, sizeof(bits)); - + char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_jablotron_clone(); fullcode = param_get64ex(Cmd, 0, 0, 16); - + //Q5 if (param_getchar(Cmd, 1) == 'Q' || param_getchar(Cmd, 1) == 'q') blocks[0] = T5555_MODULATION_BIPHASE | T5555_INVERT_OUTPUT | T5555_SET_BITRATE(64) | 2 << T5555_MAXBLOCK_SHIFT; - - // clearing the topbit needed for the preambl detection. + + // clearing the topbit needed for the preambl detection. if ((fullcode & 0x7FFFFFFFFF) != fullcode) { fullcode &= 0x7FFFFFFFFF; PrintAndLogEx(INFO, "Card Number Truncated to 39bits: %"PRIx64, fullcode); } - + if ( !getJablotronBits(fullcode, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } - + } + blocks[1] = bytebits_to_byte(bits, 32); blocks[2] = bytebits_to_byte(bits + 32, 32); PrintAndLogEx(INFO, "Preparing to clone Jablotron to T55x7 with FullCode: %"PRIx64, fullcode); print_blocks(blocks, 3); - + UsbCommand resp; UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}}; @@ -208,12 +208,12 @@ int CmdJablotronSim(const char *Cmd) { fullcode = param_get64ex(Cmd, 0, 0, 16); - // clearing the topbit needed for the preambl detection. + // clearing the topbit needed for the preambl detection. if ((fullcode & 0x7FFFFFFFFF) != fullcode) { fullcode &= 0x7FFFFFFFFF; PrintAndLogEx(INFO, "Card Number Truncated to 39bits: %"PRIx64, fullcode); } - + uint8_t clk = 64, encoding = 2, separator = 0, invert = 1; uint16_t arg1, arg2; size_t size = 64; diff --git a/client/cmdlfkeri.c b/client/cmdlfkeri.c index 560cd5c96..79fc9e6f1 100644 --- a/client/cmdlfkeri.c +++ b/client/cmdlfkeri.c @@ -5,7 +5,7 @@ // the license. //----------------------------------------------------------------------------- // Low frequency KERI tag commands -// PSK1, RF/128, RF/2, 64 bits long +// PSK1, RF/128, RF/2, 64 bits long //----------------------------------------------------------------------------- #include "cmdlfkeri.h" @@ -40,24 +40,24 @@ int usage_lf_keri_sim(void) { // find KERI preamble in already demoded data int detectKeri(uint8_t *dest, size_t *size, bool *invert) { - + uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1}; uint8_t preamble_i[] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0}; - // sanity check. + // sanity check. if ( *size < sizeof(preamble) + 100) return -1; size_t startIdx = 0; - + if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) { - + // if didn't find preamble try again inverting - if (!preambleSearch(DemodBuffer, preamble_i, sizeof(preamble_i), size, &startIdx)) + if (!preambleSearch(DemodBuffer, preamble_i, sizeof(preamble_i), size, &startIdx)) return -2; - + *invert ^= 1; } - + if (*size != 64) return -3; //wrong demoded size return (int)startIdx; @@ -69,7 +69,7 @@ int CmdKeriDemod(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - KERI: PSK1 Demod failed"); return 0; } - bool invert = false; + bool invert = false; size_t size = DemodBufferLen; int idx = detectKeri(DemodBuffer, &size, &invert); if (idx < 0) { @@ -90,35 +90,35 @@ int CmdKeriDemod(const char *Cmd) { //got a good demod uint32_t raw1 = bytebits_to_byte(DemodBuffer , 32); uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); - + //get internal id - uint32_t ID = bytebits_to_byte(DemodBuffer+29, 32); + uint32_t ID = bytebits_to_byte(DemodBuffer+29, 32); ID &= 0x7FFFFFFF; - + /* 000000000000000000000000000001XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX111 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^1###############################^^^ Preamble block 29 bits of ZEROS - 32 bit Internal ID (First bit always 1) + 32 bit Internal ID (First bit always 1) 3 bit of 1s in the end - + How this is decoded to Facility ID, Card number is unknown Facility ID = 0-31 (indicates 5 bits) Card number = up to 10 digits - + Might be a hash of FC & CN to generate Internal ID */ - + PrintAndLogEx(SUCCESS, "KERI Tag Found -- Internal ID: %u", ID); PrintAndLogEx(SUCCESS, "Raw: %08X%08X", raw1 ,raw2); - + if (invert){ PrintAndLogEx(INFO, "Had to Invert - probably KERI"); for (size_t i = 0; i < size; i++) DemodBuffer[i] ^= 1; - + CmdPrintDemodBuff("x"); - } + } return 1; } @@ -132,38 +132,38 @@ int CmdKeriClone(const char *Cmd) { uint32_t internalid = 0; uint32_t blocks[3] = { T55x7_TESTMODE_DISABLED | - T55x7_X_MODE | - T55x7_MODULATION_PSK1 | - T55x7_PSKCF_RF_2 | + T55x7_X_MODE | + T55x7_MODULATION_PSK1 | + T55x7_PSKCF_RF_2 | 2 << T55x7_MAXBLOCK_SHIFT, 0, 0}; - + // dynamic bitrate used blocks[0] |= 0xF << 18; - + char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_keri_clone(); internalid = param_get32ex(Cmd, 0, 0, 10); - + //Q5 if (tolower(param_getchar(Cmd, 1)) == 'q') { - blocks[0] = - T5555_MODULATION_PSK1 | - T5555_SET_BITRATE(128) | - T5555_PSK_RF_2 | + blocks[0] = + T5555_MODULATION_PSK1 | + T5555_SET_BITRATE(128) | + T5555_PSK_RF_2 | 2 << T5555_MAXBLOCK_SHIFT; } - - + + // MSB is ONE internalid |= 0x80000000; // 3 LSB is ONE uint64_t data = ((uint64_t)internalid << 3 ) + 7; - - // + + // blocks[1] = data >> 32; blocks[2] = data & 0xFFFFFFFF; @@ -199,21 +199,21 @@ int CmdKeriSim(const char *Cmd) { internalid <<= 3; internalid += 7; - uint8_t bits[64] = {0x00}; + uint8_t bits[64] = {0x00}; // loop to bits uint8_t j = 0; for ( int8_t i = 63; i >= 0; --i) { bits[j++] = ((internalid >> i) & 1 ); } - + uint8_t clk = 32, carrier = 2, invert = 0; uint16_t arg1, arg2; size_t size = 64; arg1 = clk << 8 | carrier; arg2 = invert; - + PrintAndLogEx(SUCCESS, "Simulating KERI - Internal Id: %u", internalid); - + UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bits, size); clearCommandBuffer(); @@ -227,7 +227,7 @@ static command_t CommandTable[] = { {"demod", CmdKeriDemod, 1, "Demodulate an KERI tag from the GraphBuffer"}, {"read", CmdKeriRead, 0, "Attempt to read and extract tag data from the antenna"}, {"clone", CmdKeriClone, 0, "clone KERI to T55x7"}, - {"sim", CmdKeriSim, 0, "simulate KERI tag"}, + {"sim", CmdKeriSim, 0, "simulate KERI tag"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdlfnedap.c b/client/cmdlfnedap.c index 25f9b624b..353ff535d 100644 --- a/client/cmdlfnedap.c +++ b/client/cmdlfnedap.c @@ -61,10 +61,10 @@ int GetNedapBits(uint32_t cn, uint8_t *nedapBits) { // fixed tagtype code? 0010 1101 = 0x2D num_to_bytebits(0x2D, 8, pre+10); - + // 46 encrypted bits - UNKNOWN ALGO // -- 16 bits checksum. Should be 4x4 checksum, based on UID and 2 constant values. - // -- 30 bits undocumented? + // -- 30 bits undocumented? //num_to_bytebits(cn, 46, pre+18); //----from this part, the UID in clear text, with a 1bit ZERO as separator between bytes. @@ -75,7 +75,7 @@ int GetNedapBits(uint32_t cn, uint8_t *nedapBits) { pre[100] = 0; pre[109] = 0; pre[118] = 0; - + // cardnumber (uid) num_to_bytebits( (cn >> 0) & 0xFF, 8, pre+65); num_to_bytebits( (cn >> 8) & 0xFF, 8, pre+74); @@ -84,19 +84,19 @@ int GetNedapBits(uint32_t cn, uint8_t *nedapBits) { // two ? num_to_bytebits( 0, 8, pre+92); num_to_bytebits( 0, 8, pre+101); - - // chksum - num_to_bytebits( (0 >> 0) & 0xFF, 8, pre+110); - num_to_bytebits( (0 >> 8) & 0xFF, 8, pre+119); - + // chksum + num_to_bytebits( (0 >> 0) & 0xFF, 8, pre+110); + num_to_bytebits( (0 >> 8) & 0xFF, 8, pre+119); + + // add paritybits (bitsource, dest, sourcelen, paritylen, parityType (odd, even,) addParity(pre, pre+64, 64, 8, 1); addParity(pre+64, pre+64, 64, 8, 1); pre[63] = GetParity( DemodBuffer, EVEN, 63); pre[127] = GetParity( DemodBuffer+64, EVEN, 63); - + memcpy(nedapBits, pre, 128); // 1111111110001011010000010110100011001001000010110101001101011001000110011010010000000000100001110001001000000001000101011100111 @@ -110,7 +110,7 @@ int GetNedapBits(uint32_t cn, uint8_t *nedapBits) { //GetParity( uint8_t *bits, uint8_t type, int length) //NEDAP demod - ASK/Biphase (or Diphase), RF/64 with preamble of 1111111110 (always a 128 bit data stream) -//print NEDAP Prox ID, encoding, encrypted ID, +//print NEDAP Prox ID, encoding, encrypted ID, int CmdLFNedapDemod(const char *Cmd) { //raw ask demod no start bit finding just get binary from wave @@ -141,19 +141,19 @@ int CmdLFNedapDemod(const char *Cmd) { /* Index map E E preamble enc tag type encrypted uid P d 33 d 90 d 04 d 71 d 40 d 45 d E7 P 1111111110 00101101000001011010001100100100001011010100110101100 1 0 00110011 0 10010000 0 00000100 0 01110001 0 01000000 0 01000101 0 11100111 1 - uid2 uid1 uid0 I I R R - 1111111110 00101101000001011010001100100100001011010100110101100 1 - - 0 00110011 - 0 10010000 + uid2 uid1 uid0 I I R R + 1111111110 00101101000001011010001100100100001011010100110101100 1 + + 0 00110011 + 0 10010000 0 00000100 0 01110001 0 01000000 0 01000101 0 11100111 1 - - Tag ID is 049033 + + Tag ID is 049033 I = Identical on all tags R = Random ? UID2, UID1, UID0 == card number @@ -167,7 +167,7 @@ int CmdLFNedapDemod(const char *Cmd) { raw[3] = bytebits_to_byte(DemodBuffer+idx,32); setDemodBuf(DemodBuffer, 128, idx); setClockGrid(g_DemodClock, g_DemodStartIdx + (idx*g_DemodClock)); - + uint8_t firstParity = GetParity( DemodBuffer, EVEN, 63); if ( firstParity != DemodBuffer[63] ) { PrintAndLogEx(DEBUG, "DEBUG: Error - Nedap 1st 64bit parity check failed: %d|%d ", DemodBuffer[63], firstParity); @@ -187,9 +187,9 @@ int CmdLFNedapDemod(const char *Cmd) { uid |= bytebits_to_byte(DemodBuffer+83, 8) << 16; uint16_t two = 0; - two = bytebits_to_byte(DemodBuffer+92, 8); + two = bytebits_to_byte(DemodBuffer+92, 8); two |= bytebits_to_byte(DemodBuffer+101, 8) << 8; - + uint16_t chksum2 = 0; chksum2 = bytebits_to_byte(DemodBuffer+110, 8); chksum2 |= bytebits_to_byte(DemodBuffer+119, 8) << 8; @@ -249,11 +249,11 @@ int CmdLFNedapClone(const char *Cmd) { if (sscanf(Cmd, "%u", &cn ) != 1) return usage_lf_nedap_clone(); cardnumber = (cn & 0x00FFFFFF); - + if ( !GetNedapBits(cardnumber, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } ((ASK/DIphase data rawdemod ab 0 64 1 0 //NEDAP - compat mode, ASK/DIphase, data rate 64, 4 data blocks @@ -291,32 +291,32 @@ int CmdLFNedapClone(const char *Cmd) { int CmdLFNedapSim(const char *Cmd) { uint32_t cardnumber = 0, cn = 0; - + char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_nedap_sim(); if (sscanf(Cmd, "%u", &cn ) != 1) return usage_lf_nedap_sim(); - + cardnumber = (cn & 0x00FFFFFF); - + uint8_t bs[128]; size_t size = sizeof(bs); memset(bs, 0x00, size); - + // NEDAP, Biphase = 2, clock 64, inverted, (DIPhase == inverted BIphase uint8_t clk = 64, encoding = 2, separator = 0, invert = 1; uint16_t arg1, arg2; arg1 = clk << 8 | encoding; arg2 = invert << 8 | separator; - + if ( !GetNedapBits(cardnumber, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } PrintAndLogEx(SUCCESS, "bin %s", sprint_bin_break(bs, 128, 32)); PrintAndLogEx(SUCCESS, "Simulating Nedap - CardNumber: %u", cardnumber ); - + UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bs, size); clearCommandBuffer(); @@ -329,51 +329,51 @@ int CmdLFNedapChk(const char *Cmd){ uint8_t data[256] = { 0x30, 0x16, 0x00, 0x71, 0x40, 0x21, 0xBE}; int len = 0; param_gethex_ex(Cmd, 0, data, &len); - + len = ( len == 0 ) ? 5 : len>>1; - + PrintAndLogEx(SUCCESS, "Input: [%d] %s", len, sprint_hex(data, len)); - + //uint8_t last = GetParity(data, EVEN, 62); //PrintAndLogEx(NORMAL, "TEST PARITY:: %d | %d ", DemodBuffer[62], last); uint8_t cl = 0x1D, ch = 0x1D, carry = 0; uint8_t al, bl, temp; - + for (int i =len; i >= 0; --i){ al = data[i]; for (int j = 8; j > 0; --j) { - + bl = al ^ ch; //PrintAndLogEx(NORMAL, "BL %02x | CH %02x \n", al, ch); - + carry = (cl & 0x80) ? 1 : 0; cl <<= 1; - + temp = (ch & 0x80) ? 1 : 0; ch = (ch << 1) | carry; carry = temp; - + carry = (al & 0x80) ? 1 : 0; al <<= 1; - + carry = (bl & 0x80) ? 1 : 0; bl <<= 1; - + if (carry) { cl ^= 0x21; ch ^= 0x10; } } } - + PrintAndLogEx(SUCCESS, "Nedap checksum: 0x%X", ((ch << 8) | cl) ); return 0; } static command_t CommandTable[] = { {"help", CmdHelp, 1, "this help"}, - {"demod", CmdLFNedapDemod,0, "demodulate an Nedap tag from the GraphBuffer"}, + {"demod", CmdLFNedapDemod,0, "demodulate an Nedap tag from the GraphBuffer"}, {"read", CmdLFNedapRead, 0, "attempt to read and extract tag data"}, // {"clone", CmdLFNedapClone,0, " clone nedap tag"}, {"sim", CmdLFNedapSim, 0, "simulate nedap tag"}, diff --git a/client/cmdlfnexwatch.c b/client/cmdlfnexwatch.c index 4057fe452..dd6bf3ff9 100644 --- a/client/cmdlfnexwatch.c +++ b/client/cmdlfnexwatch.c @@ -16,7 +16,7 @@ int detectNexWatch(uint8_t *dest, size_t *size, bool *invert) { uint8_t preamble[28] = {0,0,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; uint8_t preamble_i[28] = {1,1,1,1,1,0,1,0,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; - // sanity check. + // sanity check. if ( *size < sizeof(preamble) + 100) return -1; size_t startIdx = 0; @@ -26,7 +26,7 @@ int detectNexWatch(uint8_t *dest, size_t *size, bool *invert) { if (!preambleSearch(DemodBuffer, preamble_i, sizeof(preamble_i), size, &startIdx)) return -4; *invert ^= 1; } - + // size tests? return (int) startIdx; } @@ -56,18 +56,18 @@ int CmdNexWatchDemod(const char *Cmd) { return 0; } - + setDemodBuf(DemodBuffer, size, idx+4); setClockGrid(g_DemodClock, g_DemodStartIdx + ((idx+4)*g_DemodClock)); - + idx = 8+32; // 8 = preamble, 32 = reserved bits (always 0) - + //get ID uint32_t ID = 0; for (uint8_t k = 0; k < 4; k++){ for (uint8_t m = 0; m < 8; m++){ ID = (ID << 1) | DemodBuffer[m + k + (m*4)]; - } + } } //parity check (TBD) @@ -79,7 +79,7 @@ int CmdNexWatchDemod(const char *Cmd) { PrintAndLogEx(NORMAL, "Had to Invert - probably NexKey"); for (size_t i = 0; i < size; i++) DemodBuffer[i] ^= 1; - } + } CmdPrintDemodBuff("x"); return 1; @@ -100,7 +100,7 @@ static command_t CommandTable[] = { }; int CmdLFNEXWATCH(const char *Cmd) { - clearCommandBuffer(); + clearCommandBuffer(); CmdsParse(CommandTable, Cmd); return 0; } diff --git a/client/cmdlfnexwatch.h b/client/cmdlfnexwatch.h index 73a44f919..82782926a 100644 --- a/client/cmdlfnexwatch.h +++ b/client/cmdlfnexwatch.h @@ -20,7 +20,7 @@ #include "cmdparser.h" #include "cmddata.h" // preamblesearch #include "cmdlf.h" -#include "lfdemod.h" +#include "lfdemod.h" extern int CmdLFNEXWATCH(const char *Cmd); extern int CmdNexWatchDemod(const char *Cmd); diff --git a/client/cmdlfnoralsy.c b/client/cmdlfnoralsy.c index 0f61e26ea..a858feb2e 100644 --- a/client/cmdlfnoralsy.c +++ b/client/cmdlfnoralsy.c @@ -46,7 +46,7 @@ static uint8_t noralsy_chksum( uint8_t* bits, uint8_t len) { sum ^= bytebits_to_byte(bits+i, 4); return sum & 0x0F ; } -int getnoralsyBits(uint32_t id, uint16_t year, uint8_t *bits) { +int getnoralsyBits(uint32_t id, uint16_t year, uint8_t *bits) { //preamp num_to_bytebits(0xBB0214FF, 32, bits); // --> Have seen 0xBB0214FF / 0xBB0314FF UNKNOWN @@ -54,15 +54,15 @@ int getnoralsyBits(uint32_t id, uint16_t year, uint8_t *bits) { id = DEC2BCD(id); year = DEC2BCD(year); year &= 0xFF; - + uint16_t sub1 = (id & 0xFFF0000) >> 16; uint8_t sub2 = (id & 0x000FF00) >> 8; uint8_t sub3 = (id & 0x00000FF); - + num_to_bytebits(sub1, 12, bits+32); num_to_bytebits(year, 8, bits+44); num_to_bytebits(0, 4, bits+52); // --> UNKNOWN. Flag? - + num_to_bytebits(sub2, 8, bits+56); num_to_bytebits(sub3, 8, bits+64); @@ -91,12 +91,12 @@ int detectNoralsy(uint8_t *dest, size_t *size) { * 2520116 | BB0214FF2529900116360000 | 10111011 00000011 00010100 11111111 00100101 00101001 10010000 00000001 00010110 00110110 00000000 00000000 * aaa*aaaaiiiYY*iiiicc---- **** iiiiiiii iiiiYYYY YYYY**** iiiiiiii iiiiiiii cccccccc * -* a = fixed value BB0*14FF +* a = fixed value BB0*14FF * i = printed id, BCD-format * Y = year * c = checksum * * = unknown -* +* **/ //see ASKDemod for what args are accepted @@ -130,7 +130,7 @@ int CmdNoralsyDemod(const char *Cmd) { } setDemodBuf(DemodBuffer, 96, ans); setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); - + //got a good demod uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); @@ -144,7 +144,7 @@ int CmdNoralsyDemod(const char *Cmd) { uint16_t year = (raw2 & 0x000ff000) >> 12; year = BCD2DEC(year); year += ( year > 60 ) ? 1900: 2000; - + // calc checksums uint8_t calc1 = noralsy_chksum(DemodBuffer+32, 40); uint8_t calc2 = noralsy_chksum(DemodBuffer, 76); @@ -152,7 +152,7 @@ int CmdNoralsyDemod(const char *Cmd) { chk1 = bytebits_to_byte(DemodBuffer+72, 4); chk2 = bytebits_to_byte(DemodBuffer+76, 4); // test checksums - if ( chk1 != calc1 ) { + if ( chk1 != calc1 ) { if (g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: checksum 1 failed %x - %x\n", chk1, calc1); return 0; } @@ -160,7 +160,7 @@ int CmdNoralsyDemod(const char *Cmd) { if (g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: Error - Noralsy: checksum 2 failed %x - %x\n", chk2, calc2); return 0; } - + PrintAndLogEx(SUCCESS, "Noralsy Tag Found: Card ID %u, Year: %u Raw: %08X%08X%08X", cardid, year, raw1 ,raw2, raw3); if (raw1 != 0xBB0214FF) { PrintAndLogEx(WARNING, "Unknown bits set in first block! Expected 0xBB0214FF, Found: 0x%08X", raw1); @@ -175,36 +175,36 @@ int CmdNoralsyRead(const char *Cmd) { } int CmdNoralsyClone(const char *Cmd) { - + uint16_t year = 0; uint32_t id = 0; uint32_t blocks[4] = {T55x7_MODULATION_MANCHESTER | T55x7_BITRATE_RF_32 | T55x7_ST_TERMINATOR | 3 << T55x7_MAXBLOCK_SHIFT, 0, 0}; uint8_t bits[96]; memset(bits, 0, sizeof(bits)); - + char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_noralsy_clone(); id = param_get32ex(Cmd, 0, 0, 10); year = param_get32ex(Cmd, 1, 2000, 10); - + //Q5 if (param_getchar(Cmd, 2) == 'Q' || param_getchar(Cmd, 2) == 'q') blocks[0] = T5555_MODULATION_MANCHESTER | T5555_SET_BITRATE(32) | T5555_ST_TERMINATOR | 3 << T5555_MAXBLOCK_SHIFT; - + if ( !getnoralsyBits(id, year, bits)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } - - // + } + + // blocks[1] = bytebits_to_byte(bits, 32); blocks[2] = bytebits_to_byte(bits + 32, 32); blocks[3] = bytebits_to_byte(bits + 64, 32); PrintAndLogEx(INFO, "Preparing to clone Noralsy to T55x7 with CardId: %u", id); print_blocks(blocks, 4); - + UsbCommand resp; UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}}; @@ -241,12 +241,12 @@ int CmdNoralsySim(const char *Cmd) { size_t size = 96; arg1 = clk << 8 | encoding; arg2 = invert << 8 | separator; - + if ( !getnoralsyBits(id, year, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } - + } + PrintAndLogEx(SUCCESS, "Simulating Noralsy - CardId: %u", id); UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; diff --git a/client/cmdlfpac.c b/client/cmdlfpac.c index 73086ce59..a6a79e64a 100644 --- a/client/cmdlfpac.c +++ b/client/cmdlfpac.c @@ -55,10 +55,10 @@ int CmdPacDemod(const char *Cmd) { uint32_t raw3 = bytebits_to_byte(DemodBuffer+64, 32); uint32_t raw4 = bytebits_to_byte(DemodBuffer+96, 32); - // preamble then appears to have marker bits of "10" CS? + // preamble then appears to have marker bits of "10" CS? // 11111111001000000 10 01001100 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 00001101 10 10001100 10 100000001 // unknown checksum 9 bits at the end - + PrintAndLogEx(NORMAL, "PAC/Stanley Tag Found -- Raw: %08X%08X%08X%08X", raw1 ,raw2, raw3, raw4); PrintAndLogEx(NORMAL, "\nHow the Raw ID is translated by the reader is unknown"); return 1; diff --git a/client/cmdlfparadox.c b/client/cmdlfparadox.c index 139797a66..113036d6f 100644 --- a/client/cmdlfparadox.c +++ b/client/cmdlfparadox.c @@ -41,28 +41,28 @@ int usage_lf_paradox_sim(void) { int detectParadox(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx) { //make sure buffer has data if (*size < 96*50) return -1; - + signal_t *sp = getSignalProperties(); if (sp->isnoise) return -2; - + // FSK demodulator *size = fskdemod(dest, *size, 50, 1, 10, 8, waveStartIdx); // paradox fsk2a - //did we get a good demod? + //did we get a good demod? if (*size < 96) return -3; // 00001111 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1 - size_t startIdx = 0; + size_t startIdx = 0; uint8_t preamble[] = {0,0,0,0,1,1,1,1}; - if (preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) + if (preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) return -4; //preamble not found size_t numStart = startIdx + sizeof(preamble); // final loop, go over previously decoded FSK data and manchester decode into usable tag ID for (size_t idx = numStart; (idx-numStart) < *size - sizeof(preamble); idx+=2){ - if (dest[idx] == dest[idx+1]) + if (dest[idx] == dest[idx+1]) return -5; //not manchester data - + *hi2 = (*hi2 << 1) | (*hi >> 31); *hi = (*hi << 1) | (*lo >> 31); //Then, shift in a 0 or one into low @@ -86,8 +86,8 @@ int CmdParadoxDemod(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox not enough samples"); return 0; } - - uint32_t hi2=0, hi=0, lo=0; + + uint32_t hi2=0, hi=0, lo=0; int waveIdx=0; //get binary from fsk wave int idx = detectParadox(bits, &size, &hi2, &hi, &lo, &waveIdx); @@ -96,7 +96,7 @@ int CmdParadoxDemod(const char *Cmd) { if (idx == -1) PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox not enough samples"); else if (idx == -2) - PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox just noise detected"); + PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox just noise detected"); else if (idx == -3) PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox problem during FSK demod"); else if (idx == -4) @@ -105,18 +105,18 @@ int CmdParadoxDemod(const char *Cmd) { PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox error in Manchester data, size %d", size); else PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox error demoding fsk %d", idx); - + return 0; } setDemodBuf(bits, size, idx); - setClockGrid(50, waveIdx + (idx*50)); - + setClockGrid(50, waveIdx + (idx*50)); + if (hi2==0 && hi==0 && lo==0){ if (g_debugMode) PrintAndLogEx(DEBUG, "DEBUG: Error - Paradox no value found"); return 0; } - + uint32_t fc = ((hi & 0x3)<<6) | (lo>>26); uint32_t cardnum = (lo>>10) & 0xFFFF; uint32_t rawLo = bytebits_to_byte(bits + idx + 64, 32); @@ -125,14 +125,14 @@ int CmdParadoxDemod(const char *Cmd) { PrintAndLogEx(NORMAL, "Paradox TAG ID: %x%08x - FC: %d - Card: %d - Checksum: %02x - RAW: %08x%08x%08x", hi >> 10, - (hi & 0x3)<<26 | (lo>>10), + (hi & 0x3)<<26 | (lo>>10), fc, cardnum, (lo>>2) & 0xFF, rawHi2, rawHi, rawLo ); - + PrintAndLogEx(DEBUG, "DEBUG: Paradox idx: %d, len: %d, Printing Demod Buffer:", idx, size); if (g_debugMode) printDemodBuff(); @@ -142,7 +142,7 @@ int CmdParadoxDemod(const char *Cmd) { //by marshmellow //see ASKDemod for what args are accepted int CmdParadoxRead(const char *Cmd) { - lf_read(true, 10000); + lf_read(true, 10000); return CmdParadoxDemod(Cmd); } @@ -152,29 +152,29 @@ int CmdParadoxSim(const char *Cmd) { if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_paradox_sim(); uint32_t facilitycode = 0, cardnumber = 0, fc = 0, cn = 0; - + uint8_t bs[96]; size_t size = sizeof(bs); memset(bs, 0x00, size); - + // Paradox uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 1 FSK2a uint8_t clk = 50, invert = 1, high = 10, low = 8; - uint16_t arg1, arg2; + uint16_t arg1, arg2; arg1 = high << 8 | low; arg2 = invert << 8 | clk; - + if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) return usage_lf_paradox_sim(); facilitycode = (fc & 0x000000FF); cardnumber = (cn & 0x0000FFFF); - + // if ( !GetParadoxBits(facilitycode, cardnumber, bs)) { // PrintAndLogEx(WARNING, "Error with tag bitstream generation."); // return 1; - // } + // } PrintAndLogEx(NORMAL, "Simulating Paradox - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber ); - + UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bs, size); clearCommandBuffer(); @@ -189,7 +189,7 @@ static command_t CommandTable[] = { {"demod", CmdParadoxDemod, 1, "Demodulate a Paradox FSK tag from the GraphBuffer"}, {"read", CmdParadoxRead, 0, "Attempt to read and Extract tag data from the antenna"}, // {"clone", CmdParadoxClone,0, "clone paradox tag"}, - {"sim", CmdParadoxSim, 0, "simulate paradox tag"}, + {"sim", CmdParadoxSim, 0, "simulate paradox tag"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdlfpcf7931.c b/client/cmdlfpcf7931.c index 59ef1c818..c47a44e7b 100644 --- a/client/cmdlfpcf7931.c +++ b/client/cmdlfpcf7931.c @@ -30,7 +30,7 @@ static int CmdHelp(const char *Cmd); struct pcf7931_config configPcf = { {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}, PCF7931_DEFAULT_INITDELAY, - PCF7931_DEFAULT_OFFSET_WIDTH, + PCF7931_DEFAULT_OFFSET_WIDTH, PCF7931_DEFAULT_OFFSET_POSITION }; @@ -38,8 +38,8 @@ struct pcf7931_config configPcf = { int pcf7931_resetConfig(){ memset(configPcf.Pwd, 0xFF, sizeof(configPcf.Pwd) ); configPcf.InitDelay = PCF7931_DEFAULT_INITDELAY; - configPcf.OffsetWidth = PCF7931_DEFAULT_OFFSET_WIDTH; - configPcf.OffsetPosition = PCF7931_DEFAULT_OFFSET_POSITION; + configPcf.OffsetWidth = PCF7931_DEFAULT_OFFSET_WIDTH; + configPcf.OffsetPosition = PCF7931_DEFAULT_OFFSET_POSITION; return 0; } @@ -85,7 +85,7 @@ int usage_pcf7931_config(){ PrintAndLogEx(NORMAL, " pwd Password, hex, 7bytes, LSB-order"); PrintAndLogEx(NORMAL, " delay Tag initialization delay (in us) decimal"); PrintAndLogEx(NORMAL, " offset Low pulses width (in us) decimal"); - PrintAndLogEx(NORMAL, " offset Low pulses position (in us) decimal"); + PrintAndLogEx(NORMAL, " offset Low pulses position (in us) decimal"); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf pcf7931 config"); PrintAndLogEx(NORMAL, " lf pcf7931 config r"); @@ -94,7 +94,7 @@ int usage_pcf7931_config(){ return 0; } -int CmdLFPCF7931Read(const char *Cmd){ +int CmdLFPCF7931Read(const char *Cmd){ uint8_t ctmp = param_getchar(Cmd, 0); if ( ctmp == 'H' || ctmp == 'h' ) return usage_pcf7931_read(); @@ -110,37 +110,37 @@ int CmdLFPCF7931Read(const char *Cmd){ return 0; } -int CmdLFPCF7931Config(const char *Cmd){ +int CmdLFPCF7931Config(const char *Cmd){ uint8_t ctmp = param_getchar(Cmd, 0); if ( ctmp == 0) return pcf7931_printConfig(); if ( ctmp == 'H' || ctmp == 'h' ) return usage_pcf7931_config(); - if ( ctmp == 'R' || ctmp == 'r' ) return pcf7931_resetConfig(); - + if ( ctmp == 'R' || ctmp == 'r' ) return pcf7931_resetConfig(); + if ( param_gethex(Cmd, 0, configPcf.Pwd, 14) ) return usage_pcf7931_config(); - + configPcf.InitDelay = (param_get32ex(Cmd,1,0,10) & 0xFFFF); configPcf.OffsetWidth = (int)(param_get32ex(Cmd,2,0,10) & 0xFFFF); configPcf.OffsetPosition = (int)(param_get32ex(Cmd,3,0,10) & 0xFFFF); - + pcf7931_printConfig(); return 0; } int CmdLFPCF7931Write(const char *Cmd){ - + uint8_t ctmp = param_getchar(Cmd, 0); - if (strlen(Cmd) < 1 || ctmp == 'h' || ctmp == 'H') return usage_pcf7931_write(); + if (strlen(Cmd) < 1 || ctmp == 'h' || ctmp == 'H') return usage_pcf7931_write(); uint8_t block = 0, bytepos = 0, data = 0; - + if ( param_getdec(Cmd, 0, &block) ) return usage_pcf7931_write(); if ( param_getdec(Cmd, 1, &bytepos) ) return usage_pcf7931_write(); - + if ( (block > 7) || (bytepos > 15) ) return usage_pcf7931_write(); data = param_get8ex(Cmd, 2, 0, 16); - + PrintAndLogEx(NORMAL, "Writing block: %d", block); PrintAndLogEx(NORMAL, " pos: %d", bytepos); PrintAndLogEx(NORMAL, " data: 0x%02X", data); diff --git a/client/cmdlfpresco.c b/client/cmdlfpresco.c index 98df02fe5..1b54899bd 100644 --- a/client/cmdlfpresco.c +++ b/client/cmdlfpresco.c @@ -14,7 +14,7 @@ int usage_lf_presco_clone(void){ PrintAndLogEx(NORMAL, "clone a Presco tag to a T55x7 tag."); PrintAndLogEx(NORMAL, "Usage: lf presco clone [h] d c "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : this help"); + PrintAndLogEx(NORMAL, " h : this help"); PrintAndLogEx(NORMAL, " d : 9 digit presco card ID"); PrintAndLogEx(NORMAL, " c : 8 digit hex card number"); PrintAndLogEx(NORMAL, " : specify write to Q5 (t5555 instead of t55x7)"); @@ -31,7 +31,7 @@ int usage_lf_presco_sim(void) { PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Usage: lf presco sim [h] d or c "); PrintAndLogEx(NORMAL, "Options:"); - PrintAndLogEx(NORMAL, " h : this help"); + PrintAndLogEx(NORMAL, " h : this help"); PrintAndLogEx(NORMAL, " d : 9 digit presco card number"); PrintAndLogEx(NORMAL, " c : 8 digit hex card number"); PrintAndLogEx(NORMAL, ""); @@ -54,14 +54,14 @@ int detectPresco(uint8_t *dest, size_t *size) { // convert base 12 ID to sitecode & usercode & 8 bit other unknown code int GetWiegandFromPresco(const char *Cmd, uint32_t *sitecode, uint32_t *usercode, uint32_t *fullcode, bool *Q5) { - + uint8_t val = 0; bool hex = false, errors = false; uint8_t cmdp = 0; char id[11]; int stringlen = 0; memset(id, 0x00, sizeof(id)); - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': @@ -93,7 +93,7 @@ int GetWiegandFromPresco(const char *Cmd, uint32_t *sitecode, uint32_t *usercode if (!hex) { for (int index =0; index < strlen(id); ++index) { - + // Get value from number string. if ( id[index] == '*' ) val = 10; @@ -101,11 +101,11 @@ int GetWiegandFromPresco(const char *Cmd, uint32_t *sitecode, uint32_t *usercode val = 11; if ( id[index] >= 0x30 && id[index] <= 0x39 ) val = id[index] - 0x30; - + *fullcode += val; - + // last digit is only added, not multipled. - if ( index < strlen(id)-1 ) + if ( index < strlen(id)-1 ) *fullcode *= 12; } } @@ -146,7 +146,7 @@ int CmdPrescoDemod(const char *Cmd) { } setDemodBuf(DemodBuffer, 128, ans); setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); - + //got a good demod uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); @@ -178,7 +178,7 @@ int CmdPrescoClone(const char *Cmd) { bool Q5 = false; uint32_t sitecode=0, usercode=0, fullcode=0; uint32_t blocks[5] = {T55x7_MODULATION_MANCHESTER | T55x7_BITRATE_RF_32 | 4 << T55x7_MAXBLOCK_SHIFT | T55x7_ST_TERMINATOR, 0, 0, 0, 0}; - + // get wiegand from printed number. if (GetWiegandFromPresco(Cmd, &sitecode, &usercode, &fullcode, &Q5) == -1) return usage_lf_presco_clone(); @@ -194,7 +194,7 @@ int CmdPrescoClone(const char *Cmd) { usercode &= 0xFFFF; PrintAndLogEx(INFO, "Card Number Truncated to 16-bits (Presco): %u", usercode); } - + blocks[1] = 0x10D00000; //preamble blocks[2] = 0x00000000; blocks[3] = 0x00000000; @@ -202,7 +202,7 @@ int CmdPrescoClone(const char *Cmd) { PrintAndLogEx(INFO, "Preparing to clone Presco to T55x7 with SiteCode: %u, UserCode: %u, FullCode: %08x", sitecode, usercode, fullcode); print_blocks(blocks, 5); - + UsbCommand resp; UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}}; diff --git a/client/cmdlfpyramid.c b/client/cmdlfpyramid.c index 1153fccc3..796301761 100644 --- a/client/cmdlfpyramid.c +++ b/client/cmdlfpyramid.c @@ -80,8 +80,8 @@ int GetPyramidBits(uint32_t fc, uint32_t cn, uint8_t *pyramidBits) { // format start bit pre[79] = 1; - - // Get 26 wiegand from FacilityCode, CardNumber + + // Get 26 wiegand from FacilityCode, CardNumber uint8_t wiegand[24]; memset(wiegand, 0x00, sizeof(wiegand)); num_to_bytebits(fc, 8, wiegand); @@ -89,11 +89,11 @@ int GetPyramidBits(uint32_t fc, uint32_t cn, uint8_t *pyramidBits) { // add wiegand parity bits (dest, source, len) wiegand_add_parity(pre+80, wiegand, 24); - + // add paritybits (bitsource, dest, sourcelen, paritylen, parityType (odd, even,) addParity(pre+8, pyramidBits+8, 102, 8, 1); - // add checksum + // add checksum uint8_t csBuff[13]; for (uint8_t i = 0; i < 13; i++) csBuff[i] = bytebits_to_byte(pyramidBits + 16 + (i*8), 8); @@ -125,7 +125,7 @@ int CmdPyramidDemod(const char *Cmd) { else if (idx == -3) PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: problem during FSK demod"); else if (idx == -4) - PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: preamble not found"); + PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: preamble not found"); else if (idx == -5) PrintAndLogEx(DEBUG, "DEBUG: Error - Pyramid: size not correct: %d", size); else @@ -134,7 +134,7 @@ int CmdPyramidDemod(const char *Cmd) { } setDemodBuf(bits, size, idx); setClockGrid(50, waveIdx + (idx*50)); - + // Index map // 0 10 20 30 40 50 60 // | | | | | | | @@ -209,12 +209,12 @@ int CmdPyramidDemod(const char *Cmd) { for (j=0; j < size; ++j){ if(bits[j]) break; } - + uint8_t fmtLen = size-j-8; uint32_t fc = 0; uint32_t cardnum = 0; uint32_t code1 = 0; - + if ( fmtLen == 26 ){ fc = bytebits_to_byte(bits+73, 8); cardnum = bytebits_to_byte(bits+81, 16); @@ -267,11 +267,11 @@ int CmdPyramidClone(const char *Cmd) { facilitycode = (fc & 0x000000FF); cardnumber = (cn & 0x0000FFFF); - + if ( !GetPyramidBits(facilitycode, cardnumber, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } //Pyramid - compat mode, FSK2a, data rate 50, 4 data blocks blocks[0] = T55x7_MODULATION_FSK2a | T55x7_BITRATE_RF_50 | 4 << T55x7_MAXBLOCK_SHIFT; @@ -310,29 +310,29 @@ int CmdPyramidSim(const char *Cmd) { if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_pyramid_sim(); uint32_t facilitycode = 0, cardnumber = 0, fc = 0, cn = 0; - + uint8_t bs[128]; size_t size = sizeof(bs); memset(bs, 0x00, size); - + // Pyramid uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 0 uint8_t clk = 50, invert = 0, high = 10, low = 8; - uint16_t arg1, arg2; + uint16_t arg1, arg2; arg1 = high << 8 | low; arg2 = invert << 8 | clk; - + if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) return usage_lf_pyramid_sim(); facilitycode = (fc & 0x000000FF); cardnumber = (cn & 0x0000FFFF); - + if ( !GetPyramidBits(facilitycode, cardnumber, bs)) { PrintAndLogEx(WARNING, "Error with tag bitstream generation."); return 1; - } + } PrintAndLogEx(SUCCESS, "Simulating Farpointe/Pyramid - Facility Code: %u, CardNumber: %u", facilitycode, cardnumber ); - + UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}}; memcpy(c.d.asBytes, bs, size); clearCommandBuffer(); diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index e94ec84fe..4eb087874 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -61,7 +61,7 @@ int usage_t55xx_write(){ PrintAndLogEx(NORMAL, " d - 4 bytes of data to write (8 hex characters)"); PrintAndLogEx(NORMAL, " p - OPTIONAL password 4bytes (8 hex characters)"); PrintAndLogEx(NORMAL, " 1 - OPTIONAL write Page 1 instead of Page 0"); - PrintAndLogEx(NORMAL, " t - OPTIONAL test mode write - ****DANGER****"); + PrintAndLogEx(NORMAL, " t - OPTIONAL test mode write - ****DANGER****"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); PrintAndLogEx(NORMAL, " lf t55xx write b 3 d 11223344 - write 11223344 to block 3"); @@ -147,7 +147,7 @@ int usage_t55xx_chk(){ PrintAndLogEx(NORMAL, "Usage: lf t55xx bruteforce [h] [i <*.dic>]"); PrintAndLogEx(NORMAL, "Options:"); PrintAndLogEx(NORMAL, " h - this help"); - PrintAndLogEx(NORMAL, " m - use dictionary from flashmemory\n"); + PrintAndLogEx(NORMAL, " m - use dictionary from flashmemory\n"); PrintAndLogEx(NORMAL, " i <*.dic> - loads a default keys dictionary file <*.dic>"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); @@ -221,9 +221,9 @@ int usage_lf_deviceconfig(){ int CmdHelp(const char *Cmd); void printT5xxHeader(uint8_t page){ - PrintAndLogEx(NORMAL, "Reading Page %d:", page); + PrintAndLogEx(NORMAL, "Reading Page %d:", page); PrintAndLogEx(NORMAL, "blk | hex data | binary | ascii"); - PrintAndLogEx(NORMAL, "----+----------+----------------------------------+-------"); + PrintAndLogEx(NORMAL, "----+----------+----------------------------------+-------"); } int CmdT55xxSetConfig(const char *Cmd) { @@ -303,11 +303,11 @@ int CmdT55xxSetConfig(const char *Cmd) { config.offset = offset; cmdp+=2; break; - case 'q': + case 'q': config.Q5 = true; cmdp++; break; - case 's': + case 's': config.ST = true; cmdp++; break; @@ -333,14 +333,14 @@ int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32 if ( usepwd ) { // try reading the config block and verify that PWD bit is set before doing this! if ( !override ) { - + if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, false, 0 ) ) return 0; - + if ( !tryDetectModulation() ) { PrintAndLogEx(NORMAL, "Safety Check: Could not detect if PWD bit is set in config block. Exits."); return 0; } else { - PrintAndLogEx(NORMAL, "Safety Check: PWD bit is NOT set in config block. Reading without password..."); + PrintAndLogEx(NORMAL, "Safety Check: PWD bit is NOT set in config block. Reading without password..."); usepwd = false; page1 = false; } @@ -354,7 +354,7 @@ int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32 char blk[10] = {0}; sprintf(blk, "%02d", block); - printT55xxBlock(blk); + printT55xxBlock(blk); return 1; } @@ -405,7 +405,7 @@ int CmdT55xxReadBlock(const char *Cmd) { } bool DecodeT55xxBlock(){ - + char buf[30] = {0x00}; char *cmdStr = buf; int ans = 0; @@ -469,7 +469,7 @@ bool DecodeT55xxBlock(){ bool DecodeT5555TraceBlock() { DemodBufferLen = 0x00; - + // According to datasheet. Always: RF/64, not inverted, Manchester return (bool) ASKDemod("64 0 1", false, false, 1); } @@ -510,15 +510,15 @@ int CmdT55xxDetect(const char *Cmd){ } } if (errors) return usage_t55xx_detect(); - + // sanity check. if (!SanityOfflineCheck(useGB)) return 1; - + if ( !useGB) { if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password) ) return 1; } - + if ( !tryDetectModulation() ) PrintAndLogEx(WARNING, "Could not detect modulation automatically. Try setting it manually with \'lf t55xx config\'"); @@ -531,7 +531,7 @@ bool tryDetectModulation(){ t55xx_conf_block_t tests[15]; int bitRate = 0, clk = 0, firstClockEdge = 0; uint8_t hits = 0, fc1 = 0, fc2 = 0, ans = 0; - + ans = fskClocks(&fc1, &fc2, (uint8_t *)&clk, &firstClockEdge); if (ans && ((fc1==10 && fc2==8) || (fc1==8 && fc2==5))) { @@ -625,7 +625,7 @@ bool tryDetectModulation(){ ++hits; } } - + clk = GetPskClock("", false); if (clk > 0) { // allow undo @@ -676,7 +676,7 @@ bool tryDetectModulation(){ //undo trim samples save_restoreGB(GRAPH_RESTORE); } - } + } if ( hits == 1) { config.modulation = tests[0].modulation; config.bitrate = tests[0].bitrate; @@ -688,13 +688,13 @@ bool tryDetectModulation(){ printConfiguration( config ); return true; } - + bool retval = false; if ( hits > 1) { PrintAndLogEx(SUCCESS, "Found [%d] possible matches for modulation.", hits); for(int i=0; i 128 || bitRate < 8) continue; - //uint8_t AOR = PackBits(si, 1, DemodBuffer); si += 1; - //uint8_t PWD = PackBits(si, 1, DemodBuffer); si += 1; + //uint8_t AOR = PackBits(si, 1, DemodBuffer); si += 1; + //uint8_t PWD = PackBits(si, 1, DemodBuffer); si += 1; //uint8_t pskcr = PackBits(si, 2, DemodBuffer); si += 2; //could check psk cr //uint8_t inverse = PackBits(si, 1, DemodBuffer); si += 1; si += 1+1+2+1; @@ -866,11 +866,11 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5) int bitRate = PackBits(si, 6, DemodBuffer); si += 6; //bit rate (includes extended mode part of rate) uint8_t extend = PackBits(si, 1, DemodBuffer); si += 1; //bit 15 extended mode - uint8_t modread = PackBits(si, 5, DemodBuffer); si += 5+2+1; + uint8_t modread = PackBits(si, 5, DemodBuffer); si += 5+2+1; //uint8_t pskcr = PackBits(si, 2, DemodBuffer); si += 2+1; //could check psk cr //uint8_t nml01 = PackBits(si, 1, DemodBuffer); si += 1+5; //bit 24, 30, 31 could be tested for 0 if not extended mode //uint8_t nml02 = PackBits(si, 2, DemodBuffer); si += 2; - + //if extended mode bool extMode =( (safer == 0x6 || safer == 0x9) && extend) ? true : false; @@ -896,7 +896,7 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5) } void printT55xxBlock(const char *blockNum){ - + uint8_t i = config.offset; uint8_t endpos = 32 + i; uint32_t blockData = 0; @@ -927,13 +927,13 @@ int special(const char *Cmd) { PrintAndLogEx(NORMAL, "-------+-------+-------------------------------------+------"); int i,j = 0; for (; j < 64; ++j){ - + for (i = 0; i < 32; ++i) bits[i]=DemodBuffer[j+i]; - + blockData = PackBits(0, 32, bits); - - PrintAndLogEx(NORMAL, "%02d | 0x%08X | %s",j , blockData, sprint_bin(bits,32)); + + PrintAndLogEx(NORMAL, "%02d | 0x%08X | %s",j , blockData, sprint_bin(bits,32)); } return 0; } @@ -980,10 +980,10 @@ int CmdT55xxWakeUp(const char *Cmd) { int CmdT55xxWriteBlock(const char *Cmd) { uint8_t block = 0xFF; //default to invalid block - uint32_t data = 0; //default to blank Block + uint32_t data = 0; //default to blank Block uint32_t password = 0; //default to blank Block 7 bool usepwd = false; - bool page1 = false; + bool page1 = false; bool gotdata = false; bool testMode = false; bool errors = false; @@ -1026,21 +1026,21 @@ int CmdT55xxWriteBlock(const char *Cmd) { PrintAndLogEx(WARNING, "Block number must be between 0 and 7"); return 0; } - + UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {data, block, 0}}; UsbCommand resp; - c.d.asBytes[0] = (page1) ? 0x2 : 0; - c.d.asBytes[0] |= (testMode) ? 0x4 : 0; + c.d.asBytes[0] = (page1) ? 0x2 : 0; + c.d.asBytes[0] |= (testMode) ? 0x4 : 0; char pwdStr[16] = {0}; snprintf(pwdStr, sizeof(pwdStr), "pwd: 0x%08X", password); - + PrintAndLogEx(INFO, "Writing page %d block: %02d data: 0x%08X %s", page1, block, data, (usepwd) ? pwdStr : "" ); //Password mode if (usepwd) { c.arg[2] = password; - c.d.asBytes[0] |= 0x1; + c.d.asBytes[0] |= 0x1; } clearCommandBuffer(); SendCommand(&c); @@ -1057,7 +1057,7 @@ int CmdT55xxReadTrace(const char *Cmd) { bool pwdmode = false; uint32_t password = 0; - + if (strlen(Cmd) == 0) { // sanity check. if (!SanityOfflineCheck(false)) return 1; @@ -1071,29 +1071,29 @@ int CmdT55xxReadTrace(const char *Cmd) { } else { if (!DecodeT55xxBlock()) return 1; } - + if ( !DemodBufferLen ) return 1; - + RepaintGraphWindow(); uint8_t repeat = (config.offset > 5) ? 32 : 0; - + uint8_t si = config.offset + repeat; uint32_t bl1 = PackBits(si, 32, DemodBuffer); - uint32_t bl2 = PackBits(si+32, 32, DemodBuffer); - + uint32_t bl2 = PackBits(si+32, 32, DemodBuffer); + if (config.Q5) { uint32_t hdr = PackBits(si, 9, DemodBuffer); si += 9; - + if (hdr != 0x1FF) { PrintAndLogEx(FAILED, "Invalid Q5 Trace data header (expected 0x1FF, found %X)", hdr); return 1; } - + t5555_tracedata_t data = {.bl1 = bl1, .bl2 = bl2, .icr = 0, .lotidc = '?', .lotid = 0, .wafer = 0, .dw =0}; - + data.icr = PackBits(si, 2, DemodBuffer); si += 2; data.lotidc = 'Z' - PackBits(si, 2, DemodBuffer); si += 3; - + data.lotid = PackBits(si, 4, DemodBuffer); si += 5; data.lotid <<= 4; data.lotid |= PackBits(si, 4, DemodBuffer); si += 5; @@ -1103,11 +1103,11 @@ int CmdT55xxReadTrace(const char *Cmd) { data.lotid |= PackBits(si, 4, DemodBuffer); si += 5; data.lotid <<= 1; data.lotid |= PackBits(si, 1, DemodBuffer); si += 1; - + data.wafer = PackBits(si, 3, DemodBuffer); si += 4; data.wafer <<= 2; data.wafer |= PackBits(si, 2, DemodBuffer); si += 2; - + data.dw = PackBits(si, 2, DemodBuffer); si += 3; data.dw <<= 4; data.dw |= PackBits(si, 4, DemodBuffer); si += 5; @@ -1115,13 +1115,13 @@ int CmdT55xxReadTrace(const char *Cmd) { data.dw |= PackBits(si, 4, DemodBuffer); si += 5; data.dw <<= 4; data.dw |= PackBits(si, 4, DemodBuffer); si += 5; - + printT5555Trace(data, repeat); - + } else { - + t55x7_tracedata_t data = {.bl1 = bl1, .bl2 = bl2, .acl = 0, .mfc = 0, .cid = 0, .year = 0, .quarter = 0, .icr = 0, .lotid = 0, .wafer = 0, .dw = 0}; - + data.acl = PackBits(si, 8, DemodBuffer); si += 8; if ( data.acl != 0xE0 ) { PrintAndLogEx(FAILED, "The modulation is most likely wrong since the ACL is not 0xE0. "); @@ -1135,7 +1135,7 @@ int CmdT55xxReadTrace(const char *Cmd) { data.quarter = PackBits(si, 2, DemodBuffer); si += 2; data.lotid = PackBits(si, 14, DemodBuffer); si += 14; data.wafer = PackBits(si, 5, DemodBuffer); si += 5; - data.dw = PackBits(si, 15, DemodBuffer); + data.dw = PackBits(si, 15, DemodBuffer); time_t t = time(NULL); struct tm tm = *localtime(&t); @@ -1165,21 +1165,21 @@ void printT55x7Trace( t55x7_tracedata_t data, uint8_t repeat ){ PrintAndLogEx(NORMAL, " Raw Data - Page 1"); PrintAndLogEx(NORMAL, " Block 1 : 0x%08X %s", data.bl1, sprint_bin(DemodBuffer+config.offset+repeat,32) ); PrintAndLogEx(NORMAL, " Block 2 : 0x%08X %s", data.bl2, sprint_bin(DemodBuffer+config.offset+repeat+32,32) ); - PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); + PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); /* TRACE - BLOCK O Bits Definition HEX - 1-8 ACL Allocation class (ISO/IEC 15963-1) 0xE0 + 1-8 ACL Allocation class (ISO/IEC 15963-1) 0xE0 9-16 MFC Manufacturer ID (ISO/IEC 7816-6) 0x15 Atmel Corporation - 17-21 CID 0x1 = Atmel ATA5577M1 0x2 = Atmel ATA5577M2 + 17-21 CID 0x1 = Atmel ATA5577M1 0x2 = Atmel ATA5577M2 22-24 ICR IC revision 25-28 YEAR (BCD encoded) 9 (= 2009) - 29-30 QUARTER 1,2,3,4 + 29-30 QUARTER 1,2,3,4 31-32 LOT ID - + TRACE - BLOCK 1 - 1-12 LOT ID + 1-12 LOT ID 13-17 Wafer number 18-32 DW, die number sequential */ @@ -1188,7 +1188,7 @@ void printT55x7Trace( t55x7_tracedata_t data, uint8_t repeat ){ void printT5555Trace( t5555_tracedata_t data, uint8_t repeat ){ PrintAndLogEx(NORMAL, "-- T5555 (Q5) Trace Information -----------------------------"); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); - PrintAndLogEx(NORMAL, " ICR IC Revision : %d", data.icr ); + PrintAndLogEx(NORMAL, " ICR IC Revision : %d", data.icr ); PrintAndLogEx(NORMAL, " Lot : %c%d", data.lotidc, data.lotid); PrintAndLogEx(NORMAL, " Wafer number : %d", data.wafer); PrintAndLogEx(NORMAL, " Die Number : %d", data.dw); @@ -1196,7 +1196,7 @@ void printT5555Trace( t5555_tracedata_t data, uint8_t repeat ){ PrintAndLogEx(NORMAL, " Raw Data - Page 1"); PrintAndLogEx(NORMAL, " Block 1 : 0x%08X %s", data.bl1, sprint_bin(DemodBuffer+config.offset+repeat,32) ); PrintAndLogEx(NORMAL, " Block 2 : 0x%08X %s", data.bl2, sprint_bin(DemodBuffer+config.offset+repeat+32,32) ); - + /* ** Q5 ** TRACE - BLOCK O and BLOCK1 @@ -1224,11 +1224,11 @@ int CmdT55xxInfo(const char *Cmd){ char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) > 1 || cmdp == 'h') return usage_t55xx_info(); - + if (strlen(Cmd) == 0) { // sanity check. if (!SanityOfflineCheck(false)) return 1; - + if ( !AquireData( T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, pwdmode, password ) ) return 1; } @@ -1238,29 +1238,29 @@ int CmdT55xxInfo(const char *Cmd){ // too little space to start with if ( DemodBufferLen < 32) return 1; - // + // //PrintAndLogEx(NORMAL, "Offset+32 ==%d\n DemodLen == %d", config.offset + 32, DemodBufferLen); uint8_t si = config.offset; - uint32_t block0 = PackBits(si, 32, DemodBuffer); - uint32_t safer = PackBits(si, 4, DemodBuffer); si += 4; + uint32_t block0 = PackBits(si, 32, DemodBuffer); + uint32_t safer = PackBits(si, 4, DemodBuffer); si += 4; uint32_t resv = PackBits(si, 7, DemodBuffer); si += 7; uint32_t dbr = PackBits(si, 3, DemodBuffer); si += 3; uint32_t extend = PackBits(si, 1, DemodBuffer); si += 1; uint32_t datamod = PackBits(si, 5, DemodBuffer); si += 5; uint32_t pskcf = PackBits(si, 2, DemodBuffer); si += 2; - uint32_t aor = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t otp = PackBits(si, 1, DemodBuffer); si += 1; + uint32_t aor = PackBits(si, 1, DemodBuffer); si += 1; + uint32_t otp = PackBits(si, 1, DemodBuffer); si += 1; uint32_t maxblk = PackBits(si, 3, DemodBuffer); si += 3; - uint32_t pwd = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t sst = PackBits(si, 1, DemodBuffer); si += 1; + uint32_t pwd = PackBits(si, 1, DemodBuffer); si += 1; + uint32_t sst = PackBits(si, 1, DemodBuffer); si += 1; uint32_t fw = PackBits(si, 1, DemodBuffer); si += 1; - uint32_t inv = PackBits(si, 1, DemodBuffer); si += 1; + uint32_t inv = PackBits(si, 1, DemodBuffer); si += 1; uint32_t por = PackBits(si, 1, DemodBuffer); si += 1; - - if (config.Q5) + + if (config.Q5) PrintAndLogEx(NORMAL, _RED_(*** Warning ***) " Config Info read off a Q5 will not display as expected"); - + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "-- T55x7 Configuration & Tag Information --------------------"); PrintAndLogEx(NORMAL, "-------------------------------------------------------------"); @@ -1292,20 +1292,20 @@ int CmdT55xxDump(const char *Cmd){ char cmdp = tolower(param_getchar(Cmd, 0)); if ( cmdp == 'h') return usage_t55xx_dump(); - bool usepwd = ( strlen(Cmd) > 0); + bool usepwd = ( strlen(Cmd) > 0); if ( usepwd ){ password = param_get32ex(Cmd, 0, 0, 16); if (param_getchar(Cmd, 1) =='o' ) override = true; } - + printT5xxHeader(0); for ( uint8_t i = 0; i < 8; ++i) T55xxReadBlock(i, 0, usepwd, override, password); printT5xxHeader(1); for ( uint8_t i = 0; i < 4; i++) - T55xxReadBlock(i, 1, usepwd, override, password); + T55xxReadBlock(i, 1, usepwd, override, password); return 1; } @@ -1362,7 +1362,7 @@ char * GetBitRateStr(uint32_t id, bool xmode) { char * GetSaferStr(uint32_t id){ static char buf[40]; char *retStr = buf; - + snprintf(retStr,sizeof(buf),"%d",id); if (id == 6) { snprintf(retStr,sizeof(buf),"%d - passwd",id); @@ -1370,14 +1370,14 @@ char * GetSaferStr(uint32_t id){ if (id == 9 ){ snprintf(retStr,sizeof(buf),"%d - testmode",id); } - + return buf; } char * GetModulationStr( uint32_t id){ static char buf[60]; char *retStr = buf; - + switch (id){ case 0: snprintf(retStr,sizeof(buf),"%d - DIRECT (ASK/NRZ)",id); break; case 1: snprintf(retStr,sizeof(buf),"%d - PSK 1 phase change when input changes",id); break; @@ -1397,12 +1397,12 @@ char * GetModulationStr( uint32_t id){ } char * GetModelStrFromCID(uint32_t cid){ - + static char buf[10]; char *retStr = buf; - + if (cid == 1) snprintf(retStr, sizeof(buf),"ATA5577M1"); - if (cid == 2) snprintf(retStr, sizeof(buf),"ATA5577M2"); + if (cid == 2) snprintf(retStr, sizeof(buf),"ATA5577M2"); return buf; } @@ -1434,12 +1434,12 @@ void t55x7_create_config_block( int tagtype ){ /* T55X7_DEFAULT_CONFIG_BLOCK, T55X7_RAW_CONFIG_BLOCK T55X7_EM_UNIQUE_CONFIG_BLOCK, T55X7_FDXB_CONFIG_BLOCK, - T55X7_FDXB_CONFIG_BLOCK, T55X7_HID_26_CONFIG_BLOCK, T55X7_INDALA_64_CONFIG_BLOCK, T55X7_INDALA_224_CONFIG_BLOCK - T55X7_GUARDPROXII_CONFIG_BLOCK, T55X7_VIKING_CONFIG_BLOCK, T55X7_NORALYS_CONFIG_BLOCK, T55X7_IOPROX_CONFIG_BLOCK + T55X7_FDXB_CONFIG_BLOCK, T55X7_HID_26_CONFIG_BLOCK, T55X7_INDALA_64_CONFIG_BLOCK, T55X7_INDALA_224_CONFIG_BLOCK + T55X7_GUARDPROXII_CONFIG_BLOCK, T55X7_VIKING_CONFIG_BLOCK, T55X7_NORALYS_CONFIG_BLOCK, T55X7_IOPROX_CONFIG_BLOCK */ static char buf[60]; char *retStr = buf; - + switch (tagtype){ case 0: snprintf(retStr, sizeof(buf),"%08X - T55X7 Default", T55X7_DEFAULT_CONFIG_BLOCK); break; case 1: snprintf(retStr, sizeof(buf),"%08X - T55X7 Raw", T55X7_RAW_CONFIG_BLOCK); break; @@ -1471,7 +1471,7 @@ int CmdResetRead(const char *Cmd) { int CmdT55xxWipe(const char *Cmd) { char writeData[20] = {0}; char *ptrData = writeData; - char cmdp = param_getchar(Cmd, 0); + char cmdp = param_getchar(Cmd, 0); if ( cmdp == 'h' || cmdp == 'H') return usage_t55xx_wipe(); bool Q5 = (cmdp == 'q' || cmdp == 'Q'); @@ -1479,20 +1479,20 @@ int CmdT55xxWipe(const char *Cmd) { // Try with the default password to reset block 0 // With a pwd should work even if pwd bit not set PrintAndLogEx(INFO, "\nBeginning Wipe of a T55xx tag (assuming the tag is not password protected)\n"); - + if ( Q5 ) snprintf(ptrData,sizeof(writeData),"b 0 d 6001F004 p 0"); else snprintf(ptrData,sizeof(writeData),"b 0 d 000880E0 p 0"); - + if (!CmdT55xxWriteBlock(ptrData)) PrintAndLogEx(WARNING, "Error writing blk 0"); - + for (uint8_t blk = 1; blk<8; blk++) { - + snprintf(ptrData,sizeof(writeData),"b %d d 0", blk); - + if (!CmdT55xxWriteBlock(ptrData)) PrintAndLogEx(WARNING, "Error writing blk %d", blk); - + memset(writeData, 0x00, sizeof(writeData)); } return 0; @@ -1518,22 +1518,22 @@ int CmdT55xxChkPwds(const char *Cmd) { uint8_t timeout = 0; memset(line, 0, sizeof(line)); - + char cmdp = tolower(param_getchar(Cmd, 0)); if (strlen(Cmd) == 0 || cmdp == 'h') return usage_t55xx_chk(); - + /* if ( T55xxReadBlock(7, 0, 0, 0, 0) ) { - + // now try to validate it.. PrintAndLogEx(WARNING, "\n Block 7 was readable"); return 1; } */ - + uint64_t t1 = msclock(); - if ( cmdp == 'm' ) { + if ( cmdp == 'm' ) { UsbCommand c = {CMD_T55XX_CHKPWDS, {0,0,0} }; clearCommandBuffer(); SendCommand(&c); @@ -1547,15 +1547,15 @@ int CmdT55xxChkPwds(const char *Cmd) { return 2; } } - + if ( resp.arg[0] ) { PrintAndLogEx(SUCCESS, "\nFound a candidate [ %08X ]. Trying to validate", resp.arg[1]); - + if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, resp.arg[1])) { PrintAndLogEx(INFO, "Aquireing data from device failed. Quitting"); return 2; } - + found = tryDetectModulation(); if (found) { PrintAndLogEx(SUCCESS, "Found valid password: [ %08X ]", resp.arg[1]); @@ -1565,32 +1565,32 @@ int CmdT55xxChkPwds(const char *Cmd) { } else { PrintAndLogEx(WARNING, "Password NOT found."); } - + goto out; } - + keyBlock = calloc(stKeyBlock, 4); if (keyBlock == NULL) return 1; if (cmdp == 'i') { - + int len = strlen(Cmd+2); if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, Cmd+2, len); - - FILE * f = fopen( filename , "r"); + + FILE * f = fopen( filename , "r"); if ( !f ) { PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename); free(keyBlock); return 1; - } - + } + while( fgets(line, sizeof(line), f) ){ if (strlen(line) < 8 || line[7] == '\n') continue; - + //goto next line while (fgetc(f) != '\n' && !feof(f)) ; - + //The line start with # is comment, skip if( line[0]=='#' ) continue; @@ -1598,9 +1598,9 @@ int CmdT55xxChkPwds(const char *Cmd) { PrintAndLogEx(WARNING, "File content error. '%s' must include 8 HEX symbols", line); continue; } - - line[8] = 0; - + + line[8] = 0; + // realloc keyblock array size. if ( stKeyBlock - keycnt < 2) { p = realloc(keyBlock, 4 * (stKeyBlock += 10)); @@ -1615,24 +1615,24 @@ int CmdT55xxChkPwds(const char *Cmd) { } // clear mem memset(keyBlock + 4 * keycnt, 0, 4); - + num_to_bytes( strtoll(line, NULL, 16), 4, keyBlock + 4*keycnt); - + // PrintAndLogEx(NORMAL, "chk custom pwd[%2d] %08X", keycnt, bytes_to_num(keyBlock + 4 * keycnt, 4) ); - keycnt++; + keycnt++; memset(line, 0, sizeof(line)); } - + if (f) fclose(f); - + if (keycnt == 0) { PrintAndLogEx(WARNING, "No keys found in file"); free(keyBlock); return 1; } PrintAndLogEx(SUCCESS, "Loaded %d keys", keycnt); - + // loop uint64_t testpwd = 0x00; for (uint16_t c = 0; c < keycnt; ++c ) { @@ -1642,43 +1642,43 @@ int CmdT55xxChkPwds(const char *Cmd) { free(keyBlock); return 2; } - + if (IsCancelled()) { free(keyBlock); return 0; } - + testpwd = bytes_to_num(keyBlock + 4*c, 4); PrintAndLogEx(INFO, "Testing %08X", testpwd); - + if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, testpwd)) { PrintAndLogEx(INFO, "Aquireing data from device failed. Quitting"); free(keyBlock); return 0; } - + found = tryDetectModulation(); if ( found ) break; - + } - if ( found ) + if ( found ) PrintAndLogEx(SUCCESS, "Found valid password: [ %08X ]", testpwd); else - PrintAndLogEx(WARNING, "Password NOT found."); + PrintAndLogEx(WARNING, "Password NOT found."); } - + free(keyBlock); - + out: t1 = msclock() - t1; - PrintAndLogEx(SUCCESS, "\nTime in bruteforce: %.0f seconds\n", (float)t1/1000.0); + PrintAndLogEx(SUCCESS, "\nTime in bruteforce: %.0f seconds\n", (float)t1/1000.0); return 0; } int CmdT55xxBruteForce(const char *Cmd) { - + uint32_t start_password = 0x00000000; //start password uint32_t end_password = 0xFFFFFFFF; //end password uint32_t curr = 0; @@ -1687,52 +1687,52 @@ int CmdT55xxBruteForce(const char *Cmd) { char cmdp = tolower(param_getchar(Cmd, 0)); if (cmdp == 'h') return usage_t55xx_bruteforce(); - + uint64_t t1 = msclock(); // Try to read Block 7, first :) - + // incremental pwd range search start_password = param_get32ex(Cmd, 0, 0, 16); end_password = param_get32ex(Cmd, 1, 0, 16); - + curr = start_password; - + if ( start_password >= end_password ) { return usage_t55xx_bruteforce(); } - + PrintAndLogEx(INFO, "Search password range [%08X -> %08X]", start_password, end_password); while ( !found ){ printf("."); fflush(stdout); - + if (IsCancelled()) { return 0; } - + if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, true, curr)) { PrintAndLogEx(WARNING, "Aquiring data from device failed. Quitting"); return 0; } - + found = tryDetectModulation(); if (curr == end_password) break; curr++; } - + PrintAndLogEx(NORMAL, ""); - + if (found) PrintAndLogEx(SUCCESS, "Found valid password: [ %08X ]", curr); else PrintAndLogEx(WARNING, "Password NOT found. Last tried: [ %08X ]", --curr); t1 = msclock() - t1; - PrintAndLogEx(SUCCESS, "\nTime in bruteforce: %.0f seconds\n", (float)t1/1000.0); + PrintAndLogEx(SUCCESS, "\nTime in bruteforce: %.0f seconds\n", (float)t1/1000.0); return 0; } @@ -1745,7 +1745,7 @@ int tryOnePassword(uint32_t password) { if (tryDetectModulation()) return 1; - else + else return 0; } @@ -1767,14 +1767,14 @@ int CmdT55xxRecoverPW(const char *Cmd) { found = tryOnePassword(curr_password); if (found == -1) return 0; bit++; - + if (IsCancelled()) return 0; } // now try to use partial original password, since block 7 should have been completely // erased during the write sequence and it is possible that only partial password has been // written - // not sure from which end the bit bits are written, so try from both ends + // not sure from which end the bit bits are written, so try from both ends // from low bit to high bit bit = 0; while (bit < 32) { @@ -1789,7 +1789,7 @@ int CmdT55xxRecoverPW(const char *Cmd) { if (found == -1) return 0; bit++; prev_password = curr_password; - + if (IsCancelled()) return 0; } @@ -1809,7 +1809,7 @@ int CmdT55xxRecoverPW(const char *Cmd) { return 0; bit++; prev_password = curr_password; - + if (IsCancelled()) return 0; } @@ -1823,8 +1823,8 @@ int CmdT55xxRecoverPW(const char *Cmd) { return 0; } -// note length of data returned is different for different chips. -// some return all page 1 (64 bits) and others return just that block (32 bits) +// note length of data returned is different for different chips. +// some return all page 1 (64 bits) and others return just that block (32 bits) // unfortunately the 64 bits makes this more likely to get a false positive... bool tryDetectP1(bool getData) { uint8_t preamble[] = {1,1,1,0,0,0,0,0,0,0,0,1,0,1,0,1}; @@ -1841,13 +1841,13 @@ bool tryDetectP1(bool getData) { // try fsk clock detect. if successful it cannot be any other type of modulation... (in theory...) ans = fskClocks(&fc1, &fc2, (uint8_t *)&clk, &firstClockEdge); if (ans && ((fc1==10 && fc2==8) || (fc1==8 && fc2==5))) { - if ( FSKrawDemod("0 0", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + if ( FSKrawDemod("0 0", false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } - if ( FSKrawDemod("0 1", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + if ( FSKrawDemod("0 1", false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } @@ -1858,23 +1858,23 @@ bool tryDetectP1(bool getData) { clk = GetAskClock("", false); if (clk > 0) { if ( ASKDemod_ext("0 0 1", false, false, 1, &st) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } st = true; if ( ASKDemod_ext("0 1 1", false, false, 1, &st) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } if ( ASKbiphaseDemod("0 0 0 2", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } if ( ASKbiphaseDemod("0 0 1 2", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } @@ -1884,17 +1884,17 @@ bool tryDetectP1(bool getData) { clk = GetNrzClock("", false); //has the most false positives :( if (clk > 0) { if ( NRZrawDemod("0 0 1", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } if ( NRZrawDemod("0 1 1", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { return true; } } - + // Fewer card uses PSK // try psk clock detect. if successful it cannot be any other type of modulation... (in theory...) clk = GetPskClock("", false); @@ -1904,13 +1904,13 @@ bool tryDetectP1(bool getData) { // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise) //CmdLtrim("160"); if ( PSKDemod("0 0 6", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { //save_restoreGB(0); return true; } if ( PSKDemod("0 1 6", false) && - preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { //save_restoreGB(0); return true; @@ -1918,14 +1918,14 @@ bool tryDetectP1(bool getData) { // PSK2 - needs a call to psk1TOpsk2. if ( PSKDemod("0 0 6", false)) { psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && + if (preambleSearchEx(DemodBuffer, preamble, sizeof(preamble), &DemodBufferLen, &startIdx, false) && (DemodBufferLen == 32 || DemodBufferLen == 64) ) { //save_restoreGB(0); return true; } } // inverse waves does not affect PSK2 demod //undo trim samples - //save_restoreGB(0); + //save_restoreGB(0); // no other modulation clocks = 2 or 4 so quit searching if (fc1 != 8) return false; } @@ -2013,7 +2013,7 @@ int CmdT55xxSetDeviceConfig(const char *Cmd){ //Validations if (errors || cmdp == 0) return usage_lf_deviceconfig(); - + t55xx_config config = { startgap*8, writegap*8, write0*8, write1*8, readgap*8 }; UsbCommand c = {CMD_SET_LF_T55XX_CONFIG, {shall_persist,0,0} }; @@ -2036,7 +2036,7 @@ static command_t CommandTable[] = { {"read", CmdT55xxReadBlock, 0, "b p [password] [o] [1] -- Read T55xx block data. Optional [p password], [override], [page1]"}, {"resetread", CmdResetRead, 0, "Send Reset Cmd then lf read the stream to attempt to identify the start of it (needs a demod and/or plot after)"}, {"recoverpw", CmdT55xxRecoverPW, 0, "[password] Try to recover from bad password write from a cloner. Only use on PW protected chips!"}, - {"special", special, 0, "Show block changes with 64 different offsets"}, + {"special", special, 0, "Show block changes with 64 different offsets"}, {"trace", CmdT55xxReadTrace, 1, "[1] Show T55x7 traceability data (page 1/ blk 0-1)"}, {"wakeup", CmdT55xxWakeUp, 0, "Send AOR wakeup command"}, {"wipe", CmdT55xxWipe, 0, "[q] Wipe a T55xx tag and set defaults (will destroy any data on tag)"}, diff --git a/client/cmdlft55xx.h b/client/cmdlft55xx.h index 775f7ccca..c4e0fc98b 100644 --- a/client/cmdlft55xx.h +++ b/client/cmdlft55xx.h @@ -75,15 +75,15 @@ enum { typedef struct { uint32_t bl1; - uint32_t bl2; - uint32_t acl; - uint32_t mfc; - uint32_t cid; - uint32_t year; - uint32_t quarter; + uint32_t bl2; + uint32_t acl; + uint32_t mfc; + uint32_t cid; + uint32_t year; + uint32_t quarter; uint32_t icr; - uint32_t lotid; - uint32_t wafer; + uint32_t lotid; + uint32_t wafer; uint32_t dw; } t55x7_tracedata_t; @@ -99,18 +99,18 @@ typedef struct { typedef struct { enum { - DEMOD_NRZ = 0x00, + DEMOD_NRZ = 0x00, DEMOD_PSK1 = 0x01, DEMOD_PSK2 = 0x02, DEMOD_PSK3 = 0x03, - DEMOD_FSK1 = 0x04, - DEMOD_FSK1a = 0x05, - DEMOD_FSK2 = 0x06, - DEMOD_FSK2a = 0x07, - DEMOD_FSK = 0xF0, //generic FSK (auto detect FCs) + DEMOD_FSK1 = 0x04, + DEMOD_FSK1a = 0x05, + DEMOD_FSK2 = 0x06, + DEMOD_FSK2a = 0x07, + DEMOD_FSK = 0xF0, //generic FSK (auto detect FCs) DEMOD_ASK = 0x08, DEMOD_BI = 0x10, - DEMOD_BIa = 0x18, + DEMOD_BIa = 0x18, } modulation; bool inverted; uint8_t offset; diff --git a/client/cmdlfti.c b/client/cmdlfti.c index e5f3530f0..9928faf27 100644 --- a/client/cmdlfti.c +++ b/client/cmdlfti.c @@ -207,7 +207,7 @@ int CmdTIDemod(const char *Cmd) } RepaintGraphWindow(); - + PrintAndLogEx(INFO, "INFO: raw tag bits = %s", bits); TagType = (shift3>>8)&0xff; @@ -249,16 +249,16 @@ int CmdTIDemod(const char *Cmd) crc = update_crc16(crc, (shift1>>8)&0xff); crc = update_crc16(crc, (shift1>>16)&0xff); crc = update_crc16(crc, (shift1>>24)&0xff); - + //crc = crc16_ccitt(message, sizeof(message); char *crcStr = (crc == (shift2&0xffff) ) ? "Passed" : "Failed"; - + PrintAndLogEx(NORMAL, "Tag data = %08X%08X [Crc %04X %s]", shift1, shift0, crc, crcStr ); if (crc != (shift2&0xffff)) PrintAndLogEx(WARNING, "Error: CRC mismatch, calculated %04X, got %04X", crc, shift2&0xffff); - + } else { PrintAndLogEx(WARNING, "Unknown tag type."); diff --git a/client/cmdlfviking.c b/client/cmdlfviking.c index 33a5588d3..7f32ab5e5 100644 --- a/client/cmdlfviking.c +++ b/client/cmdlfviking.c @@ -52,18 +52,18 @@ int detectViking(uint8_t *dest, size_t *size) { if (*size < 64*2) return -2; size_t startIdx = 0; uint8_t preamble[] = {1,1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; - if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) + if (!preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx)) return -4; //preamble not found - - uint32_t checkCalc = bytebits_to_byte(dest+startIdx,8) ^ - bytebits_to_byte(dest+startIdx+8,8) ^ - bytebits_to_byte(dest+startIdx+16,8) ^ - bytebits_to_byte(dest+startIdx+24,8) ^ - bytebits_to_byte(dest+startIdx+32,8) ^ - bytebits_to_byte(dest+startIdx+40,8) ^ - bytebits_to_byte(dest+startIdx+48,8) ^ + + uint32_t checkCalc = bytebits_to_byte(dest+startIdx,8) ^ + bytebits_to_byte(dest+startIdx+8,8) ^ + bytebits_to_byte(dest+startIdx+16,8) ^ + bytebits_to_byte(dest+startIdx+24,8) ^ + bytebits_to_byte(dest+startIdx+32,8) ^ + bytebits_to_byte(dest+startIdx+40,8) ^ + bytebits_to_byte(dest+startIdx+48,8) ^ bytebits_to_byte(dest+startIdx+56,8); - if ( checkCalc != 0xA8 ) return -5; + if ( checkCalc != 0xA8 ) return -5; if (*size != 64) return -6; //return start position return (int)startIdx; @@ -108,18 +108,18 @@ int CmdVikingClone(const char *Cmd) { bool Q5 = false; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_viking_clone(); - + id = param_get32ex(Cmd, 0, 0, 16); if (id == 0) return usage_lf_viking_clone(); - + cmdp = param_getchar(Cmd, 1); if ( cmdp == 'Q' || cmdp == 'q') Q5 = true; rawID = getVikingBits(id); - + PrintAndLogEx(INFO, "Preparing to clone Viking tag - ID: %08X, Raw: %08X%08X",id,(uint32_t)(rawID >> 32),(uint32_t) (rawID & 0xFFFFFFFF)); - + UsbCommand c = {CMD_VIKING_CLONE_TAG, {rawID >> 32, rawID & 0xFFFFFFFF, Q5}}; clearCommandBuffer(); SendCommand(&c); @@ -150,7 +150,7 @@ int CmdVikingSim(const char *Cmd) { arg2 = invert << 8 | separator; PrintAndLogEx(SUCCESS, "Simulating Viking - ID: %08X, Raw: %08X%08X",id,(uint32_t)(rawID >> 32),(uint32_t) (rawID & 0xFFFFFFFF)); - + UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}}; num_to_bytebits(rawID, size, c.d.asBytes); clearCommandBuffer(); diff --git a/client/cmdlfvisa2000.c b/client/cmdlfvisa2000.c index 031894728..430aea8f4 100644 --- a/client/cmdlfvisa2000.c +++ b/client/cmdlfvisa2000.c @@ -56,7 +56,7 @@ static uint8_t visa_parity( uint32_t id) { ,1,0,0,1 ,1,0,0,1 ,0,1,1,0 - }; + }; uint8_t par = 0; par |= par_lut[ (id >> 28) & 0xF ] << 7; par |= par_lut[ (id >> 24) & 0xF ] << 6; @@ -66,7 +66,7 @@ static uint8_t visa_parity( uint32_t id) { par |= par_lut[ (id >> 8) & 0xF ] << 2; par |= par_lut[ (id >> 4) & 0xF ] << 1; par |= par_lut[ (id & 0xF) ]; - return par; + return par; } // by iceman @@ -91,15 +91,15 @@ int detectVisa2k(uint8_t *dest, size_t *size) { * i = card id * p = even parity bit for each nibble in card id. * c = checksum (xor of card id) -* +* **/ //see ASKDemod for what args are accepted int CmdVisa2kDemod(const char *Cmd) { - + save_restoreGB(GRAPH_SAVE); - + //sCmdAskEdgeDetect(""); - + //ASK / Manchester bool st = true; if (!ASKDemod_ext("64 0 0", false, false, 1, &st)) { @@ -124,18 +124,18 @@ int CmdVisa2kDemod(const char *Cmd) { } setDemodBuf(DemodBuffer, 96, ans); setClockGrid(g_DemodClock, g_DemodStartIdx + (ans*g_DemodClock)); - + //got a good demod uint32_t raw1 = bytebits_to_byte(DemodBuffer, 32); uint32_t raw2 = bytebits_to_byte(DemodBuffer+32, 32); uint32_t raw3 = bytebits_to_byte(DemodBuffer+64, 32); - + // chksum uint8_t calc = visa_chksum(raw2); - uint8_t chk = raw3 & 0xF; - + uint8_t chk = raw3 & 0xF; + // test checksums - if ( chk != calc ) { + if ( chk != calc ) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 checksum failed %x - %x\n", chk, calc); save_restoreGB(GRAPH_RESTORE); return 0; @@ -146,7 +146,7 @@ int CmdVisa2kDemod(const char *Cmd) { if ( calc_par != chk_par) { PrintAndLogEx(DEBUG, "DEBUG: error: Visa2000 parity failed %x - %x\n", chk_par, calc_par); save_restoreGB(GRAPH_RESTORE); - return 0; + return 0; } PrintAndLogEx(SUCCESS, "Visa2000 Tag Found: Card ID %u, Raw: %08X%08X%08X", raw2, raw1 ,raw2, raw3); return 1; @@ -167,17 +167,17 @@ int CmdVisa2kClone(const char *Cmd) { if (strlen(Cmd) == 0 || cmdp == 'h') return usage_lf_visa2k_clone(); id = param_get32ex(Cmd, 0, 0, 10); - + //Q5 if (param_getchar(Cmd, 1) == 'Q' || param_getchar(Cmd, 1) == 'q') blocks[0] = T5555_MODULATION_MANCHESTER | T5555_SET_BITRATE(64) | T5555_ST_TERMINATOR | 3 << T5555_MAXBLOCK_SHIFT; - + blocks[2] = id; - blocks[3] = (visa_parity(id) << 4) | visa_chksum(id); + blocks[3] = (visa_parity(id) << 4) | visa_chksum(id); PrintAndLogEx(INFO, "Preparing to clone Visa2000 to T55x7 with CardId: %u", id); print_blocks(blocks, 4); - + UsbCommand resp; UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}}; @@ -224,7 +224,7 @@ int CmdVisa2kSim(const char *Cmd) { static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdVisa2kDemod, 1, "demodulate an VISA2000 tag from the GraphBuffer"}, + {"demod", CmdVisa2kDemod, 1, "demodulate an VISA2000 tag from the GraphBuffer"}, {"read", CmdVisa2kRead, 0, "attempt to read and extract tag data from the antenna"}, {"clone", CmdVisa2kClone, 0, "clone Visa2000 to t55x7"}, {"sim", CmdVisa2kSim, 0, "simulate Visa2000 tag"}, diff --git a/client/cmdmain.c b/client/cmdmain.c index 9b71df21d..20e388b43 100644 --- a/client/cmdmain.c +++ b/client/cmdmain.c @@ -23,7 +23,7 @@ static command_t CommandTable[] = { {"hw", CmdHW, 1, "{ Hardware commands... }"}, {"lf", CmdLF, 1, "{ Low Frequency commands... }"}, {"emv", CmdEMV, 1, "{ EMV iso14443 and iso7816... }"}, - {"rem", CmdRem, 1, "{ Add text to row in log file }"}, + {"rem", CmdRem, 1, "{ Add text to row in log file }"}, {"reveng", CmdRev, 1, "{ Crc calculations from the RevEng software... }"}, {"script", CmdScript, 1, "{ Scripting commands }"}, {"trace", CmdTrace, 1, "{ Trace manipulation... }"}, diff --git a/client/cmdmain.h b/client/cmdmain.h index 629cd98af..a1ef64e1a 100644 --- a/client/cmdmain.h +++ b/client/cmdmain.h @@ -31,7 +31,7 @@ #include "cmdscript.h" #include "cmdcrc.h" #include "cmdanalyse.h" -#include "emv/cmdemv.h" // EMV +#include "emv/cmdemv.h" // EMV #ifdef WITH_FLASH #include "cmdflashmem.h" // rdv40 flashmem commands diff --git a/client/cmdparser.c b/client/cmdparser.c index 974439298..bbe7b2d8d 100644 --- a/client/cmdparser.c +++ b/client/cmdparser.c @@ -82,7 +82,7 @@ void dumpCommandsRecursive(const command_t cmds[], int markdown) { int i = 0; int w_cmd = 25; int w_off = 8; - // First, dump all single commands, which are not a container for + // First, dump all single commands, which are not a container for // other commands if (markdown) { PrintAndLogEx(NORMAL, "|%-*s|%-*s|%s\n",w_cmd,"command",w_off,"offline","description"); @@ -96,7 +96,7 @@ void dumpCommandsRecursive(const command_t cmds[], int markdown) { char* cmd_offline = "N"; if (cmds[i].Help[0] == '{' && ++i) continue; - if ( cmds[i].Offline) + if ( cmds[i].Offline) cmd_offline = "Y"; if (markdown) PrintAndLogEx(NORMAL, "|`%s%-*s`|%-*s|`%s`\n", parent, w_cmd-(int)strlen(parent)-2, cmds[i].Name, w_off, cmd_offline, cmds[i].Help); @@ -106,7 +106,7 @@ void dumpCommandsRecursive(const command_t cmds[], int markdown) { } PrintAndLogEx(NORMAL, "\n\n"); i = 0; - + // Then, print the categories. These will go into subsections with their own tables while (cmds[i].Name) { if(cmds[i].Help[0] != '{' && ++i) continue; @@ -118,7 +118,7 @@ void dumpCommandsRecursive(const command_t cmds[], int markdown) { char *old_parent = parent; parent = currentparent; // This is what causes the recursion, since commands Parse-implementation - // in turn calls the CmdsParse above. + // in turn calls the CmdsParse above. if (markdown) cmds[i].Parse("XX_internal_command_dump_markdown_XX"); else diff --git a/client/cmdparser.h b/client/cmdparser.h index 97b8f2813..eeb9a1460 100644 --- a/client/cmdparser.h +++ b/client/cmdparser.h @@ -9,7 +9,7 @@ //----------------------------------------------------------------------------- #ifndef CMDPARSER_H__ -#define CMDPARSER_H__ +#define CMDPARSER_H__ typedef struct command_s { diff --git a/client/cmdscript.c b/client/cmdscript.c index 7159fa70b..6ded9c1a9 100644 --- a/client/cmdscript.c +++ b/client/cmdscript.c @@ -63,7 +63,7 @@ bool endsWith(char* base, char* str) { } /** -* Generate a sorted list of available commands, what it does is +* Generate a sorted list of available commands, what it does is * generate a file listing of the script-directory for files * ending with .lua */ @@ -129,7 +129,7 @@ int CmdScriptRun(const char *Cmd) { if (!endsWith(script_name, ".lua")) { suffix = ".lua"; } - + char script_path[strlen(get_my_executable_directory()) + strlen(LUA_SCRIPTS_DIRECTORY) + strlen(script_name) + strlen(suffix) + 1]; strcpy(script_path, get_my_executable_directory()); strcat(script_path, LUA_SCRIPTS_DIRECTORY); diff --git a/client/cmdsmartcard.c b/client/cmdsmartcard.c index f371c87ce..42d777ee4 100644 --- a/client/cmdsmartcard.c +++ b/client/cmdsmartcard.c @@ -36,7 +36,7 @@ int usage_sm_reader(void) { PrintAndLogEx(NORMAL, " s : silent (no messages)"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " sc reader"); + PrintAndLogEx(NORMAL, " sc reader"); return 0; } int usage_sm_info(void) { @@ -45,7 +45,7 @@ int usage_sm_info(void) { PrintAndLogEx(NORMAL, " s : silent (no messages)"); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " sc info"); + PrintAndLogEx(NORMAL, " sc info"); return 0; } int usage_sm_upgrade(void) { @@ -64,7 +64,7 @@ int usage_sm_setclock(void) { PrintAndLogEx(NORMAL, " c <> : clockspeed (0 = 16mhz, 1=8mhz, 2=4mhz) "); PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, "Examples:"); - PrintAndLogEx(NORMAL, " sc setclock c 2"); + PrintAndLogEx(NORMAL, " sc setclock c 2"); return 0; } int usage_sm_brute(void) { @@ -93,29 +93,29 @@ static int smart_loadjson(const char *preferredName, const char *suffix, json_t *root = json_load_file(fileName, 0, &error); if (!*root) { PrintAndLogEx(ERR, "json (%s) error on line %d: %s", fileName, error.line, error.text); - retval = 2; + retval = 2; goto out; } - + if (!json_is_array(*root)) { PrintAndLogEx(ERR, "Invalid json (%s) format. root must be an array.", fileName); - retval = 3; + retval = 3; goto out; } PrintAndLogEx(SUCCESS, "Loaded file (%s) OK.", fileName); -out: +out: free(fileName); - return retval; + return retval; } uint8_t GetATRTA1(uint8_t *atr, size_t atrlen) { - if (atrlen > 2) { + if (atrlen > 2) { uint8_t T0 = atr[1]; if (T0 & 0x10) return atr[2]; } - + return 0x11; // default value is ‘0x11’, corresponding to fmax=5 MHz, Fi=372, Di=1. } @@ -178,7 +178,7 @@ float FArray[] = { int GetATRDi(uint8_t *atr, size_t atrlen) { uint8_t TA1 = GetATRTA1(atr, atrlen); - return DiArray[TA1 & 0x0F]; // The 4 low-order bits of TA1 (4th MSbit to 1st LSbit) encode Di + return DiArray[TA1 & 0x0F]; // The 4 low-order bits of TA1 (4th MSbit to 1st LSbit) encode Di } int GetATRFi(uint8_t *atr, size_t atrlen) { @@ -192,31 +192,31 @@ float GetATRF(uint8_t *atr, size_t atrlen) { } static int PrintATR(uint8_t *atr, size_t atrlen) { - + uint8_t T0 = atr[1]; uint8_t K = T0 & 0x0F; uint8_t TD1 = 0, T1len = 0, TD1len = 0, TDilen = 0; - + if (T0 & 0x10) { PrintAndLog("\t- TA1 (Maximum clock frequency, proposed bit duration) [ 0x%02x ]", atr[2 + T1len]); T1len++; } - + if (T0 & 0x20) { PrintAndLog("\t- TB1 (Deprecated: VPP requirements) [ 0x%02x ]", atr[2 + T1len]); T1len++; } - + if (T0 & 0x40) { PrintAndLog("\t- TC1 (Extra delay between bytes required by card) [ 0x%02x ]", atr[2 + T1len]); T1len++; } - + if (T0 & 0x80) { TD1 = atr[2 + T1len]; PrintAndLog("\t- TD1 (First offered transmission protocol, presence of TA2..TD2) [ 0x%02x ] Protocol T%d", TD1, TD1 & 0x0f); T1len++; - + if (TD1 & 0x10) { PrintAndLog("\t- TA2 (Specific protocol and parameters to be used after the ATR) [ 0x%02x ]", atr[2 + T1len + TD1len]); TD1len++; @@ -254,7 +254,7 @@ static int PrintATR(uint8_t *atr, size_t atrlen) { TDi = atr[2 + T1len + TD1len + TDilen]; PrintAndLog("\t- TD%d [ 0x%02x ] Protocol T%d", vi, TDi, TDi & 0x0f); TDilen++; - + nextCycle = true; vi++; } @@ -265,7 +265,7 @@ static int PrintATR(uint8_t *atr, size_t atrlen) { uint8_t vxor = 0; for (int i = 1; i < atrlen; i++) vxor ^= atr[i]; - + if (vxor) PrintAndLogEx(WARNING, "Check summ error. Must be 0 got 0x%02X", vxor); else @@ -274,26 +274,26 @@ static int PrintATR(uint8_t *atr, size_t atrlen) { if (atr[0] != 0x3b) PrintAndLogEx(WARNING, "Not a direct convention [ 0x%02x ]", atr[0]); - + uint8_t calen = 2 + T1len + TD1len + TDilen + K; - + if (atrlen != calen && atrlen != calen + 1) // may be CRC PrintAndLogEx(ERR, "ATR length error. len: %d, T1len: %d, TD1len: %d, TDilen: %d, K: %d", atrlen, T1len, TD1len, TDilen, K); - + if (K > 0) PrintAndLogEx(INFO, "\nHistorical bytes | len 0x%02d | format %02x", K, atr[2 + T1len + TD1len + TDilen]); - + if (K > 1) { PrintAndLogEx(INFO, "\tHistorical bytes"); dump_buffer(&atr[2 + T1len + TD1len + TDilen], K, NULL, 1); } - + return 0; } bool smart_select(bool silent, smart_card_atr_t *atr) { if (atr) - memset(atr, 0, sizeof(smart_card_atr_t)); + memset(atr, 0, sizeof(smart_card_atr_t)); UsbCommand c = {CMD_SMART_ATR, {0, 0, 0}}; clearCommandBuffer(); @@ -303,21 +303,21 @@ bool smart_select(bool silent, smart_card_atr_t *atr) { if (!silent) PrintAndLogEx(WARNING, "smart card select failed"); return false; } - + uint8_t isok = resp.arg[0] & 0xFF; if (!isok) { if (!silent) PrintAndLogEx(WARNING, "smart card select failed"); return false; - } + } smart_card_atr_t card; memcpy(&card, (smart_card_atr_t *)resp.d.asBytes, sizeof(smart_card_atr_t)); if (atr) - memcpy(atr, &card, sizeof(smart_card_atr_t)); + memcpy(atr, &card, sizeof(smart_card_atr_t)); if (!silent) - PrintAndLogEx(INFO, "ISO7816-3 ATR : %s", sprint_hex(card.atr, card.atr_len)); + PrintAndLogEx(INFO, "ISO7816-3 ATR : %s", sprint_hex(card.atr, card.atr_len)); return true; } @@ -328,27 +328,27 @@ static int smart_wait(uint8_t *data, bool silent) { if (!silent) PrintAndLogEx(WARNING, "smart card response timeout"); return -1; } - - uint32_t len = resp.arg[0]; + + uint32_t len = resp.arg[0]; if ( !len ) { if (!silent) PrintAndLogEx(WARNING, "smart card response failed"); - return -2; + return -2; } - memcpy(data, resp.d.asBytes, len); - if (len >= 2) { - if (!silent) PrintAndLogEx(SUCCESS, "%02X%02X | %s", data[len - 2], data[len - 1], GetAPDUCodeDescription(data[len - 2], data[len - 1])); + memcpy(data, resp.d.asBytes, len); + if (len >= 2) { + if (!silent) PrintAndLogEx(SUCCESS, "%02X%02X | %s", data[len - 2], data[len - 1], GetAPDUCodeDescription(data[len - 2], data[len - 1])); } else { if (!silent) PrintAndLogEx(SUCCESS, " %d | %s", len, sprint_hex_inrow_ex(data, len, 8)); } - + return len; } static int smart_responseEx(uint8_t *data, bool silent) { - - int datalen = smart_wait(data, silent); + + int datalen = smart_wait(data, silent); bool needGetData = false; - + if (datalen < 2 ) { goto out; } @@ -359,9 +359,9 @@ static int smart_responseEx(uint8_t *data, bool silent) { if (needGetData) { int len = data[datalen - 1]; - if (!silent) PrintAndLogEx(INFO, "Requesting 0x%02X bytes response", len); + if (!silent) PrintAndLogEx(INFO, "Requesting 0x%02X bytes response", len); uint8_t getstatus[] = {0x00, ISO7816_GET_RESPONSE, 0x00, 0x00, len}; - UsbCommand cStatus = {CMD_SMART_RAW, {SC_RAW, sizeof(getstatus), 0}}; + UsbCommand cStatus = {CMD_SMART_RAW, {SC_RAW, sizeof(getstatus), 0}}; memcpy(cStatus.d.asBytes, getstatus, sizeof(getstatus) ); clearCommandBuffer(); SendCommand(&cStatus); @@ -371,14 +371,14 @@ static int smart_responseEx(uint8_t *data, bool silent) { if (datalen < 2 ) { goto out; } - + // data wo ACK - if (datalen != len + 2) { + if (datalen != len + 2) { // data with ACK if (datalen == len + 2 + 1) { // 2 - response, 1 - ACK if (data[0] != ISO7816_GET_RESPONSE) { if (!silent) { - PrintAndLogEx(ERR, "GetResponse ACK error. len 0x%x | data[0] %02X", len, data[0]); + PrintAndLogEx(ERR, "GetResponse ACK error. len 0x%x | data[0] %02X", len, data[0]); } datalen = 0; goto out; @@ -389,12 +389,12 @@ static int smart_responseEx(uint8_t *data, bool silent) { } else { // wrong length if (!silent) { - PrintAndLogEx(WARNING, "GetResponse wrong length. Must be 0x%02X got 0x%02X", len, datalen - 3); + PrintAndLogEx(WARNING, "GetResponse wrong length. Must be 0x%02X got 0x%02X", len, datalen - 3); } } } } - + out: return datalen; } @@ -407,15 +407,15 @@ int CmdSmartRaw(const char *Cmd) { int hexlen = 0; bool active = false; - bool active_select = false; - bool useT0 = false; + bool active_select = false; + bool useT0 = false; uint8_t cmdp = 0; bool errors = false, reply = true, decodeTLV = false, breakloop = false; uint8_t data[USB_CMD_DATA_SIZE] = {0x00}; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { - case 'h': return usage_sm_raw(); + case 'h': return usage_sm_raw(); case 'r': reply = false; cmdp++; @@ -431,11 +431,11 @@ int CmdSmartRaw(const char *Cmd) { case 't': decodeTLV = true; cmdp++; - break; + break; case '0': useT0 = true; cmdp++; - break; + break; case 'd': { switch (param_gethex_to_eol(Cmd, cmdp+1, data, sizeof(data), &hexlen)) { case 1: @@ -461,14 +461,14 @@ int CmdSmartRaw(const char *Cmd) { if ( breakloop ) break; } - + //Validations - if (errors || cmdp == 0 ) return usage_sm_raw(); + if (errors || cmdp == 0 ) return usage_sm_raw(); // arg0 = RFU flags // arg1 = length - UsbCommand c = {CMD_SMART_RAW, {0, hexlen, 0}}; - + UsbCommand c = {CMD_SMART_RAW, {0, hexlen, 0}}; + if (active || active_select) { c.arg[0] |= SC_CONNECT; if (active_select) @@ -480,28 +480,28 @@ int CmdSmartRaw(const char *Cmd) { c.arg[0] |= SC_RAW_T0; else c.arg[0] |= SC_RAW; - } - + } + memcpy(c.d.asBytes, data, hexlen ); clearCommandBuffer(); - SendCommand(&c); - + SendCommand(&c); + // reading response from smart card if ( reply ) { uint8_t* buf = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t)); if ( !buf ) - return 1; - + return 1; + int len = smart_response(buf); if ( len < 0 ) { free(buf); return 2; } - + if ( buf[0] == 0x6C ) { data[4] = buf[1]; - + memcpy(c.d.asBytes, data, sizeof(data) ); clearCommandBuffer(); SendCommand(&c); @@ -520,54 +520,54 @@ int CmdSmartRaw(const char *Cmd) { int ExchangeAPDUSC(uint8_t *datain, int datainlen, bool activateCard, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { *dataoutlen = 0; - + if (activateCard) smart_select(false, NULL); PrintAndLogEx(DEBUG, "APDU SC"); - UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, datainlen, 0}}; + UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, datainlen, 0}}; if (activateCard) { c.arg[0] |= SC_SELECT | SC_CONNECT; } memcpy(c.d.asBytes, datain, datainlen); clearCommandBuffer(); - SendCommand(&c); - + SendCommand(&c); + int len = smart_responseEx(dataout, true); - + if ( len < 0 ) { return 1; } - + // retry if (len > 1 && dataout[len - 2] == 0x6c && datainlen > 4) { - UsbCommand c2 = {CMD_SMART_RAW, {SC_RAW_T0, datainlen, 0}}; + UsbCommand c2 = {CMD_SMART_RAW, {SC_RAW_T0, datainlen, 0}}; memcpy(c2.d.asBytes, datain, 5); - + // transfer length via T=0 c2.d.asBytes[4] = dataout[len - 1]; - + clearCommandBuffer(); - SendCommand(&c2); - + SendCommand(&c2); + len = smart_responseEx(dataout, true); - } - + } + *dataoutlen = len; return 0; -} +} int CmdSmartUpgrade(const char *Cmd) { PrintAndLogEx(WARNING, "WARNING - Smartcard socket firmware upgrade."); PrintAndLogEx(WARNING, "A dangerous command, do wrong and you will brick the smart card socket"); - + FILE *f; char filename[FILE_PATH_SIZE] = {0}; uint8_t cmdp = 0; bool errors = false; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'f': @@ -576,8 +576,8 @@ int CmdSmartUpgrade(const char *Cmd) { PrintAndLogEx(FAILED, "Filename too long"); errors = true; break; - } - cmdp += 2; + } + cmdp += 2; break; case 'h': return usage_sm_upgrade(); @@ -587,17 +587,17 @@ int CmdSmartUpgrade(const char *Cmd) { break; } } - + //Validations - if (errors || cmdp == 0 ) return usage_sm_upgrade(); - + if (errors || cmdp == 0 ) return usage_sm_upgrade(); + // load file f = fopen(filename, "rb"); if ( !f ){ PrintAndLogEx(FAILED, "File: " _YELLOW_(%s) ": not found or locked.", filename); return 1; - } - + } + // get filesize in order to malloc memory fseek(f, 0, SEEK_END); long fsize = ftell(f); @@ -608,18 +608,18 @@ int CmdSmartUpgrade(const char *Cmd) { fclose(f); return 1; } - + uint8_t *dump = calloc(fsize, sizeof(uint8_t)); if (!dump) { PrintAndLogDevice(WARNING, "error, cannot allocate memory "); fclose(f); return 1; } - + size_t bytes_read = fread(dump, 1, fsize, f); if (f) fclose(f); - + PrintAndLogEx(SUCCESS, "Smartcard socket firmware uploading to PM3"); //Send to device uint32_t index = 0; @@ -627,20 +627,20 @@ int CmdSmartUpgrade(const char *Cmd) { uint32_t bytes_remaining = bytes_read; while (bytes_remaining > 0){ - uint32_t bytes_in_packet = MIN(USB_CMD_DATA_SIZE, bytes_remaining); + uint32_t bytes_in_packet = MIN(USB_CMD_DATA_SIZE, bytes_remaining); UsbCommand c = {CMD_SMART_UPLOAD, {index + bytes_sent, bytes_in_packet, 0}}; // Fill usb bytes with 0xFF memset(c.d.asBytes, 0xFF, USB_CMD_DATA_SIZE); memcpy(c.d.asBytes, dump + bytes_sent, bytes_in_packet); clearCommandBuffer(); - SendCommand(&c); + SendCommand(&c); if ( !WaitForResponseTimeout(CMD_ACK, NULL, 2000) ) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); free(dump); return 1; } - + bytes_remaining -= bytes_in_packet; bytes_sent += bytes_in_packet; printf("."); fflush(stdout); @@ -648,9 +648,9 @@ int CmdSmartUpgrade(const char *Cmd) { free(dump); printf("\n"); PrintAndLogEx(SUCCESS, "Smartcard socket firmware updating, don\'t turn off your PM3!"); - + // trigger the firmware upgrade - UsbCommand c = {CMD_SMART_UPGRADE, {bytes_read, 0, 0}}; + UsbCommand c = {CMD_SMART_UPGRADE, {bytes_read, 0, 0}}; clearCommandBuffer(); SendCommand(&c); UsbCommand resp; @@ -668,13 +668,13 @@ int CmdSmartUpgrade(const char *Cmd) { int CmdSmartInfo(const char *Cmd){ uint8_t cmdp = 0; bool errors = false, silent = false; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_sm_info(); - case 's': + case 's': silent = true; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -682,10 +682,10 @@ int CmdSmartInfo(const char *Cmd){ } cmdp++; } - + //Validations if (errors ) return usage_sm_info(); - + UsbCommand c = {CMD_SMART_ATR, {0, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -694,16 +694,16 @@ int CmdSmartInfo(const char *Cmd){ if (!silent) PrintAndLogEx(WARNING, "smart card select failed"); return 1; } - + uint8_t isok = resp.arg[0] & 0xFF; if (!isok) { if (!silent) PrintAndLogEx(WARNING, "smart card select failed"); return 1; - } - + } + smart_card_atr_t card; memcpy(&card, (smart_card_atr_t *)resp.d.asBytes, sizeof(smart_card_atr_t)); - + // print header PrintAndLogEx(INFO, "--- Smartcard Information ---------"); PrintAndLogEx(INFO, "-------------------------------------------------------------"); @@ -714,7 +714,7 @@ int CmdSmartInfo(const char *Cmd){ PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "ATR"); PrintATR(card.atr, card.atr_len); - + // print D/F (brom byte TA1 or defaults) PrintAndLogEx(NORMAL, ""); PrintAndLogEx(INFO, "D/F (TA1)"); @@ -723,11 +723,11 @@ int CmdSmartInfo(const char *Cmd){ float F = GetATRF(card.atr, card.atr_len); if (GetATRTA1(card.atr, card.atr_len) == 0x11) PrintAndLogEx(INFO, "Using default values..."); - + PrintAndLogEx(NORMAL, "\t- Di %d", Di); PrintAndLogEx(NORMAL, "\t- Fi %d", Fi); PrintAndLogEx(NORMAL, "\t- F %.1f MHz", F); - + if (Di && Fi) { PrintAndLogEx(NORMAL, "\t- Cycles/ETU %d", Fi/Di); PrintAndLogEx(NORMAL, "\t- %.1f bits/sec at 4MHz", (float)4000000 / (Fi/Di)); @@ -742,24 +742,24 @@ int CmdSmartInfo(const char *Cmd){ int CmdSmartReader(const char *Cmd){ uint8_t cmdp = 0; bool errors = false, silent = false; - + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_sm_reader(); - case 's': + case 's': silent = true; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; break; } - cmdp++; + cmdp++; } - + //Validations if (errors ) return usage_sm_reader(); - + UsbCommand c = {CMD_SMART_ATR, {0, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -768,16 +768,16 @@ int CmdSmartReader(const char *Cmd){ if (!silent) PrintAndLogEx(WARNING, "smart card select failed"); return 1; } - + uint8_t isok = resp.arg[0] & 0xFF; if (!isok) { if (!silent) PrintAndLogEx(WARNING, "smart card select failed"); return 1; - } + } smart_card_atr_t card; memcpy(&card, (smart_card_atr_t *)resp.d.asBytes, sizeof(smart_card_atr_t)); - - PrintAndLogEx(INFO, "ISO7816-3 ATR : %s", sprint_hex(card.atr, card.atr_len)); + + PrintAndLogEx(INFO, "ISO7816-3 ATR : %s", sprint_hex(card.atr, card.atr_len)); return 0; } @@ -788,23 +788,23 @@ int CmdSmartSetClock(const char *Cmd){ while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_sm_setclock(); - case 'c': + case 'c': clock = param_get8ex(Cmd, cmdp+1, 2, 10); if ( clock > 2) errors = true; - + cmdp += 2; - break; + break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; break; } } - + //Validations if (errors || cmdp == 0) return usage_sm_setclock(); - + UsbCommand c = {CMD_SMART_SETCLOCK, {clock, 0, 0}}; clearCommandBuffer(); SendCommand(&c); @@ -813,15 +813,15 @@ int CmdSmartSetClock(const char *Cmd){ PrintAndLogEx(WARNING, "smart card select failed"); return 1; } - + uint8_t isok = resp.arg[0] & 0xFF; if (!isok) { PrintAndLogEx(WARNING, "smart card set clock failed"); return 1; } - + switch (clock) { - case 0: + case 0: PrintAndLogEx(SUCCESS, "Clock changed to 16mhz giving 10800 baudrate"); break; case 1: @@ -844,36 +844,36 @@ int CmdSmartList(const char *Cmd) { static void smart_brute_prim(){ uint8_t* buf = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t)); - if ( !buf ) + if ( !buf ) return; - + int len = 0; - uint8_t get_card_data[] = { + uint8_t get_card_data[] = { 0x80, 0xCA, 0x9F, 0x13, 0x00, 0x80, 0xCA, 0x9F, 0x17, 0x00, 0x80, 0xCA, 0x9F, 0x36, 0x00, 0x80, 0xCA, 0x9F, 0x4f, 0x00 }; - - UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, 5, 0}}; - + + UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, 5, 0}}; + PrintAndLogEx(INFO, "Reading primitives"); for (int i = 0; i < sizeof(get_card_data); i += 5) { - + memcpy(c.d.asBytes, get_card_data+i, 5 ); clearCommandBuffer(); SendCommand(&c); - + len = smart_responseEx(buf, true); if ( len > 2 ) { - + //if ( decodeTLV ) { //if (!TLVPrintFromBuffer(buf, len-2)) { PrintAndLogEx(SUCCESS, "\tHEX %d |: %s", len, sprint_hex(buf, len)); //} - //} + //} } len = 0; } @@ -883,20 +883,20 @@ static void smart_brute_prim(){ static int smart_brute_sfi(bool decodeTLV){ uint8_t* buf = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t)); - if ( !buf ) + if ( !buf ) return 1; - + int len = 0; // READ RECORD uint8_t READ_RECORD[] = {0x00, 0xB2, 0x00, 0x00, 0x00}; - UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, sizeof(READ_RECORD), 0}}; + UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, sizeof(READ_RECORD), 0}}; PrintAndLogEx(INFO, "Start SFI brute forcing"); - + for (uint8_t sfi=1; sfi <= 31; sfi++) { printf("."); fflush(stdout); - + for (uint16_t rec=1; rec <= 255; rec++) { if (ukbhit()) { @@ -904,40 +904,40 @@ static int smart_brute_sfi(bool decodeTLV){ PrintAndLogEx(NORMAL, "\naborted via keyboard!\n"); free(buf); return 1; - } - + } + READ_RECORD[2] = rec; READ_RECORD[3] = (sfi << 3) | 4; memcpy(c.d.asBytes, READ_RECORD, sizeof(READ_RECORD) ); clearCommandBuffer(); SendCommand(&c); - + len = smart_responseEx(buf, true); - + if ( buf[0] == 0x6C ) { READ_RECORD[4] = buf[1]; - + memcpy(c.d.asBytes, READ_RECORD, sizeof(READ_RECORD) ); clearCommandBuffer(); SendCommand(&c); len = smart_responseEx(buf, true); - - READ_RECORD[4] = 0; + + READ_RECORD[4] = 0; } - + if ( len > 4 ) { - + PrintAndLogEx(SUCCESS, "\n\t file %02d, record %02d found", sfi, rec); - + uint8_t modifier = (buf[0] == 0xC0) ? 1 : 0; - + if ( decodeTLV ) { if (!TLVPrintFromBuffer(buf + modifier, len-2-modifier)) { PrintAndLogEx(SUCCESS, "\tHEX: %s", sprint_hex(buf, len)); } - } - } + } + } memset(buf, 0x00, USB_CMD_DATA_SIZE); } } @@ -948,77 +948,77 @@ static int smart_brute_sfi(bool decodeTLV){ static void smart_brute_options(bool decodeTLV) { uint8_t* buf = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t)); - if ( !buf ) + if ( !buf ) return; - + uint8_t GET_PROCESSING_OPTIONS[] = {0x80, 0xA8, 0x00, 0x00, 0x02, 0x83, 0x00, 0x00}; - + // Get processing options command - UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, sizeof(GET_PROCESSING_OPTIONS), 0}}; - memcpy(c.d.asBytes, GET_PROCESSING_OPTIONS, sizeof(GET_PROCESSING_OPTIONS) ); + UsbCommand c = {CMD_SMART_RAW, {SC_RAW_T0, sizeof(GET_PROCESSING_OPTIONS), 0}}; + memcpy(c.d.asBytes, GET_PROCESSING_OPTIONS, sizeof(GET_PROCESSING_OPTIONS) ); clearCommandBuffer(); SendCommand(&c); - + int len = smart_responseEx(buf, true); if ( len > 4 ) { - PrintAndLogEx(SUCCESS, "Got processing options"); + PrintAndLogEx(SUCCESS, "Got processing options"); if ( decodeTLV ) { TLVPrintFromBuffer(buf, len-2); } } else { PrintAndLogEx(FAILED, "Getting processing options failed"); } - + free(buf); } int CmdSmartBruteforceSFI(const char *Cmd) { uint8_t cmdp = 0; - bool errors = false, decodeTLV = false; //, useT0 = false; - + bool errors = false, decodeTLV = false; //, useT0 = false; + while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { switch (tolower(param_getchar(Cmd, cmdp))) { - case 'h': return usage_sm_brute(); + case 'h': return usage_sm_brute(); case 't': decodeTLV = true; cmdp++; break; -/* +/* case '0': useT0 = true; cmdp++; break; -*/ +*/ default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; break; } } - - //Validations - if (errors) return usage_sm_brute(); - const char *SELECT = "00a40400%02x%s"; - + //Validations + if (errors) return usage_sm_brute(); + + const char *SELECT = "00a40400%02x%s"; + // uint8_t GENERATE_AC[] = {0x80, 0xAE}; // uint8_t GET_CHALLENGE[] = {0x00, 0x84, 0x00}; // uint8_t GET_DATA[] = {0x80, 0xCA, 0x00, 0x00, 0x00}; // uint8_t SELECT[] = {0x00, 0xA4, 0x04, 0x00}; // uint8_t UNBLOCK_PIN[] = {0x84, 0x24, 0x00, 0x00, 0x00}; // uint8_t VERIFY[] = {0x00, 0x20, 0x00, 0x80}; - + // Select AID command - UsbCommand cAid = {CMD_SMART_RAW, {SC_RAW_T0, 0, 0}}; - + UsbCommand cAid = {CMD_SMART_RAW, {SC_RAW_T0, 0, 0}}; + PrintAndLogEx(INFO, "Importing AID list"); json_t *root = NULL; smart_loadjson("aidlist", "json", &root); uint8_t* buf = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t)); if ( !buf ) - return 1; + return 1; PrintAndLogEx(INFO, "Selecting card"); if ( !smart_select(false, NULL) ) { @@ -1027,14 +1027,14 @@ int CmdSmartBruteforceSFI(const char *Cmd) { } char* caid = NULL; - + for (int i = 0; i < json_array_size(root); i++) { - + printf("+"); fflush(stdout); if (caid) free(caid); - + json_t *data, *jaid; data = json_array_get(root, i); @@ -1043,47 +1043,47 @@ int CmdSmartBruteforceSFI(const char *Cmd) { json_decref(root); return 1; } - + jaid = json_object_get(data, "AID"); if (!json_is_string(jaid)) { PrintAndLogEx(ERR, "AID data [%d] is not a string", i + 1); json_decref(root); return 1; } - + const char* aid = json_string_value(jaid); - if ( !aid ) + if ( !aid ) continue; size_t aidlen = strlen(aid); caid = calloc( 8+2+aidlen+1, sizeof(uint8_t)); - snprintf(caid, 8+2+aidlen+1, SELECT, aidlen >> 1, aid); - + snprintf(caid, 8+2+aidlen+1, SELECT, aidlen >> 1, aid); + int hexlen = 0; int res = param_gethex_to_eol(caid, 0, cAid.d.asBytes, sizeof(cAid.d.asBytes), &hexlen); - if ( res ) + if ( res ) continue; - + cAid.arg[1] = hexlen; clearCommandBuffer(); - SendCommand(&cAid); - - int len = smart_responseEx(buf, true); + SendCommand(&cAid); + + int len = smart_responseEx(buf, true); if ( len < 3 ) continue; - + json_t *jvendor, *jname; jvendor = json_object_get(data, "Vendor"); if (!json_is_string(jvendor)) { PrintAndLogEx(ERR, "Vendor data [%d] is not a string", i + 1); continue; } - + const char* vendor = json_string_value(jvendor); if ( !vendor ) continue; - + jname = json_object_get(data, "Name"); if (!json_is_string(jname)) { PrintAndLogEx(ERR, "Name data [%d] is not a string", i + 1); @@ -1104,19 +1104,19 @@ int CmdSmartBruteforceSFI(const char *Cmd) { PrintAndLogEx(SUCCESS, "\nSFI brute force done\n"); } - if (caid) + if (caid) free(caid); - + free(buf); json_decref(root); - + PrintAndLogEx(SUCCESS, "\nSearch completed."); return 0; } static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"list", CmdSmartList, 0, "List ISO 7816 history"}, + {"list", CmdSmartList, 0, "List ISO 7816 history"}, {"info", CmdSmartInfo, 1, "Tag information"}, {"reader", CmdSmartReader, 1, "Act like an IS07816 reader"}, {"raw", CmdSmartRaw, 1, "Send raw hex data to tag"}, diff --git a/client/cmdtrace.c b/client/cmdtrace.c index cf55970b0..a93195635 100644 --- a/client/cmdtrace.c +++ b/client/cmdtrace.c @@ -14,7 +14,7 @@ static int CmdHelp(const char *Cmd); // trace pointer static uint8_t *trace; long traceLen = 0; - + int usage_trace_list(){ PrintAndLogEx(NORMAL, "List protocol data in trace buffer."); PrintAndLogEx(NORMAL, "Usage: trace list [f][c| <0|1>"); @@ -30,7 +30,7 @@ int usage_trace_list(){ PrintAndLogEx(NORMAL, " des - interpret data as DESFire communications"); #ifdef WITH_EMV PrintAndLogEx(NORMAL, " emv - interpret data as EMV / communications"); -#endif +#endif PrintAndLogEx(NORMAL, " iclass - interpret data as iclass communications"); PrintAndLogEx(NORMAL, " topaz - interpret data as topaz communications"); PrintAndLogEx(NORMAL, " 7816 - interpret data as iso7816-4 communications"); @@ -62,7 +62,7 @@ bool is_last_record(uint16_t tracepos, uint8_t *trace, uint16_t traceLen) { } bool next_record_is_response(uint16_t tracepos, uint8_t *trace) { - uint16_t next_records_datalen = *((uint16_t *)(trace + tracepos + sizeof(uint32_t) + sizeof(uint16_t))); + uint16_t next_records_datalen = *((uint16_t *)(trace + tracepos + sizeof(uint32_t) + sizeof(uint16_t))); return(next_records_datalen & 0x8000); } @@ -100,7 +100,7 @@ bool merge_topaz_reader_frames(uint32_t timestamp, uint32_t *duration, uint16_t } *duration = last_timestamp - timestamp; - + return true; } @@ -116,7 +116,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui uint8_t mfData[32] = {0}; size_t mfDataLen = 0; - + first_timestamp = *((uint32_t *)(trace)); timestamp = *((uint32_t *)(trace + tracepos)); tracepos += 4; @@ -150,7 +150,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui frame = topaz_reader_command; } } - + //Check the CRC status uint8_t crcStatus = 2; @@ -165,8 +165,8 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui crcStatus = iso14443B_CRC_check(frame, data_len); break; case PROTO_MIFARE: - crcStatus = mifare_CRC_check(isResponse, frame, data_len); - break; + crcStatus = mifare_CRC_check(isResponse, frame, data_len); + break; case ISO_14443A: case MFDES: crcStatus = iso14443A_CRC_check(isResponse, frame, data_len); @@ -175,7 +175,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui crcStatus = iso15693_CRC_check(frame, data_len); break; case ISO_7816_4: - default: + default: break; } } @@ -190,11 +190,11 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui uint8_t parityBits = parityBytes[j >> 3]; if (protocol != LEGIC && - protocol != ISO_14443B && + protocol != ISO_14443B && protocol != ISO_7816_4 && (isResponse || protocol == ISO_14443A) && (oddparity8(frame[j]) != ((parityBits >> (7-(j&0x0007))) & 0x01))) { - + snprintf(line[j/18]+(( j % 18) * 4),110, "%02x! ", frame[j]); } else { snprintf(line[j/18]+(( j % 18) * 4),110, "%02x ", frame[j]); @@ -228,7 +228,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui if ( protocol == PROTO_MIFARE ) annotateMifare(explanation, sizeof(explanation), frame, data_len, parityBytes, parity_len, isResponse); - + if (!isResponse) { switch(protocol) { case ICLASS: annotateIclass(explanation,sizeof(explanation),frame,data_len); break; @@ -274,7 +274,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui }; if (is_last_record(tracepos, trace, traceLen)) return traceLen; - + if (showWaitCycles && !isResponse && next_record_is_response(tracepos, trace)) { uint32_t next_timestamp = *((uint32_t *)(trace + tracepos)); PrintAndLogEx(NORMAL, " %10u | %10u | %s |fdt (Frame Delay Time): %d", @@ -298,7 +298,7 @@ void printFelica(uint16_t traceLen, uint8_t *trace) { if (tracepos + 3 >= traceLen) break; - + uint16_t gap = *((uint16_t *)(trace + tracepos)); uint8_t crc_ok = trace[tracepos+2]; tracepos += 3; @@ -377,7 +377,7 @@ void printFelica(uint16_t traceLen, uint8_t *trace) { case FELICA_UPDATE_RNDID_ACK: snprintf(expbuf,49,"Update IDr Resp");break; default: snprintf(expbuf,49,"Unknown");break; } - + int num_lines = MIN((len )/16 + 1, 16); for (int j = 0; j < num_lines ; j++) { if (j == 0) { @@ -412,7 +412,7 @@ static int SanityOfflineCheck( bool useTraceBuffer ){ int CmdTraceList(const char *Cmd) { clearCommandBuffer(); - + bool showWaitCycles = false; bool markCRCBytes = false; bool isOnline = true; @@ -426,10 +426,10 @@ int CmdTraceList(const char *Cmd) { char cmdp = 0; while (param_getchar(Cmd, cmdp) != 0x00 && !errors) { - + int slen = param_getstr(Cmd, cmdp, type, sizeof(type) ); if ( slen == 1) { - + switch ( tolower(param_getchar(Cmd, cmdp))) { case 'h': return usage_trace_list(); @@ -447,24 +447,24 @@ int CmdTraceList(const char *Cmd) { break; case '1': isOnline = false; - cmdp++; + cmdp++; break; default: PrintAndLogEx(WARNING, "Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; break; } - - } else { - + + } else { + str_lower(type); - + // validate type of output if (strcmp(type, "iclass") == 0) protocol = ICLASS; else if(strcmp(type, "14a") == 0) protocol = ISO_14443A; else if(strcmp(type, "14b") == 0) protocol = ISO_14443B; else if(strcmp(type, "topaz") == 0) protocol = TOPAZ; - else if(strcmp(type, "7816") == 0) protocol = ISO_7816_4; + else if(strcmp(type, "7816") == 0) protocol = ISO_7816_4; else if(strcmp(type, "des") == 0) protocol = MFDES; else if(strcmp(type, "legic") == 0) protocol = LEGIC; else if(strcmp(type, "15") == 0) protocol = ISO_15693; @@ -472,22 +472,22 @@ int CmdTraceList(const char *Cmd) { else if(strcmp(type, "mf") == 0) protocol = PROTO_MIFARE; else if(strcmp(type, "raw") == 0) protocol = -1;//No crc, no annotations else errors = true; - + cmdp++; - } + } } - + //if (!SanityOfflineCheck(isOnline)) return 1; - + //Validations if (errors) return usage_trace_list(); - + uint16_t tracepos = 0; // reserv some space. if (!trace) trace = calloc(USB_CMD_DATA_SIZE, sizeof(uint8_t)); - + if ( isOnline ) { // Query for the size of the trace, downloading USB_CMD_DATA_SIZE UsbCommand response; @@ -495,7 +495,7 @@ int CmdTraceList(const char *Cmd) { PrintAndLogEx(WARNING, "timeout while waiting for reply."); return 1; } - + traceLen = response.arg[2]; if (traceLen > USB_CMD_DATA_SIZE) { uint8_t *p = realloc(trace, traceLen); @@ -510,14 +510,14 @@ int CmdTraceList(const char *Cmd) { free(trace); return 3; } - } + } } PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %d bytes)", traceLen); PrintAndLogEx(INFO, ""); if (protocol == FELICA) { printFelica(traceLen, trace); - } else { + } else { PrintAndLogEx(NORMAL, "Start = Start of Start Bit, End = End of last modulation. Src = Source of Transfer"); if ( protocol == ISO_14443A || protocol == PROTO_MIFARE) PrintAndLogEx(NORMAL, "iso14443a - All times are in carrier periods (1/13.56Mhz)"); @@ -530,7 +530,7 @@ int CmdTraceList(const char *Cmd) { PrintAndLogEx(NORMAL, "ISO15693 - Timings are not as accurate"); if ( protocol == ISO_7816_4 ) PrintAndLogEx(NORMAL, "ISO7816-4 / Smartcard - Timings N/A yet"); - + PrintAndLogEx(NORMAL, ""); PrintAndLogEx(NORMAL, " Start | End | Src | Data (! denotes parity error) | CRC | Annotation"); PrintAndLogEx(NORMAL, "------------+------------+-----+-------------------------------------------------------------------------+-----+--------------------"); @@ -544,24 +544,24 @@ int CmdTraceList(const char *Cmd) { } int CmdTraceLoad(const char *Cmd) { - + FILE *f = NULL; char filename[FILE_PATH_SIZE]; char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') return usage_trace_load(); - - param_getstr(Cmd, 0, filename, sizeof(filename)); - - if ((f = fopen(filename, "rb")) == NULL) { + if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') return usage_trace_load(); + + param_getstr(Cmd, 0, filename, sizeof(filename)); + + if ((f = fopen(filename, "rb")) == NULL) { PrintAndLogEx(FAILED, "Could not open file %s", filename); return 0; } - + // get filesize in order to malloc memory fseek(f, 0, SEEK_END); long fsize = ftell(f); - fseek(f, 0, SEEK_SET); - + fseek(f, 0, SEEK_SET); + if (fsize < 0) { PrintAndLogEx(FAILED, "error, when getting filesize"); fclose(f); @@ -571,7 +571,7 @@ int CmdTraceLoad(const char *Cmd) { PrintAndLogEx(FAILED, "error, file is too small"); fclose(f); return 4; - } + } if ( trace ) free(trace); @@ -579,36 +579,36 @@ int CmdTraceLoad(const char *Cmd) { trace = calloc(fsize, sizeof(uint8_t)); if (!trace) { PrintAndLogEx(FAILED, "Cannot allocate memory for trace"); - fclose(f); + fclose(f); return 2; } - + size_t bytes_read = fread(trace, 1, fsize, f); traceLen = bytes_read; fclose(f); - PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %d bytes) loaded from file %s", traceLen, filename); + PrintAndLogEx(SUCCESS, "Recorded Activity (TraceLen = %d bytes) loaded from file %s", traceLen, filename); return 0; } int CmdTraceSave(const char *Cmd) { - + if (traceLen == 0 ) { PrintAndLogEx(WARNING, "trace is empty, exiting..."); return 0; } - + char filename[FILE_PATH_SIZE]; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') return usage_trace_save(); - - param_getstr(Cmd, 0, filename, sizeof(filename)); + + param_getstr(Cmd, 0, filename, sizeof(filename)); saveFile(filename, "bin", trace, traceLen); return 0; } static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"list", CmdTraceList, 1, "List protocol data in trace buffer"}, + {"list", CmdTraceList, 1, "List protocol data in trace buffer"}, {"load", CmdTraceLoad, 1, "Load trace from file"}, {"save", CmdTraceSave, 1, "Save trace buffer to file"}, {NULL, NULL, 0, NULL} @@ -617,7 +617,7 @@ static command_t CommandTable[] = { int CmdTrace(const char *Cmd) { clearCommandBuffer(); CmdsParse(CommandTable, Cmd); - return 0; + return 0; } int CmdHelp(const char *Cmd) { diff --git a/client/cmdtrace.h b/client/cmdtrace.h index c6ba0cc38..ca56fd3cc 100644 --- a/client/cmdtrace.h +++ b/client/cmdtrace.h @@ -17,7 +17,7 @@ #include #include #include "proxmark3.h" -#include "protocols.h" +#include "protocols.h" #include "parity.h" // oddparity #include "cmdhflist.h" // annotations #include "iso15693tools.h" // ISO15693 crc @@ -34,7 +34,7 @@ extern int CmdTraceLoad(const char *Cmd); extern int CmdTraceSave(const char *Cmd); // usages helptext -extern int usage_trace_list(void); +extern int usage_trace_list(void); extern int usage_trace_load(void); extern int usage_trace_save(void); #endif diff --git a/client/comms.c b/client/comms.c index f08c5f413..7e9441a95 100644 --- a/client/comms.c +++ b/client/comms.c @@ -57,7 +57,7 @@ void SendCommand(UsbCommand *c) { #ifdef COMMS_DEBUG PrintAndLogEx(NORMAL, "Sending %d bytes | cmd %04x\n", sizeof(UsbCommand), c->cmd); #endif - + if (offline) { PrintAndLogEx(NORMAL, "Sending bytes to proxmark failed - offline"); return; @@ -65,22 +65,22 @@ void SendCommand(UsbCommand *c) { pthread_mutex_lock(&txBufferMutex); /** - This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive, + This causes hangups at times, when the pm3 unit is unresponsive or disconnected. The main console thread is alive, but comm thread just spins here. Not good.../holiman **/ while (txBuffer_pending) { - // wait for communication thread to complete sending a previous commmand - pthread_cond_wait(&txBufferSig, &txBufferMutex); + // wait for communication thread to complete sending a previous commmand + pthread_cond_wait(&txBufferSig, &txBufferMutex); } txBuffer = *c; txBuffer_pending = true; - - // tell communication thread that a new command can be send + + // tell communication thread that a new command can be send pthread_cond_signal(&txBufferSig); pthread_mutex_unlock(&txBufferMutex); - + //__atomic_test_and_set(&txcmd_pending, __ATOMIC_SEQ_CST); } @@ -101,7 +101,7 @@ void clearCommandBuffer() { * @param UC */ static void storeCommand(UsbCommand *command) { - + pthread_mutex_lock(&rxBufferMutex); if ( ( cmd_head+1) % CMD_BUFFER_SIZE == cmd_tail) { //If these two are equal, we're about to overwrite in the @@ -114,7 +114,7 @@ static void storeCommand(UsbCommand *command) { memcpy(destination, command, sizeof(UsbCommand)); //increment head and wrap - cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; + cmd_head = (cmd_head +1) % CMD_BUFFER_SIZE; pthread_mutex_unlock(&rxBufferMutex); } /** @@ -129,7 +129,7 @@ static int getCommand(UsbCommand* response) { pthread_mutex_unlock(&rxBufferMutex); return 0; } - + //Pick out the next unread command UsbCommand* last_unread = &rxBuffer[cmd_tail]; memcpy(response, last_unread, sizeof(UsbCommand)); @@ -146,17 +146,17 @@ static int getCommand(UsbCommand* response) { // that we weren't necessarily expecting, for example a debug print. //----------------------------------------------------------------------------- static void UsbCommandReceived(UsbCommand* c) { - + switch(c->cmd) { // First check if we are handling a debug message case CMD_DEBUG_PRINT_STRING: { char s[USB_CMD_DATA_SIZE+1]; - memset(s, 0x00, sizeof(s)); + memset(s, 0x00, sizeof(s)); size_t len = MIN(c->arg[0], USB_CMD_DATA_SIZE); - memcpy(s, c->d.asBytes, len); + memcpy(s, c->d.asBytes, len); uint64_t flag = c->arg[1]; - + switch (flag) { case FLAG_RAWPRINT: printf("%s", s); @@ -183,7 +183,7 @@ static void UsbCommandReceived(UsbCommand* c) { } // iceman: hw status - down the path on device, runs printusbspeed which starts sending a lot of // CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K packages which is not dealt with. I wonder if simply ignoring them will - // work. lets try it. + // work. lets try it. default: { storeCommand(c); break; @@ -192,14 +192,14 @@ static void UsbCommandReceived(UsbCommand* c) { } /* -bool hookUpPM3() { +bool hookUpPM3() { bool ret = false; sp = uart_open( comport ); if (sp == INVALID_SERIAL_PORT) { PrintAndLogEx(WARNING, "Reconnect failed, retrying... (reason: invalid serial port)\n"); sp = NULL; - serial_port_name = NULL; + serial_port_name = NULL; ret = false; offline = 1; } else if (sp == CLAIMED_SERIAL_PORT) { @@ -208,7 +208,7 @@ bool hookUpPM3() { serial_port_name = NULL; ret = false; offline = 1; - } else { + } else { PrintAndLogEx(SUCCESS, "Proxmark reconnected\n"); serial_port_name = ; ret = true; @@ -221,44 +221,44 @@ bool hookUpPM3() { void #ifdef __has_attribute #if __has_attribute(force_align_arg_pointer) -__attribute__((force_align_arg_pointer)) +__attribute__((force_align_arg_pointer)) #endif #endif *uart_communication(void *targ) { communication_arg_t *conn = (communication_arg_t*)targ; - size_t rxlen, totallen = 0; + size_t rxlen, totallen = 0; UsbCommand rx; UsbCommand *prx = ℞ - + //int counter_to_offline = 0; #if defined(__MACH__) && defined(__APPLE__) disableAppNap("Proxmark3 polling UART"); #endif - + while (conn->run) { rxlen = 0; bool ACK_received = false; - + if (uart_receive(sp, (uint8_t *)prx, sizeof(UsbCommand) - (prx - &rx), &rxlen) && rxlen) { prx += rxlen; totallen += rxlen; - + if ( totallen < sizeof(UsbCommand)) { - + // iceman: this looping is no working as expected at all. The reassemble of package is nonfunctional. // solved so far with increasing the timeouts of the serial port configuration. PrintAndLogEx(NORMAL, "Foo %d | %d (loop)", prx - &rx, rxlen); continue; } - + totallen = 0; UsbCommandReceived(&rx); if (rx.cmd == CMD_ACK) { ACK_received = true; } } - + prx = ℞ pthread_mutex_lock(&txBufferMutex); @@ -274,11 +274,11 @@ __attribute__((force_align_arg_pointer)) if (txBuffer_pending) { if (!uart_send(sp, (uint8_t*) &txBuffer, sizeof(UsbCommand))) { - //counter_to_offline++; + //counter_to_offline++; PrintAndLogEx(WARNING, "sending bytes to proxmark failed"); } txBuffer_pending = false; - + // tell main thread that txBuffer is empty pthread_cond_signal(&txBufferSig); } @@ -293,13 +293,13 @@ __attribute__((force_align_arg_pointer)) #if defined(__MACH__) && defined(__APPLE__) enableAppNap(); #endif - + pthread_exit(NULL); return NULL; } bool OpenProxmark(void *port, bool wait_for_port, int timeout, bool flash_mode) { - + char *portname = (char *)port; if (!wait_for_port) { sp = uart_open(portname); @@ -331,7 +331,7 @@ bool OpenProxmark(void *port, bool wait_for_port, int timeout, bool flash_mode) serial_port_name = portname; conn.run = true; conn.block_after_ACK = flash_mode; - pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn); + pthread_create(&USB_communication_thread, NULL, &uart_communication, &conn); //pthread_create(&FPC_communication_thread, NULL, &uart_communication, &conn); fflush(stdout); @@ -350,10 +350,10 @@ void CloseProxmark(void) { pthread_join(USB_communication_thread, NULL); } #else - pthread_join(USB_communication_thread, NULL); + pthread_join(USB_communication_thread, NULL); //pthread_join(FPC_communication_thread, NULL); #endif - + if (sp) { uart_close(sp); } @@ -376,7 +376,7 @@ void CloseProxmark(void) { /** * @brief Waits for a certain response type. This method waits for a maximum of * ms_timeout milliseconds for a specified response command. - + * @param cmd command to wait for, or CMD_UNKNOWN to take any command. * @param response struct to copy received command into. * @param ms_timeout display message after 3 seconds @@ -384,25 +384,25 @@ void CloseProxmark(void) { * @return true if command was returned, otherwise false */ bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning) { - + UsbCommand resp; if (response == NULL) response = &resp; uint64_t start_time = msclock(); - + // Wait until the command is received while (true) { while ( getCommand(response) ) { if (cmd == CMD_UNKNOWN || response->cmd == cmd) - return true; + return true; } if (msclock() - start_time > ms_timeout) break; - + if (msclock() - start_time > 3000 && show_warning) { // 3 seconds elapsed (but this doesn't mean the timeout was exceeded) PrintAndLogEx(NORMAL, "Waiting for a response from the proxmark..."); @@ -435,7 +435,7 @@ bool WaitForResponse(uint32_t cmd, UsbCommand* response) { * @return true if command was returned, otherwise false */ bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint32_t start_index, UsbCommand *response, size_t ms_timeout, bool show_warning) { - + if (dest == NULL) return false; if (bytes == 0) return true; @@ -443,9 +443,9 @@ bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint3 if (response == NULL) response = &resp; - // clear + // clear clearCommandBuffer(); - + switch (memtype) { case BIG_BUF: { UsbCommand c = {CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K, {start_index, bytes, 0}}; @@ -454,10 +454,10 @@ bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint3 } case BIG_BUF_EML: { UsbCommand c = {CMD_DOWNLOAD_EML_BIGBUF, {start_index, bytes, 0}}; - SendCommand(&c); + SendCommand(&c); return dl_it(dest, bytes, start_index, response, ms_timeout, show_warning, CMD_DOWNLOADED_EML_BIGBUF); } - case FLASH_MEM: { + case FLASH_MEM: { UsbCommand c = {CMD_FLASHMEM_DOWNLOAD, {start_index, bytes, 0}}; SendCommand(&c); return dl_it(dest, bytes, start_index, response, ms_timeout, show_warning, CMD_FLASHMEM_DOWNLOADED); @@ -473,46 +473,46 @@ bool GetFromDevice(DeviceMemType_t memtype, uint8_t *dest, uint32_t bytes, uint3 } bool dl_it(uint8_t *dest, uint32_t bytes, uint32_t start_index, UsbCommand *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd) { - + uint32_t bytes_completed = 0; uint64_t start_time = msclock(); - + while (true) { - + if (getCommand(response)) { // sample_buf is a array pointer, located in data.c // arg0 = offset in transfer. Startindex of this chunk // arg1 = length bytes to transfer - // arg2 = bigbuff tracelength (?) + // arg2 = bigbuff tracelength (?) if (response->cmd == rec_cmd) { - + uint32_t offset = response->arg[0]; uint32_t copy_bytes = MIN(bytes - bytes_completed, response->arg[1]); //uint32_t tracelen = c->arg[2]; - + // extended bounds check1. upper limit is USB_CMD_DATA_SIZE // shouldn't happen copy_bytes = MIN(copy_bytes, USB_CMD_DATA_SIZE); - - // extended bounds check2. + + // extended bounds check2. if ( offset + copy_bytes > bytes ) { PrintAndLogEx(FAILED, "ERROR: Out of bounds when downloading from device, offset %u | len %u | total len %u > buf_size %u", offset, copy_bytes, offset+copy_bytes, bytes); break; - } - + } + memcpy(dest + offset, response->d.asBytes, copy_bytes); bytes_completed += copy_bytes; } else if (response->cmd == CMD_ACK) { return true; } } - + if (msclock() - start_time > ms_timeout) { PrintAndLogEx(FAILED, "Timed out while trying to download data from device"); break; } - + if (msclock() - start_time > 3000 && show_warning) { // 3 seconds elapsed (but this doesn't mean the timeout was exceeded) PrintAndLogEx(NORMAL, "Waiting for a response from the proxmark..."); diff --git a/client/comms.h b/client/comms.h index e311f5e0c..d3303be3f 100644 --- a/client/comms.h +++ b/client/comms.h @@ -20,7 +20,7 @@ #include "ui.h" #include "common.h" #include "util_posix.h" -#include "util.h" +#include "util.h" #include "util_darwin.h" #if defined(__linux__) && !defined(NO_UNLINK) @@ -43,7 +43,7 @@ typedef struct { bool run; // If TRUE, continue running the uart_communication thread bool block_after_ACK; // if true, block after receiving an ACK package } communication_arg_t; - + bool dl_it(uint8_t *dest, uint32_t bytes, uint32_t start_index, UsbCommand *response, size_t ms_timeout, bool show_warning, uint32_t rec_cmd); @@ -56,7 +56,7 @@ void clearCommandBuffer(); bool OpenProxmark(void *port, bool wait_for_port, int timeout, bool flash_mode); void CloseProxmark(void); - + bool WaitForResponseTimeoutW(uint32_t cmd, UsbCommand* response, size_t ms_timeout, bool show_warning); bool WaitForResponseTimeout(uint32_t cmd, UsbCommand* response, size_t ms_timeout); bool WaitForResponse(uint32_t cmd, UsbCommand* response); diff --git a/client/crypto/asn1dump.c b/client/crypto/asn1dump.c index a0abdf3cf..38d03d353 100644 --- a/client/crypto/asn1dump.c +++ b/client/crypto/asn1dump.c @@ -12,7 +12,7 @@ #include "asn1dump.h" #include #include -#include +#include #include #include #include @@ -110,7 +110,7 @@ static void asn1_tag_dump_str_time(const struct tlv *tlv, const struct asn1_tag *needdump = false; int startindx = longyear ? 4 : 2; - + if (len > 4) { fprintf(f, "\tvalue: '"); while (true) { @@ -119,42 +119,42 @@ static void asn1_tag_dump_str_time(const struct tlv *tlv, const struct asn1_tag fprintf(f, "20"); fwrite(tlv->value, 1, longyear ? 4 : 2, f); fprintf(f, "-"); - if (len < startindx + 2) + if (len < startindx + 2) break; // month fwrite(&tlv->value[startindx], 1, 2, f); fprintf(f, "-"); - if (len < startindx + 4) + if (len < startindx + 4) break; // day fwrite(&tlv->value[startindx + 2], 1, 2, f); fprintf(f, " "); - if (len < startindx + 6) + if (len < startindx + 6) break; // hour fwrite(&tlv->value[startindx + 4], 1, 2, f); fprintf(f, ":"); - if (len < startindx + 8) + if (len < startindx + 8) break; // min fwrite(&tlv->value[startindx + 6], 1, 2, f); fprintf(f, ":"); - if (len < startindx + 10) + if (len < startindx + 10) break; // sec fwrite(&tlv->value[startindx + 8], 1, 2, f); - if (len < startindx + 11) + if (len < startindx + 11) break; // time zone fprintf(f, " zone: %.*s", len - 10 - (longyear ? 4 : 2), &tlv->value[startindx + 10]); - + break; } fprintf(f, "'\n"); } else { fprintf(f, "\n"); *needdump = true; - } + } } static void asn1_tag_dump_string(const struct tlv *tlv, const struct asn1_tag *tag, FILE *f, int level){ @@ -170,7 +170,7 @@ static void asn1_tag_dump_octet_string(const struct tlv *tlv, const struct asn1_ *needdump = true; break; } - + if (*needdump) { fprintf(f, "'\n"); } else { @@ -239,7 +239,7 @@ static char *asn1_oid_description(const char *oid, bool with_group_desc) { size_t len = strlen(get_my_executable_directory()); if ( len > 300 ) len = 299; - + strncpy(fname, get_my_executable_directory(), len); strcat(fname, "crypto/oids.json"); if (access(fname, F_OK) < 0) { @@ -249,19 +249,19 @@ static char *asn1_oid_description(const char *oid, bool with_group_desc) { goto error; // file not found } } - + // load `oids.json` root = json_load_file(fname, 0, &error); - + if (!root || !json_is_object(root)) { goto error; } - + json_t *elm = json_object_get(root, oid); if (!elm) { goto error; } - + if (JsonLoadStr(elm, "$.d", res)) goto error; @@ -271,10 +271,10 @@ static char *asn1_oid_description(const char *oid, bool with_group_desc) { strcat(res, strext); strcat(res, ")"); } - + json_decref(root); return res; - + error: if (root) json_decref(root); @@ -287,15 +287,15 @@ static void asn1_tag_dump_object_id(const struct tlv *tlv, const struct asn1_tag asn1_buf.len = tlv->len; asn1_buf.p = (uint8_t *)tlv->value; char pstr[300]; - mbedtls_oid_get_numeric_string(pstr, sizeof(pstr), &asn1_buf); + mbedtls_oid_get_numeric_string(pstr, sizeof(pstr), &asn1_buf); fprintf(f, " %s", pstr); - + char *jsondesc = asn1_oid_description(pstr, true); if (jsondesc) { fprintf(f, " - %s", jsondesc); - } else { + } else { const char *ppstr; - mbedtls_oid_get_attr_short_name(&asn1_buf, &ppstr); + mbedtls_oid_get_attr_short_name(&asn1_buf, &ppstr); if (ppstr && strnlen(ppstr, 1)) { fprintf(f, " (%s)\n", ppstr); return; @@ -355,6 +355,6 @@ bool asn1_tag_dump(const struct tlv *tlv, FILE *f, int level, bool *candump) { *candump = false; break; }; - + return true; } diff --git a/client/crypto/asn1utils.c b/client/crypto/asn1utils.c index 5be323b45..f8b296e60 100644 --- a/client/crypto/asn1utils.c +++ b/client/crypto/asn1utils.c @@ -34,10 +34,10 @@ int ecdsa_asn1_get_signature(uint8_t *signature, size_t signaturelen, uint8_t *r mbedtls_mpi_free(&xmpi); goto exit; } - + res = mbedtls_mpi_write_binary(&xmpi, rval, 32); mbedtls_mpi_free(&xmpi); - if (res) + if (res) goto exit; mbedtls_mpi_init(&xmpi); @@ -46,10 +46,10 @@ int ecdsa_asn1_get_signature(uint8_t *signature, size_t signaturelen, uint8_t *r mbedtls_mpi_free(&xmpi); goto exit; } - + res = mbedtls_mpi_write_binary(&xmpi, sval, 32); mbedtls_mpi_free(&xmpi); - if (res) + if (res) goto exit; // check size @@ -72,7 +72,7 @@ static bool print_cb(void *data, const struct tlv *tlv, int level, bool is_leaf) } int asn1_print(uint8_t *asn1buf, size_t asn1buflen, char *indent) { - + struct tlvdb *t = NULL; t = tlvdb_parse_multi(asn1buf, asn1buflen); if (t) { @@ -82,7 +82,7 @@ int asn1_print(uint8_t *asn1buf, size_t asn1buflen, char *indent) { PrintAndLogEx(ERR, "Can't parse data as TLV tree."); return 1; } - + return 0; } diff --git a/client/crypto/libpcrypto.c b/client/crypto/libpcrypto.c index 896048bf0..37668b4e4 100644 --- a/client/crypto/libpcrypto.c +++ b/client/crypto/libpcrypto.c @@ -30,7 +30,7 @@ int aes_encode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int l uint8_t iiv[16] = {0}; if (iv) memcpy(iiv, iv, 16); - + mbedtls_aes_context aes; mbedtls_aes_init(&aes); if (mbedtls_aes_setkey_enc(&aes, key, 128)) @@ -46,7 +46,7 @@ int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int l uint8_t iiv[16] = {0}; if (iv) memcpy(iiv, iv, 16); - + mbedtls_aes_context aes; mbedtls_aes_init(&aes); if (mbedtls_aes_setkey_dec(&aes, key, 128)) @@ -62,20 +62,20 @@ int aes_decode(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *output, int l // https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/AES_CMAC.pdf int aes_cmac(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) { memset(mac, 0x00, 16); - - // NIST 800-38B + + // NIST 800-38B return mbedtls_aes_cmac_prf_128(key, MBEDTLS_AES_BLOCK_SIZE, input, length, mac); } int aes_cmac8(uint8_t *iv, uint8_t *key, uint8_t *input, uint8_t *mac, int length) { uint8_t cmac[16] = {0}; memset(mac, 0x00, 8); - + int res = aes_cmac(iv, key, input, cmac, length); if (res) return res; - - for(int i = 0; i < 8; i++) + + for(int i = 0; i < 8; i++) mac[i] = cmac[i * 2 + 1]; return 0; @@ -88,73 +88,73 @@ static int fixed_rand(void *rng_state, unsigned char *output, size_t len) { } else { memset(output, 0x00, len); } - + return 0; } int sha256hash(uint8_t *input, int length, uint8_t *hash) { if (!hash || !input) return 1; - + mbedtls_sha256_context sctx; mbedtls_sha256_init(&sctx); - mbedtls_sha256_starts(&sctx, 0); // SHA-256, not 224 + mbedtls_sha256_starts(&sctx, 0); // SHA-256, not 224 mbedtls_sha256_update(&sctx, input, length); - mbedtls_sha256_finish(&sctx, hash); + mbedtls_sha256_finish(&sctx, hash); mbedtls_sha256_free(&sctx); - + return 0; } int ecdsa_init_str(mbedtls_ecdsa_context *ctx, char * key_d, char *key_x, char *key_y) { if (!ctx) return 1; - + int res; mbedtls_ecdsa_init(ctx); res = mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256R1); // secp256r1 - if (res) + if (res) return res; - + if (key_d) { res = mbedtls_mpi_read_string(&ctx->d, 16, key_d); - if (res) + if (res) return res; } - + if (key_x && key_y) { res = mbedtls_ecp_point_read_string(&ctx->Q, 16, key_x, key_y); - if (res) + if (res) return res; } - + return 0; } int ecdsa_init(mbedtls_ecdsa_context *ctx, uint8_t * key_d, uint8_t *key_xy) { if (!ctx) return 1; - + int res; mbedtls_ecdsa_init(ctx); res = mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256R1); // secp256r1 - if (res) + if (res) return res; - + if (key_d) { res = mbedtls_mpi_read_binary(&ctx->d, key_d, 32); - if (res) + if (res) return res; } - + if (key_xy) { res = mbedtls_ecp_point_read_binary(&ctx->grp, &ctx->Q, key_xy, 32 * 2 + 1); - if (res) + if (res) return res; } - + return 0; } @@ -188,7 +188,7 @@ int ecdsa_key_create(uint8_t * key_d, uint8_t *key_xy) { res = mbedtls_ecp_point_write_binary(&ctx.grp, &ctx.Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &keylen, public_key, sizeof(public_key)); if (res) goto exit; - + if (keylen != 65) { // 0x04 res = 1; goto exit; @@ -212,20 +212,20 @@ char *ecdsa_get_error(int ret) { int ecdsa_public_key_from_pk(mbedtls_pk_context *pk, uint8_t *key, size_t keylen) { int res = 0; size_t realkeylen = 0; - if (keylen < 65) + if (keylen < 65) return 1; - + mbedtls_ecdsa_context ctx; mbedtls_ecdsa_init(&ctx); - + res = mbedtls_ecp_group_load(&ctx.grp, MBEDTLS_ECP_DP_SECP256R1); // secp256r1 if (res) goto exit; - + res = mbedtls_ecdsa_from_keypair(&ctx, mbedtls_pk_ec(*pk) ); if (res) goto exit; - + res = mbedtls_ecp_point_write_binary(&ctx.grp, &ctx.Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &realkeylen, key, keylen); if (realkeylen != 65) res = 2; @@ -237,8 +237,8 @@ exit: int ecdsa_signature_create(uint8_t *key_d, uint8_t *key_xy, uint8_t *input, int length, uint8_t *signature, size_t *signaturelen) { int res; *signaturelen = 0; - - uint8_t shahash[32] = {0}; + + uint8_t shahash[32] = {0}; res = sha256hash(input, length, shahash); if (res) return res; @@ -254,10 +254,10 @@ int ecdsa_signature_create(uint8_t *key_d, uint8_t *key_xy, uint8_t *input, int if (res) goto exit; - mbedtls_ecdsa_context ctx; + mbedtls_ecdsa_context ctx; ecdsa_init(&ctx, key_d, key_xy); res = mbedtls_ecdsa_write_signature(&ctx, MBEDTLS_MD_SHA256, shahash, sizeof(shahash), signature, signaturelen, mbedtls_ctr_drbg_random, &ctr_drbg); - + exit: mbedtls_ctr_drbg_free(&ctr_drbg); mbedtls_ecdsa_free(&ctx); @@ -267,49 +267,49 @@ exit: int ecdsa_signature_create_test(char * key_d, char *key_x, char *key_y, char *random, uint8_t *input, int length, uint8_t *signature, size_t *signaturelen) { int res; *signaturelen = 0; - - uint8_t shahash[32] = {0}; + + uint8_t shahash[32] = {0}; res = sha256hash(input, length, shahash); if (res) return res; int rndlen = 0; param_gethex_to_eol(random, 0, fixed_rand_value, sizeof(fixed_rand_value), &rndlen); - - mbedtls_ecdsa_context ctx; + + mbedtls_ecdsa_context ctx; ecdsa_init_str(&ctx, key_d, key_x, key_y); res = mbedtls_ecdsa_write_signature(&ctx, MBEDTLS_MD_SHA256, shahash, sizeof(shahash), signature, signaturelen, fixed_rand, NULL); - + mbedtls_ecdsa_free(&ctx); return res; } int ecdsa_signature_verify_keystr(char *key_x, char *key_y, uint8_t *input, int length, uint8_t *signature, size_t signaturelen) { int res; - uint8_t shahash[32] = {0}; + uint8_t shahash[32] = {0}; res = sha256hash(input, length, shahash); if (res) return res; - mbedtls_ecdsa_context ctx; + mbedtls_ecdsa_context ctx; ecdsa_init_str(&ctx, NULL, key_x, key_y); res = mbedtls_ecdsa_read_signature(&ctx, shahash, sizeof(shahash), signature, signaturelen); - + mbedtls_ecdsa_free(&ctx); return res; } int ecdsa_signature_verify(uint8_t *key_xy, uint8_t *input, int length, uint8_t *signature, size_t signaturelen) { int res; - uint8_t shahash[32] = {0}; + uint8_t shahash[32] = {0}; res = sha256hash(input, length, shahash); if (res) return res; - mbedtls_ecdsa_context ctx; + mbedtls_ecdsa_context ctx; ecdsa_init(&ctx, NULL, key_xy); res = mbedtls_ecdsa_read_signature(&ctx, shahash, sizeof(shahash), signature, signaturelen); - + mbedtls_ecdsa_free(&ctx); return res; } @@ -325,8 +325,8 @@ int ecdsa_nist_test(bool verbose) { int res; uint8_t input[] = "Example of ECDSA with P-256"; int length = strlen((char *)input); - uint8_t signature[300] = {0}; - size_t siglen = 0; + uint8_t signature[300] = {0}; + size_t siglen = 0; // NIST ecdsa test if (verbose) @@ -334,32 +334,32 @@ int ecdsa_nist_test(bool verbose) { // make signature res = ecdsa_signature_create_test(T_PRIVATE_KEY, T_Q_X, T_Q_Y, T_K, input, length, signature, &siglen); // printf("res: %x signature[%x]: %s\n", (res<0)?-res:res, siglen, sprint_hex(signature, siglen)); - if (res) + if (res) goto exit; // check vectors - uint8_t rval[300] = {0}; - uint8_t sval[300] = {0}; + uint8_t rval[300] = {0}; + uint8_t sval[300] = {0}; res = ecdsa_asn1_get_signature(signature, siglen, rval, sval); if (res) goto exit; - + int slen = 0; uint8_t rval_s[33] = {0}; param_gethex_to_eol(T_R, 0, rval_s, sizeof(rval_s), &slen); - uint8_t sval_s[33] = {0}; + uint8_t sval_s[33] = {0}; param_gethex_to_eol(T_S, 0, sval_s, sizeof(sval_s), &slen); if (strncmp((char *)rval, (char *)rval_s, 32) || strncmp((char *)sval, (char *)sval_s, 32)) { printf("R or S check error\n"); res = 100; goto exit; } - + // verify signature res = ecdsa_signature_verify_keystr(T_Q_X, T_Q_Y, input, length, signature, siglen); - if (res) + if (res) goto exit; - + // verify wrong signature input[0] ^= 0xFF; res = ecdsa_signature_verify_keystr(T_Q_X, T_Q_Y, input, length, signature, siglen); @@ -378,27 +378,27 @@ int ecdsa_nist_test(bool verbose) { uint8_t key_xy[32 * 2 + 2] = {0}; memset(signature, 0x00, sizeof(signature)); siglen = 0; - + res = ecdsa_key_create(key_d, key_xy); - if (res) + if (res) goto exit; res = ecdsa_signature_create(key_d, key_xy, input, length, signature, &siglen); - if (res) + if (res) goto exit; res = ecdsa_signature_verify(key_xy, input, length, signature, siglen); - if (res) + if (res) goto exit; input[0] ^= 0xFF; res = ecdsa_signature_verify(key_xy, input, length, signature, siglen); - if (!res) + if (!res) goto exit; - + if (verbose) printf("passed\n\n"); - + return 0; exit: if (verbose) diff --git a/client/emv/apduinfo.c b/client/emv/apduinfo.c index b1bb84dae..17e87c45f 100644 --- a/client/emv/apduinfo.c +++ b/client/emv/apduinfo.c @@ -270,10 +270,10 @@ int CodeCmp(const char *code1, const char *code2) { } if (cmp == 4) return 0; - + if (cmp + xsymb == 4) return xsymb; - + return -1; } @@ -282,17 +282,17 @@ const APDUCode* const GetAPDUCode(uint8_t sw1, uint8_t sw2) { int res; int mineq = APDUCodeTableLen; int mineqindx = 0; - + sprintf(buf, "%02X%02X", sw1, sw2); - + for (int i = 0; i < APDUCodeTableLen; i++) { res = CodeCmp(APDUCodeTable[i].ID, buf); - + // equal - if (res == 0) { + if (res == 0) { return &APDUCodeTable[i]; } - + // with some 'X' if (res > 0 && mineq > res) { mineq = res; @@ -304,7 +304,7 @@ const APDUCode* const GetAPDUCode(uint8_t sw1, uint8_t sw2) { if (mineqindx < APDUCodeTableLen) { return &APDUCodeTable[mineqindx]; } - + return NULL; } diff --git a/client/emv/apduinfo.h b/client/emv/apduinfo.h index a3fa2049b..c64230502 100644 --- a/client/emv/apduinfo.h +++ b/client/emv/apduinfo.h @@ -27,7 +27,7 @@ typedef struct { const uint8_t Type; const char *Description; } APDUCode; - + extern const APDUCode* const GetAPDUCode(uint8_t sw1, uint8_t sw2); extern const char* GetAPDUCodeDescription(uint8_t sw1, uint8_t sw2); diff --git a/client/emv/cmdemv.c b/client/emv/cmdemv.c index f14d23f2d..5d73e88c9 100644 --- a/client/emv/cmdemv.c +++ b/client/emv/cmdemv.c @@ -58,8 +58,8 @@ int CmdEMVSelect(const char *cmd) { uint8_t data[APDU_AID_LEN] = {0}; int datalen = 0; - CLIParserInit("emv select", - "Executes select applet command", + CLIParserInit("emv select", + "Executes select applet command", "Usage:\n\temv select -s a00000000101 -> select card, select applet\n\temv select -st a00000000101 -> select card, select applet, show result in TLV\n"); void* argtable[] = { @@ -73,7 +73,7 @@ int CmdEMVSelect(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool activateField = arg_get_lit(1); bool leaveSignalON = arg_get_lit(2); bool APDULogging = arg_get_lit(3); @@ -84,9 +84,9 @@ int CmdEMVSelect(const char *cmd) { PrintChannel(channel); CLIGetHexWithReturn(6, data, &datalen); CLIParserFree(); - + SetAPDULogging(APDULogging); - + // exec uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; @@ -94,11 +94,11 @@ int CmdEMVSelect(const char *cmd) { int res = EMVSelect(channel, activateField, leaveSignalON, data, datalen, buf, sizeof(buf), &len, &sw, NULL); if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); - + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + if (res) return res; - + if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -107,8 +107,8 @@ int CmdEMVSelect(const char *cmd) { int CmdEMVSearch(const char *cmd) { - CLIParserInit("emv search", - "Tries to select all applets from applet list:\n", + CLIParserInit("emv search", + "Tries to select all applets from applet list:\n", "Usage:\n\temv search -s -> select card and search\n\temv search -st -> select card, search and show result in TLV\n"); void* argtable[] = { @@ -121,7 +121,7 @@ int CmdEMVSearch(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool activateField = arg_get_lit(1); bool leaveSignalON = arg_get_lit(2); bool APDULogging = arg_get_lit(3); @@ -131,9 +131,9 @@ int CmdEMVSearch(const char *cmd) { channel = ECC_CONTACT; PrintChannel(channel); CLIParserFree(); - + SetAPDULogging(APDULogging); - + struct tlvdb *t = NULL; const char *al = "Applets list"; t = tlvdb_fixed(1, strlen(al), (const unsigned char *)al); @@ -142,23 +142,23 @@ int CmdEMVSearch(const char *cmd) { tlvdb_free(t); return 2; } - + PrintAndLogEx(SUCCESS, "Search completed."); // print list here - if (!decodeTLV) { + if (!decodeTLV) { TLVPrintAIDlistFromSelectTLV(t); } - + tlvdb_free(t); - + return 0; } int CmdEMVPPSE(const char *cmd) { - - CLIParserInit("emv pse", - "Executes PSE/PPSE select command. It returns list of applet on the card:\n", + + CLIParserInit("emv pse", + "Executes PSE/PPSE select command. It returns list of applet on the card:\n", "Usage:\n\temv pse -s1 -> select, get pse\n\temv pse -st2 -> select, get ppse, show result in TLV\n"); void* argtable[] = { @@ -173,7 +173,7 @@ int CmdEMVPPSE(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool activateField = arg_get_lit(1); bool leaveSignalON = arg_get_lit(2); uint8_t PSENum = 2; @@ -187,23 +187,23 @@ int CmdEMVPPSE(const char *cmd) { if (arg_get_lit(7)) channel = ECC_CONTACT; PrintChannel(channel); - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); - + // exec uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; uint16_t sw = 0; int res = EMVSelectPSE(channel, activateField, leaveSignalON, PSENum, buf, sizeof(buf), &len, &sw); - + if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); if (res) return res; - - + + if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -214,11 +214,11 @@ int CmdEMVGPO(const char *cmd) { uint8_t data[APDU_RES_LEN] = {0}; int datalen = 0; - CLIParserInit("emv gpo", - "Executes Get Processing Options command. It returns data in TLV format (0x77 - format2) or plain format (0x80 - format1).\nNeeds a EMV applet to be selected.", + CLIParserInit("emv gpo", + "Executes Get Processing Options command. It returns data in TLV format (0x77 - format2) or plain format (0x80 - format1).\nNeeds a EMV applet to be selected.", "Usage:\n\temv gpo -k -> execute GPO\n" "\temv gpo -t 01020304 -> execute GPO with 4-byte PDOL data, show result in TLV\n" - "\temv gpo -pmt 9F 37 04 -> load params from file, make PDOL data from PDOL, execute GPO with PDOL, show result in TLV\n"); + "\temv gpo -pmt 9F 37 04 -> load params from file, make PDOL data from PDOL, execute GPO with PDOL, show result in TLV\n"); void* argtable[] = { arg_param_begin, @@ -232,7 +232,7 @@ int CmdEMVGPO(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool leaveSignalON = arg_get_lit(1); bool paramsLoadFromFile = arg_get_lit(2); bool dataMakeFromPDOL = arg_get_lit(3); @@ -243,14 +243,14 @@ int CmdEMVGPO(const char *cmd) { channel = ECC_CONTACT; PrintChannel(channel); CLIGetHexWithReturn(7, data, &datalen); - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); - + // Init TLV tree const char *alr = "Root terminal TLV tree"; struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr); - + // calc PDOL struct tlv *pdol_data_tlv = NULL; struct tlvdb *tmp_ext = NULL; @@ -266,7 +266,7 @@ int CmdEMVGPO(const char *cmd) { PrintAndLogEx(INFO, "Params loading from file..."); ParamLoadFromJson(tlvRoot); }; - + tmp_ext = tlvdb_external(0x9f38, datalen, data); pdol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x83); if (!pdol_data_tlv){ @@ -291,25 +291,25 @@ int CmdEMVGPO(const char *cmd) { return 4; } PrintAndLogEx(INFO, "PDOL data[%d]: %s", pdol_data_tlv_data_len, sprint_hex(pdol_data_tlv_data, pdol_data_tlv_data_len)); - + // exec uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; uint16_t sw = 0; int res = EMVGPO(channel, leaveSignalON, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); - + if (pdol_data_tlv != &data_tlv) free(pdol_data_tlv); - tlvdb_free(tmp_ext); + tlvdb_free(tmp_ext); tlvdb_free(tlvRoot); - + if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); if (res) return res; - + if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -320,8 +320,8 @@ int CmdEMVReadRecord(const char *cmd) { uint8_t data[APDU_RES_LEN] = {0}; int datalen = 0; - CLIParserInit("emv readrec", - "Executes Read Record command. It returns data in TLV format.\nNeeds a bank applet to be selected and sometimes needs GPO to be executed.", + CLIParserInit("emv readrec", + "Executes Read Record command. It returns data in TLV format.\nNeeds a bank applet to be selected and sometimes needs GPO to be executed.", "Usage:\n\temv readrec -k 0101 -> read file SFI=01, SFIrec=01\n\temv readrec -kt 0201-> read file 0201 and show result in TLV\n"); void* argtable[] = { @@ -334,7 +334,7 @@ int CmdEMVReadRecord(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool leaveSignalON = arg_get_lit(1); bool APDULogging = arg_get_lit(2); bool decodeTLV = arg_get_lit(3); @@ -344,27 +344,27 @@ int CmdEMVReadRecord(const char *cmd) { PrintChannel(channel); CLIGetHexWithReturn(5, data, &datalen); CLIParserFree(); - + if (datalen != 2) { PrintAndLogEx(ERR, "Command needs to have 2 bytes of data"); return 1; } - + SetAPDULogging(APDULogging); - + // exec uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; uint16_t sw = 0; int res = EMVReadRecord(channel, leaveSignalON, data[0], data[1], buf, sizeof(buf), &len, &sw, NULL); - + if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); if (res) return res; - - + + if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -375,12 +375,12 @@ int CmdEMVAC(const char *cmd) { uint8_t data[APDU_RES_LEN] = {0}; int datalen = 0; - CLIParserInit("emv genac", - "Generate Application Cryptogram command. It returns data in TLV format .\nNeeds a EMV applet to be selected and GPO to be executed.", + CLIParserInit("emv genac", + "Generate Application Cryptogram command. It returns data in TLV format .\nNeeds a EMV applet to be selected and GPO to be executed.", "Usage:\n\temv genac -k 0102 -> generate AC with 2-byte CDOLdata and keep field ON after command\n" "\temv genac -t 01020304 -> generate AC with 4-byte CDOL data, show result in TLV\n" "\temv genac -Daac 01020304 -> generate AC with 4-byte CDOL data and terminal decision 'declined'\n" - "\temv genac -pmt 9F 37 04 -> load params from file, make CDOL data from CDOL, generate AC with CDOL, show result in TLV"); + "\temv genac -pmt 9F 37 04 -> load params from file, make CDOL data from CDOL, generate AC with CDOL, show result in TLV"); void* argtable[] = { arg_param_begin, @@ -396,7 +396,7 @@ int CmdEMVAC(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, false); - + bool leaveSignalON = arg_get_lit(1); bool trTypeCDA = arg_get_lit(2); uint8_t termDecision = 0xff; @@ -426,14 +426,14 @@ int CmdEMVAC(const char *cmd) { channel = ECC_CONTACT; PrintChannel(channel); CLIGetHexWithReturn(9, data, &datalen); - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); - + // Init TLV tree const char *alr = "Root terminal TLV tree"; struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr); - + // calc CDOL struct tlv *cdol_data_tlv = NULL; struct tlvdb *tmp_ext = NULL; @@ -442,7 +442,7 @@ int CmdEMVAC(const char *cmd) { .len = datalen, .value = (uint8_t *)data, }; - + if (dataMakeFromCDOL) { ParamLoadDefaults(tlvRoot); @@ -450,7 +450,7 @@ int CmdEMVAC(const char *cmd) { PrintAndLogEx(INFO, "Params loading from file..."); ParamLoadFromJson(tlvRoot); }; - + tmp_ext = tlvdb_external(0x8c, datalen, data); cdol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x01); // 0x01 - dummy tag if (!cdol_data_tlv){ @@ -465,7 +465,7 @@ int CmdEMVAC(const char *cmd) { } cdol_data_tlv = &data_tlv; } - + PrintAndLogEx(INFO, "CDOL data[%d]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len)); // exec @@ -473,29 +473,29 @@ int CmdEMVAC(const char *cmd) { size_t len = 0; uint16_t sw = 0; int res = EMVAC(channel, leaveSignalON, termDecision, (uint8_t *)cdol_data_tlv->value, cdol_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot); - + if (cdol_data_tlv != &data_tlv) free(cdol_data_tlv); tlvdb_free(tmp_ext); tlvdb_free(tlvRoot); - + if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); if (res) return res; - + if (decodeTLV) TLVPrintFromBuffer(buf, len); - return 0; + return 0; } int CmdEMVGenerateChallenge(const char *cmd) { - CLIParserInit("emv challenge", - "Executes Generate Challenge command. It returns 4 or 8-byte random number from card.\nNeeds a EMV applet to be selected and GPO to be executed.", + CLIParserInit("emv challenge", + "Executes Generate Challenge command. It returns 4 or 8-byte random number from card.\nNeeds a EMV applet to be selected and GPO to be executed.", "Usage:\n\temv challenge -> get challenge\n\temv challenge -k -> get challenge, keep fileld ON\n"); void* argtable[] = { @@ -506,34 +506,34 @@ int CmdEMVGenerateChallenge(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool leaveSignalON = arg_get_lit(1); bool APDULogging = arg_get_lit(2); EMVCommandChannel channel = ECC_CONTACTLESS; if (arg_get_lit(3)) channel = ECC_CONTACT; PrintChannel(channel); - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); - + // exec uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; uint16_t sw = 0; int res = EMVGenerateChallenge(channel, leaveSignalON, buf, sizeof(buf), &len, &sw, NULL); - + if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); if (res) return res; PrintAndLogEx(SUCCESS, "Challenge: %s", sprint_hex(buf, len)); - + if (len != 4 && len != 8) PrintAndLogEx(WARNING, "Length of challenge must be 4 or 8, but it %d", len); - + return 0; } @@ -541,14 +541,14 @@ int CmdEMVInternalAuthenticate(const char *cmd) { uint8_t data[APDU_RES_LEN] = {0}; int datalen = 0; - CLIParserInit("emv intauth", + CLIParserInit("emv intauth", "Generate Internal Authenticate command. Usually needs 4-byte random number. It returns data in TLV format .\n" - "Needs a EMV applet to be selected and GPO to be executed.", - + "Needs a EMV applet to be selected and GPO to be executed.", + "Usage:\n" "\temv intauth -k 01020304 -> execute Internal Authenticate with 4-byte DDOLdata and keep field ON after command\n" "\temv intauth -t 01020304 -> execute Internal Authenticate with 4-byte DDOL data, show result in TLV\n" - "\temv intauth -pmt 9F 37 04 -> load params from file, make DDOL data from DDOL, Internal Authenticate with DDOL, show result in TLV"); + "\temv intauth -pmt 9F 37 04 -> load params from file, make DDOL data from DDOL, Internal Authenticate with DDOL, show result in TLV"); void* argtable[] = { arg_param_begin, @@ -562,7 +562,7 @@ int CmdEMVInternalAuthenticate(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, false); - + bool leaveSignalON = arg_get_lit(1); bool paramsLoadFromFile = arg_get_lit(2); bool dataMakeFromDDOL = arg_get_lit(3); @@ -573,14 +573,14 @@ int CmdEMVInternalAuthenticate(const char *cmd) { channel = ECC_CONTACT; PrintChannel(channel); CLIGetHexWithReturn(7, data, &datalen); - CLIParserFree(); - + CLIParserFree(); + SetAPDULogging(APDULogging); // Init TLV tree const char *alr = "Root terminal TLV tree"; struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr); - + // calc DDOL struct tlv *ddol_data_tlv = NULL; struct tlvdb *tmp_ext = NULL; @@ -589,7 +589,7 @@ int CmdEMVInternalAuthenticate(const char *cmd) { .len = datalen, .value = (uint8_t *)data, }; - + if (dataMakeFromDDOL) { ParamLoadDefaults(tlvRoot); @@ -597,7 +597,7 @@ int CmdEMVInternalAuthenticate(const char *cmd) { PrintAndLogEx(INFO, "Params loading from file..."); ParamLoadFromJson(tlvRoot); }; - + tmp_ext = tlvdb_external(0x9f49, datalen, data); ddol_data_tlv = dol_process((const struct tlv *)tmp_ext, tlvRoot, 0x01); // 0x01 - dummy tag if (!ddol_data_tlv){ @@ -612,44 +612,44 @@ int CmdEMVInternalAuthenticate(const char *cmd) { } ddol_data_tlv = &data_tlv; } - + PrintAndLogEx(INFO, "DDOL data[%d]: %s", ddol_data_tlv->len, sprint_hex(ddol_data_tlv->value, ddol_data_tlv->len)); - + // exec uint8_t buf[APDU_RES_LEN] = {0}; size_t len = 0; uint16_t sw = 0; int res = EMVInternalAuthenticate(channel, leaveSignalON, data, datalen, buf, sizeof(buf), &len, &sw, NULL); - + if (ddol_data_tlv != &data_tlv) free(ddol_data_tlv); - tlvdb_free(tmp_ext); - tlvdb_free(tlvRoot); - + tlvdb_free(tmp_ext); + tlvdb_free(tlvRoot); + if (sw) - PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); + PrintAndLogEx(INFO, "APDU response status: %04x - %s", sw, GetAPDUCodeDescription(sw >> 8, sw & 0xff)); if (res) return res; - + if (decodeTLV) TLVPrintFromBuffer(buf, len); - return 0; + return 0; } #define dreturn(n) {free(pdol_data_tlv); tlvdb_free(tlvSelect); tlvdb_free(tlvRoot); DropFieldEx( channel ); return n;} void InitTransactionParameters(struct tlvdb *tlvRoot, bool paramLoadJSON, enum TransactionType TrType, bool GenACGPO) { - + ParamLoadDefaults(tlvRoot); if (paramLoadJSON) { PrintAndLog("* * Transaction parameters loading from JSON..."); ParamLoadFromJson(tlvRoot); } - + //9F66:(Terminal Transaction Qualifiers (TTQ)) len:4 char *qVSDC = "\x26\x00\x00\x00"; if (GenACGPO) { @@ -660,7 +660,7 @@ void InitTransactionParameters(struct tlvdb *tlvRoot, bool paramLoadJSON, enum T TLV_ADD(0x9F66, "\x86\x00\x00\x00"); // MSD break; // not standard for contactless. just for test. - case TT_VSDC: + case TT_VSDC: TLV_ADD(0x9F66, "\x46\x00\x00\x00"); // VSDC break; case TT_QVSDCMCHIP: @@ -680,7 +680,7 @@ void ProcessGPOResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t len, PrintAndLog("GPO response format1:"); TLVPrintFromBuffer(buf, len); } - + if (len < 4 || (len - 4) % 4) { PrintAndLogEx(ERR, "GPO response format1 parsing error. length=%d", len); } else { @@ -697,7 +697,7 @@ void ProcessGPOResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t len, tlvdb_add(tlvRoot, f1AFL); if (decodeTLV) TLVPrintFromTLV(f1AFL); - } + } } else { if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -710,38 +710,38 @@ void ProcessACResponseFormat1(struct tlvdb *tlvRoot, uint8_t *buf, size_t len, b PrintAndLog("GPO response format1:"); TLVPrintFromBuffer(buf, len); } - + uint8_t elmlen = len - 2; // wo 0x80XX - + if (len < 4 + 2 || (elmlen - 2) % 4 || elmlen != buf[1]) { PrintAndLogEx(ERR, "GPO response format1 parsing error. length=%d", len); } else { struct tlvdb *tlvElm = NULL; if (decodeTLV) PrintAndLog("\n------------ Format1 decoded ------------"); - + // CID (Cryptogram Information Data) tlvdb_change_or_add_node_ex(tlvRoot, 0x9f27, 1, &buf[2], &tlvElm); if (decodeTLV) TLVPrintFromTLV(tlvElm); // ATC (Application Transaction Counter) - tlvdb_change_or_add_node_ex(tlvRoot, 0x9f36, 2, &buf[3], &tlvElm); + tlvdb_change_or_add_node_ex(tlvRoot, 0x9f36, 2, &buf[3], &tlvElm); if (decodeTLV) TLVPrintFromTLV(tlvElm); // AC (Application Cryptogram) - tlvdb_change_or_add_node_ex(tlvRoot, 0x9f26, MIN(8, elmlen - 3), &buf[5], &tlvElm); + tlvdb_change_or_add_node_ex(tlvRoot, 0x9f26, MIN(8, elmlen - 3), &buf[5], &tlvElm); if (decodeTLV) TLVPrintFromTLV(tlvElm); // IAD (Issuer Application Data) - optional if (len > 11 + 2) { - tlvdb_change_or_add_node_ex(tlvRoot, 0x9f10, elmlen - 11, &buf[13], &tlvElm); + tlvdb_change_or_add_node_ex(tlvRoot, 0x9f10, elmlen - 11, &buf[13], &tlvElm); if (decodeTLV) TLVPrintFromTLV(tlvElm); - } - } + } + } } else { if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -756,15 +756,15 @@ int CmdEMVExec(const char *cmd) { size_t AIDlen = 0; uint8_t ODAiList[4096]; size_t ODAiListLen = 0; - + int res; - + struct tlvdb *tlvSelect = NULL; struct tlvdb *tlvRoot = NULL; struct tlv *pdol_data_tlv = NULL; - CLIParserInit("emv exec", - "Executes EMV contactless transaction", + CLIParserInit("emv exec", + "Executes EMV contactless transaction", "Usage:\n" "\temv exec -sat -> select card, execute MSD transaction, show APDU and TLV\n" "\temv exec -satc -> select card, execute CDA transaction, show APDU and TLV\n"); @@ -785,7 +785,7 @@ int CmdEMVExec(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool activateField = arg_get_lit(1); bool showAPDU = arg_get_lit(2); bool decodeTLV = arg_get_lit(3); @@ -807,17 +807,17 @@ int CmdEMVExec(const char *cmd) { PrintChannel(channel); uint8_t psenum = (channel == ECC_CONTACT) ? 1 : 2; CLIParserFree(); - + #ifndef WITH_SMARTCARD // not compiled with smartcard functionality, we need to exit if ( channel == ECC_CONTACT ) { PrintAndLogEx(WARNING, "PM3 Client is not compiled with support for SMARTCARD. Exiting."); return 0; } -#endif +#endif SetAPDULogging(showAPDU); - + // init applets list tree const char *al = "Applets list"; tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al); @@ -831,12 +831,12 @@ int CmdEMVExec(const char *cmd) { res = EMVSearchPSE(channel, activateField, true, psenum, decodeTLV, tlvSelect); // check PPSE and select application id - if (!res) { + if (!res) { TLVPrintAIDlistFromSelectTLV(tlvSelect); EMVSelectApplication(tlvSelect, AID, &AIDlen); } } - + // Search if (!AIDlen) { PrintAndLogEx(NORMAL, "\n* Search AID in list."); @@ -849,42 +849,42 @@ int CmdEMVExec(const char *cmd) { TLVPrintAIDlistFromSelectTLV(tlvSelect); EMVSelectApplication(tlvSelect, AID, &AIDlen); } - + // Init TLV tree const char *alr = "Root terminal TLV tree"; tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr); - + // check if we found EMV application on card if (!AIDlen) { PrintAndLogEx(WARNING, "Can't select AID. EMV AID not found"); dreturn(2); } - + // Select PrintAndLogEx(NORMAL, "\n* Selecting AID:%s", sprint_hex_inrow(AID, AIDlen)); SetAPDULogging(showAPDU); res = EMVSelect(channel, false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot); - - if (res) { + + if (res) { PrintAndLogEx(WARNING, "Can't select AID (%d). Exit...", res); dreturn(3); } - + if (decodeTLV) TLVPrintFromBuffer(buf, len); PrintAndLog("* Selected."); - + PrintAndLog("\n* Init transaction parameters."); InitTransactionParameters(tlvRoot, paramLoadJSON, TrType, GenACGPO); TLVPrintFromTLV(tlvRoot); // TODO delete!!! - + PrintAndLogEx(NORMAL, "\n* Calc PDOL."); pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83); if (!pdol_data_tlv){ PrintAndLogEx(WARNING, "Error: can't create PDOL TLV."); dreturn(4); } - + size_t pdol_data_tlv_data_len; unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len); if (!pdol_data_tlv_data) { @@ -895,40 +895,40 @@ int CmdEMVExec(const char *cmd) { PrintAndLogEx(NORMAL, "\n* GPO."); res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); - + free(pdol_data_tlv_data); //free(pdol_data_tlv); --- free on exit. - - if (res) { + + if (res) { PrintAndLogEx(NORMAL, "GPO error(%d): %4x. Exit...", res, sw); dreturn(5); } // process response template format 1 [id:80 2b AIP + x4b AFL] and format 2 [id:77 TLV] ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV); - + // extract PAN from track2 { const struct tlv *track2 = tlvdb_get(tlvRoot, 0x57, NULL); if (!tlvdb_get(tlvRoot, 0x5a, NULL) && track2 && track2->len >= 8) { struct tlvdb *pan = GetPANFromTrack2(track2); if (pan) { - tlvdb_add(tlvRoot, pan); - - const struct tlv *pantlv = tlvdb_get(tlvRoot, 0x5a, NULL); + tlvdb_add(tlvRoot, pan); + + const struct tlv *pantlv = tlvdb_get(tlvRoot, 0x5a, NULL); PrintAndLogEx(NORMAL, "\n* * Extracted PAN from track2: %s", sprint_hex(pantlv->value, pantlv->len)); } else { PrintAndLogEx(NORMAL, "\n* * WARNING: Can't extract PAN from track2."); } } } - + PrintAndLogEx(NORMAL, "\n* Read records from AFL."); const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL); if (!AFL || !AFL->len) PrintAndLogEx(NORMAL, "WARNING: AFL not found."); - + while (AFL && AFL->len) { if (AFL->len % 4) { PrintAndLogEx(WARNING, "Error: Wrong AFL length: %d", AFL->len); @@ -940,27 +940,27 @@ int CmdEMVExec(const char *cmd) { uint8_t SFIstart = AFL->value[i * 4 + 1]; uint8_t SFIend = AFL->value[i * 4 + 2]; uint8_t SFIoffline = AFL->value[i * 4 + 3]; - + PrintAndLogEx(NORMAL, "* * SFI[%02x] start:%02x end:%02x offline count:%02x", SFI, SFIstart, SFIend, SFIoffline); if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) { PrintAndLogEx(NORMAL, "SFI ERROR! Skipped..."); continue; } - + for (int n = SFIstart; n <= SFIend; n++) { PrintAndLogEx(NORMAL, "* * * SFI[%02x] %d", SFI, n); - + res = EMVReadRecord(channel, true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot); if (res) { PrintAndLogEx(WARNING, "Error SFI[%02x]. APDU error %4x", SFI, sw); continue; } - + if (decodeTLV) { TLVPrintFromBuffer(buf, len); PrintAndLogEx(NORMAL, ""); } - + // Build Input list for Offline Data Authentication // EMV 4.3 book3 10.3, page 96 if (SFIoffline > 0) { @@ -978,25 +978,25 @@ int CmdEMVExec(const char *cmd) { memcpy(&ODAiList[ODAiListLen], buf, len); ODAiListLen += len; } - + SFIoffline--; } } } - + break; - } - + } + // copy Input list for Offline Data Authentication if (ODAiListLen) { struct tlvdb *oda = tlvdb_fixed(0x21, ODAiListLen, ODAiList); // not a standard tag - tlvdb_add(tlvRoot, oda); + tlvdb_add(tlvRoot, oda); PrintAndLogEx(NORMAL, "* Input list for Offline Data Authentication added to TLV. len=%d \n", ODAiListLen); } // get AIP uint16_t AIP = 0; - const struct tlv *AIPtlv = tlvdb_get(tlvRoot, 0x82, NULL); + const struct tlv *AIPtlv = tlvdb_get(tlvRoot, 0x82, NULL); if (AIPtlv) { AIP = AIPtlv->value[0] + AIPtlv->value[1] * 0x100; PrintAndLogEx(NORMAL, "* * AIP=%04x", AIP); @@ -1012,10 +1012,10 @@ int CmdEMVExec(const char *cmd) { // DDA if (AIP & 0x0020) { - PrintAndLogEx(NORMAL, "\n* DDA"); + PrintAndLogEx(NORMAL, "\n* DDA"); trDDA(channel, decodeTLV, tlvRoot); - } - + } + // transaction check // qVSDC @@ -1025,11 +1025,11 @@ int CmdEMVExec(const char *cmd) { if (AC) { PrintAndLogEx(NORMAL, "\n--> qVSDC transaction."); PrintAndLogEx(NORMAL, "* AC path"); - + // 9F36: Application Transaction Counter (ATC) const struct tlv *ATC = tlvdb_get(tlvRoot, 0x9F36, NULL); if (ATC) { - + // 9F10: Issuer Application Data - optional const struct tlv *IAD = tlvdb_get(tlvRoot, 0x9F10, NULL); @@ -1038,7 +1038,7 @@ int CmdEMVExec(const char *cmd) { PrintAndLogEx(NORMAL, "AC: %s", sprint_hex(AC->value, AC->len)); if (IAD) { PrintAndLogEx(NORMAL, "IAD: %s", sprint_hex(IAD->value, IAD->len)); - + if (IAD->len >= IAD->value[0] + 1) { PrintAndLogEx(NORMAL, "\tKey index: 0x%02x", IAD->value[1]); PrintAndLogEx(NORMAL, "\tCrypto ver: 0x%02x(%03d)", IAD->value[2], IAD->value[2]); @@ -1049,13 +1049,13 @@ int CmdEMVExec(const char *cmd) { } else { PrintAndLogEx(NORMAL, "WARNING: IAD not found."); } - + } else { PrintAndLogEx(WARNING, "Error AC: Application Transaction Counter (ATC) not found."); } } } - + // Mastercard M/CHIP if (GetCardPSVendor(AID, AIDlen) == CV_MASTERCARD && (TrType == TT_QVSDCMCHIP || TrType == TT_CDA)){ const struct tlv *CDOL1 = tlvdb_get(tlvRoot, 0x8c, NULL); @@ -1072,7 +1072,7 @@ int CmdEMVExec(const char *cmd) { PrintAndLogEx(WARNING, "Error GetChallenge. Wrong challenge length %d", len); dreturn(6); } - + // ICC Dynamic Number struct tlvdb * ICCDynN = tlvdb_fixed(0x9f4c, len, buf); tlvdb_add(tlvRoot, ICCDynN); @@ -1080,39 +1080,39 @@ int CmdEMVExec(const char *cmd) { PrintAndLogEx(NORMAL, "\n* * ICC Dynamic Number:"); TLVPrintFromTLV(ICCDynN); } - + PrintAndLogEx(NORMAL, "* * Calc CDOL1"); struct tlv *cdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x8c, NULL), tlvRoot, 0x01); // 0x01 - dummy tag if (!cdol_data_tlv) { PrintAndLogEx(WARNING, "Error: can't create CDOL1 TLV."); dreturn(6); } - + PrintAndLogEx(NORMAL, "CDOL1 data[%d]: %s", cdol_data_tlv->len, sprint_hex(cdol_data_tlv->value, cdol_data_tlv->len)); - + PrintAndLogEx(NORMAL, "* * AC1"); // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD res = EMVAC(channel, true, (TrType == TT_CDA) ? EMVAC_TC + EMVAC_CDAREQ : EMVAC_TC, (uint8_t *)cdol_data_tlv->value, cdol_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot); - - if (res) { + + if (res) { PrintAndLogEx(NORMAL, "AC1 error(%d): %4x. Exit...", res, sw); dreturn(7); } - + if (decodeTLV) TLVPrintFromBuffer(buf, len); - + // CDA PrintAndLogEx(NORMAL, "\n* CDA:"); struct tlvdb *ac_tlv = tlvdb_parse_multi(buf, len); res = trCDA(tlvRoot, ac_tlv, pdol_data_tlv, cdol_data_tlv); - if (res) { + if (res) { PrintAndLogEx(NORMAL, "CDA error (%d)", res); } - + free(ac_tlv); free(cdol_data_tlv); - + PrintAndLogEx(NORMAL, "\n* M/Chip transaction result:"); // 9F27: Cryptogram Information Data (CID) const struct tlv *CID = tlvdb_get(tlvRoot, 0x9F27, NULL); @@ -1140,14 +1140,14 @@ int CmdEMVExec(const char *cmd) { } else { PrintAndLogEx(WARNING, "Error: CID(9F27) not found."); } - + } } - + // MSD - if (AIP & 0x8000 && TrType == TT_MSD) { + if (AIP & 0x8000 && TrType == TT_MSD) { PrintAndLogEx(NORMAL, "\n--> MSD transaction."); - + PrintAndLogEx(NORMAL, "* MSD dCVV path. Check dCVV"); const struct tlv *track2 = tlvdb_get(tlvRoot, 0x57, NULL); @@ -1157,7 +1157,7 @@ int CmdEMVExec(const char *cmd) { struct tlvdb *dCVV = GetdCVVRawFromTrack2(track2); PrintAndLogEx(NORMAL, "dCVV raw data:"); TLVPrintFromTLV(dCVV); - + if (GetCardPSVendor(AID, AIDlen) == CV_MASTERCARD) { PrintAndLogEx(NORMAL, "\n* Mastercard calculate UDOL"); @@ -1179,16 +1179,16 @@ int CmdEMVExec(const char *cmd) { } PrintAndLogEx(NORMAL, "UDOL data[%d]: %s", udol_data_tlv->len, sprint_hex(udol_data_tlv->value, udol_data_tlv->len)); - + PrintAndLogEx(NORMAL, "\n* Mastercard compute cryptographic checksum(UDOL)"); - + res = MSCComputeCryptoChecksum(channel, true, (uint8_t *)udol_data_tlv->value, udol_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot); if (res) { PrintAndLogEx(WARNING, "Error Compute Crypto Checksum. APDU error %4x", sw); free(udol_data_tlv); dreturn(9); } - + // Mastercard compute cryptographic checksum result TLVPrintFromBuffer(buf, len); PrintAndLogEx(NORMAL, ""); @@ -1204,21 +1204,21 @@ int CmdEMVExec(const char *cmd) { // VSDC if (GetCardPSVendor(AID, AIDlen) == CV_VISA && (TrType == TT_VSDC || TrType == TT_CDA)){ PrintAndLogEx(NORMAL, "\n--> VSDC transaction."); - + PrintAndLogEx(NORMAL, "* * Calc CDOL1"); struct tlv *cdol1_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x8c, NULL), tlvRoot, 0x01); // 0x01 - dummy tag if (!cdol1_data_tlv) { PrintAndLogEx(WARNING, "Error: can't create CDOL1 TLV."); dreturn(6); } - + PrintAndLogEx(NORMAL, "CDOL1 data[%d]: %s", cdol1_data_tlv->len, sprint_hex(cdol1_data_tlv->value, cdol1_data_tlv->len)); - + PrintAndLogEx(NORMAL, "* * AC1"); // EMVAC_TC + EMVAC_CDAREQ --- to get SDAD res = EMVAC(channel, true, (TrType == TT_CDA) ? EMVAC_TC + EMVAC_CDAREQ : EMVAC_TC, (uint8_t *)cdol1_data_tlv->value, cdol1_data_tlv->len, buf, sizeof(buf), &len, &sw, tlvRoot); - - if (res) { + + if (res) { PrintAndLogEx(NORMAL, "AC1 error(%d): %4x. Exit...", res, sw); free(cdol1_data_tlv); dreturn(7); @@ -1246,10 +1246,10 @@ int CmdEMVExec(const char *cmd) { uint8_t IDDlen = 0; // Issuer discretionary data length PrintAndLogEx(NORMAL, "IAD length: %d", IAD->len); PrintAndLogEx(NORMAL, "VDDlen: %d", VDDlen); - if (VDDlen < IAD->len - 1) + if (VDDlen < IAD->len - 1) IDDlen = IAD->value[VDDlen + 1]; PrintAndLogEx(NORMAL, "IDDlen: %d", IDDlen); - + uint8_t DerivKeyIndex = IAD->value[1]; CryptoVersion = IAD->value[2]; @@ -1267,22 +1267,22 @@ int CmdEMVExec(const char *cmd) { } } if (IDDlen) - PrintAndLogEx(NORMAL, "IDD: %s", sprint_hex(&IAD->value[VDDlen + 1], IDDlen)); + PrintAndLogEx(NORMAL, "IDD: %s", sprint_hex(&IAD->value[VDDlen + 1], IDDlen)); } else { PrintAndLogEx(NORMAL, "Issuer Application Data (IAD) not found."); } - + PrintAndLogEx(NORMAL, "\n* * Processing online request"); // authorization response code from acquirer const char HostResponse[] = "00"; // 0x3030 size_t HostResponseLen = sizeof(HostResponse) - 1; PrintAndLogEx(NORMAL, "Host Response: `%s`", HostResponse); - tlvdb_change_or_add_node(tlvRoot, 0x8a, HostResponseLen, (const unsigned char *)HostResponse); - + tlvdb_change_or_add_node(tlvRoot, 0x8a, HostResponseLen, (const unsigned char *)HostResponse); + if (CryptoVersion == 10) { PrintAndLogEx(NORMAL, "\n* * Generate ARPC"); - + // Application Cryptogram (AC) const struct tlv *AC = tlvdb_get(tlvRoot, 0x9f26, NULL); if (AC && (AC->len > 0)) { @@ -1294,18 +1294,18 @@ int CmdEMVExec(const char *cmd) { for (int i = 0; (i < HostResponseLen) && (i < rawARPClen); i++) rawARPC[i] ^= HostResponse[i]; PrintAndLogEx(NORMAL, "raw ARPC: %s", sprint_hex(rawARPC, rawARPClen)); - + // here must be calculation of ARPC, but we dont know a bank keys. PrintAndLogEx(NORMAL, "ARPC: n/a"); - + } else { PrintAndLogEx(NORMAL, "Application Cryptogram (AC) not found."); } // here must be external authenticate, but we dont know ARPC - + } - + // needs to send AC2 command (res == ARQC) if ((CID & EMVAC_AC_MASK) == EMVAC_ARQC) { @@ -1315,14 +1315,14 @@ int CmdEMVExec(const char *cmd) { PrintAndLogEx(WARNING, "Error: can't create CDOL2 TLV."); dreturn(6); } - + PrintAndLogEx(NORMAL, "CDOL2 data[%d]: %s", cdol2_data_tlv->len, sprint_hex(cdol2_data_tlv->value, cdol2_data_tlv->len)); - + //PrintAndLogEx(NORMAL, "* * AC2"); - - + + // here must be AC2, but we dont make external authenticate ( - + /* // AC2 PRINT_INDENT(level); if ((CID & EMVAC_AC2_MASK) == EMVAC_AAC2) fprintf(f, "\tAC2: AAC (Transaction declined)\n"); @@ -1331,11 +1331,11 @@ int CmdEMVExec(const char *cmd) { if ((CID & EMVAC_AC2_MASK) == EMVAC_AC2_MASK) fprintf(f, "\tAC2: RFU\n"); */ } - + } - + DropFieldEx( channel ); - + // Destroy TLV's free(pdol_data_tlv); tlvdb_free(tlvSelect); @@ -1355,8 +1355,8 @@ int CmdEMVScan(const char *cmd) { json_t *root; json_error_t error; - CLIParserInit("emv scan", - "Scan EMV card and save it contents to a file.", + CLIParserInit("emv scan", + "Scan EMV card and save it contents to a file.", "It executes EMV contactless transaction and saves result to a file which can be used for emulation\n" "Usage:\n\temv scan -at -> scan MSD transaction mode and show APDU and TLV\n" "\temv scan -c -> scan CDA transaction mode\n"); @@ -1378,7 +1378,7 @@ int CmdEMVScan(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + bool showAPDU = arg_get_lit(1); bool decodeTLV = arg_get_lit(2); bool extractTLVElements = arg_get_lit(3); @@ -1404,17 +1404,17 @@ int CmdEMVScan(const char *cmd) { int relfnamelen = 0; CLIGetStrWithReturn(12, relfname, &relfnamelen); CLIParserFree(); - + #ifndef WITH_SMARTCARD // not compiled with smartcard functionality, we need to exit if ( channel == ECC_CONTACT ) { PrintAndLogEx(WARNING, "PM3 Client is not compiled with support for SMARTCARD. Exiting."); return 0; } -#endif +#endif SetAPDULogging(showAPDU); - + // current path + file name if (!strstr(crelfname, ".json")) strcat(crelfname, ".json"); @@ -1426,12 +1426,12 @@ int CmdEMVScan(const char *cmd) { root = json_load_file(fname, 0, &error); if (!root) { PrintAndLogEx(ERR, "Json error on line %d: %s", error.line, error.text); - return 1; + return 1; } - + if (!json_is_object(root)) { PrintAndLogEx(ERR, "Invalid json format. root must be an object."); - return 1; + return 1; } } else { root = json_object(); @@ -1441,16 +1441,16 @@ int CmdEMVScan(const char *cmd) { DropFieldEx( channel ); JsonSaveStr(root, "$.File.Created", "proxmark3 `emv scan`"); - + if (channel == ECC_CONTACTLESS) { // iso 14443 select PrintAndLogEx(NORMAL, "--> GET UID, ATS."); - + iso14a_card_select_t card; if (Hf14443_4aGetCardData(&card)) { return 2; } - + JsonSaveStr(root, "$.Card.Contactless.Communication", "iso14443-4a"); JsonSaveBufAsHex(root, "$.Card.Contactless.UID", (uint8_t *)&card.uid, card.uidlen); JsonSaveHex(root, "$.Card.Contactless.ATQA", card.atqa[0] + (card.atqa[1] << 2), 2); @@ -1458,22 +1458,22 @@ int CmdEMVScan(const char *cmd) { JsonSaveBufAsHex(root, "$.Card.Contactless.ATS", (uint8_t *)card.ats, card.ats_len); } else { PrintAndLogEx(NORMAL, "--> GET ATR."); - + smart_card_atr_t card; smart_select(true, &card); if (!card.atr_len) { PrintAndLogEx(ERR, "Can't get ATR from a smart card."); return 1; } - + JsonSaveStr(root, "$.Card.Contact.Communication", "iso7816"); JsonSaveBufAsHex(root, "$.Card.Contact.ATR", (uint8_t *)card.atr, card.atr_len); } - + // init applets list tree const char *al = "Applets list"; struct tlvdb *tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al); - + // EMV PPSE PrintAndLogEx(NORMAL, "--> PPSE."); res = EMVSelectPSE(channel, true, true, 2, buf, sizeof(buf), &len, &sw); @@ -1481,9 +1481,9 @@ int CmdEMVScan(const char *cmd) { if (!res && sw == 0x9000){ if (decodeTLV) TLVPrintFromBuffer(buf, len); - + JsonSaveBufAsHex(root, "$.PPSE.AID", (uint8_t *)"2PAY.SYS.DDF01", 14); - + struct tlvdb *fci = tlvdb_parse_multi(buf, len); if (extractTLVElements) JsonSaveTLVTree(root, root, "$.PPSE.FCITemplate", fci); @@ -1496,8 +1496,8 @@ int CmdEMVScan(const char *cmd) { res = EMVSearchPSE(channel, false, true, psenum, decodeTLV, tlvSelect); // check PPSE and select application id - if (!res) { - TLVPrintAIDlistFromSelectTLV(tlvSelect); + if (!res) { + TLVPrintAIDlistFromSelectTLV(tlvSelect); } else { // EMV SEARCH with AID list SetAPDULogging(false); @@ -1526,7 +1526,7 @@ int CmdEMVScan(const char *cmd) { } JsonSaveBufAsHex(root, "$.Application.AID", AID, AIDlen); - + // Init TLV tree const char *alr = "Root terminal TLV tree"; struct tlvdb *tlvRoot = tlvdb_fixed(1, strlen(alr), (const unsigned char *)alr); @@ -1536,14 +1536,14 @@ int CmdEMVScan(const char *cmd) { PrintAndLogEx(NORMAL, "\n-->Selecting AID:%s.", sprint_hex_inrow(AID, AIDlen)); SetAPDULogging(showAPDU); res = EMVSelect(channel, false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot); - - if (res) { + + if (res) { PrintAndLogEx(ERR, "Can't select AID (%d). Exit...", res); tlvdb_free(tlvRoot); DropFieldEx( channel ); return 5; } - + if (decodeTLV) TLVPrintFromBuffer(buf, len); @@ -1562,7 +1562,7 @@ int CmdEMVScan(const char *cmd) { // create transaction parameters PrintAndLogEx(NORMAL, "-->Init transaction parameters."); InitTransactionParameters(tlvRoot, paramLoadJSON, TrType, GenACGPO); - + PrintAndLogEx(NORMAL, "-->Calc PDOL."); struct tlv *pdol_data_tlv = dol_process(tlvdb_get(tlvRoot, 0x9f38, NULL), tlvRoot, 0x83); if (!pdol_data_tlv){ @@ -1571,7 +1571,7 @@ int CmdEMVScan(const char *cmd) { DropFieldEx( channel ); return 6; } - + size_t pdol_data_tlv_data_len; unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len); if (!pdol_data_tlv_data) { @@ -1584,18 +1584,18 @@ int CmdEMVScan(const char *cmd) { PrintAndLogEx(INFO, "-->GPO."); res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); - + free(pdol_data_tlv_data); free(pdol_data_tlv); - - if (res) { + + if (res) { PrintAndLogEx(ERR, "GPO error(%d): %4x. Exit...", res, sw); tlvdb_free(tlvRoot); DropFieldEx( channel ); return 7; } ProcessGPOResponseFormat1(tlvRoot, buf, len, decodeTLV); - + struct tlvdb *gpofci = tlvdb_parse_multi(buf, len); if (extractTLVElements) JsonSaveTLVTree(root, root, "$.Application.GPO", gpofci); @@ -1609,7 +1609,7 @@ int CmdEMVScan(const char *cmd) { PrintAndLogEx(INFO, "-->Read records from AFL."); const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL); - + while(AFL && AFL->len) { if (AFL->len % 4) { PrintAndLogEx(ERR, "Wrong AFL length: %d", AFL->len); @@ -1620,7 +1620,7 @@ int CmdEMVScan(const char *cmd) { if (!sfijson) { json_t *app = json_path_get(root, "$.Application"); json_object_set_new(app, "Records", json_array()); - + sfijson = json_path_get(root, "$.Application.Records"); } if (!json_is_array(sfijson)) { @@ -1632,34 +1632,34 @@ int CmdEMVScan(const char *cmd) { uint8_t SFIstart = AFL->value[i * 4 + 1]; uint8_t SFIend = AFL->value[i * 4 + 2]; uint8_t SFIoffline = AFL->value[i * 4 + 3]; - + PrintAndLogEx(INFO, "--->SFI[%02x] start:%02x end:%02x offline:%02x", SFI, SFIstart, SFIend, SFIoffline); if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) { PrintAndLogEx(ERR, "SFI ERROR! Skipped..."); continue; } - + for(int n = SFIstart; n <= SFIend; n++) { PrintAndLogEx(INFO, "---->SFI[%02x] %d", SFI, n); - + res = EMVReadRecord(channel, true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot); if (res) { PrintAndLogEx(ERR, "SFI[%02x]. APDU error %4x", SFI, sw); continue; } - + if (decodeTLV) { TLVPrintFromBuffer(buf, len); PrintAndLog(""); } - + json_t *jsonelm = json_object(); json_array_append_new(sfijson, jsonelm); JsonSaveHex(jsonelm, "SFI", SFI, 1); JsonSaveHex(jsonelm, "RecordNum", n, 1); JsonSaveHex(jsonelm, "Offline", SFIoffline, 1); - + struct tlvdb *rsfi = tlvdb_parse_multi(buf, len); if (extractTLVElements) JsonSaveTLVTree(root, jsonelm, "$.Data", rsfi); @@ -1668,10 +1668,10 @@ int CmdEMVScan(const char *cmd) { tlvdb_free(rsfi); } } - + break; } - + // getting certificates if (tlvdb_get(tlvRoot, 0x90, NULL)) { PrintAndLogEx(INFO, "-->Recovering certificates."); @@ -1679,22 +1679,22 @@ int CmdEMVScan(const char *cmd) { RecoveryCertificates(tlvRoot, root); PKISetStrictExecution(true); } - + // free tlv object tlvdb_free(tlvRoot); DropFieldEx( channel ); - + res = json_dump_file(root, fname, JSON_INDENT(2)); if (res) { PrintAndLogEx(ERR, "Can't save the file: %s", fname); return 200; } PrintAndLogEx(SUCCESS, "File `%s` saved.", fname); - + // free json object json_decref(root); - + return 0; } @@ -1713,9 +1713,9 @@ int CmdEMVRoca(const char *cmd) { size_t len = 0; uint16_t sw = 0; int res; - - CLIParserInit("emv roca", - "Tries to extract public keys and run the ROCA test against them.\n", + + CLIParserInit("emv roca", + "Tries to extract public keys and run the ROCA test against them.\n", "Usage:\n" "\temv roca -w -> select --CONTACT-- card and run test\n" "\temv roca -> select --CONTACTLESS-- card and run test\n" @@ -1728,7 +1728,7 @@ int CmdEMVRoca(const char *cmd) { arg_param_end }; CLIExecWithReturn(cmd, argtable, true); - + EMVCommandChannel channel = ECC_CONTACTLESS; if (arg_get_lit(1)) return roca_self_test(); @@ -1737,20 +1737,20 @@ int CmdEMVRoca(const char *cmd) { channel = ECC_CONTACT; PrintChannel(channel); CLIParserFree(); - + #ifndef WITH_SMARTCARD // not compiled with smartcard functionality, we need to exit if ( channel == ECC_CONTACT ) { PrintAndLogEx(WARNING, "PM3 Client is not compiled with support for SMARTCARD. Exiting."); return 0; } -#endif +#endif // select card uint8_t psenum = (channel == ECC_CONTACT) ? 1 : 2; - + SetAPDULogging(false); - + // init applets list tree const char *al = "Applets list"; struct tlvdb *tlvSelect = tlvdb_fixed(1, strlen(al), (const unsigned char *)al); @@ -1760,8 +1760,8 @@ int CmdEMVRoca(const char *cmd) { res = EMVSearchPSE(channel, false, true, psenum, false, tlvSelect); // check PPSE and select application id - if (!res) { - TLVPrintAIDlistFromSelectTLV(tlvSelect); + if (!res) { + TLVPrintAIDlistFromSelectTLV(tlvSelect); } else { // EMV SEARCH with AID list PrintAndLogEx(NORMAL, "--> AID search."); @@ -1795,8 +1795,8 @@ int CmdEMVRoca(const char *cmd) { // EMV SELECT applet PrintAndLogEx(NORMAL, "\n-->Selecting AID:%s.", sprint_hex_inrow(AID, AIDlen)); res = EMVSelect(channel, false, true, AID, AIDlen, buf, sizeof(buf), &len, &sw, tlvRoot); - - if (res) { + + if (res) { PrintAndLogEx(ERR, "Can't select AID (%d). Exit...", res); tlvdb_free(tlvRoot); DropFieldEx( channel ); @@ -1814,7 +1814,7 @@ int CmdEMVRoca(const char *cmd) { DropFieldEx( channel ); return 6; } - + size_t pdol_data_tlv_data_len; unsigned char *pdol_data_tlv_data = tlv_encode(pdol_data_tlv, &pdol_data_tlv_data_len); if (!pdol_data_tlv_data) { @@ -1828,21 +1828,21 @@ int CmdEMVRoca(const char *cmd) { PrintAndLogEx(INFO, "-->GPO."); res = EMVGPO(channel, true, pdol_data_tlv_data, pdol_data_tlv_data_len, buf, sizeof(buf), &len, &sw, tlvRoot); - + free(pdol_data_tlv_data); free(pdol_data_tlv); - - if (res) { + + if (res) { PrintAndLogEx(ERR, "GPO error(%d): %4x. Exit...", res, sw); tlvdb_free(tlvRoot); DropFieldEx( channel ); return 7; } ProcessGPOResponseFormat1(tlvRoot, buf, len, false); - + PrintAndLogEx(INFO, "-->Read records from AFL."); const struct tlv *AFL = tlvdb_get(tlvRoot, 0x94, NULL); - + while(AFL && AFL->len) { if (AFL->len % 4) { PrintAndLogEx(ERR, "Wrong AFL length: %d", AFL->len); @@ -1854,16 +1854,16 @@ int CmdEMVRoca(const char *cmd) { uint8_t SFIstart = AFL->value[i * 4 + 1]; uint8_t SFIend = AFL->value[i * 4 + 2]; uint8_t SFIoffline = AFL->value[i * 4 + 3]; - + PrintAndLogEx(INFO, "--->SFI[%02x] start:%02x end:%02x offline:%02x", SFI, SFIstart, SFIend, SFIoffline); if (SFI == 0 || SFI == 31 || SFIstart == 0 || SFIstart > SFIend) { PrintAndLogEx(ERR, "SFI ERROR! Skipped..."); continue; } - + for(int n = SFIstart; n <= SFIend; n++) { PrintAndLogEx(INFO, "---->SFI[%02x] %d", SFI, n); - + res = EMVReadRecord(channel, true, SFI, n, buf, sizeof(buf), &len, &sw, tlvRoot); if (res) { PrintAndLogEx(ERR, "SFI[%02x]. APDU error %4x", SFI, sw); @@ -1871,7 +1871,7 @@ int CmdEMVRoca(const char *cmd) { } } } - + break; } @@ -1892,7 +1892,7 @@ int CmdEMVRoca(const char *cmd) { PrintAndLogEx(WARNING, "WARNING: Issuer certificate not found. Exit."); goto out; } - + PrintAndLogEx(SUCCESS, "Issuer PK recovered. RID %s IDX %02hhx CSN %s", sprint_hex(issuer_pk->rid, 5), issuer_pk->index, @@ -1912,9 +1912,9 @@ int CmdEMVRoca(const char *cmd) { icc_pk->index, sprint_hex(icc_pk->serial, 3) ); - + PrintAndLogEx(INFO, "ICC pk modulus: %s", sprint_hex_inrow(icc_pk->modulus, icc_pk->mlen)); - + // icc_pk->exp, icc_pk->elen // icc_pk->modulus, icc_pk->mlen if (icc_pk->elen > 0 && icc_pk->mlen > 0) { @@ -1923,13 +1923,13 @@ int CmdEMVRoca(const char *cmd) { } else { PrintAndLogEx(INFO, "ICC pk is OK("); } - } - + } + PKISetStrictExecution(true); } out: - + // free tlv object tlvdb_free(tlvRoot); @@ -1951,14 +1951,14 @@ static command_t CommandTable[] = { {"scan", CmdEMVScan, 0, "Scan EMV card and save it contents to json file for emulator."}, {"test", CmdEMVTest, 0, "Crypto logic test."}, /* - {"getrng", CmdEMVGetrng, 0, "get random number from terminal"}, + {"getrng", CmdEMVGetrng, 0, "get random number from terminal"}, {"eload", CmdEmvELoad, 0, "load EMV tag into device"}, {"dump", CmdEmvDump, 0, "dump EMV tag values"}, {"sim", CmdEmvSim, 0, "simulate EMV tag"}, - {"clone", CmdEmvClone, 0, "clone an EMV tag"}, + {"clone", CmdEmvClone, 0, "clone an EMV tag"}, */ - {"list", CmdEMVList, 0, "[Deprecated] List ISO7816 history"}, - {"roca", CmdEMVRoca, 0, "Extract public keys and run ROCA test"}, + {"list", CmdEMVList, 0, "[Deprecated] List ISO7816 history"}, + {"roca", CmdEMVRoca, 0, "Extract public keys and run ROCA test"}, {NULL, NULL, 0, NULL} }; diff --git a/client/emv/crypto.c b/client/emv/crypto.c index c8ced6d43..d8ec5fc08 100644 --- a/client/emv/crypto.c +++ b/client/emv/crypto.c @@ -29,7 +29,7 @@ static bool crypto_init(void) if (crypto_backend) return true; - crypto_backend = crypto_polarssl_init(); + crypto_backend = crypto_polarssl_init(); if (!crypto_backend) return false; diff --git a/client/emv/crypto_polarssl.c b/client/emv/crypto_polarssl.c index 938535059..f04b6c9e5 100644 --- a/client/emv/crypto_polarssl.c +++ b/client/emv/crypto_polarssl.c @@ -98,11 +98,11 @@ static struct crypto_pk *crypto_pk_polarssl_open_rsa(va_list vl) int explen = va_arg(vl, size_t); mbedtls_rsa_init(&cp->ctx, MBEDTLS_RSA_PKCS_V15, 0); - + cp->ctx.len = modlen; // size(N) in bytes mbedtls_mpi_read_binary(&cp->ctx.N, (const unsigned char *)mod, modlen); mbedtls_mpi_read_binary(&cp->ctx.E, (const unsigned char *)exp, explen); - + int res = mbedtls_rsa_check_pubkey(&cp->ctx); if(res != 0) { fprintf(stderr, "PolarSSL public key error res=%x exp=%d mod=%d.\n", res * -1, explen, modlen); @@ -133,10 +133,10 @@ static struct crypto_pk *crypto_pk_polarssl_open_priv_rsa(va_list vl) int dqlen = va_arg(vl, size_t); // calc QP via Q and P // char *inv = va_arg(vl, char *); -// int invlen = va_arg(vl, size_t); - +// int invlen = va_arg(vl, size_t); + mbedtls_rsa_init(&cp->ctx, MBEDTLS_RSA_PKCS_V15, 0); - + cp->ctx.len = modlen; // size(N) in bytes mbedtls_mpi_read_binary(&cp->ctx.N, (const unsigned char *)mod, modlen); mbedtls_mpi_read_binary(&cp->ctx.E, (const unsigned char *)exp, explen); @@ -147,7 +147,7 @@ static struct crypto_pk *crypto_pk_polarssl_open_priv_rsa(va_list vl) mbedtls_mpi_read_binary(&cp->ctx.DP, (const unsigned char *)dp, dplen); mbedtls_mpi_read_binary(&cp->ctx.DQ, (const unsigned char *)dq, dqlen); mbedtls_mpi_inv_mod(&cp->ctx.QP, &cp->ctx.Q, &cp->ctx.P); - + int res = mbedtls_rsa_check_privkey(&cp->ctx); if(res != 0) { fprintf(stderr, "PolarSSL private key error res=%x exp=%d mod=%d.\n", res * -1, explen, modlen); @@ -166,7 +166,7 @@ static int myrand(void *rng_state, unsigned char *output, size_t len) { for( i = 0; i < len; ++i ) output[i] = rand(); - + return 0; } @@ -175,21 +175,21 @@ static struct crypto_pk *crypto_pk_polarssl_genkey_rsa(va_list vl) { struct crypto_pk_polarssl *cp = malloc(sizeof(*cp)); memset(cp, 0x00, sizeof(*cp)); - + int transient = va_arg(vl, int); unsigned int nbits = va_arg(vl, unsigned int); unsigned int exp = va_arg(vl, unsigned int); if (transient) { } - + int res = mbedtls_rsa_gen_key(&cp->ctx, &myrand, NULL, nbits, exp); if (res) { fprintf(stderr, "PolarSSL private key generation error res=%x exp=%d nbits=%d.\n", res * -1, exp, nbits); free(cp); return NULL; } - + return &cp->cp; } @@ -206,7 +206,7 @@ static unsigned char *crypto_pk_polarssl_encrypt(const struct crypto_pk *_cp, co struct crypto_pk_polarssl *cp = (struct crypto_pk_polarssl *)_cp; int res; unsigned char *result; - + *clen = 0; size_t keylen = mbedtls_mpi_size(&cp->ctx.N); @@ -222,9 +222,9 @@ static unsigned char *crypto_pk_polarssl_encrypt(const struct crypto_pk *_cp, co free(result); return NULL; } - + *clen = keylen; - + return result; } @@ -233,7 +233,7 @@ static unsigned char *crypto_pk_polarssl_decrypt(const struct crypto_pk *_cp, co struct crypto_pk_polarssl *cp = (struct crypto_pk_polarssl *)_cp; int res; unsigned char *result; - + *clen = 0; size_t keylen = mbedtls_mpi_size(&cp->ctx.N); @@ -249,9 +249,9 @@ static unsigned char *crypto_pk_polarssl_decrypt(const struct crypto_pk *_cp, co free(result); return NULL; } - + *clen = keylen; - + return result; } @@ -286,7 +286,7 @@ static unsigned char *crypto_pk_polarssl_get_parameter(const struct crypto_pk *_ printf("Error get parameter. Param=%d", param); break; } - + return result; } diff --git a/client/emv/emv_pk.c b/client/emv/emv_pk.c index 091ab8062..211e4edc2 100644 --- a/client/emv/emv_pk.c +++ b/client/emv/emv_pk.c @@ -486,7 +486,7 @@ struct emv_pk *emv_pk_get_ca_pk(const unsigned char *rid, unsigned char idx) } */ if (!pk) { - const char *relfname = "emv/capk.txt"; + const char *relfname = "emv/capk.txt"; char fname[strlen(get_my_executable_directory()) + strlen(relfname) + 1]; strcpy(fname, get_my_executable_directory()); diff --git a/client/emv/emv_pki.c b/client/emv/emv_pki.c index 84224a957..2c661f11a 100644 --- a/client/emv/emv_pki.c +++ b/client/emv/emv_pki.c @@ -75,7 +75,7 @@ static unsigned char *emv_pki_decode_message(const struct emv_pk *enc_pk, printf("Recovered data:\n"); dump_buffer(data, data_len, stdout, 0); }*/ - + if (data[data_len-1] != 0xbc || data[0] != 0x6a || data[1] != msgtype) { printf("ERROR: Certificate format\n"); free(data); @@ -117,7 +117,7 @@ static unsigned char *emv_pki_decode_message(const struct emv_pk *enc_pk, printf("ERROR: Calculated wrong hash\n"); printf("decoded: %s\n",sprint_hex(data + data_len - 1 - hash_len, hash_len)); printf("calculated: %s\n",sprint_hex(hash, hash_len)); - + if (strictExecution) { crypto_hash_close(ch); free(data); @@ -206,7 +206,7 @@ static struct emv_pk *emv_pki_decode_key_ex(const struct emv_pk *enc_pk, return NULL; } - if (showData){ + if (showData){ printf("Recovered data:\n"); dump_buffer(data, data_len, stdout, 0); } @@ -308,7 +308,7 @@ struct emv_pk *emv_pki_recover_icc_cert(const struct emv_pk *pk, struct tlvdb *d .len = sdatl_len, .value = sdatl }; - + struct emv_pk *res = emv_pki_decode_key(pk, 4, tlvdb_get(db, 0x5a, NULL), tlvdb_get(db, 0x9f46, NULL), @@ -316,7 +316,7 @@ struct emv_pk *emv_pki_recover_icc_cert(const struct emv_pk *pk, struct tlvdb *d tlvdb_get(db, 0x9f48, NULL), sda_tlv, &sda_tdata); - + free(sdatl); // malloc here: emv_pki_sdatl_fill return res; } @@ -335,9 +335,9 @@ struct emv_pk *emv_pki_recover_icc_pe_cert(const struct emv_pk *pk, struct tlvdb unsigned char *emv_pki_sdatl_fill(const struct tlvdb *db, size_t *sdatl_len) { uint8_t buf[2048] = {0}; size_t len = 0; - + *sdatl_len = 0; - + const struct tlv *sda_tl = tlvdb_get(db, 0x9f4a, NULL); if (!sda_tl || sda_tl->len <= 0) return NULL; @@ -348,16 +348,16 @@ unsigned char *emv_pki_sdatl_fill(const struct tlvdb *db, size_t *sdatl_len) { if (elm) { memcpy(&buf[len], elm->value, elm->len); len += elm->len; - } + } } - + if (len) { *sdatl_len = len; unsigned char *value = malloc(len); memcpy(value, buf, len); return value; } - + return NULL; } @@ -365,7 +365,7 @@ unsigned char *emv_pki_sdatl_fill(const struct tlvdb *db, size_t *sdatl_len) { struct tlvdb *emv_pki_recover_dac_ex(const struct emv_pk *enc_pk, const struct tlvdb *db, const struct tlv *sda_tlv, bool showData) { size_t data_len; - + // Static Data Authentication Tag List size_t sdatl_len; unsigned char *sdatl = emv_pki_sdatl_fill(db, &sdatl_len); @@ -383,7 +383,7 @@ struct tlvdb *emv_pki_recover_dac_ex(const struct emv_pk *enc_pk, const struct t NULL); free(sdatl); // malloc here: emv_pki_sdatl_fill - + if (!data || data_len < 5) return NULL; @@ -436,7 +436,7 @@ struct tlvdb *emv_pki_recover_idn_ex(const struct emv_pk *enc_pk, const struct t // 9f4c ICC Dynamic Number struct tlvdb *idn_db = tlvdb_fixed(0x9f4c, idn_len, data + 5); - + free(data); return idn_db; @@ -475,7 +475,7 @@ struct tlvdb *emv_pki_recover_atc_ex(const struct emv_pk *enc_pk, const struct t // 9f36 Application Transaction Counter (ATC) struct tlvdb *atc_db = tlvdb_fixed(0x9f36, idn_len, data + 5); - + free(data); return atc_db; diff --git a/client/emv/emv_roca.c b/client/emv/emv_roca.c index 6f90f11b5..f98117450 100644 --- a/client/emv/emv_roca.c +++ b/client/emv/emv_roca.c @@ -3,7 +3,7 @@ * Copyright (C) 2017-2018 Sectigo Limited * modified 2018 iceman (dropped openssl bignum, now use mbedtls lib) * modified 2018 merlok - * + * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or @@ -30,10 +30,10 @@ static uint8_t g_primes[ROCA_PRINTS_LENGTH] = { mbedtls_mpi g_prints[ROCA_PRINTS_LENGTH]; void rocacheck_init(void) { - + for (int i = 0; i < ROCA_PRINTS_LENGTH; i++) mbedtls_mpi_init(&g_prints[i]); - + mbedtls_mpi_read_string(&g_prints[0], 10, "1026"); mbedtls_mpi_read_string(&g_prints[1], 10, "5658"); mbedtls_mpi_read_string(&g_prints[2], 10, "107286"); @@ -61,7 +61,7 @@ void rocacheck_cleanup(void) { int bitand_is_zero( mbedtls_mpi* a, mbedtls_mpi* b ) { for (int i = 0; i < mbedtls_mpi_bitlen(a); i++) { - + if (mbedtls_mpi_get_bit(a, i) && mbedtls_mpi_get_bit(b, i)) return 0; } @@ -70,7 +70,7 @@ int bitand_is_zero( mbedtls_mpi* a, mbedtls_mpi* b ) { mbedtls_mpi_uint mpi_get_uint(const mbedtls_mpi *X) { - + if (X->n == 1 && X->s > 0) { return X->p[0]; } @@ -79,12 +79,12 @@ mbedtls_mpi_uint mpi_get_uint(const mbedtls_mpi *X) { } void print_mpi(const char *msg, int radix, const mbedtls_mpi *X) { - + char Xchar[400] = {0}; size_t len = 0; - - mbedtls_mpi_write_string(X, radix, Xchar, sizeof(Xchar), &len); - printf("%s[%d] %s\n", msg, len, Xchar); + + mbedtls_mpi_write_string(X, radix, Xchar, sizeof(Xchar), &len); + printf("%s[%d] %s\n", msg, len, Xchar); } bool emv_rocacheck(const unsigned char *buf, size_t buflen, bool verbose) { @@ -97,13 +97,13 @@ bool emv_rocacheck(const unsigned char *buf, size_t buflen, bool verbose) { rocacheck_init(); MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary(&t_modulus, buf, buflen) ); - + for (int i = 0; i < ROCA_PRINTS_LENGTH; i++) { mbedtls_mpi t_temp; mbedtls_mpi t_prime; mbedtls_mpi g_one; - + mbedtls_mpi_init(&t_temp); mbedtls_mpi_init(&t_prime); mbedtls_mpi_init(&g_one); @@ -111,18 +111,18 @@ bool emv_rocacheck(const unsigned char *buf, size_t buflen, bool verbose) { MBEDTLS_MPI_CHK( mbedtls_mpi_read_string(&g_one, 10, "1") ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_int(&t_prime, &t_prime, g_primes[i]) ); - - MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi(&t_temp, &t_modulus, &t_prime) ); - + + MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi(&t_temp, &t_modulus, &t_prime) ); + MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l(&g_one, mpi_get_uint(&t_temp)) ); - + if (bitand_is_zero(&g_one, &g_prints[i])) { if (verbose) PrintAndLogEx(FAILED, "No fingerprint found.\n"); goto cleanup; } - - mbedtls_mpi_free(&g_one); + + mbedtls_mpi_free(&g_one); mbedtls_mpi_free(&t_temp); mbedtls_mpi_free(&t_prime); } @@ -149,9 +149,9 @@ int roca_self_test(void) { "\x27\x83\x30\xd3\xf4\x71\xa2\x53\x8f\xa6\x67\x80\x2e\xd2\xa3\xc4"\ "\x4a\x8b\x7d\xea\x82\x6e\x88\x8d\x0a\xa3\x41\xfd\x66\x4f\x7f\xa7"; - + if (emv_rocacheck(keyp, 64, false)) { - PrintAndLogEx(SUCCESS, "Weak modulus [ %s]", _GREEN_(PASS) ); + PrintAndLogEx(SUCCESS, "Weak modulus [ %s]", _GREEN_(PASS) ); } else { ret++; @@ -168,8 +168,8 @@ int roca_self_test(void) { ret++; PrintAndLogEx(FAILED, "Strong modulus [ %s]", _RED_(FAIL) ); } else { - PrintAndLogEx(SUCCESS, "Strong modulus [ %s]", _GREEN_(PASS) ); + PrintAndLogEx(SUCCESS, "Strong modulus [ %s]", _GREEN_(PASS) ); } - + return ret; } diff --git a/client/emv/emv_roca.h b/client/emv/emv_roca.h index 9e12e4256..b37d4de14 100644 --- a/client/emv/emv_roca.h +++ b/client/emv/emv_roca.h @@ -3,7 +3,7 @@ * Copyright (C) 2017-2018 Sectigo Limited * modified 2018 iceman (dropped openssl bignum, now use mbedtls lib) * modified 2018 merlok - * + * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or diff --git a/client/emv/emv_tags.c b/client/emv/emv_tags.c index 521598b67..2cad81397 100644 --- a/client/emv/emv_tags.c +++ b/client/emv/emv_tags.c @@ -199,13 +199,13 @@ static const struct emv_tag emv_tags[] = { { 0x5f2d, "Language Preference", EMV_TAG_STRING }, { 0x5f30, "Service Code", EMV_TAG_NUMERIC }, { 0x5f34, "Application Primary Account Number (PAN) Sequence Number", EMV_TAG_NUMERIC }, - { 0x5f36, "Transaction Currency Exponent", EMV_TAG_NUMERIC }, + { 0x5f36, "Transaction Currency Exponent", EMV_TAG_NUMERIC }, { 0x5f50, "Issuer URL", EMV_TAG_STRING }, { 0x5f53, "International Bank Account Number (IBAN)" }, { 0x5f54, "Bank Identifier Code (BIC)" }, { 0x5f55, "Issuer Country Code (alpha2 format)", EMV_TAG_STRING }, { 0x5f56, "Issuer Country Code (alpha3 format)", EMV_TAG_STRING }, - + { 0x61 , "Application Template" }, { 0x6f , "File Control Information (FCI) Template" }, { 0x70 , "READ RECORD Response Message Template" }, @@ -240,7 +240,7 @@ static const struct emv_tag emv_tags[] = { { 0x9b , "Transaction Status Information" }, { 0x9c , "Transaction Type", EMV_TAG_NUMERIC }, { 0x9d , "Directory Definition File (DDF) Name" }, - + { 0x9f01, "Acquirer Identifier", EMV_TAG_NUMERIC }, { 0x9f02, "Amount, Authorised (Numeric)", EMV_TAG_NUMERIC }, { 0x9f03, "Amount, Other (Numeric)", EMV_TAG_NUMERIC }, @@ -268,10 +268,10 @@ static const struct emv_tag emv_tags[] = { { 0x9f1b, "Terminal Floor Limit" }, { 0x9f1c, "Terminal Identification", EMV_TAG_STRING }, { 0x9f1d, "Terminal Risk Management Data" }, - { 0x9f1e, "Interface Device (IFD) Serial Number", EMV_TAG_STRING }, + { 0x9f1e, "Interface Device (IFD) Serial Number", EMV_TAG_STRING }, { 0x9f1f, "Track 1 Discretionary Data", EMV_TAG_STRING }, { 0x9f20, "Track 2 Discretionary Data", EMV_TAG_STRING }, - { 0x9f21, "Transaction Time" }, + { 0x9f21, "Transaction Time" }, { 0x9f22, "Certification Authority Public Key Index - Terminal" }, { 0x9f23, "Upper Consecutive Offline Limit" }, { 0x9f26, "Application Cryptogram" }, @@ -308,20 +308,20 @@ static const struct emv_tag emv_tags[] = { { 0x9f4d, "Log Entry" }, { 0x9f4e, "Merchant Name and Location", EMV_TAG_STRING }, { 0x9f4f, "Log Format", EMV_TAG_DOL }, - + { 0x9f50, "Offline Accumulator Balance" }, { 0x9f51, "Application Currency Code" }, { 0x9f51, "DRDOL" }, { 0x9f52, "Application Default Action (ADA)" }, { 0x9f52, "Terminal Compatibility Indicator" }, - + { 0x9f53, "Transaction Category Code" }, { 0x9f54, "DS ODS Card" }, - - { 0x9f55, "Mobile Support Indicator" }, + + { 0x9f55, "Mobile Support Indicator" }, { 0x9f55, "Issuer Authentication Flags" }, - + { 0x9f56, "Issuer Authentication Indicator" }, { 0x9f57, "Issuer Country Code" }, { 0x9f58, "Consecutive Transaction Counter Limit (CTCL)" }, @@ -332,7 +332,7 @@ static const struct emv_tag emv_tags[] = { { 0x9f5d, "Application Capabilities Information" }, { 0x9f5e, "Data Storage Identifier" }, { 0x9f5f, "DS Slot Availability" }, - + { 0x9f60, "CVC3 (Track1)" }, { 0x9f61, "CVC3 (Track2)" }, { 0x9f62, "PCVC3 (Track1)" }, @@ -421,7 +421,7 @@ static const struct emv_tag emv_tags[] = { { 0xff8103, "Tags To Write After Gen AC" }, { 0xff8104, "Data To Send" }, { 0xff8105, "Data Record" }, - { 0xff8106, "Discretionary Data" }, + { 0xff8106, "Discretionary Data" }, }; static int emv_sort_tag(tlv_tag_t tag) { @@ -554,13 +554,13 @@ static void emv_tag_dump_cvr(const struct tlv *tlv, const struct emv_tag *tag, F fprintf(f, "\tINVALID!\n"); return; } - + if (tlv->len != tlv->value[0] + 1) { PRINT_INDENT(level); fprintf(f, "\tINVALID length!\n"); return; } - + if (tlv->len >= 2) { // AC1 PRINT_INDENT(level); @@ -587,7 +587,7 @@ static void emv_tag_dump_cvr(const struct tlv *tlv, const struct emv_tag *tag, F PRINT_INDENT(level); fprintf(f, "\tSuccessfully processed issuer script commands: %x\n", tlv->value[4] >> 4); } - + // mask 0F 0F F0 0F uint8_t data[20] = {0}; memcpy(data, &tlv->value[1], tlv->len - 1); @@ -606,7 +606,7 @@ static void emv_tag_dump_cvr(const struct tlv *tlv, const struct emv_tag *tag, F .type = EMV_TAG_BITMASK, .data = EMV_CVR, }; - + if (data[0] || data[1] || data[2] || data[3]) emv_tag_dump_bitmask(&bit_tlv, &bit_tag, f, level); } @@ -618,7 +618,7 @@ static void emv_tag_dump_cid(const struct tlv *tlv, const struct emv_tag *tag, F fprintf(f, "\tINVALID!\n"); return; } - + PRINT_INDENT(level); if ((tlv->value[0] & EMVAC_AC_MASK) == EMVAC_AAC) fprintf(f, "\tAC1: AAC (Transaction declined)\n"); if ((tlv->value[0] & EMVAC_AC_MASK) == EMVAC_TC) fprintf(f, "\tAC1: TC (Transaction approved)\n"); @@ -757,7 +757,7 @@ static void emv_tag_dump_afl(const struct tlv *tlv, const struct emv_tag *tag, F fprintf(f, "\tINVALID!\n"); return; } - + for (int i = 0; i < tlv->len / 4; i++) { PRINT_INDENT(level); fprintf(f, "SFI[%02x] start:%02x end:%02x offline:%02x\n", tlv->value[i * 4 + 0] >> 3, tlv->value[i * 4 + 1], tlv->value[i * 4 + 2], tlv->value[i * 4 + 3]); @@ -819,13 +819,13 @@ bool emv_tag_dump(const struct tlv *tlv, FILE *f, int level) { char *emv_get_tag_name(const struct tlv *tlv) { static char *defstr = ""; - - if (!tlv) + + if (!tlv) return defstr; const struct emv_tag *tag = emv_get_tag(tlv); if (tag) return tag->name; - + return defstr; } diff --git a/client/emv/emvcore.c b/client/emv/emvcore.c index 7af08690c..796fc22ea 100644 --- a/client/emv/emvcore.c +++ b/client/emv/emvcore.c @@ -14,7 +14,7 @@ // Got from here. Thanks) // https://eftlab.co.uk/index.php/site-map/knowledge-base/211-emv-aid-rid-pix -static const char *PSElist [] = { +static const char *PSElist [] = { "325041592E5359532E4444463031", // 2PAY.SYS.DDF01 - Visa Proximity Payment System Environment - PPSE "315041592E5359532E4444463031" // 1PAY.SYS.DDF01 - Visa Payment System Environment - PSE }; @@ -32,28 +32,28 @@ typedef struct { const char* aid; } TAIDList; -static const TAIDList AIDlist [] = { +static const TAIDList AIDlist [] = { // Visa International - { CV_VISA, "A00000000305076010"}, // VISA ELO Credit - { CV_VISA, "A0000000031010" }, // VISA Debit/Credit (Classic) - { CV_VISA, "A000000003101001" }, // VISA Credit - { CV_VISA, "A000000003101002" }, // VISA Debit + { CV_VISA, "A00000000305076010"}, // VISA ELO Credit + { CV_VISA, "A0000000031010" }, // VISA Debit/Credit (Classic) + { CV_VISA, "A000000003101001" }, // VISA Credit + { CV_VISA, "A000000003101002" }, // VISA Debit { CV_VISA, "A0000000032010" }, // VISA Electron - { CV_VISA, "A0000000032020" }, // VISA - { CV_VISA, "A0000000033010" }, // VISA Interlink - { CV_VISA, "A0000000034010" }, // VISA Specific - { CV_VISA, "A0000000035010" }, // VISA Specific - { CV_VISA, "A0000000036010" }, // Domestic Visa Cash Stored Value - { CV_VISA, "A0000000036020" }, // International Visa Cash Stored Value - { CV_VISA, "A0000000038002" }, // VISA Auth, VisaRemAuthen EMV-CAP (DPA) - { CV_VISA, "A0000000038010" }, // VISA Plus - { CV_VISA, "A0000000039010" }, // VISA Loyalty - { CV_VISA, "A000000003999910" }, // VISA Proprietary ATM + { CV_VISA, "A0000000032020" }, // VISA + { CV_VISA, "A0000000033010" }, // VISA Interlink + { CV_VISA, "A0000000034010" }, // VISA Specific + { CV_VISA, "A0000000035010" }, // VISA Specific + { CV_VISA, "A0000000036010" }, // Domestic Visa Cash Stored Value + { CV_VISA, "A0000000036020" }, // International Visa Cash Stored Value + { CV_VISA, "A0000000038002" }, // VISA Auth, VisaRemAuthen EMV-CAP (DPA) + { CV_VISA, "A0000000038010" }, // VISA Plus + { CV_VISA, "A0000000039010" }, // VISA Loyalty + { CV_VISA, "A000000003999910" }, // VISA Proprietary ATM // Visa USA { CV_VISA, "A000000098" }, // Debit Card { CV_VISA, "A0000000980848" }, // Debit Card // Mastercard International - { CV_MASTERCARD, "A00000000401" }, // MasterCard PayPass + { CV_MASTERCARD, "A00000000401" }, // MasterCard PayPass { CV_MASTERCARD, "A0000000041010" }, // MasterCard Credit { CV_MASTERCARD, "A00000000410101213" }, // MasterCard Credit { CV_MASTERCARD, "A00000000410101215" }, // MasterCard Credit @@ -65,7 +65,7 @@ static const TAIDList AIDlist [] = { { CV_MASTERCARD, "A0000000045010" }, // MasterCard Specific { CV_MASTERCARD, "A0000000046000" }, // Cirrus { CV_MASTERCARD, "A0000000048002" }, // SecureCode Auth EMV-CAP - { CV_MASTERCARD, "A0000000049999" }, // MasterCard PayPass + { CV_MASTERCARD, "A0000000049999" }, // MasterCard PayPass // American Express { CV_AMERICANEXPRESS, "A000000025" }, { CV_AMERICANEXPRESS, "A0000000250000" }, @@ -74,14 +74,14 @@ static const TAIDList AIDlist [] = { { CV_AMERICANEXPRESS, "A000000025010701" }, { CV_AMERICANEXPRESS, "A000000025010801" }, // Groupement des Cartes Bancaires "CB" - { CV_CB, "A0000000421010" }, // Cartes Bancaire EMV Card - { CV_CB, "A0000000422010" }, - { CV_CB, "A0000000423010" }, - { CV_CB, "A0000000424010" }, - { CV_CB, "A0000000425010" }, + { CV_CB, "A0000000421010" }, // Cartes Bancaire EMV Card + { CV_CB, "A0000000422010" }, + { CV_CB, "A0000000423010" }, + { CV_CB, "A0000000424010" }, + { CV_CB, "A0000000425010" }, // JCB CO., LTD. - { CV_JCB, "A00000006510" }, // JCB - { CV_JCB, "A0000000651010" }, // JCB J Smart Credit + { CV_JCB, "A00000006510" }, // JCB + { CV_JCB, "A0000000651010" }, // JCB J Smart Credit // Other { CV_OTHER, "A0000001544442" }, // Banricompras Debito - Banrisul - Banco do Estado do Rio Grande do SUL - S.A. { CV_OTHER, "F0000000030001" }, // BRADESCO @@ -106,8 +106,8 @@ enum CardPSVendor GetCardPSVendor(uint8_t * AID, size_t AIDlen) { if (strncmp(AIDlist[i].aid, buf, strlen(AIDlist[i].aid)) == 0){ return AIDlist[i].vendor; } - } - + } + return CV_NA; } @@ -125,7 +125,7 @@ bool TLVPrintFromBuffer(uint8_t *data, int datalen) { t = tlvdb_parse_multi(data, datalen); if (t) { PrintAndLogEx(NORMAL, "-------------------- TLV decoded --------------------"); - + tlvdb_visit(t, print_cb, NULL, 0); tlvdb_free(t); return true; @@ -136,9 +136,9 @@ bool TLVPrintFromBuffer(uint8_t *data, int datalen) { } void TLVPrintFromTLVLev(struct tlvdb *tlv, int level) { - if (!tlv) + if (!tlv) return; - + tlvdb_visit(tlv, print_cb, NULL, level); } @@ -154,18 +154,18 @@ void TLVPrintAIDlistFromSelectTLV(struct tlvdb *tlv) { struct tlvdb *ttmp = tlvdb_find(tlv, 0x6f); if (!ttmp) PrintAndLogEx(NORMAL, "| none |"); - + while (ttmp) { const struct tlv *tgAID = tlvdb_get_inchild(ttmp, 0x84, NULL); const struct tlv *tgName = tlvdb_get_inchild(ttmp, 0x50, NULL); const struct tlv *tgPrio = tlvdb_get_inchild(ttmp, 0x87, NULL); if (!tgAID) break; - PrintAndLogEx(NORMAL, "|%s| %s |%s|", - sprint_hex_inrow_ex(tgAID->value, tgAID->len, 18), - (tgPrio) ? sprint_hex(tgPrio->value, 1) : " ", + PrintAndLogEx(NORMAL, "|%s| %s |%s|", + sprint_hex_inrow_ex(tgAID->value, tgAID->len, 18), + (tgPrio) ? sprint_hex(tgPrio->value, 1) : " ", (tgName) ? sprint_ascii_ex(tgName->value, tgName->len, 25) : " "); - + ttmp = tlvdb_find_next(ttmp, 0x6f); } @@ -183,19 +183,19 @@ struct tlvdb *GetPANFromTrack2(const struct tlv *track2) { for (int i = 0; i < track2->len; ++i, tmp += 2) sprintf(tmp, "%02x", (unsigned int)track2->value[i]); - + int posD = strchr(track2Hex, 'd') - track2Hex; if (posD < 1) return NULL; - + track2Hex[posD] = 0; if (strlen(track2Hex) % 2) { track2Hex[posD] = 'F'; track2Hex[posD + 1] = '\0'; } - + param_gethex_to_eol(track2Hex, 0, PAN, sizeof(PAN), &PANlen); - + return tlvdb_fixed(0x5a, PANlen, PAN); } @@ -206,13 +206,13 @@ struct tlvdb *GetdCVVRawFromTrack2(const struct tlv *track2) { int dCVVlen = 0; const int PINlen = 5; // must calculated from 9F67 MSD Offset but i have not seen this tag) char *tmp = track2Hex; - + if (!track2) return NULL; - + for (int i = 0; i < track2->len; ++i, tmp += 2) sprintf(tmp, "%02x", (unsigned int)track2->value[i]); - + int posD = strchr(track2Hex, 'd') - track2Hex; if (posD < 1) return NULL; @@ -226,9 +226,9 @@ struct tlvdb *GetdCVVRawFromTrack2(const struct tlv *track2) { memcpy(dCVVHex + 9, track2Hex + posD + 1, 4); // service code memcpy(dCVVHex + 13, track2Hex + posD + 5, 3); - + param_gethex_to_eol(dCVVHex, 0, dCVV, sizeof(dCVV), &dCVVlen); - + return tlvdb_fixed(0x02, dCVVlen, dCVV); } @@ -239,17 +239,17 @@ int EMVExchangeEx(EMVCommandChannel channel, bool ActivateField, bool LeaveField if (sw) *sw = 0; uint16_t isw = 0; int res = 0; - + if (ActivateField) { DropFieldEx( channel ); msleep(50); } - + // COMPUTE APDU memcpy(data, &apdu, 5); if (apdu.data) memcpy(&data[5], apdu.data, apdu.Lc); - + if (APDULogging) PrintAndLogEx(SUCCESS, ">>>> %s", sprint_hex(data, (IncludeLe?6:5) + apdu.Lc)); @@ -262,24 +262,24 @@ int EMVExchangeEx(EMVCommandChannel channel, bool ActivateField, bool LeaveField } break; case ECC_CONTACT: -#ifdef WITH_SMARTCARD +#ifdef WITH_SMARTCARD res = ExchangeAPDUSC(data, (IncludeLe?6:5) + apdu.Lc, ActivateField, LeaveFieldON, Result, (int)MaxResultLen, (int *)ResultLen); #else res = 1; -#endif +#endif if (res) { return res; } break; } - + if (APDULogging) PrintAndLogEx(SUCCESS, "<<<< %s", sprint_hex(Result, *ResultLen)); if (*ResultLen < 2) { return 200; } - + *ResultLen -= 2; isw = Result[*ResultLen] * 0x0100 + Result[*ResultLen + 1]; if (sw) @@ -301,7 +301,7 @@ int EMVExchangeEx(EMVCommandChannel channel, bool ActivateField, bool LeaveField struct tlvdb *t = tlvdb_parse_multi(Result, *ResultLen); tlvdb_add(tlv, t); } - + return 0; } @@ -328,7 +328,7 @@ int EMVSelectPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO default: return -1; } - + // select res = EMVSelect(channel, ActivateField, LeaveFieldON, buf, len, Result, MaxResultLen, ResultLen, sw, NULL); @@ -351,11 +351,11 @@ int EMVSelectWithRetry(EMVCommandChannel channel, bool ActivateField, bool Leave PrintAndLogEx(WARNING, "Exit..."); return 1; } - + retrycnt = 0; PrintAndLogEx(NORMAL, "Retry failed [%s]. Skiped...", sprint_hex_inrow(AID, AIDLen)); return res; - } + } } } while (res && res != 5); @@ -379,7 +379,7 @@ int EMVCheckAID(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlvdbel tlvdbelm = tlvdb_find_next(tlvdbelm, 0x61); continue; } - + if (res) break; @@ -411,7 +411,7 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO PrintAndLogEx(FAILED, "Select PSE error. APDU error: %04x.", sw); return 1; } - + struct tlvdb *t = NULL; t = tlvdb_parse_multi(data, datalen); if (t) { @@ -421,18 +421,18 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO uint8_t sfin = 0; tlv_get_uint8(tlvdb_get_tlv(tsfi), &sfin); PrintAndLogEx(INFO, "* PPSE get SFI: 0x%02x.", sfin); - + for (uint8_t ui = 0x01; ui <= 0x10; ui++) { PrintAndLogEx(INFO, "* * Get SFI: 0x%02x. num: 0x%02x", sfin, ui); res = EMVReadRecord(channel, true, sfin, ui, sfidata[ui], APDU_RES_LEN, &sfidatalen[ui], &sw, NULL); - + // end of records if (sw == 0x6a83) { sfidatalen[ui] = 0; PrintAndLogEx(INFO, "* * PPSE get SFI. End of records."); break; } - + // error catch! if (sw != 0x9000) { sfidatalen[ui] = 0; @@ -455,7 +455,7 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO PrintAndLogEx(FAILED, "SFI 0x%02d don't have records.", sfidatalen[ui]); continue; } - res = EMVCheckAID(channel, decodeTLV, tsfitmp, tlv); + res = EMVCheckAID(channel, decodeTLV, tsfitmp, tlv); fileFound = true; } tlvdb_free(tsfi); @@ -470,21 +470,21 @@ int EMVSearchPSE(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldO res = EMVCheckAID(channel, decodeTLV, ttmp, tlv); fileFound = true; } - + if (!fileFound) PrintAndLogEx(FAILED, "PPSE don't have records."); tlvdb_free(t); } else { PrintAndLogEx(WARNING, "PPSE ERROR: Can't get TLV from response."); - } + } } else { PrintAndLogEx(WARNING, "PPSE ERROR: Can't select PPSE AID. Error: %d", res); } - + if(!LeaveFieldON) DropFieldEx( channel ); - + return res; } @@ -494,7 +494,7 @@ int EMVSearch(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, uint8_t data[APDU_RES_LEN] = {0}; size_t datalen = 0; uint16_t sw = 0; - + int res = 0; int retrycnt = 0; for(int i = 0; i < AIDlistLen; i ++) { @@ -510,20 +510,20 @@ int EMVSearch(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, PrintAndLogEx(WARNING, "Exit..."); return 1; } - + retrycnt = 0; PrintAndLogEx(FAILED, "Retry failed [%s]. Skipped...", AIDlist[i].aid); } continue; } retrycnt = 0; - + if (res) continue; - + if (!datalen) continue; - + if (decodeTLV) { PrintAndLogEx(SUCCESS, "%s", AIDlist[i].aid); TLVPrintFromBuffer(data, datalen); @@ -536,25 +536,25 @@ int EMVSearch(EMVCommandChannel channel, bool ActivateField, bool LeaveFieldON, int EMVSelectApplication(struct tlvdb *tlv, uint8_t *AID, size_t *AIDlen) { // check priority. 0x00 - highest int prio = 0xffff; - + *AIDlen = 0; struct tlvdb *ttmp = tlvdb_find(tlv, 0x6f); if (!ttmp) return 1; - + while (ttmp) { const struct tlv *tgAID = tlvdb_get_inchild(ttmp, 0x84, NULL); const struct tlv *tgPrio = tlvdb_get_inchild(ttmp, 0x87, NULL); - + if (!tgAID) break; if (tgPrio) { - int pt = bytes_to_num((uint8_t*)tgPrio->value, (tgPrio->len < 2) ? tgPrio->len : 2); + int pt = bytes_to_num((uint8_t*)tgPrio->value, (tgPrio->len < 2) ? tgPrio->len : 2); if (pt < prio) { prio = pt; - + memcpy(AID, tgAID->value, tgAID->len); *AIDlen = tgAID->len; } @@ -562,13 +562,13 @@ int EMVSelectApplication(struct tlvdb *tlv, uint8_t *AID, size_t *AIDlen) { // takes the first application from list wo priority if (!*AIDlen) { memcpy(AID, tgAID->value, tgAID->len); - *AIDlen = tgAID->len; + *AIDlen = tgAID->len; } } - + ttmp = tlvdb_find_next(ttmp, 0x6f); } - + return 0; } @@ -606,7 +606,7 @@ int MSCComputeCryptoChecksum(EMVCommandChannel channel, bool LeaveFieldON, uint8 return EMVExchange(channel, LeaveFieldON, (sAPDU){0x80, 0x2a, 0x8e, 0x80, UDOLlen, UDOL}, Result, MaxResultLen, ResultLen, sw, tlv); } -// Authentication +// Authentication struct emv_pk *get_ca_pk(struct tlvdb *db) { const struct tlv *df_tlv = tlvdb_get(db, 0x84, NULL); const struct tlv *caidx_tlv = tlvdb_get(db, 0x8f, NULL); @@ -625,7 +625,7 @@ int trSDA(struct tlvdb *tlv) { PrintAndLogEx(WARNING, "Error: Key not found. Exit."); return 2; } - + struct emv_pk *issuer_pk = emv_pki_recover_issuer_cert(pk, tlv); if (!issuer_pk) { emv_pk_free(pk); @@ -652,7 +652,7 @@ int trSDA(struct tlvdb *tlv) { PrintAndLogEx(WARNING, "Can't find input list for Offline Data Authentication. Exit."); return 3; } - + struct tlvdb *dac_db = emv_pki_recover_dac(issuer_pk, tlv, sda_tlv); if (dac_db) { const struct tlv *dac_tlv = tlvdb_get(dac_db, 0x9f45, NULL); @@ -664,7 +664,7 @@ int trSDA(struct tlvdb *tlv) { PrintAndLogEx(WARNING, "SSAD verify error"); return 4; } - + emv_pk_free(issuer_pk); emv_pk_free(pk); return 0; @@ -708,7 +708,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { issuer_pk->serial[1], issuer_pk->serial[2] ); - + struct emv_pk *icc_pk = emv_pki_recover_icc_cert(issuer_pk, tlv, sda_tlv); if (!icc_pk) { emv_pk_free(pk); @@ -769,7 +769,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { const struct tlv *atc_tlv = tlvdb_get(atc_db, 0x9f36, NULL); if(atc_tlv) { PrintAndLogEx(NORMAL, "\nATC (Application Transaction Counter) [%zu] %s", atc_tlv->len, sprint_hex_inrow(atc_tlv->value, atc_tlv->len)); - + const struct tlv *core_atc_tlv = tlvdb_get(tlv, 0x9f36, NULL); if(tlv_equal(core_atc_tlv, atc_tlv)) { PrintAndLogEx(SUCCESS, "ATC check OK."); @@ -797,7 +797,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { emv_pk_free(icc_pk); return 4; } - + PrintAndLogEx(NORMAL, "\n* * Calc DDOL"); const struct tlv *ddol_tlv = tlvdb_get(tlv, 0x9f49, NULL); if (!ddol_tlv) { @@ -818,7 +818,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { PrintAndLogEx(NORMAL, "\n* * Internal Authenticate"); int res = EMVInternalAuthenticate(channel, true, (uint8_t *)ddol_data_tlv->value, ddol_data_tlv->len, buf, sizeof(buf), &len, &sw, NULL); - if (res) { + if (res) { PrintAndLogEx(WARNING, "Internal Authenticate error(%d): %4x. Exit...", res, sw); free(ddol_data_tlv); emv_pk_free(pk); @@ -835,13 +835,13 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { // parse response 0x80 struct tlvdb *t80 = tlvdb_parse_multi(buf, len); const struct tlv * t80tlv = tlvdb_get_tlv(t80); - + // 9f4b Signed Dynamic Application Data dda_db = tlvdb_fixed(0x9f4b, t80tlv->len, t80tlv->value); tlvdb_add(tlv, dda_db); - + tlvdb_free(t80); - + if (decodeTLV){ PrintAndLogEx(NORMAL, "* * * Decode response format 1:"); TLVPrintFromTLV(dda_db); @@ -858,7 +858,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { return 7; } tlvdb_add(tlv, dda_db); - + if (decodeTLV) TLVPrintFromTLV(dda_db); } @@ -892,7 +892,7 @@ int trDDA(EMVCommandChannel channel, bool decodeTLV, struct tlvdb *tlv) { return 9; } } - + emv_pk_free(pk); emv_pk_free(issuer_pk); emv_pk_free(icc_pk); @@ -931,7 +931,7 @@ int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, st issuer_pk->serial[1], issuer_pk->serial[2] ); - + struct emv_pk *icc_pk = emv_pki_recover_icc_cert(issuer_pk, tlv, sda_tlv); if (!icc_pk) { PrintAndLogEx(WARNING, "Error: ICC setrificate not found. Exit."); @@ -963,12 +963,12 @@ int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, st emv_pk_free(icc_pk); return 4; } - + PrintAndLogEx(NORMAL, "\n* * Check Signed Dynamic Application Data (SDAD)"); struct tlvdb *idn_db = emv_pki_perform_cda_ex(icc_pk, tlv, ac_tlv, pdol_data_tlv, // pdol ac_data_tlv, // cdol1 - NULL, // cdol2 + NULL, // cdol2 true); if (idn_db) { const struct tlv *idn_tlv = tlvdb_get(idn_db, 0x9f4c, NULL); @@ -986,7 +986,7 @@ int trCDA(struct tlvdb *tlv, struct tlvdb *ac_tlv, struct tlv *pdol_data_tlv, st } int RecoveryCertificates(struct tlvdb *tlvRoot, json_t *root) { - + struct emv_pk *pk = get_ca_pk(tlvRoot); if (!pk) { PrintAndLog("ERROR: Key not found. Exit."); @@ -1036,11 +1036,11 @@ int RecoveryCertificates(struct tlvdb *tlvRoot, json_t *root) { icc_pk->serial[1], icc_pk->serial[2] ); - + char *icc_pk_c = emv_pk_dump_pk(icc_pk); JsonSaveStr(root, "$.ApplicationData.ICCPublicKeyDec", icc_pk_c); JsonSaveBufAsHex(root, "$.ApplicationData.ICCPublicKeyModulus", icc_pk->modulus, icc_pk->mlen); free(issuer_pk_c); - + return 0; } diff --git a/client/emv/emvjson.c b/client/emv/emvjson.c index dc409a2a5..4468d49b3 100644 --- a/client/emv/emvjson.c +++ b/client/emv/emvjson.c @@ -64,7 +64,7 @@ char* GetApplicationDataName(tlv_tag_t tag) { for (int i = 0; i < ApplicationDataLen; i++) if (ApplicationData[i].Tag == tag) return ApplicationData[i].Name; - + return NULL; } @@ -73,7 +73,7 @@ int JsonSaveJsonObject(json_t *root, char *path, json_t *value) { if (strlen(path) < 1) return 1; - + if (path[0] == '$') { if (json_path_set(root, path, value, 0, &error)) { PrintAndLog("ERROR: can't set json path: ", error.text); @@ -124,9 +124,9 @@ int JsonSaveHex(json_t *elm, char *path, uint64_t data, int datalen) { len = 1; } else { len = datalen; - } + } num_to_bytes(data, len, bdata); - + return JsonSaveBufAsHex(elm, path, bdata, len); } @@ -135,7 +135,7 @@ int JsonSaveTLVValue(json_t *root, char *path, struct tlvdb *tlvdbelm) { if (tlvelm) return JsonSaveBufAsHex(root, path, (uint8_t *)tlvelm->value, tlvelm->len); else - return 1; + return 1; } int JsonSaveTLVElm(json_t *elm, char *path, struct tlv *tlvelm, bool saveName, bool saveValue, bool saveAppDataLink) { @@ -143,13 +143,13 @@ int JsonSaveTLVElm(json_t *elm, char *path, struct tlv *tlvelm, bool saveName, b if (strlen(path) < 1 || !tlvelm) return 1; - + if (path[0] == '$') { json_t *obj = json_path_get(elm, path); if (!obj) { obj = json_object(); - + if (json_is_array(elm)) { if (json_array_append_new(elm, obj)) { PrintAndLog("ERROR: can't append array: %s", path); @@ -162,12 +162,12 @@ int JsonSaveTLVElm(json_t *elm, char *path, struct tlv *tlvelm, bool saveName, b } } } - + if (saveAppDataLink) { char * AppDataName = GetApplicationDataName(tlvelm->tag); if (AppDataName) JsonSaveStr(obj, "appdata", AppDataName); - } else { + } else { char * name = emv_get_tag_name(tlvelm); if (saveName && name && strlen(name) > 0 && strncmp(name, "Unknown", 7)) JsonSaveStr(obj, "name", emv_get_tag_name(tlvelm)); @@ -193,13 +193,13 @@ int JsonSaveTLVTree(json_t *root, json_t *elm, char *path, struct tlvdb *tlvdbel char * AppDataName = NULL; if (tlvpelm) AppDataName = GetApplicationDataName(tlvpelm->tag); - + if (AppDataName) { char appdatalink[200] = {0}; sprintf(appdatalink, "$.ApplicationData.%s", AppDataName); JsonSaveBufAsHex(root, appdatalink, (uint8_t *)tlvpelm->value, tlvpelm->len); } - + json_t *pelm = json_path_get(elm, path); if (pelm && json_is_array(pelm)) { json_t *appendelm = json_object(); @@ -210,20 +210,20 @@ int JsonSaveTLVTree(json_t *root, json_t *elm, char *path, struct tlvdb *tlvdbel JsonSaveTLVTreeElm(elm, path, tlvp, !AppDataName, !tlvdb_elm_get_children(tlvp), AppDataName); pelm = json_path_get(elm, path); } - + if (tlvdb_elm_get_children(tlvp)) { // get path element if(!pelm) return 1; - + // check childs element and add it if not found json_t *chjson = json_path_get(pelm, "$.Childs"); if (!chjson) { json_object_set_new(pelm, "Childs", json_array()); - + chjson = json_path_get(pelm, "$.Childs"); } - + // check if (!json_is_array(chjson)) { PrintAndLog("E->Internal logic error. `$.Childs` is not an array."); @@ -240,8 +240,8 @@ int JsonSaveTLVTree(json_t *root, json_t *elm, char *path, struct tlvdb *tlvdbel } bool HexToBuffer(const char *errormsg, const char *hexvalue, uint8_t * buffer, size_t maxbufferlen, size_t *bufferlen) { - int buflen = 0; - + int buflen = 0; + switch (param_gethex_to_eol(hexvalue, 0, buffer, maxbufferlen, &buflen)) { case 1: PrintAndLog("%s Invalid HEX value.", errormsg); @@ -253,15 +253,15 @@ bool HexToBuffer(const char *errormsg, const char *hexvalue, uint8_t * buffer, s PrintAndLog("%s Hex value must have even number of digits.", errormsg); return false; } - + if (buflen > maxbufferlen) { PrintAndLog("%s HEX length (%d) more than %d", errormsg, (bufferlen) ? *bufferlen : -1, maxbufferlen); return false; } - + if ( bufferlen ) *bufferlen = buflen; - + return true; } @@ -272,27 +272,27 @@ int JsonLoadStr(json_t *root, char *path, char *value) { json_t *jelm = json_path_get((const json_t *)root, path); if (!jelm || !json_is_string(jelm)) return 2; - + const char * strval = json_string_value(jelm); if (!strval) return 1; - + memcpy(value, strval, strlen(strval)); - + return 0; } int JsonLoadBufAsHex(json_t *elm, char *path, uint8_t *data, size_t maxbufferlen, size_t *datalen) { if (datalen) *datalen = 0; - + json_t *jelm = json_path_get((const json_t *)elm, path); if (!jelm || !json_is_string(jelm)) return 1; - + if (!HexToBuffer("ERROR load", json_string_value(jelm), data, maxbufferlen, datalen)) return 2; - + return 0; }; @@ -302,11 +302,11 @@ bool ParamLoadFromJson(struct tlvdb *tlv) { if (!tlv) { PrintAndLog("ERROR load params: tlv tree is NULL."); - return false; + return false; } // current path + file name - const char *relfname = "emv/defparams.json"; + const char *relfname = "emv/defparams.json"; char fname[strlen(get_my_executable_directory()) + strlen(relfname) + 1]; strcpy(fname, get_my_executable_directory()); strcat(fname, relfname); @@ -314,16 +314,16 @@ bool ParamLoadFromJson(struct tlvdb *tlv) { root = json_load_file(fname, 0, &error); if (!root) { PrintAndLog("Load params: json error on line %d: %s", error.line, error.text); - return false; + return false; } - + if (!json_is_array(root)) { PrintAndLog("Load params: Invalid json format. root must be array."); - return false; + return false; } - + PrintAndLog("Load params: json(%d) OK", json_array_size(root)); - + for(int i = 0; i < json_array_size(root); i++) { json_t *data, *jtag, *jlength, *jvalue; @@ -334,7 +334,7 @@ bool ParamLoadFromJson(struct tlvdb *tlv) { json_decref(root); return false; } - + jtag = json_object_get(data, "tag"); if(!json_is_string(jtag)) { @@ -360,39 +360,39 @@ bool ParamLoadFromJson(struct tlvdb *tlv) { json_decref(root); return false; } - + int tlvLength = json_integer_value(jlength); if (tlvLength > 250) { PrintAndLog("Load params: data [%d] length more than 250", i + 1); json_decref(root); return false; } - + PrintAndLog("TLV param: %s[%d]=%s", tlvTag, tlvLength, tlvValue); uint8_t buf[251] = {0}; size_t buflen = 0; - - if (!HexToBuffer("TLV Error type:", tlvTag, buf, 4, &buflen)) { + + if (!HexToBuffer("TLV Error type:", tlvTag, buf, 4, &buflen)) { json_decref(root); return false; } tlv_tag_t tag = 0; for (int i = 0; i < buflen; i++) { tag = (tag << 8) | buf[i]; - } - + } + if (!HexToBuffer("TLV Error value:", tlvValue, buf, sizeof(buf) - 1, &buflen)) { json_decref(root); return false; } - + if (buflen != tlvLength) { PrintAndLog("Load params: data [%d] length of HEX must(%d) be identical to length in TLV param(%d)", i + 1, buflen, tlvLength); json_decref(root); return false; } - - tlvdb_change_or_add_node(tlv, tag, tlvLength, (const unsigned char *)buf); + + tlvdb_change_or_add_node(tlv, tag, tlvLength, (const unsigned char *)buf); } json_decref(root); diff --git a/client/emv/test/cda_test.c b/client/emv/test/cda_test.c index 536a5862b..a029558d6 100644 --- a/client/emv/test/cda_test.c +++ b/client/emv/test/cda_test.c @@ -423,7 +423,7 @@ int exec_cda_test(bool verbose) { int ret; fprintf(stdout, "\n"); - + ret = cda_test_raw(verbose); if (ret) { fprintf(stderr, "CDA raw test: failed\n"); diff --git a/client/emv/test/cda_test.h b/client/emv/test/cda_test.h index 1d321a26e..8d80043cd 100644 --- a/client/emv/test/cda_test.h +++ b/client/emv/test/cda_test.h @@ -13,6 +13,6 @@ * Lesser General Public License for more details. */ -#include - +#include + extern int exec_cda_test(bool verbose); diff --git a/client/emv/test/cryptotest.c b/client/emv/test/cryptotest.c index 4e8df1a25..5d7017f9c 100644 --- a/client/emv/test/cryptotest.c +++ b/client/emv/test/cryptotest.c @@ -36,25 +36,25 @@ int ExecuteCryptoTests(bool verbose) { int res; bool TestFail = false; - + res = mbedtls_mpi_self_test(verbose); if (res) TestFail = true; - + res = mbedtls_aes_self_test(verbose); if (res) TestFail = true; res = mbedtls_des_self_test(verbose); if (res) TestFail = true; - + res = mbedtls_sha1_self_test(verbose); if (res) TestFail = true; res = mbedtls_md5_self_test(verbose); if (res) TestFail = true; - + res = mbedtls_rsa_self_test(verbose); if (res) TestFail = true; - + res = mbedtls_entropy_self_test(verbose); if (res) TestFail = true; @@ -63,7 +63,7 @@ int ExecuteCryptoTests(bool verbose) { res = mbedtls_ctr_drbg_self_test(verbose); if (res) TestFail = true; - + res = mbedtls_base64_self_test(verbose); if (res) TestFail = true; @@ -78,13 +78,13 @@ int ExecuteCryptoTests(bool verbose) { res = mbedtls_x509_self_test(verbose); if (res) TestFail = true; - + res = exec_sda_test(verbose); if (res) TestFail = true; res = exec_dda_test(verbose); if (res) TestFail = true; - + res = exec_cda_test(verbose); if (res) TestFail = true; @@ -95,12 +95,12 @@ int ExecuteCryptoTests(bool verbose) { if (res) TestFail = true; PrintAndLog("\n--------------------------"); - + if (TestFail) PrintAndLogEx(FAILED, "\tTest(s) [ %s ]", _RED_(FAIL) ); else PrintAndLogEx(SUCCESS, "\tTest(s) [ %s ]", _GREEN_(OK) ); - + return TestFail; } diff --git a/client/emv/test/dda_test.h b/client/emv/test/dda_test.h index 354cd7e13..1ae1a0660 100644 --- a/client/emv/test/dda_test.h +++ b/client/emv/test/dda_test.h @@ -13,6 +13,6 @@ * Lesser General Public License for more details. */ -#include - +#include + extern int exec_dda_test(bool verbose); diff --git a/client/emv/test/sda_test.h b/client/emv/test/sda_test.h index 43a4c9482..8d47aa9b3 100644 --- a/client/emv/test/sda_test.h +++ b/client/emv/test/sda_test.h @@ -12,5 +12,5 @@ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ - + extern int exec_sda_test(bool verbose); diff --git a/client/emv/tlv.c b/client/emv/tlv.c index a309d0659..31277c325 100644 --- a/client/emv/tlv.c +++ b/client/emv/tlv.c @@ -11,7 +11,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * https://github.com/lumag/emv-tools/blob/master/lib/tlv.c */ @@ -37,8 +37,8 @@ #define TLV_LEN_INVALID (~0) // http://radek.io/2012/11/10/magical-container_of-macro/ -//#define container_of(ptr, type, member) ({ -// const typeof( ((type *)0)->member ) *__mptr = (ptr); +//#define container_of(ptr, type, member) ({ +// const typeof( ((type *)0)->member ) *__mptr = (ptr); // (type *)( (char *)__mptr - offsetof(type,member) );}) struct tlvdb { @@ -301,14 +301,14 @@ void tlvdb_free(struct tlvdb *tlvdb) struct tlvdb *tlvdb_find_next(struct tlvdb *tlvdb, tlv_tag_t tag) { if (!tlvdb) return NULL; - + return tlvdb_find(tlvdb->next, tag); } struct tlvdb *tlvdb_find(struct tlvdb *tlvdb, tlv_tag_t tag) { if (!tlvdb) return NULL; - + for (; tlvdb; tlvdb = tlvdb->next) { if (tlvdb->tag.tag == tag) return tlvdb; @@ -320,16 +320,16 @@ struct tlvdb *tlvdb_find(struct tlvdb *tlvdb, tlv_tag_t tag) { struct tlvdb *tlvdb_find_full(struct tlvdb *tlvdb, tlv_tag_t tag) { if (!tlvdb) return NULL; - + for (; tlvdb; tlvdb = tlvdb->next) { if (tlvdb->tag.tag == tag) return tlvdb; - + if (tlvdb->children) { struct tlvdb * ch = tlvdb_find_full(tlvdb->children, tag); if (ch) return ch; - } + } } return NULL; @@ -338,7 +338,7 @@ struct tlvdb *tlvdb_find_full(struct tlvdb *tlvdb, tlv_tag_t tag) { struct tlvdb *tlvdb_find_path(struct tlvdb *tlvdb, tlv_tag_t tag[]) { int i = 0; struct tlvdb *tnext = tlvdb; - + while (tnext && tag[i]) { tnext = tlvdb_find(tnext, tag[i]); i++; @@ -346,7 +346,7 @@ struct tlvdb *tlvdb_find_path(struct tlvdb *tlvdb, tlv_tag_t tag[]) { tnext = tnext->children; } } - + return tnext; } @@ -354,11 +354,11 @@ void tlvdb_add(struct tlvdb *tlvdb, struct tlvdb *other) { if (tlvdb == other) return; - + while (tlvdb->next) { if (tlvdb->next == other) return; - + tlvdb = tlvdb->next; } @@ -383,20 +383,20 @@ void tlvdb_change_or_add_node_ex(struct tlvdb *tlvdb, tlv_tag_t tag, size_t len, struct tlvdb *tnewelm = tlvdb_fixed(tag, len, value); tnewelm->next = telm->next; tnewelm->parent = telm->parent; - + // if telm stayed first in children chain if (telm->parent && telm->parent->children == telm) { telm->parent->children = tnewelm; } - + // if telm have previous element if (telm != tlvdb) { // elm in root struct tlvdb *celm = tlvdb; // elm in child list of node if (telm->parent && telm->parent->children) - celm = telm->parent->children; - + celm = telm->parent->children; + // find previous element for (; celm; celm = celm->next) { if (celm->next == telm) { @@ -405,15 +405,15 @@ void tlvdb_change_or_add_node_ex(struct tlvdb *tlvdb, tlv_tag_t tag, size_t len, } } } - + // free old element with childrens telm->next = NULL; tlvdb_free(telm); - + if (tlvdb_elm) *tlvdb_elm = tnewelm; } - + return; } @@ -557,18 +557,18 @@ struct tlvdb *tlvdb_elm_get_parent(struct tlvdb *tlvdb) bool tlvdb_get_uint8(struct tlvdb *tlvRoot, tlv_tag_t tag, uint8_t *value) { - const struct tlv *tlvelm = tlvdb_get(tlvRoot, tag, NULL); + const struct tlv *tlvelm = tlvdb_get(tlvRoot, tag, NULL); return tlv_get_uint8(tlvelm, value); } -bool tlv_get_uint8(const struct tlv *etlv, uint8_t *value) +bool tlv_get_uint8(const struct tlv *etlv, uint8_t *value) { *value = 0; if (etlv) { if (etlv->len == 0) return true; - + if (etlv->len == 1) { *value = etlv->value[0]; @@ -585,7 +585,7 @@ bool tlv_get_int(const struct tlv *etlv, int *value) { if (etlv->len == 0) return true; - + if (etlv->len <= 4) { for (int i = 0; i < etlv->len; i++) diff --git a/client/emv/tlv.h b/client/emv/tlv.h index e75bbf986..7e171c102 100644 --- a/client/emv/tlv.h +++ b/client/emv/tlv.h @@ -11,7 +11,7 @@ * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. - * + * * https://github.com/lumag/emv-tools/blob/master/lib/include/openemv/tlv.h */ diff --git a/client/fido/additional_ca.c b/client/fido/additional_ca.c index 564eda2ae..ccda7f251 100644 --- a/client/fido/additional_ca.c +++ b/client/fido/additional_ca.c @@ -5,7 +5,7 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// CA PEM certificates +// CA PEM certificates //----------------------------------------------------------------------------- // diff --git a/client/fido/additional_ca.h b/client/fido/additional_ca.h index 856583039..d0f642e46 100644 --- a/client/fido/additional_ca.h +++ b/client/fido/additional_ca.h @@ -5,7 +5,7 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// CA PEM certificates +// CA PEM certificates //----------------------------------------------------------------------------- // @@ -14,7 +14,7 @@ #include -// Concatenation of all CA certificates in PEM format if available +// Concatenation of all CA certificates in PEM format if available extern const char additional_ca_pem[]; extern const size_t additional_ca_pem_len; diff --git a/client/fido/cbortools.c b/client/fido/cbortools.c index 01691dad1..8883ac475 100644 --- a/client/fido/cbortools.c +++ b/client/fido/cbortools.c @@ -28,7 +28,7 @@ static CborError dumpelm(CborValue *it, bool *got_next, int nestingLevel) { CborType type = cbor_value_get_type(it); indent(nestingLevel); switch (type) { - case CborMapType: + case CborMapType: case CborArrayType: { printf(type == CborArrayType ? "Array[" : "Map["); break; @@ -67,14 +67,14 @@ static CborError dumpelm(CborValue *it, bool *got_next, int nestingLevel) { case CborTagType: { CborTag tag; - cbor_value_get_tag(it, &tag); + cbor_value_get_tag(it, &tag); printf("Tag(%lld)", (long long)tag); break; } case CborSimpleType: { uint8_t type; - cbor_value_get_simple_type(it, &type); + cbor_value_get_simple_type(it, &type); printf("simple(%u)", type); break; } @@ -118,7 +118,7 @@ static CborError dumpelm(CborValue *it, bool *got_next, int nestingLevel) { printf("CborInvalidType!!!"); break; } - + return CborNoError; } @@ -131,7 +131,7 @@ static CborError dumprecursive(uint8_t cmdCode, bool isResponse, CborValue *it, bool got_next; switch (type) { - case CborMapType: + case CborMapType: case CborArrayType: { // recursive type CborValue recursed; @@ -189,7 +189,7 @@ int TinyCborInit(uint8_t *data, size_t length, CborValue *cb) { CborError err = cbor_parser_init(data, length, 0, &parser, cb); if (err) return err; - + return 0; } @@ -199,20 +199,20 @@ int TinyCborPrintFIDOPackage(uint8_t cmdCode, bool isResponse, uint8_t *data, si res = TinyCborInit(data, length, &cb); if (res) return res; - + CborError err = dumprecursive(cmdCode, isResponse, &cb, false, 0); if (err) { fprintf(stderr, -#if __WORDSIZE == 64 +#if __WORDSIZE == 64 "CBOR parsing failure at offset %" PRId64 " : %s\n", #else - "CBOR parsing failure at offset %" PRId32 " : %s\n", + "CBOR parsing failure at offset %" PRId32 " : %s\n", #endif cb.ptr - data, cbor_error_string(err)); return 1; - } - + } + return 0; } @@ -220,15 +220,15 @@ int JsonObjElmCount(json_t *elm) { int res = 0; const char *key; json_t *value; - + if (!json_is_object(elm)) return 0; - + json_object_foreach(elm, key, value) { if (strlen(key) > 0 && key[0] != '.') - res++; + res++; } - + return res; } @@ -237,7 +237,7 @@ int JsonToCbor(json_t *elm, CborEncoder *encoder) { return 1; int res; - + // CBOR map == JSON object if (json_is_object(elm)) { CborEncoder map; @@ -246,17 +246,17 @@ int JsonToCbor(json_t *elm, CborEncoder *encoder) { res = cbor_encoder_create_map(encoder, &map, JsonObjElmCount(elm)); cbor_check(res); - + json_object_foreach(elm, key, value) { if (strlen(key) > 0 && key[0] != '.') { - res = cbor_encode_text_stringz(&map, key); + res = cbor_encode_text_stringz(&map, key); cbor_check(res); - + // RECURSION! JsonToCbor(value, &map); } } - + res = cbor_encoder_close_container(encoder, &map); cbor_check(res); } @@ -266,15 +266,15 @@ int JsonToCbor(json_t *elm, CborEncoder *encoder) { size_t index; json_t *value; CborEncoder array; - + res = cbor_encoder_create_array(encoder, &array, json_array_size(elm)); cbor_check(res); - + json_array_foreach(elm, index, value) { // RECURSION! JsonToCbor(value, &array); } - + res = cbor_encoder_close_container(encoder, &array); cbor_check(res); } @@ -304,15 +304,15 @@ int JsonToCbor(json_t *elm, CborEncoder *encoder) { return 100; res = cbor_encode_byte_string(encoder, data, datalen); - cbor_check(res); + cbor_check(res); } else { res = cbor_encode_text_stringz(encoder, val); cbor_check(res); } } - - - + + + return 0; } @@ -324,7 +324,7 @@ int CborMapGetKeyById(CborParser *parser, CborValue *map, uint8_t *data, size_t if (cbor_value_get_type(&cb) != CborMapType) return 1; - + err = cbor_value_enter_container(&cb, map); cbor_check(err); @@ -335,10 +335,10 @@ int CborMapGetKeyById(CborParser *parser, CborValue *map, uint8_t *data, size_t return 1; cbor_value_get_int64(map, &indx); - + err = cbor_value_advance(map); cbor_check(err); - + if (indx == key) return 0; @@ -361,17 +361,17 @@ CborError CborGetArrayBinStringValueEx(CborValue *elm, uint8_t *data, size_t max CborValue array; if (datalen) *datalen = 0; - + size_t slen = maxdatalen; size_t totallen = 0; CborError res = cbor_value_enter_container(elm, &array); cbor_check(res); - + while (!cbor_value_at_end(&array)) { res = cbor_value_copy_byte_string(&array, &data[totallen], &slen, &array); cbor_check(res); - + totallen += slen; if (delimeter) { memcpy(&data[totallen], delimeter, delimeterlen); @@ -386,13 +386,13 @@ CborError CborGetArrayBinStringValueEx(CborValue *elm, uint8_t *data, size_t max if (datalen) *datalen = totallen; - return CborNoError; + return CborNoError; }; CborError CborGetBinStringValue(CborValue *elm, uint8_t *data, size_t maxdatalen, size_t *datalen) { if (datalen) *datalen = 0; - + size_t slen = maxdatalen; CborError res = cbor_value_copy_byte_string(elm, data, &slen, elm); @@ -401,24 +401,24 @@ CborError CborGetBinStringValue(CborValue *elm, uint8_t *data, size_t maxdatalen if (datalen) *datalen = slen; - return CborNoError; + return CborNoError; }; CborError CborGetArrayStringValue(CborValue *elm, char *data, size_t maxdatalen, size_t *datalen, char *delimeter) { CborValue array; if (datalen) *datalen = 0; - + size_t slen = maxdatalen; size_t totallen = 0; CborError res = cbor_value_enter_container(elm, &array); cbor_check(res); - + while (!cbor_value_at_end(&array)) { res = cbor_value_copy_text_string(&array, &data[totallen], &slen, &array); cbor_check(res); - + totallen += slen; if (delimeter) { strcat(data, delimeter); @@ -434,13 +434,13 @@ CborError CborGetArrayStringValue(CborValue *elm, char *data, size_t maxdatalen, if (datalen) *datalen = totallen; - return CborNoError; + return CborNoError; }; CborError CborGetStringValue(CborValue *elm, char *data, size_t maxdatalen, size_t *datalen) { if (datalen) *datalen = 0; - + size_t slen = maxdatalen; CborError res = cbor_value_copy_text_string(elm, data, &slen, elm); @@ -449,13 +449,13 @@ CborError CborGetStringValue(CborValue *elm, char *data, size_t maxdatalen, size if (datalen) *datalen = slen; - return CborNoError; + return CborNoError; }; CborError CborGetStringValueBuf(CborValue *elm) { static char stringBuf[2048]; memset(stringBuf, 0x00, sizeof(stringBuf)); - + return CborGetStringValue(elm, stringBuf, sizeof(stringBuf), NULL); }; @@ -465,10 +465,10 @@ int CBOREncodeElm(json_t *root, char *rootElmId, CborEncoder *encoder) { elm = json_path_get(root, rootElmId); else elm = json_object_get(root, rootElmId); - + if (!elm) return 1; - + int res = JsonToCbor(elm, encoder); return res; @@ -479,11 +479,11 @@ CborError CBOREncodeClientDataHash(json_t *root, CborEncoder *encoder) { size_t jlen; JsonLoadBufAsHex(root, "$.ClientDataHash", buf, sizeof(buf), &jlen); - + // fill with 0x00 if not found if (!jlen) jlen = 32; - + int res = cbor_encode_byte_string(encoder, buf, jlen); cbor_check(res); diff --git a/client/fido/cose.c b/client/fido/cose.c index e45f46290..86c016314 100644 --- a/client/fido/cose.c +++ b/client/fido/cose.c @@ -22,13 +22,13 @@ typedef struct { char *Name; char *Description; } COSEValueNameDesc_t; - + typedef struct { int Value; char *Type; char *Name; char *Description; -} COSEValueTypeNameDesc_t; +} COSEValueTypeNameDesc_t; // kty - Key Type Values COSEValueNameDesc_t COSEKeyTypeValueDesc[] = { @@ -141,7 +141,7 @@ COSEValueNameDesc_t *GetCOSEAlgElm(int id) { return &COSEAlg[i]; return NULL; } - + const char *GetCOSEAlgName(int id) { COSEValueNameDesc_t *elm = GetCOSEAlgElm(id); if (elm) @@ -164,11 +164,11 @@ int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public if(verbose) PrintAndLog("----------- CBOR decode ----------------"); - + // kty int res = CborMapGetKeyById(&parser, &map, data, datalen, 1); if(!res) { - cbor_value_get_int64(&map, &i64); + cbor_value_get_int64(&map, &i64); if(verbose) PrintAndLog("kty [%lld] %s", (long long)i64, GetCOSEktyDescription(i64)); if (i64 != 2) @@ -178,26 +178,26 @@ int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public // algorithm res = CborMapGetKeyById(&parser, &map, data, datalen, 3); if(!res) { - cbor_value_get_int64(&map, &i64); + cbor_value_get_int64(&map, &i64); if(verbose) PrintAndLog("algorithm [%lld] %s", (long long)i64, GetCOSEAlgDescription(i64)); if (i64 != -7) PrintAndLog("ERROR: algorithm must be -7."); } - + // curve res = CborMapGetKeyById(&parser, &map, data, datalen, -1); if(!res) { - cbor_value_get_int64(&map, &i64); + cbor_value_get_int64(&map, &i64); if(verbose) PrintAndLog("curve [%lld] %s", (long long)i64, GetCOSECurveDescription(i64)); if (i64 != 1) PrintAndLog("ERROR: curve must be 1."); } - + // plain key public_key[0] = 0x04; - + // x - coordinate res = CborMapGetKeyById(&parser, &map, data, datalen, -2); if(!res) { @@ -229,10 +229,10 @@ int COSEGetECDSAKey(uint8_t *data, size_t datalen, bool verbose, uint8_t *public if(verbose) PrintAndLog("d - private key [%d]: %s", len, sprint_hex(private_key, len)); } - + if(verbose) PrintAndLog("----------- CBOR decode ----------------"); - + return 0; } diff --git a/client/fido/fidocore.c b/client/fido/fidocore.c index 49088ec28..a91a57d8f 100644 --- a/client/fido/fidocore.c +++ b/client/fido/fidocore.c @@ -101,7 +101,7 @@ fido2Desc_t fido2CmdGetInfoRespDesc[] = { {fido2CmdMakeCredential, ptQuery, 0x07, "options"}, {fido2CmdMakeCredential, ptQuery, 0x08, "pinAuth"}, {fido2CmdMakeCredential, ptQuery, 0x09, "pinProtocol"}, - + {fido2CmdGetAssertion, ptResponse, 0x01, "credential"}, {fido2CmdGetAssertion, ptResponse, 0x02, "authData"}, {fido2CmdGetAssertion, ptResponse, 0x03, "signature"}, @@ -115,12 +115,12 @@ fido2Desc_t fido2CmdGetInfoRespDesc[] = { {fido2CmdGetAssertion, ptQuery, 0x05, "options"}, {fido2CmdGetAssertion, ptQuery, 0x06, "pinAuth"}, {fido2CmdGetAssertion, ptQuery, 0x07, "pinProtocol"}, - + {fido2CmdGetNextAssertion, ptResponse, 0x01, "credential"}, {fido2CmdGetNextAssertion, ptResponse, 0x02, "authData"}, {fido2CmdGetNextAssertion, ptResponse, 0x03, "signature"}, {fido2CmdGetNextAssertion, ptResponse, 0x04, "publicKeyCredentialUserEntity"}, - + {fido2CmdGetInfo, ptResponse, 0x01, "versions"}, {fido2CmdGetInfo, ptResponse, 0x02, "extensions"}, {fido2CmdGetInfo, ptResponse, 0x03, "aaguid"}, @@ -140,7 +140,7 @@ fido2Desc_t fido2CmdGetInfoRespDesc[] = { {fido2CmdClientPIN, ptQuery, 0x06, "pinHashEnc"}, {fido2CmdClientPIN, ptQuery, 0x07, "getKeyAgreement"}, {fido2CmdClientPIN, ptQuery, 0x08, "getRetries"}, - + {fido2COSEKey, ptResponse, 0x01, "kty"}, {fido2COSEKey, ptResponse, 0x03, "alg"}, {fido2COSEKey, ptResponse, -1, "crv"}, @@ -153,7 +153,7 @@ char *fido2GetCmdErrorDescription(uint8_t errorCode) { for (int i = 0; i < sizeof(fido2Errors) / sizeof(fido2Error_t); i++) if (fido2Errors[i].ErrorCode == errorCode) return fido2Errors[i].Description; - + return fido2Errors[0].Description; } @@ -169,7 +169,7 @@ char *fido2GetCmdMemberDescription(uint8_t cmdCode, bool isResponse, int memberN int FIDOSelect(bool ActivateField, bool LeaveFieldON, uint8_t *Result, size_t MaxResultLen, size_t *ResultLen, uint16_t *sw) { uint8_t data[] = {0xA0, 0x00, 0x00, 0x06, 0x47, 0x2F, 0x00, 0x01}; - + return EMVSelect(ECC_CONTACTLESS, ActivateField, LeaveFieldON, data, sizeof(data), Result, MaxResultLen, ResultLen, sw, NULL); } @@ -183,9 +183,9 @@ int FIDOExchange(sAPDU apdu, uint8_t *Result, size_t MaxResultLen, size_t *Resul res = EMVExchange(ECC_CONTACTLESS, true, (sAPDU){0x00, 0xC0, 0x00, 0x00, 0x00, NULL}, &Result[oldlen], MaxResultLen - oldlen, ResultLen, sw, NULL); if (res == 5) // apdu result (sw) not a 0x9000 res = 0; - + *ResultLen += oldlen; - if (*ResultLen > MaxResultLen) + if (*ResultLen > MaxResultLen) return 100; } return res; @@ -220,7 +220,7 @@ int FIDO2GetAssertion(uint8_t *params, uint8_t paramslen, uint8_t *Result, size_ int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *publicKey, size_t publicKeyMaxLen) { int res; - + // load CA's mbedtls_x509_crt cacert; mbedtls_x509_crt_init(&cacert); @@ -228,9 +228,9 @@ int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *pu if (res < 0) { PrintAndLog("ERROR: CA parse certificate returned -0x%x - %s", -res, ecdsa_get_error(res)); } - if (verbose) + if (verbose) PrintAndLog("CA load OK. %d skipped", res); - + // load DER certificate from authenticator's data mbedtls_x509_crt cert; mbedtls_x509_crt_init(&cert); @@ -238,14 +238,14 @@ int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *pu if (res) { PrintAndLog("ERROR: DER parse returned 0x%x - %s", (res<0)?-res:res, ecdsa_get_error(res)); } - + // get certificate info char linfo[300] = {0}; if (verbose) { mbedtls_x509_crt_info(linfo, sizeof(linfo), " ", &cert); PrintAndLog("DER certificate info:\n%s", linfo); } - + // verify certificate uint32_t verifyflags = 0; res = mbedtls_x509_crt_verify(&cert, &cacert, NULL, NULL, &verifyflags, NULL, NULL); @@ -254,13 +254,13 @@ int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *pu } else { PrintAndLog("Certificate OK.\n"); } - + if (verbose) { memset(linfo, 0x00, sizeof(linfo)); mbedtls_x509_crt_verify_info(linfo, sizeof(linfo), " ", verifyflags); PrintAndLog("Verification info:\n%s", linfo); } - + // get public key res = ecdsa_public_key_from_pk(&cert.pk, publicKey, publicKeyMaxLen); if (res) { @@ -275,7 +275,7 @@ int FIDOCheckDERAndGetKey(uint8_t *der, size_t derLen, bool verbose, uint8_t *pu mbedtls_x509_crt_free(&cert); mbedtls_x509_crt_free(&cacert); - + return 0; } @@ -291,7 +291,7 @@ int FIDO2CreateMakeCredentionalReq(json_t *root, uint8_t *data, size_t maxdatale int res; CborEncoder encoder; CborEncoder map; - + cbor_encoder_init(&encoder, data, maxdatalen, 0); // create main map @@ -334,31 +334,31 @@ int FIDO2CreateMakeCredentionalReq(json_t *root, uint8_t *data, size_t maxdatale } res = cbor_encoder_close_container(&encoder, &map); fido_check(res); - + size_t len = cbor_encoder_get_buffer_size(&encoder, data); if (datalen) *datalen = len; - + return 0; } bool CheckrpIdHash(json_t *json, uint8_t *hash) { char hashval[300] = {0}; uint8_t hash2[32] = {0}; - + JsonLoadStr(json, "$.RelyingPartyEntity.id", hashval); int res = sha256hash((uint8_t *)hashval, strlen(hashval), hash2); if (res) return false; - + return !memcmp(hash, hash2, 32); } // check ANSI X9.62 format ECDSA signature (on P-256) int FIDO2CheckSignature(json_t *root, uint8_t *publickey, uint8_t *sign, size_t signLen, uint8_t *authData, size_t authDataLen, bool verbose) { int res; - uint8_t rval[300] = {0}; - uint8_t sval[300] = {0}; + uint8_t rval[300] = {0}; + uint8_t sval[300] = {0}; res = ecdsa_asn1_get_signature(sign, signLen, rval, sval); if (!res) { if (verbose) { @@ -372,12 +372,12 @@ int FIDO2CheckSignature(json_t *root, uint8_t *publickey, uint8_t *sign, size_t if (res || clientDataHashLen != 32) { PrintAndLog("ERROR: Can't get clientDataHash from json!"); return 2; - } - + } + uint8_t xbuf[4096] = {0}; size_t xbuflen = 0; res = FillBuffer(xbuf, sizeof(xbuf), &xbuflen, - authData, authDataLen, // rpIdHash[32] + flags[1] + signCount[4] + authData, authDataLen, // rpIdHash[32] + flags[1] + signCount[4] clientDataHash, 32, // Hash of the serialized client data. "$.ClientDataHash" from json NULL, 0); //PrintAndLog("--xbuf(%d)[%d]: %s", res, xbuflen, sprint_hex(xbuf, xbuflen)); @@ -391,12 +391,12 @@ int FIDO2CheckSignature(json_t *root, uint8_t *publickey, uint8_t *sign, size_t return res; } else { PrintAndLog("Signature is OK."); - } + } } else { PrintAndLog("Invalid signature. res=%d.", res); return res; } - + return 0; } @@ -407,37 +407,37 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b char *buf; uint8_t *ubuf; size_t n; - + // fmt res = CborMapGetKeyById(&parser, &map, data, dataLen, 1); if (res) return res; - + res = cbor_value_dup_text_string(&map, &buf, &n, &map); cbor_check(res); PrintAndLog("format: %s", buf); free(buf); // authData - uint8_t authData[400] = {0}; + uint8_t authData[400] = {0}; size_t authDataLen = 0; res = CborMapGetKeyById(&parser, &map, data, dataLen, 2); if (res) return res; res = cbor_value_dup_byte_string(&map, &ubuf, &n, &map); cbor_check(res); - + authDataLen = n; - memcpy(authData, ubuf, authDataLen); - + memcpy(authData, ubuf, authDataLen); + if (verbose2) { PrintAndLog("authData[%d]: %s", n, sprint_hex_inrow(authData, authDataLen)); } else { PrintAndLog("authData[%d]: %s...", n, sprint_hex(authData, MIN(authDataLen, 16))); } - + PrintAndLog("RP ID Hash: %s", sprint_hex(ubuf, 32)); - + // check RP ID Hash if (CheckrpIdHash(root, ubuf)) { PrintAndLog("rpIdHash OK."); @@ -460,17 +460,17 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b uint32_t cntr = (uint32_t)bytes_to_num(&ubuf[33], 4); PrintAndLog("Counter: %d", cntr); JsonSaveInt(root, "$.AppData.Counter", cntr); - + // attestation data PrintAndLog("AAGUID: %s", sprint_hex(&ubuf[37], 16)); JsonSaveBufAsHexCompact(root, "$.AppData.AAGUID", &ubuf[37], 16); - + // Credential ID uint8_t cridlen = (uint16_t)bytes_to_num(&ubuf[53], 2); PrintAndLog("Credential id[%d]: %s", cridlen, sprint_hex_inrow(&ubuf[55], cridlen)); JsonSaveInt(root, "$.AppData.CredentialIdLen", cridlen); JsonSaveBufAsHexCompact(root, "$.AppData.CredentialId", &ubuf[55], cridlen); - + //Credentional public key (COSE_KEY) uint8_t coseKey[65] = {0}; uint16_t cplen = n - 55 - cridlen; @@ -480,14 +480,14 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b PrintAndLog("Credentional public key (COSE_KEY)[%d]: %s...", cplen, sprint_hex(&ubuf[55 + cridlen], MIN(cplen, 16))); } JsonSaveBufAsHexCompact(root, "$.AppData.COSE_KEY", &ubuf[55 + cridlen], cplen); - + if (showCBOR) { PrintAndLog("COSE structure:"); PrintAndLog("---------------- CBOR ------------------"); - TinyCborPrintFIDOPackage(fido2COSEKey, true, &ubuf[55 + cridlen], cplen); + TinyCborPrintFIDOPackage(fido2COSEKey, true, &ubuf[55 + cridlen], cplen); PrintAndLog("---------------- CBOR ------------------"); } - + res = COSEGetECDSAKey(&ubuf[55 + cridlen], cplen, verbose, coseKey); if (res) { PrintAndLog("ERROR: Can't get COSE_KEY."); @@ -497,27 +497,27 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b } free(ubuf); - + // attStmt - we are check only as DER certificate int64_t alg = 0; uint8_t sign[128] = {0}; size_t signLen = 0; uint8_t der[4097] = {0}; size_t derLen = 0; - + res = CborMapGetKeyById(&parser, &map, data, dataLen, 3); if (res) return res; res = cbor_value_enter_container(&map, &mapsmt); cbor_check(res); - + while (!cbor_value_at_end(&mapsmt)) { char key[100] = {0}; res = CborGetStringValue(&mapsmt, key, sizeof(key), &n); cbor_check(res); if (!strcmp(key, "alg")) { - cbor_value_get_int64(&mapsmt, &alg); + cbor_value_get_int64(&mapsmt, &alg); PrintAndLog("Alg [%lld] %s", (long long)alg, GetCOSEAlgDescription(alg)); res = cbor_value_advance_fixed(&mapsmt); cbor_check(res); @@ -544,11 +544,11 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b PrintAndLog("DER [%d]: %s...", derLen, sprint_hex(der, MIN(derLen, 16))); } JsonSaveBufAsHexCompact(root, "$.AppData.DER", der, derLen); - } + } } res = cbor_value_leave_container(&map, &mapsmt); cbor_check(res); - + uint8_t public_key[65] = {0}; // print DER certificate in TLV view @@ -562,7 +562,7 @@ int FIDO2MakeCredentionalParseRes(json_t *root, uint8_t *data, size_t dataLen, b // check ANSI X9.62 format ECDSA signature (on P-256) FIDO2CheckSignature(root, public_key, sign, signLen, authData, authDataLen, verbose); - + return 0; } @@ -575,7 +575,7 @@ int FIDO2CreateGetAssertionReq(json_t *root, uint8_t *data, size_t maxdatalen, s int res; CborEncoder encoder; CborEncoder map, array, mapint; - + cbor_encoder_init(&encoder, data, maxdatalen, 0); // create main map @@ -605,15 +605,15 @@ int FIDO2CreateGetAssertionReq(json_t *root, uint8_t *data, size_t maxdatalen, s fido_check_if(res) { res = cbor_encode_text_stringz(&mapint, "type"); fido_check(res); - + res = cbor_encode_text_stringz(&mapint, "public-key"); - fido_check(res); - + fido_check(res); + res = cbor_encode_text_stringz(&mapint, "id"); - fido_check(res); - + fido_check(res); + res = CBOREncodeElm(root, "$.AppData.CredentialId", &mapint); - fido_check(res); + fido_check(res); } res = cbor_encoder_close_container(&array, &mapint); fido_check(res); @@ -632,11 +632,11 @@ int FIDO2CreateGetAssertionReq(json_t *root, uint8_t *data, size_t maxdatalen, s } res = cbor_encoder_close_container(&encoder, &map); fido_check(res); - + size_t len = cbor_encoder_get_buffer_size(&encoder, data); if (datalen) *datalen = len; - + return 0; } @@ -646,7 +646,7 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool int res; uint8_t *ubuf; size_t n; - + // credential res = CborMapGetKeyById(&parser, &map, data, dataLen, 1); if (res) @@ -654,7 +654,7 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool res = cbor_value_enter_container(&map, &mapint); cbor_check(res); - + while (!cbor_value_at_end(&mapint)) { char key[100] = {0}; res = CborGetStringValue(&mapint, key, sizeof(key), &n); @@ -676,27 +676,27 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool } res = cbor_value_leave_container(&map, &mapint); cbor_check(res); - + // authData - uint8_t authData[400] = {0}; + uint8_t authData[400] = {0}; size_t authDataLen = 0; res = CborMapGetKeyById(&parser, &map, data, dataLen, 2); if (res) return res; res = cbor_value_dup_byte_string(&map, &ubuf, &n, &map); cbor_check(res); - + authDataLen = n; - memcpy(authData, ubuf, authDataLen); - + memcpy(authData, ubuf, authDataLen); + if (verbose2) { PrintAndLog("authData[%d]: %s", n, sprint_hex_inrow(authData, authDataLen)); } else { PrintAndLog("authData[%d]: %s...", n, sprint_hex(authData, MIN(authDataLen, 16))); } - + PrintAndLog("RP ID Hash: %s", sprint_hex(ubuf, 32)); - + // check RP ID Hash if (CheckrpIdHash(root, ubuf)) { PrintAndLog("rpIdHash OK."); @@ -719,17 +719,17 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool uint32_t cntr = (uint32_t)bytes_to_num(&ubuf[33], 4); PrintAndLog("Counter: %d", cntr); JsonSaveInt(root, "$.AppData.Counter", cntr); - + free(ubuf); // publicKeyCredentialUserEntity res = CborMapGetKeyById(&parser, &map, data, dataLen, 4); - if (res) { + if (res) { PrintAndLog("UserEntity n/a"); } else { res = cbor_value_enter_container(&map, &mapint); cbor_check(res); - + while (!cbor_value_at_end(&mapint)) { char key[100] = {0}; res = CborGetStringValue(&mapint, key, sizeof(key), &n); @@ -747,7 +747,7 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool res = CborGetBinStringValue(&mapint, cid, sizeof(cid), &n); cbor_check(res); PrintAndLog("UserEntity id [%d]: %s", n, sprint_hex(cid, n)); - + // check uint8_t idbuf[100] = {0}; size_t idbuflen; @@ -764,15 +764,15 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool res = cbor_value_leave_container(&map, &mapint); cbor_check(res); } - - + + // signature res = CborMapGetKeyById(&parser, &map, data, dataLen, 3); if (res) return res; res = cbor_value_dup_byte_string(&map, &ubuf, &n, &map); cbor_check(res); - + uint8_t *sign = ubuf; size_t signLen = n; @@ -787,7 +787,7 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool uint8_t PublicKey[65] = {0}; size_t PublicKeyLen = 0; JsonLoadBufAsHex(root, "$.AppData.COSEPublicKey", PublicKey, 65, &PublicKeyLen); - + // check ANSI X9.62 format ECDSA signature (on P-256) FIDO2CheckSignature(root, PublicKey, sign, signLen, authData, authDataLen, verbose); @@ -799,9 +799,9 @@ int FIDO2GetAssertionParseRes(json_t *root, uint8_t *data, size_t dataLen, bool PrintAndLog("numberOfCredentials: 1 by default"); } else { int64_t numberOfCredentials = 0; - cbor_value_get_int64(&map, &numberOfCredentials); + cbor_value_get_int64(&map, &numberOfCredentials); PrintAndLog("numberOfCredentials: %lld", (long long)numberOfCredentials); } - + return 0; } diff --git a/client/fido/fidocore.h b/client/fido/fidocore.h index b0b50e2ac..931cf146b 100644 --- a/client/fido/fidocore.h +++ b/client/fido/fidocore.h @@ -25,7 +25,7 @@ typedef enum { fido2CmdClientPIN = 0x06, fido2CmdReset = 0x07, fido2CmdGetNextAssertion = 0x08, - + // another data fido2COSEKey = 0xF0 } fido2Commands; diff --git a/client/flasher.c b/client/flasher.c index a20b264b9..c1ec7b4f1 100644 --- a/client/flasher.c +++ b/client/flasher.c @@ -39,13 +39,13 @@ static void usage(char *argv0) { fprintf(stdout, "Usage: %s [-b] image.elf [image.elf...]\n\n", argv0); fprintf(stdout, "\t-b\tEnable flashing of bootloader area (DANGEROUS)\n\n"); fprintf(stdout, "\nExample:\n\n\t %s "SERIAL_PORT_H" armsrc/obj/fullimage.elf\n", argv0); -#ifdef __linux__ +#ifdef __linux__ fprintf(stdout, "\nNote (Linux): if the flasher gets stuck in 'Waiting for Proxmark to reappear on ',\n"); fprintf(stdout, " you need to blacklist proxmark for modem-manager - see wiki for more details:\n\n"); fprintf(stdout, " https://github.com/Proxmark/proxmark3/wiki/Gentoo Linux\n\n"); fprintf(stdout, " https://github.com/Proxmark/proxmark3/wiki/Ubuntu Linux\n\n"); fprintf(stdout, " https://github.com/Proxmark/proxmark3/wiki/OSX\n\n"); -#endif +#endif } int main(int argc, char **argv) { @@ -78,7 +78,7 @@ int main(int argc, char **argv) { num_files++; } } - + char* serial_port_name = argv[1]; if (!OpenProxmark(serial_port_name, true, 60, true)) { diff --git a/client/fpga_compress.c b/client/fpga_compress.c index 6e6e67be4..1f959fa9f 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -27,18 +27,18 @@ #define COMPRESS_LEVEL 9 // use best possible compression #define COMPRESS_WINDOW_BITS 15 // default = max = 15 for a window of 2^15 = 32KBytes #define COMPRESS_MEM_LEVEL 9 // determines the amount of memory allocated during compression. Default = 8. -/* COMPRESS_STRATEGY can be - Z_DEFAULT_STRATEGY (the default), +/* COMPRESS_STRATEGY can be + Z_DEFAULT_STRATEGY (the default), Z_FILTERED (more huffmann, less string matching), Z_HUFFMAN_ONLY (huffman only, no string matching) Z_RLE (distances limited to one) Z_FIXED (prevents the use of dynamic Huffman codes) -*/ +*/ #define COMPRESS_STRATEGY Z_DEFAULT_STRATEGY // zlib tuning parameters: #define COMPRESS_GOOD_LENGTH 258 -#define COMPRESS_MAX_LAZY 258 +#define COMPRESS_MAX_LAZY 258 #define COMPRESS_MAX_NICE_LENGTH 258 #define COMPRESS_MAX_CHAIN 8192 @@ -75,7 +75,7 @@ static bool all_feof(FILE *infile[], uint8_t num_infiles) if (!feof(infile[i])) { return false; } - } + } return true; } @@ -92,21 +92,21 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn fpga_config = calloc(num_infiles * HARDNESTED_TABLE_SIZE, sizeof(uint8_t)); } else { fpga_config = calloc(num_infiles * FPGA_CONFIG_SIZE, sizeof(uint8_t)); - } + } // read the input files. Interleave them into fpga_config[] i = 0; do { if (i >= num_infiles * (hardnested_mode ? HARDNESTED_TABLE_SIZE : FPGA_CONFIG_SIZE)) { if (hardnested_mode) { - fprintf(stderr, -#if __WORDSIZE == 64 + fprintf(stderr, +#if __WORDSIZE == 64 "Input file too big (> %" PRIu64 " bytes). This is probably not a hardnested bitflip state table.\n" #else - "Input file too big (> %lu bytes). This is probably not a hardnested bitflip state table.\n" -#endif + "Input file too big (> %lu bytes). This is probably not a hardnested bitflip state table.\n" +#endif , HARDNESTED_TABLE_SIZE); - + } else { fprintf(stderr, "Input files too big (total > %lu bytes). These are probably not PM3 FPGA config files.\n", num_infiles * FPGA_CONFIG_SIZE); } @@ -136,8 +136,8 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn compressed_fpga_stream.zalloc = fpga_deflate_malloc; compressed_fpga_stream.zfree = fpga_deflate_free; compressed_fpga_stream.opaque = Z_NULL; - - ret = deflateInit2(&compressed_fpga_stream, + + ret = deflateInit2(&compressed_fpga_stream, COMPRESS_LEVEL, Z_DEFLATED, COMPRESS_WINDOW_BITS, @@ -149,7 +149,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn uint8_t *outbuf = calloc(outsize_max, sizeof(uint8_t)); compressed_fpga_stream.next_out = outbuf; compressed_fpga_stream.avail_out = outsize_max; - + if (ret == Z_OK) { ret = deflateTune(&compressed_fpga_stream, COMPRESS_GOOD_LENGTH, @@ -157,11 +157,11 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn COMPRESS_MAX_NICE_LENGTH, COMPRESS_MAX_CHAIN); } - + if (ret == Z_OK) { ret = deflate(&compressed_fpga_stream, Z_FINISH); } - + fprintf(stdout, "compressed %u input bytes to %lu output bytes\n", i, compressed_fpga_stream.total_out); if (ret != Z_STREAM_END) { @@ -176,10 +176,10 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn free(fpga_config); return(EXIT_FAILURE); } - + for (i = 0; i < compressed_fpga_stream.total_out; i++) { fputc(outbuf[i], outfile); - } + } free(outbuf); deflateEnd(&compressed_fpga_stream); @@ -189,9 +189,9 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile, bool hardn fclose(outfile); free(infile); free(fpga_config); - + return(EXIT_SUCCESS); - + } @@ -201,7 +201,7 @@ int zlib_decompress(FILE *infile, FILE *outfile) uint8_t outbuf[DECOMPRESS_BUF_SIZE]; uint8_t inbuf[DECOMPRESS_BUF_SIZE]; int32_t ret; - + z_stream compressed_fpga_stream; // initialize zlib structures @@ -212,9 +212,9 @@ int zlib_decompress(FILE *infile, FILE *outfile) compressed_fpga_stream.zalloc = fpga_deflate_malloc; compressed_fpga_stream.zfree = fpga_deflate_free; compressed_fpga_stream.opaque = Z_NULL; - + ret = inflateInit2(&compressed_fpga_stream, 0); - + do { if (compressed_fpga_stream.avail_in == 0) { compressed_fpga_stream.next_in = inbuf; @@ -260,7 +260,7 @@ int zlib_decompress(FILE *infile, FILE *outfile) fclose(infile); return(EXIT_FAILURE); } - + } @@ -319,7 +319,7 @@ static int FpgaGatherVersion(FILE *infile, char* infile_name, char *dst, int len { unsigned int fpga_info_len; char tempstr[40] = {0x00}; - + dst[0] = '\0'; for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { @@ -345,7 +345,7 @@ static int FpgaGatherVersion(FILE *infile, char* infile_name, char *dst, int len } strncat(dst, tempstr, len-1); } - + if (bitparse_find_section(infile, 'c', &fpga_info_len)) { strncat(dst, " on ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { @@ -356,7 +356,7 @@ static int FpgaGatherVersion(FILE *infile, char* infile_name, char *dst, int len } strncat(dst, tempstr, len-1); } - + if (bitparse_find_section(infile, 'd', &fpga_info_len)) { strncat(dst, " at ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { @@ -389,11 +389,11 @@ static void print_version_info_preamble(FILE *outfile, int num_infiles) { } static int generate_fpga_version_info(FILE *infile[], char *infile_names[], int num_infiles, FILE *outfile) { - + char version_string[80] = ""; - + print_version_info_preamble(outfile, num_infiles); - + for (int i = 0; i < num_infiles; i++) { FpgaGatherVersion(infile[i], infile_names[i], version_string, sizeof(version_string)); fprintf(outfile, "\t\" %s\"", version_string); @@ -401,7 +401,7 @@ static int generate_fpga_version_info(FILE *infile[], char *infile_names[], int fprintf(outfile, ","); } fprintf(outfile,"\n"); - } + } fprintf(outfile, "};\n"); return 0; } @@ -411,19 +411,19 @@ int main(int argc, char **argv) FILE **infiles; char **infile_names; FILE *outfile; - + if (argc == 1 || argc == 2) { usage(); return(EXIT_FAILURE); } - + if (!strcmp(argv[1], "-d")) { // Decompress infiles = calloc(1, sizeof(FILE*)); if (argc != 4) { usage(); return(EXIT_FAILURE); - } + } infiles[0] = fopen(argv[2], "rb"); if (infiles[0] == NULL) { fprintf(stderr, "Error. Cannot open input file %s\n\n", argv[2]); @@ -454,10 +454,10 @@ int main(int argc, char **argv) } else { // compress 1..n fpga files num_input_files = argc-2; } - + infiles = calloc(num_input_files, sizeof(FILE*)); infile_names = calloc(num_input_files, sizeof(char*)); - for (uint16_t i = 0; i < num_input_files; i++) { + for (uint16_t i = 0; i < num_input_files; i++) { infile_names[i] = argv[i+((hardnested_mode || generate_version_file)?2:1)]; infiles[i] = fopen(infile_names[i], "rb"); if (infiles[i] == NULL) { diff --git a/client/graph.c b/client/graph.c index 42bb79c84..db29919bc 100644 --- a/client/graph.c +++ b/client/graph.c @@ -16,7 +16,7 @@ int s_Buff[MAX_GRAPH_TRACE_LEN]; /* write a manchester bit to the graph */ void AppendGraph(int redraw, int clock, int bit) { int i; - //set first half the clock bit (all 1's or 0's for a 0 or 1 bit) + //set first half the clock bit (all 1's or 0's for a 0 or 1 bit) for (i = 0; i < (int)(clock / 2); ++i) GraphBuffer[GraphTraceLen++] = bit ; //set second half of the clock bit (all 0's or 1's for a 0 or 1 bit) @@ -59,12 +59,12 @@ void save_restoreGB(uint8_t saveOpt) { void setGraphBuf(uint8_t *buf, size_t size) { if ( buf == NULL ) return; - + ClearGraph(0); - + if ( size > MAX_GRAPH_TRACE_LEN ) size = MAX_GRAPH_TRACE_LEN; - + for (uint16_t i = 0; i < size; ++i) GraphBuffer[i] = buf[i] - 128; @@ -85,22 +85,22 @@ size_t getFromGraphBuf(uint8_t *buf) { return i; } -// A simple test to see if there is any data inside Graphbuffer. +// A simple test to see if there is any data inside Graphbuffer. bool HasGraphData(){ if ( GraphTraceLen <= 0) { PrintAndLogEx(NORMAL, "No data available, try reading something first"); return false; } - return true; + return true; } // Get or auto-detect ask clock rate int GetAskClock(const char *str, bool printAns) { int clock = param_get32ex(str, 0, 0, 10); - if (clock > 0) + if (clock > 0) return clock; - + // Auto-detect clock uint8_t bits[MAX_GRAPH_TRACE_LEN] = {0}; size_t size = getFromGraphBuf(bits); @@ -115,7 +115,7 @@ int GetAskClock(const char *str, bool printAns) { if (st == false) { idx = DetectASKClock(bits, size, &clock, 20); } - + if ( clock > 0 ) { setClockGrid(clock, idx); } @@ -146,9 +146,9 @@ uint8_t GetPskCarrier(const char *str, bool printAns) { int GetPskClock(const char* str, bool printAns) { int clock = param_get32ex(str, 0, 0, 10); - if (clock != 0) + if (clock != 0) return clock; - + // Auto-detect clock uint8_t grph[MAX_GRAPH_TRACE_LEN] = {0}; size_t size = getFromGraphBuf(grph); @@ -169,9 +169,9 @@ int GetPskClock(const char* str, bool printAns) { int GetNrzClock(const char* str, bool printAns) { int clock = param_get32ex(str, 0, 0, 10); - if (clock != 0) + if (clock != 0) return clock; - + // Auto-detect clock uint8_t grph[MAX_GRAPH_TRACE_LEN] = {0}; size_t size = getFromGraphBuf(grph); @@ -192,17 +192,17 @@ int GetNrzClock(const char* str, bool printAns) { int GetFskClock(const char* str, bool printAns) { int clock = param_get32ex(str, 0, 0, 10); - if (clock != 0) + if (clock != 0) return clock; uint8_t fc1 = 0, fc2 = 0, rf1 = 0; int firstClockEdge = 0; - + if ( !fskClocks(&fc1, &fc2, &rf1, &firstClockEdge)) return 0; - + if ((fc1==10 && fc2==8) || (fc1==8 && fc2==5)){ - if (printAns) + if (printAns) PrintAndLogEx(SUCCESS, "Detected Field Clocks: FC/%d, FC/%d - Bit Clock: RF/%d", fc1, fc2, rf1); setClockGrid(rf1, firstClockEdge); return rf1; @@ -215,15 +215,15 @@ int GetFskClock(const char* str, bool printAns) { bool fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, int *firstClockEdge) { uint8_t bits[MAX_GRAPH_TRACE_LEN] = {0}; size_t size = getFromGraphBuf(bits); - if (size == 0) + if (size == 0) return false; - + uint16_t ans = countFC(bits, size, true); if (ans == 0) { PrintAndLogEx(DEBUG, "DEBUG: No data found"); return false; } - + *fc1 = (ans >> 8) & 0xFF; *fc2 = ans & 0xFF; *rf1 = detectFSKClk(bits, size, *fc1, *fc2, firstClockEdge); diff --git a/client/hardnested/hardnested_bf_core.c b/client/hardnested/hardnested_bf_core.c index 6bf29b795..e80a9cd19 100644 --- a/client/hardnested/hardnested_bf_core.c +++ b/client/hardnested/hardnested_bf_core.c @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- // @@ -19,7 +19,7 @@ // - don't rollback. Start with 2nd byte of nonce instead // - reuse results of filter subfunctions // - reuse results of previous nonces if some first bits are identical -// +// //----------------------------------------------------------------------------- // aczid's Copyright notice: // @@ -100,7 +100,7 @@ typedef union { // size of nonce to be decrypted #define KEYSTREAM_SIZE 24 -// this needs to be compiled several times for each instruction set. +// this needs to be compiled several times for each instruction set. // For each instruction set, define a dedicated function name: #if defined (__AVX512F__) #define BITSLICE_TEST_NONCES bitslice_test_nonces_AVX512 @@ -114,7 +114,7 @@ typedef union { #elif defined (__SSE2__) #define BITSLICE_TEST_NONCES bitslice_test_nonces_SSE2 #define CRACK_STATES_BITSLICED crack_states_bitsliced_SSE2 -#elif defined (__MMX__) +#elif defined (__MMX__) #define BITSLICE_TEST_NONCES bitslice_test_nonces_MMX #define CRACK_STATES_BITSLICED crack_states_bitsliced_MMX #else @@ -208,7 +208,7 @@ void BITSLICE_TEST_NONCES(uint32_t nonces_to_bruteforce, uint32_t *bf_test_nonce const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, statelist_t *p, uint32_t *keys_found, uint64_t *num_keys_tested, uint32_t nonces_to_bruteforce, uint8_t *bf_test_nonce_2nd_byte, noncelist_t *nonces){ // Unlike aczid's implementation this doesn't roll back at all when performing bitsliced bruteforce. - // We know that the best first byte is already shifted in. Testing with the remaining three bytes of + // We know that the best first byte is already shifted in. Testing with the remaining three bytes of // the nonces is sufficient to eliminate most of them. The small rest is tested with a simple unsliced // brute forcing (including roll back). @@ -223,7 +223,7 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, uint32_t elimination_step = 0; #define MAX_ELIMINATION_STEP 32 uint64_t keys_eliminated[MAX_ELIMINATION_STEP] = {0}; -#endif +#endif #ifdef DEBUG_KEY_ELIMINATION bool bucket_contains_test_key[(p->len[EVEN_STATE] - 1)/MAX_BITSLICES + 1]; #endif @@ -233,7 +233,7 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, memset(bs_ones.bytes, 0xff, VECTOR_SIZE); bitslice_t bs_zeroes; memset(bs_zeroes.bytes, 0x00, VECTOR_SIZE); - + // bitslice all the even states bitslice_t **restrict bitsliced_even_states = (bitslice_t **)malloc(((p->len[EVEN_STATE] - 1)/MAX_BITSLICES + 1) * sizeof(bitslice_t *)); if (bitsliced_even_states == NULL) { @@ -284,10 +284,10 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, lstate_p[bit_idx].bytes64[slice_idx>>6] |= 1ull << (slice_idx & 0x3f); } } - } + } bitsliced_even_states[bitsliced_blocks] = lstate_p; // bitsliced_even_feedback[bitsliced_blocks] = bs_ones; - bitsliced_even_feedback[bitsliced_blocks] = lstate_p[(47- 0)/2].value ^ + bitsliced_even_feedback[bitsliced_blocks] = lstate_p[(47- 0)/2].value ^ lstate_p[(47-10)/2].value ^ lstate_p[(47-12)/2].value ^ lstate_p[(47-14)/2].value ^ lstate_p[(47-24)/2].value ^ lstate_p[(47-42)/2].value; bitsliced_blocks++; @@ -298,9 +298,9 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, if(*keys_found){ goto out; } - + // set odd state bits and pre-compute first keystream bit vector. This is the same for all blocks of even states - + state_p = &states[KEYSTREAM_SIZE]; uint32_t o = *p_odd; @@ -316,13 +316,13 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, state_p[state_idx] = bs_zeroes; } } - + bitslice_value_t crypto1_bs_f20b_2[16]; bitslice_value_t crypto1_bs_f20b_3[8]; crypto1_bs_f20b_2[0] = f20b(state_p[47-25].value, state_p[47-27].value, state_p[47-29].value, state_p[47-31].value); crypto1_bs_f20b_3[0] = f20b(state_p[47-41].value, state_p[47-43].value, state_p[47-45].value, state_p[47-47].value); - + bitslice_value_t ksb[8]; ksb[0] = f20c(f20a(state_p[47- 9].value, state_p[47-11].value, state_p[47-13].value, state_p[47-15].value), f20b(state_p[47-17].value, state_p[47-19].value, state_p[47-21].value, state_p[47-23].value), @@ -347,11 +347,11 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, // pre-compute first feedback bit vector. This is the same for all nonces bitslice_value_t fbb[8]; - fbb[0] = odd_feedback ^ bitsliced_even_feedback[block_idx]; + fbb[0] = odd_feedback ^ bitsliced_even_feedback[block_idx]; // vector to contain test results (1 = passed, 0 = failed) bitslice_t results = bs_ones; - + // parity_bits bitslice_value_t par[8]; par[0] = bs_zeroes.value; @@ -398,7 +398,7 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, f20a_1 = f20a(state_p[47- 9].value, state_p[47-11].value, state_p[47-13].value, state_p[47-15].value); f20b_1 = crypto1_bs_f20b_2[KEYSTREAM_SIZE - ks_idx - 8]; f20b_2 = f20b(state_p[47-25].value, state_p[47-27].value, state_p[47-29].value, state_p[47-31].value); - crypto1_bs_f20b_2[KEYSTREAM_SIZE - ks_idx] = f20b_2; + crypto1_bs_f20b_2[KEYSTREAM_SIZE - ks_idx] = f20b_2; } else if (ks_idx > KEYSTREAM_SIZE - 24){ f20a_1 = f20a(state_p[47- 9].value, state_p[47-11].value, state_p[47-13].value, state_p[47-15].value); f20b_1 = crypto1_bs_f20b_2[KEYSTREAM_SIZE - ks_idx - 8]; @@ -407,7 +407,7 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, f20a_1 = f20a(state_p[47- 9].value, state_p[47-11].value, state_p[47-13].value, state_p[47-15].value); f20b_1 = f20b(state_p[47-17].value, state_p[47-19].value, state_p[47-21].value, state_p[47-23].value); f20b_2 = f20b(state_p[47-25].value, state_p[47-27].value, state_p[47-29].value, state_p[47-31].value); - } + } // update keystream bit ks_bits = f20c(f20a_1, f20b_1, f20b_2, f20a_2, f20b_3); @@ -436,7 +436,7 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, && results.bytes64[3] == 0 #endif ) { -#if defined (DEBUG_BRUTE_FORCE) +#if defined (DEBUG_BRUTE_FORCE) if (elimination_step < MAX_ELIMINATION_STEP) { keys_eliminated[elimination_step] += MAX_BITSLICES; } @@ -450,14 +450,14 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, goto stop_tests; } // prepare for next nonce byte -#if defined (DEBUG_BRUTE_FORCE) +#if defined (DEBUG_BRUTE_FORCE) elimination_step++; #endif parity_bit_vector = bs_zeroes.value; - } + } // update feedback bit vector if (ks_idx != 0) { - fb_bits = + fb_bits = (state_p[47- 0].value ^ state_p[47- 5].value ^ state_p[47- 9].value ^ state_p[47-10].value ^ state_p[47-12].value ^ state_p[47-14].value ^ state_p[47-15].value ^ state_p[47-17].value ^ state_p[47-19].value ^ @@ -513,9 +513,9 @@ const uint64_t CRACK_STATES_BITSLICED(uint32_t cuid, uint8_t *best_first_bytes, } } stop_tests: -#if defined (DEBUG_BRUTE_FORCE) +#if defined (DEBUG_BRUTE_FORCE) elimination_step = 0; -#endif +#endif bucket_states_tested += bucket_size[block_idx]; // prepare to set new states state_p = &states[KEYSTREAM_SIZE]; @@ -529,12 +529,12 @@ out: free(bitsliced_even_states); free_bitslice(bitsliced_even_feedback); __sync_fetch_and_add(num_keys_tested, bucket_states_tested); - -#if defined (DEBUG_BRUTE_FORCE) + +#if defined (DEBUG_BRUTE_FORCE) for (uint32_t i = 0; i < MAX_ELIMINATION_STEP; i++) { printf("Eliminated after %2u test_bytes: %5.2f%%\n", i+1, (float)keys_eliminated[i] / bucket_states_tested * 100); } -#endif +#endif return key; } @@ -550,17 +550,17 @@ static SIMDExecInstr intSIMDInstr = SIMD_AUTO; void SetSIMDInstr(SIMDExecInstr instr) { intSIMDInstr = instr; - + crack_states_bitsliced_function_p = &crack_states_bitsliced_dispatch; bitslice_test_nonces_function_p = &bitslice_test_nonces_dispatch; } SIMDExecInstr GetSIMDInstr() { SIMDExecInstr instr = SIMD_NONE; - + #if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) - #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) + #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) instr = SIMD_AVX512; else if (__builtin_cpu_supports("avx2")) instr = SIMD_AVX2; #else @@ -573,7 +573,7 @@ SIMDExecInstr GetSIMDInstr() { #endif #endif instr = SIMD_NONE; - + return instr; } @@ -581,7 +581,7 @@ SIMDExecInstr GetSIMDInstrAuto() { SIMDExecInstr instr = intSIMDInstr; if (instr == SIMD_AUTO) return GetSIMDInstr(); - + return instr; } @@ -589,8 +589,8 @@ SIMDExecInstr GetSIMDInstrAuto() { const uint64_t crack_states_bitsliced_dispatch(uint32_t cuid, uint8_t *best_first_bytes, statelist_t *p, uint32_t *keys_found, uint64_t *num_keys_tested, uint32_t nonces_to_bruteforce, uint8_t *bf_test_nonce_2nd_byte, noncelist_t *nonces) { switch(GetSIMDInstrAuto()) { #if defined (__i386__) || defined (__x86_64__) - #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) - #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) + #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) + #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) case SIMD_AVX512: crack_states_bitsliced_function_p = &crack_states_bitsliced_AVX512; break; @@ -612,7 +612,7 @@ const uint64_t crack_states_bitsliced_dispatch(uint32_t cuid, uint8_t *best_firs default: crack_states_bitsliced_function_p = &crack_states_bitsliced_NOSIMD; break; - } + } // call the most optimized function for this CPU return (*crack_states_bitsliced_function_p)(cuid, best_first_bytes, p, keys_found, num_keys_tested, nonces_to_bruteforce, bf_test_nonce_2nd_byte, nonces); @@ -620,7 +620,7 @@ const uint64_t crack_states_bitsliced_dispatch(uint32_t cuid, uint8_t *best_firs void bitslice_test_nonces_dispatch(uint32_t nonces_to_bruteforce, uint32_t *bf_test_nonce, uint8_t *bf_test_nonce_par) { switch(GetSIMDInstrAuto()) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) case SIMD_AVX512: @@ -644,7 +644,7 @@ void bitslice_test_nonces_dispatch(uint32_t nonces_to_bruteforce, uint32_t *bf_t default: bitslice_test_nonces_function_p = &bitslice_test_nonces_NOSIMD; break; - } + } // call the most optimized function for this CPU (*bitslice_test_nonces_function_p)(nonces_to_bruteforce, bf_test_nonce, bf_test_nonce_par); diff --git a/client/hardnested/hardnested_bf_core.h b/client/hardnested/hardnested_bf_core.h index b3df05474..c7d0b03dd 100644 --- a/client/hardnested/hardnested_bf_core.h +++ b/client/hardnested/hardnested_bf_core.h @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- // @@ -19,7 +19,7 @@ // - don't rollback. Start with 2nd byte of nonce instead // - reuse results of filter subfunctions // - reuse results of previous nonces if some first bits are identical -// +// //----------------------------------------------------------------------------- // aczid's Copyright notice: // diff --git a/client/hardnested/hardnested_bitarray_core.c b/client/hardnested/hardnested_bitarray_core.c index aca4f149d..1abdd8c79 100644 --- a/client/hardnested/hardnested_bitarray_core.c +++ b/client/hardnested/hardnested_bitarray_core.c @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- // some helper functions which can benefit from SIMD instructions or other special instructions @@ -25,7 +25,7 @@ #include #endif -// this needs to be compiled several times for each instruction set. +// this needs to be compiled several times for each instruction set. // For each instruction set, define a dedicated function name: #if defined (__AVX512F__) #define MALLOC_BITARRAY malloc_bitarray_AVX512 @@ -83,7 +83,7 @@ #define COUNT_BITARRAY_AND2 count_bitarray_AND2_SSE2 #define COUNT_BITARRAY_AND3 count_bitarray_AND3_SSE2 #define COUNT_BITARRAY_AND4 count_bitarray_AND4_SSE2 -#elif defined (__MMX__) +#elif defined (__MMX__) #define MALLOC_BITARRAY malloc_bitarray_MMX #define FREE_BITARRAY free_bitarray_MMX #define BITCOUNT bitcount_MMX @@ -169,7 +169,7 @@ inline void FREE_BITARRAY(uint32_t *x) #endif } - + inline uint32_t BITCOUNT(uint32_t a) { return __builtin_popcountl(a); @@ -200,12 +200,12 @@ inline void BITARRAY_LOW20_AND(uint32_t *restrict A, uint32_t *restrict B) { uint16_t *a = (uint16_t *)__builtin_assume_aligned(A, __BIGGEST_ALIGNMENT__); uint16_t *b = (uint16_t *)__builtin_assume_aligned(B, __BIGGEST_ALIGNMENT__); - + for (uint32_t i = 0; i < (1<<20); i++) { if (!b[i]) { a[i] = 0; } - } + } } @@ -227,14 +227,14 @@ inline uint32_t COUNT_BITARRAY_LOW20_AND(uint32_t *restrict A, uint32_t *restric uint16_t *a = (uint16_t *)__builtin_assume_aligned(A, __BIGGEST_ALIGNMENT__); uint16_t *b = (uint16_t *)__builtin_assume_aligned(B, __BIGGEST_ALIGNMENT__); uint32_t count = 0; - + for (uint32_t i = 0; i < (1<<20); i++) { if (!b[i]) { a[i] = 0; } count += BITCOUNT(a[i]); } - return count; + return count; } @@ -318,7 +318,7 @@ count_bitarray_AND4_t *count_bitarray_AND4_function_p = &count_bitarray_AND4_dis // determine the available instruction set at runtime and call the correct function uint32_t *malloc_bitarray_dispatch(uint32_t x) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) malloc_bitarray_function_p = &malloc_bitarray_AVX512; @@ -331,7 +331,7 @@ uint32_t *malloc_bitarray_dispatch(uint32_t x) { else if (__builtin_cpu_supports("mmx")) malloc_bitarray_function_p = &malloc_bitarray_MMX; else #endif -#endif +#endif malloc_bitarray_function_p = &malloc_bitarray_NOSIMD; // call the most optimized function for this CPU @@ -360,7 +360,7 @@ void free_bitarray_dispatch(uint32_t *x) { } uint32_t bitcount_dispatch(uint32_t a) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) bitcount_function_p = &bitcount_AVX512; @@ -381,7 +381,7 @@ uint32_t bitcount_dispatch(uint32_t a) { } uint32_t count_states_dispatch(uint32_t *bitarray) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) count_states_function_p = &count_states_AVX512; @@ -393,7 +393,7 @@ uint32_t count_states_dispatch(uint32_t *bitarray) { else if (__builtin_cpu_supports("sse2")) count_states_function_p = &count_states_SSE2; else if (__builtin_cpu_supports("mmx")) count_states_function_p = &count_states_MMX; else - #endif + #endif #endif count_states_function_p = &count_states_NOSIMD; @@ -402,7 +402,7 @@ uint32_t count_states_dispatch(uint32_t *bitarray) { } void bitarray_AND_dispatch(uint32_t *A, uint32_t *B) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) bitarray_AND_function_p = &bitarray_AND_AVX512; @@ -444,7 +444,7 @@ void bitarray_low20_AND_dispatch(uint32_t *A, uint32_t *B) { } uint32_t count_bitarray_AND_dispatch(uint32_t *A, uint32_t *B) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) count_bitarray_AND_function_p = &count_bitarray_AND_AVX512; @@ -465,7 +465,7 @@ uint32_t count_bitarray_AND_dispatch(uint32_t *A, uint32_t *B) { } uint32_t count_bitarray_low20_AND_dispatch(uint32_t *A, uint32_t *B) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) count_bitarray_low20_AND_function_p = &count_bitarray_low20_AND_AVX512; @@ -486,7 +486,7 @@ uint32_t count_bitarray_low20_AND_dispatch(uint32_t *A, uint32_t *B) { } void bitarray_AND4_dispatch(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) bitarray_AND4_function_p = &bitarray_AND4_AVX512; @@ -507,7 +507,7 @@ void bitarray_AND4_dispatch(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D) } void bitarray_OR_dispatch(uint32_t *A, uint32_t *B) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) bitarray_OR_function_p = &bitarray_OR_AVX512; @@ -528,7 +528,7 @@ void bitarray_OR_dispatch(uint32_t *A, uint32_t *B) { } uint32_t count_bitarray_AND2_dispatch(uint32_t *A, uint32_t *B) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) count_bitarray_AND2_function_p = &count_bitarray_AND2_AVX512; @@ -549,7 +549,7 @@ uint32_t count_bitarray_AND2_dispatch(uint32_t *A, uint32_t *B) { } uint32_t count_bitarray_AND3_dispatch(uint32_t *A, uint32_t *B, uint32_t *C) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) count_bitarray_AND3_function_p = &count_bitarray_AND3_AVX512; @@ -570,7 +570,7 @@ uint32_t count_bitarray_AND3_dispatch(uint32_t *A, uint32_t *B, uint32_t *C) { } uint32_t count_bitarray_AND4_dispatch(uint32_t *A, uint32_t *B, uint32_t *C, uint32_t *D) { -#if defined (__i386__) || defined (__x86_64__) +#if defined (__i386__) || defined (__x86_64__) #if !defined(__APPLE__) || (defined(__APPLE__) && (__clang_major__ > 8 || __clang_major__ == 8 && __clang_minor__ >= 1)) #if (__GNUC__ >= 5) && (__GNUC__ > 5 || __GNUC_MINOR__ > 2) if (__builtin_cpu_supports("avx512f")) count_bitarray_AND4_function_p = &count_bitarray_AND4_AVX512; diff --git a/client/hardnested/hardnested_bitarray_core.h b/client/hardnested/hardnested_bitarray_core.h index 0d92d6b9a..b12fcf89d 100644 --- a/client/hardnested/hardnested_bitarray_core.h +++ b/client/hardnested/hardnested_bitarray_core.h @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- // @@ -19,7 +19,7 @@ // - don't rollback. Start with 2nd byte of nonce instead // - reuse results of filter subfunctions // - reuse results of previous nonces if some first bits are identical -// +// //----------------------------------------------------------------------------- // aczid's Copyright notice: // diff --git a/client/hardnested/hardnested_bruteforce.c b/client/hardnested/hardnested_bruteforce.c index 1a09d7a49..49cd4908d 100644 --- a/client/hardnested/hardnested_bruteforce.c +++ b/client/hardnested/hardnested_bruteforce.c @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- // @@ -19,7 +19,7 @@ // - don't rollback. Start with 2nd byte of nonce instead // - reuse results of filter subfunctions // - reuse results of previous nonces if some first bits are identical -// +// //----------------------------------------------------------------------------- // aczid's Copyright notice: // @@ -89,7 +89,7 @@ static uint32_t keys_found = 0; static uint64_t num_keys_tested; static uint64_t found_bs_key = 0; -inline uint8_t trailing_zeros(uint8_t byte) +inline uint8_t trailing_zeros(uint8_t byte) { static const uint8_t trailing_zeros_LUT[256] = { 8, 0, 1, 0, 2, 0, 1, 0, 3, 0, 1, 0, 2, 0, 1, 0, @@ -126,7 +126,7 @@ bool verify_key(uint32_t cuid, noncelist_t *nonces, uint8_t *best_first_bytes, u for (int8_t byte_pos = 3; byte_pos >= 0; byte_pos--) { uint8_t test_par_enc_bit = (test_nonce->par_enc >> byte_pos) & 0x01; // the encoded parity bit uint8_t test_byte_enc = (test_nonce->nonce_enc >> (8*byte_pos)) & 0xff; // the encoded nonce byte - uint8_t test_byte_dec = crypto1_byte(&pcs, test_byte_enc /* ^ (cuid >> (8*byte_pos)) */, true) ^ test_byte_enc; // decode the nonce byte + uint8_t test_byte_dec = crypto1_byte(&pcs, test_byte_enc /* ^ (cuid >> (8*byte_pos)) */, true) ^ test_byte_enc; // decode the nonce byte uint8_t ks_par = filter(pcs.odd); // the keystream bit to encode/decode the parity bit uint8_t test_par_enc2 = ks_par ^ evenparity8(test_byte_dec); // determine the decoded byte's parity and encode it if (test_par_enc_bit != test_par_enc2) { @@ -138,10 +138,10 @@ bool verify_key(uint32_t cuid, noncelist_t *nonces, uint8_t *best_first_bytes, u } return true; } -static void* +static void* #ifdef __has_attribute #if __has_attribute(force_align_arg_pointer) - __attribute__((force_align_arg_pointer)) + __attribute__((force_align_arg_pointer)) #endif #endif crack_states_thread(void* x){ @@ -161,9 +161,9 @@ crack_states_thread(void* x){ while(current_bucket < bucket_count){ statelist_t *bucket = buckets[current_bucket]; if(bucket){ -#if defined (DEBUG_BRUTE_FORCE) +#if defined (DEBUG_BRUTE_FORCE) printf("Thread %u starts working on bucket %u\n", thread_id, current_bucket); -#endif +#endif const uint64_t key = crack_states_bitsliced(thread_arg->cuid, thread_arg->best_first_bytes, bucket, &keys_found, &num_keys_tested, nonces_to_bruteforce, bf_test_nonce_2nd_byte, thread_arg->nonces); if(key != -1){ __atomic_fetch_add(&keys_found, 1, __ATOMIC_SEQ_CST); @@ -173,7 +173,7 @@ crack_states_thread(void* x){ char keystr[18]; sprintf(keystr, "%012" PRIx64 " ", key); sprintf(progress_text, "Brute force phase completed. Key found: " _YELLOW_(%s), keystr); - hardnested_print_progress(thread_arg->num_acquired_nonces, progress_text, 0.0, 0); + hardnested_print_progress(thread_arg->num_acquired_nonces, progress_text, 0.0, 0); break; } else if(keys_found){ break; @@ -212,20 +212,20 @@ void prepare_bf_test_nonces(noncelist_t *nonces, uint8_t best_first_byte) // trailing_zeros(bf_test_nonce_2nd_byte[1] ^ bf_test_nonce_2nd_byte[0]), // trailing_zeros(bf_test_nonce_2nd_byte[2] ^ bf_test_nonce_2nd_byte[1]), // trailing_zeros(bf_test_nonce_2nd_byte[3] ^ bf_test_nonce_2nd_byte[2])); - + uint8_t best_4[4] = {0}; int sum_best = -1; for (uint16_t n1 = 0; n1 < nonces_to_bruteforce; n1++) { for (uint16_t n2 = 0; n2 < nonces_to_bruteforce; n2++) { if (n2 != n1) { for (uint16_t n3 = 0; n3 < nonces_to_bruteforce; n3++) { - if ((n3 != n2 && n3 != n1) || nonces_to_bruteforce < 3 - // && trailing_zeros(bf_test_nonce_2nd_byte[n1] ^ bf_test_nonce_2nd_byte[n2]) + if ((n3 != n2 && n3 != n1) || nonces_to_bruteforce < 3 + // && trailing_zeros(bf_test_nonce_2nd_byte[n1] ^ bf_test_nonce_2nd_byte[n2]) // > trailing_zeros(bf_test_nonce_2nd_byte[n2] ^ bf_test_nonce_2nd_byte[n3]) ) { for (uint16_t n4 = 0; n4 < nonces_to_bruteforce; n4++) { if ((n4 != n3 && n4 != n2 && n4 != n1) || nonces_to_bruteforce < 4 - // && trailing_zeros(bf_test_nonce_2nd_byte[n2] ^ bf_test_nonce_2nd_byte[n3]) + // && trailing_zeros(bf_test_nonce_2nd_byte[n2] ^ bf_test_nonce_2nd_byte[n3]) // > trailing_zeros(bf_test_nonce_2nd_byte[n3] ^ bf_test_nonce_2nd_byte[n4]) ) { int sum = nonces_to_bruteforce > 1 ? trailing_zeros(bf_test_nonce_2nd_byte[n1] ^ bf_test_nonce_2nd_byte[n2]) : 0.0 @@ -245,13 +245,13 @@ void prepare_bf_test_nonces(noncelist_t *nonces, uint8_t best_first_byte) } } } - + uint32_t bf_test_nonce_temp[4]; uint8_t bf_test_nonce_par_temp[4]; uint8_t bf_test_nonce_2nd_byte_temp[4]; for (uint8_t i = 0; i < 4 && i < nonces_to_bruteforce; i++) { - bf_test_nonce_temp[i] = bf_test_nonce[best_4[i]]; - + bf_test_nonce_temp[i] = bf_test_nonce[best_4[i]]; + bf_test_nonce_par_temp[i] = bf_test_nonce_par[best_4[i]]; bf_test_nonce_2nd_byte_temp[i] = bf_test_nonce_2nd_byte[best_4[i]]; } @@ -295,13 +295,13 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint write_benchfile(candidates); #endif bool silent = (bf_rate != NULL); - + keys_found = 0; num_keys_tested = 0; found_bs_key = 0; - + bitslice_test_nonces(nonces_to_bruteforce, bf_test_nonce, bf_test_nonce_par); - + // count number of states to go bucket_count = 0; for (statelist_t *p = candidates; p != NULL; p = p->next) { @@ -313,7 +313,7 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint uint64_t start_time = msclock(); -#if defined(__linux__) || defined(__APPLE__) +#if defined(__linux__) || defined(__APPLE__) if ( NUM_BRUTE_FORCE_THREADS < 0 ) return false; #endif @@ -328,7 +328,7 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint noncelist_t *nonces; uint8_t *best_first_bytes; } thread_args[NUM_BRUTE_FORCE_THREADS]; - + for (uint32_t i = 0; i < NUM_BRUTE_FORCE_THREADS; i++){ thread_args[i].thread_ID = i; thread_args[i].silent = silent; @@ -347,10 +347,10 @@ bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint if (bf_rate != NULL) *bf_rate = (float)num_keys_tested / ((float)elapsed_time / 1000.0); - + if ( keys_found > 0) *foundkey = found_bs_key; - + return (keys_found != 0); } @@ -361,7 +361,7 @@ static bool read_bench_data(statelist_t *test_candidates) { uint32_t temp = 0; uint32_t num_states = 0; uint32_t states_read = 0; - + char bench_file_path[strlen(get_my_executable_directory()) + strlen(TEST_BENCH_FILENAME) + 1]; strcpy(bench_file_path, get_my_executable_directory()); strcat(bench_file_path, TEST_BENCH_FILENAME); @@ -371,7 +371,7 @@ static bool read_bench_data(statelist_t *test_candidates) { return false; } bytes_read = fread(&nonces_to_bruteforce, 1, sizeof(nonces_to_bruteforce), benchfile); - if (bytes_read != sizeof(nonces_to_bruteforce)) { + if (bytes_read != sizeof(nonces_to_bruteforce)) { fclose(benchfile); return false; } @@ -388,7 +388,7 @@ static bool read_bench_data(statelist_t *test_candidates) { return false; } } - bytes_read = fread(&num_states, 1, sizeof(uint32_t), benchfile); + bytes_read = fread(&num_states, 1, sizeof(uint32_t), benchfile); if (bytes_read != sizeof(uint32_t)) { fclose(benchfile); return false; @@ -420,9 +420,9 @@ static bool read_bench_data(statelist_t *test_candidates) { for (uint32_t i = states_read; i < TEST_BENCH_SIZE; i++) { test_candidates->states[ODD_STATE][i] = test_candidates->states[ODD_STATE][i-states_read]; } - + fclose(benchfile); - return true; + return true; } @@ -435,7 +435,7 @@ float brute_force_benchmark() { test_candidates[i].next = test_candidates + i + 1; test_candidates[i+1].states[ODD_STATE] = test_candidates[0].states[ODD_STATE]; test_candidates[i+1].states[EVEN_STATE] = test_candidates[0].states[EVEN_STATE]; - } + } test_candidates[NUM_BRUTE_FORCE_THREADS-1].next = NULL; if (!read_bench_data(test_candidates)) { @@ -449,13 +449,13 @@ float brute_force_benchmark() { test_candidates[i].states[ODD_STATE][TEST_BENCH_SIZE] = -1; test_candidates[i].states[EVEN_STATE][TEST_BENCH_SIZE] = -1; } - + uint64_t maximum_states = TEST_BENCH_SIZE*TEST_BENCH_SIZE*(uint64_t)NUM_BRUTE_FORCE_THREADS; float bf_rate; uint64_t found_key = 0; brute_force_bs(&bf_rate, test_candidates, 0, 0, maximum_states, NULL, 0, &found_key); - + free(test_candidates[0].states[ODD_STATE]); free(test_candidates[0].states[EVEN_STATE]); diff --git a/client/hardnested/hardnested_bruteforce.h b/client/hardnested/hardnested_bruteforce.h index c978a82c3..68dc7442d 100644 --- a/client/hardnested/hardnested_bruteforce.h +++ b/client/hardnested/hardnested_bruteforce.h @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- @@ -30,7 +30,7 @@ typedef struct { extern void prepare_bf_test_nonces(noncelist_t *nonces, uint8_t best_first_byte); extern bool brute_force_bs(float *bf_rate, statelist_t *candidates, uint32_t cuid, uint32_t num_acquired_nonces, uint64_t maximum_states, noncelist_t *nonces, uint8_t *best_first_bytes, uint64_t *found_key); extern float brute_force_benchmark(); -extern uint8_t trailing_zeros(uint8_t byte); +extern uint8_t trailing_zeros(uint8_t byte); extern bool verify_key(uint32_t cuid, noncelist_t *nonces, uint8_t *best_first_bytes, uint32_t odd, uint32_t even); #endif diff --git a/client/hardnested/hardnested_tables.c b/client/hardnested/hardnested_tables.c index 278ed9596..9a520603b 100644 --- a/client/hardnested/hardnested_tables.c +++ b/client/hardnested/hardnested_tables.c @@ -10,7 +10,7 @@ // attacks this doesn't rely on implementation errors but only on the // inherent weaknesses of the crypto1 cypher. Described in // Carlo Meijer, Roel Verdult, "Ciphertext-only Cryptanalysis on Hardened -// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on +// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on // Computer and Communications Security, 2015 //----------------------------------------------------------------------------- // @@ -39,7 +39,7 @@ typedef enum { static uint16_t PartialSumProperty(uint32_t state, odd_even_t odd_even) -{ +{ uint16_t sum = 0; for (uint16_t j = 0; j < 16; j++) { uint32_t st = state; @@ -203,7 +203,7 @@ static void init_part_sum_bitarrays(void) } } for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { - //printf("(%d, %" PRIu16 ")...", odd_even, part_sum_a0); + //printf("(%d, %" PRIu16 ")...", odd_even, part_sum_a0); for (uint32_t state = 0; state < (1<<20); state++) { uint16_t part_sum_a0 = PartialSumProperty(state, odd_even) / 2; for (uint16_t low_bits = 0; low_bits < 1<<4; low_bits++) { @@ -215,7 +215,7 @@ static void init_part_sum_bitarrays(void) } -static void free_part_sum_bitarrays(void) +static void free_part_sum_bitarrays(void) { printf("free_part_sum_bitarrays()..."); for (int16_t part_sum_a0 = (NUM_PART_SUMS-1); part_sum_a0 >= 0; part_sum_a0--) { @@ -257,7 +257,7 @@ void init_sum_bitarray(uint16_t sum_a0) printf("done.\n"); } - + static void free_sum_bitarray(void) { printf("free_sum_bitarray()..."); @@ -275,10 +275,10 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t #else #define NUM_TEST_STATES (1<<23) #endif - + time_t start_time = time(NULL); time_t last_check_time = start_time; - + uint32_t *restrict test_bitarray[2]; uint32_t *restrict test_not_bitarray[2]; @@ -291,7 +291,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t clear_bitarray24(test_not_bitarray[EVEN_STATE]); test_not_bitarray[ODD_STATE] = malloc_bitarray(sizeof(uint32_t) * (1<<19)); clear_bitarray24(test_not_bitarray[ODD_STATE]); - + uint32_t count[2]; bool all_odd_states_are_possible_for_notbitflip = false; @@ -302,7 +302,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t if (difftime(time_now, last_check_time) > 5*60) { // print status every 5 minutes float runtime = difftime(time_now, start_time); float remaining_time = runtime * ((1<<23) - even_state) / even_state; - printf("\n%1.1f hours elapsed, expected completion in %1.1f hours (%1.1f days)", runtime/3600, remaining_time/3600, remaining_time/3600/24); + printf("\n%1.1f hours elapsed, expected completion in %1.1f hours (%1.1f days)", runtime/3600, remaining_time/3600, remaining_time/3600/24); last_check_time = time_now; } for (uint32_t odd_state = next_state(sum_a0_bitarray[ODD_STATE], -1); odd_state < (1<<24); odd_state = next_state(test_bitarray[ODD_STATE], odd_state)) { @@ -319,15 +319,15 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t } cs_delta; cs_delta.odd = 0; cs_delta.even = 0; - + uint_fast16_t keystream = 0; - + // decrypt 9 bits for (int i = 0; i < 9; i++) { - uint_fast8_t keystream_bit = filter(cs.odd & 0x000fffff) ^ filter((cs.odd & 0x000fffff) ^ cs_delta.odd); + uint_fast8_t keystream_bit = filter(cs.odd & 0x000fffff) ^ filter((cs.odd & 0x000fffff) ^ cs_delta.odd); keystream = keystream << 1 | keystream_bit; uint_fast8_t nt_bit = BIT(bitflip, i) ^ keystream_bit; - uint_fast8_t LSFR_feedback = BIT(cs_delta.odd, 2) ^ BIT(cs_delta.even, 2) ^ BIT(cs_delta.odd, 3); + uint_fast8_t LSFR_feedback = BIT(cs_delta.odd, 2) ^ BIT(cs_delta.even, 2) ^ BIT(cs_delta.odd, 3); cs_delta.even = cs_delta.even << 1 | (LSFR_feedback ^ nt_bit); uint_fast8_t tmp = cs_delta.odd; @@ -341,7 +341,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t cs.odd = even_state >> (7 - i) / 2; } } - + if (evenparity32(keystream) == evenparity32(bitflip)) { // found valid bitflip state even_state_is_possible = true; @@ -353,7 +353,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t set_bit24(test_not_bitarray[EVEN_STATE], even_state); set_bit24(test_not_bitarray[EVEN_STATE], 1 << 23 | even_state); set_bit24(test_not_bitarray[ODD_STATE], odd_state); - } + } } if (!even_state_is_possible) { all_odd_states_are_possible_for_notbitflip = true; @@ -364,9 +364,9 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { count[odd_even] = count_states(test_bitarray[odd_even]); if (count[odd_even] != 1<<24) { - printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", - count[odd_even], - odd_even==EVEN_STATE?"even":"odd", + printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", + count[odd_even], + odd_even==EVEN_STATE?"even":"odd", bitflip, (1<<24) - count[odd_even], (float)((1<<24) - count[odd_even]) / (1<<24) * 100.0); #ifndef TEST_RUN @@ -391,9 +391,9 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t } count[odd_even] = count_states(test_bitarray_2nd); if (count[odd_even] != 1<<24) { - printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", - count[odd_even], - odd_even==EVEN_STATE?"even":"odd", + printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", + count[odd_even], + odd_even==EVEN_STATE?"even":"odd", bitflip | BITFLIP_2ND_BYTE, (1<<24) - count[odd_even], (float)((1<<24) - count[odd_even]) / (1<<24) * 100.0); #ifndef TEST_RUN @@ -418,7 +418,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t if (difftime(time_now, last_check_time) > 5*60) { // print status every 5 minutes float runtime = difftime(time_now, start_time); float remaining_time = runtime * ((1<<23) - even_state) / even_state; - printf("\n%1.1f hours elapsed, expected completion in %1.1f hours (%1.1f days)", runtime/3600, remaining_time/3600, remaining_time/3600/24); + printf("\n%1.1f hours elapsed, expected completion in %1.1f hours (%1.1f days)", runtime/3600, remaining_time/3600, remaining_time/3600/24); last_check_time = time_now; } for (uint32_t odd_state = next_state(sum_a0_bitarray[ODD_STATE], -1); odd_state < (1<<24); odd_state = next_state(sum_a0_bitarray[ODD_STATE], odd_state)) { @@ -438,16 +438,16 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t } cs_delta; cs_delta.odd = 0; cs_delta.even = 0; - + uint_fast16_t keystream = 0; // uint_fast16_t nt = 0; - + // decrypt 9 bits for (int i = 0; i < 9; i++) { - uint_fast8_t keystream_bit = filter(cs.odd & 0x000fffff) ^ filter((cs.odd & 0x000fffff) ^ cs_delta.odd); + uint_fast8_t keystream_bit = filter(cs.odd & 0x000fffff) ^ filter((cs.odd & 0x000fffff) ^ cs_delta.odd); keystream = keystream << 1 | keystream_bit; uint_fast8_t nt_bit = BIT(bitflip|0x100, i) ^ keystream_bit; - uint_fast8_t LSFR_feedback = BIT(cs_delta.odd, 2) ^ BIT(cs_delta.even, 2) ^ BIT(cs_delta.odd, 3); + uint_fast8_t LSFR_feedback = BIT(cs_delta.odd, 2) ^ BIT(cs_delta.even, 2) ^ BIT(cs_delta.odd, 3); cs_delta.even = cs_delta.even << 1 | (LSFR_feedback ^ nt_bit); uint_fast8_t tmp = cs_delta.odd; @@ -461,7 +461,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t cs.odd = even_state >> (7 - i) / 2; } } - + if (evenparity32(keystream) != evenparity32(bitflip)) { // found valid !bitflip state even_state_is_possible = true; @@ -471,14 +471,14 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t } } } - + printf("\nAnalysis completed. Checking for effective !bitflip properties...\n"); for (odd_even_t odd_even = EVEN_STATE; odd_even <= ODD_STATE; odd_even++) { count[odd_even] = count_states(test_not_bitarray[odd_even]); if (count[odd_even] != 1<<24) { - printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", - count[odd_even], - odd_even==EVEN_STATE?"even":"odd", + printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", + count[odd_even], + odd_even==EVEN_STATE?"even":"odd", bitflip|0x100, (1<<24) - count[odd_even], (float)((1<<24) - count[odd_even]) / (1<<24) * 100.0); #ifndef TEST_RUN @@ -503,9 +503,9 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t } count[odd_even] = count_states(test_bitarray_2nd); if (count[odd_even] != 1<<24) { - printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", - count[odd_even], - odd_even==EVEN_STATE?"even":"odd", + printf("Writing %d possible %s states for bitflip property %03x (%d (%1.2f%%) states eliminated)\n", + count[odd_even], + odd_even==EVEN_STATE?"even":"odd", bitflip | 0x100| BITFLIP_2ND_BYTE, (1<<24) - count[odd_even], (float)((1<<24) - count[odd_even]) / (1<<24) * 100.0); #ifndef TEST_RUN @@ -524,7 +524,7 @@ static void precalculate_bit0_bitflip_bitarrays(uint8_t const bitflip, uint16_t free_bitarray(test_not_bitarray[EVEN_STATE]); free_bitarray(test_bitarray[ODD_STATE]); free_bitarray(test_bitarray[EVEN_STATE]); - + exit(0); } @@ -533,7 +533,7 @@ int main (int argc, char *argv[]) { unsigned int bitflip_in; int sum_a0; - + printf("Create tables required by hardnested attack.\n"); printf("Expect a runtime in the range of days or weeks.\n"); printf("Single thread only. If you want to use several threads, start it multiple times :-)\n\n"); @@ -550,7 +550,7 @@ int main (int argc, char *argv[]) { printf("Bitflip property must be less than or equal to 0xff\n\n"); return 1; } - + if(argc == 3) { sscanf(argv[2], "%d", &sum_a0); } @@ -577,16 +577,16 @@ int main (int argc, char *argv[]) { case 256: break; default: sum_a0 = -1; } - + printf("Calculating for bitflip = %02x, sum_a0 = %d\n", bitflip_in, sum_a0); - + init_part_sum_bitarrays(); init_sum_bitarray(sum_a0); - + precalculate_bit0_bitflip_bitarrays(bitflip_in, sum_a0); free_sum_bitarray(); free_part_sum_bitarrays(); - + return 0; } \ No newline at end of file diff --git a/client/hid-flasher/proxusb.c b/client/hid-flasher/proxusb.c index eb0860ec1..45100e9ed 100644 --- a/client/hid-flasher/proxusb.c +++ b/client/hid-flasher/proxusb.c @@ -155,7 +155,7 @@ usb_dev_handle* findProxmark(int verbose, unsigned int *iface) else { iSelection = 1; } - + iSelection --; for (int i = 0; i < iUnit; i++) { diff --git a/client/hid-flasher/usb_cmd.h b/client/hid-flasher/usb_cmd.h index 59027c9d3..002c41252 100644 --- a/client/hid-flasher/usb_cmd.h +++ b/client/hid-flasher/usb_cmd.h @@ -200,7 +200,7 @@ typedef struct { #define CMD_MIFARE_SNIFFER 0x0630 //ultralightC #define CMD_MIFAREUC_AUTH 0x0724 -//0x0725 and 0x0726 no longer used +//0x0725 and 0x0726 no longer used #define CMD_MIFAREUC_SETPWD 0x0727 @@ -214,7 +214,7 @@ typedef struct { #define CMD_MIFARE_DESFIRE 0x072e #define CMD_MIFARE_COLLECT_NONCES 0x072f - + #define CMD_HF_SNIFFER 0x0800 #define CMD_UNKNOWN 0xFFFF diff --git a/client/jansson/lookup3.h b/client/jansson/lookup3.h index 2fe4c258f..ec2d0ffd6 100644 --- a/client/jansson/lookup3.h +++ b/client/jansson/lookup3.h @@ -3,8 +3,8 @@ lookup3.c, by Bob Jenkins, May 2006, Public Domain. These are functions for producing 32-bit hashes for hash table lookup. -hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() -are externally useful functions. Routines to test the hash are included +hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() +are externally useful functions. Routines to test the hash are included if SELF_TEST is defined. You can use this free for any purpose. It's in the public domain. It has no warranty. @@ -12,7 +12,7 @@ You probably want to use hashlittle(). hashlittle() and hashbig() hash byte arrays. hashlittle() is is faster than hashbig() on little-endian machines. Intel and AMD are little-endian machines. On second thought, you probably want hashlittle2(), which is identical to -hashlittle() except it returns two 32-bit hashes for the price of one. +hashlittle() except it returns two 32-bit hashes for the price of one. You could implement hashbig2() if you wanted but I haven't bothered here. If you want to find a hash of, say, exactly 7 integers, do @@ -25,9 +25,9 @@ If you want to find a hash of, say, exactly 7 integers, do then use c as the hash value. If you have a variable length array of 4-byte integers to hash, use hashword(). If you have a byte array (like a character string), use hashlittle(). If you have several byte arrays, or -a mix of things, see the comments above hashlittle(). +a mix of things, see the comments above hashlittle(). -Why is this so big? I read 12 bytes at a time into 3 4-byte integers, +Why is this so big? I read 12 bytes at a time into 3 4-byte integers, then mix those integers. This is fast (you can do a lot more thorough mixing with 12*3 instructions on 3 integers than you can with 3 instructions on 1 byte), but shoehorning those bytes into integers efficiently is messy. @@ -94,7 +94,7 @@ This was tested for: the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. -* the base values were pseudorandom, all zero but one bit set, or +* the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that @@ -104,7 +104,7 @@ satisfy this are 14 9 3 7 17 3 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing for "differ" defined as + with a one-bit base and a two-bit delta. I -used http://burtleburtle.net/bob/hash/avalanche.html to choose +used http://burtleburtle.net/bob/hash/avalanche.html to choose the operations, constants, and arrangements of the variables. This does not achieve avalanche. There are input bits of (a,b,c) @@ -143,7 +143,7 @@ produce values of c that look totally different. This was tested for the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. -* the base values were pseudorandom, all zero but one bit set, or +* the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. These constants passed: @@ -236,7 +236,7 @@ static uint32_t hashlittle(const void *key, size_t length, uint32_t initval) } /*----------------------------- handle the last (probably partial) block */ - /* + /* * "k[2]&0xffffff" actually reads beyond the end of the string, but * then masks off the part it's not allowed to read. Because the * string is aligned, the masked-off tail is in the same word as the diff --git a/client/jansson/path.c b/client/jansson/path.c index e3098f5f4..785a3e824 100644 --- a/client/jansson/path.c +++ b/client/jansson/path.c @@ -3,7 +3,7 @@ * * Jansson is free software; you can redistribute it and/or modify * it under the terms of the MIT license. See LICENSE for details. - * + * * source here https://github.com/rogerz/jansson/blob/json_path/src/path.c */ diff --git a/client/loclass/cipher.c b/client/loclass/cipher.c index e8553ba6c..bf921c452 100644 --- a/client/loclass/cipher.c +++ b/client/loclass/cipher.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ @@ -218,7 +218,7 @@ void MAC(uint8_t* k, BitstreamIn input, BitstreamOut out) BitstreamIn input_32_zeroes = {zeroes_32,sizeof(zeroes_32)*8,0}; State initState = suc(k,init(k),&input); output(k,initState,&input_32_zeroes,&out); -} +} void doMAC(uint8_t *cc_nr_p, uint8_t *div_key_p, uint8_t mac[4]) { @@ -228,7 +228,7 @@ void doMAC(uint8_t *cc_nr_p, uint8_t *div_key_p, uint8_t mac[4]) memcpy(cc_nr, cc_nr_p, 12); memcpy(div_key, div_key_p, 8); - + reverse_arraybytes(cc_nr, 12); BitstreamIn bitstream = {cc_nr, 12 * 8, 0}; uint8_t dest []= {0,0,0,0,0,0,0,0}; diff --git a/client/loclass/cipher.h b/client/loclass/cipher.h index 632910a98..c6d2f0320 100644 --- a/client/loclass/cipher.h +++ b/client/loclass/cipher.h @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ diff --git a/client/loclass/cipherutils.c b/client/loclass/cipherutils.c index e22c88894..43b892fd8 100644 --- a/client/loclass/cipherutils.c +++ b/client/loclass/cipherutils.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ #include @@ -212,7 +212,7 @@ int testBitStream() //printf("Bits left: %d\n", bitsLeft(&in)); //printf("Bits out: %d\n", numBits(&out)); } - + if(memcmp(input, output, sizeof(input)) == 0) { PrintAndLogDevice(SUCCESS, " Bitstream test 1 ok"); } else { @@ -240,11 +240,11 @@ int testReversedBitstream() while (bitsLeft(&in) > 0) { pushBit(&reversed_out, tailBit(&in)); } - + while (bitsLeft(&reversed_in) > 0) { pushBit(&out, tailBit(&reversed_in)); } - + if (memcmp(input, output, sizeof(input)) == 0) { PrintAndLogDevice(SUCCESS, " Bitstream test 2 ok"); } else { diff --git a/client/loclass/cipherutils.h b/client/loclass/cipherutils.h index 21d11aac0..bc40c560b 100644 --- a/client/loclass/cipherutils.h +++ b/client/loclass/cipherutils.h @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ diff --git a/client/loclass/elite_crack.c b/client/loclass/elite_crack.c index 630fa72a6..fa370a940 100644 --- a/client/loclass/elite_crack.c +++ b/client/loclass/elite_crack.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,9 +31,9 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * - * + * + * + * ****************************************************************************/ #include #include @@ -147,7 +147,7 @@ void hash1(uint8_t csn[] , uint8_t k[]) { k[5] = ~rl( csn[5] + k[3] ) + 1; k[6] = rr( csn[6] + (k[4] ^ 0x3c) ); k[7] = rl( csn[7] + (k[5] ^ 0xc3) ); - + k[7] &= 0x7F; k[6] &= 0x7F; k[5] &= 0x7F; @@ -217,7 +217,7 @@ void hash2(uint8_t *key64, uint8_t *outp_keytable) { int i; for (i=0; i<8; i++) key64_negated[i]= ~key64[i]; - + // Once again, key is on iclass-format desencrypt_iclass(key64, key64_negated, z[0]); @@ -319,7 +319,7 @@ int bruteforceItem(dumpdata item, uint16_t keytable[]) { int i; for (i=0; i<8; i++) { if (keytable[key_index[i]] & (CRACKED | BEING_CRACKED)) continue; - + bytes_to_recover[numbytes_to_recover++] = key_index[i]; keytable[key_index[i]] |= BEING_CRACKED; @@ -355,7 +355,7 @@ int bruteforceItem(dumpdata item, uint16_t keytable[]) { PrintAndLogDevice(INFO, "Bruteforcing byte %d", bytes_to_recover[i]); while (!found && !(brute & endmask)) { - + //Update the keytable with the brute-values for (i=0; i < numbytes_to_recover; i++) { keytable[bytes_to_recover[i]] &= 0xFF00; @@ -383,7 +383,7 @@ int bruteforceItem(dumpdata item, uint16_t keytable[]) { if (memcmp(calculated_MAC, item.mac, 4) == 0) { printf("\r\n"); for (i =0 ; i < numbytes_to_recover; i++) { - PrintAndLogDevice(INFO, "%d: 0x%02x", bytes_to_recover[i], 0xFF & keytable[bytes_to_recover[i]]); + PrintAndLogDevice(INFO, "%d: 0x%02x", bytes_to_recover[i], 0xFF & keytable[bytes_to_recover[i]]); } found = true; break; @@ -397,7 +397,7 @@ int bruteforceItem(dumpdata item, uint16_t keytable[]) { fflush(stdout); } } - + if (!found) { PrintAndLogDevice(NORMAL, "\n"); PrintAndLogDevice(WARNING, "Failed to recover %d bytes using the following CSN", numbytes_to_recover); printvar("[!] CSN", item.csn, 8); @@ -501,7 +501,7 @@ int bruteforceDump(uint8_t dump[], size_t dumpsize, uint16_t keytable[]) { } free(attack); - PrintAndLogDevice(SUCCESS, "time: %" PRIu64 " seconds", (msclock()-t1)/1000); + PrintAndLogDevice(SUCCESS, "time: %" PRIu64 " seconds", (msclock()-t1)/1000); // Pick out the first 16 bytes of the keytable. // The keytable is now in 16-bit ints, where the upper 8 bits @@ -511,7 +511,7 @@ int bruteforceDump(uint8_t dump[], size_t dumpsize, uint16_t keytable[]) { for (i = 0 ; i < 16 ; i++) { first16bytes[i] = keytable[i] & 0xFF; - + if (!(keytable[i] & CRACKED)) PrintAndLogDevice(WARNING, "error, we are missing byte %d, custom key calculation will fail...", i); } @@ -551,7 +551,7 @@ int bruteforceFile(const char *filename, uint16_t keytable[]) { size_t bytes_read = fread(dump, 1, fsize, f); fclose(f); - + if (bytes_read < fsize) { PrintAndLogDevice(WARNING, "Error, could only read %d bytes (should be %d)", bytes_read, fsize ); } diff --git a/client/loclass/elite_crack.h b/client/loclass/elite_crack.h index 5413d84d0..f2cce1064 100644 --- a/client/loclass/elite_crack.h +++ b/client/loclass/elite_crack.h @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ diff --git a/client/loclass/fileutils.c b/client/loclass/fileutils.c index f9d4db8d1..c26bb2a5d 100644 --- a/client/loclass/fileutils.c +++ b/client/loclass/fileutils.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ #include "fileutils.h" @@ -101,12 +101,12 @@ int saveFileEML(const char *preferredName, const char *suffix, uint8_t* data, si sprintf(fileName,"%s-%d.%s", preferredName, num, suffix); num++; } - + /* We should have a valid filename now, e.g. dumpdata-3.bin */ /*Opening file for writing in text mode*/ FILE *f = fopen(fileName, "w+"); - if (!f) { + if (!f) { PrintAndLogDevice(WARNING, "file not found or locked. '" _YELLOW_(%s)"'", fileName); retval = 1; goto out; @@ -114,7 +114,7 @@ int saveFileEML(const char *preferredName, const char *suffix, uint8_t* data, si for (i = 0; i < datalen; i++) { fprintf(f, "%02X", data[i] ); - + // no extra line in the end if ( (i+1) % blocksize == 0 && currblock != blocks ) { fprintf(f, "\n"); @@ -131,8 +131,8 @@ int saveFileEML(const char *preferredName, const char *suffix, uint8_t* data, si fflush(f); fclose(f); PrintAndLogDevice(SUCCESS, "saved %d blocks to text file " _YELLOW_(%s), blocks, fileName); - -out: + +out: free(fileName); return retval; } @@ -165,13 +165,13 @@ int saveFileJSON(const char *preferredName, const char *suffix, JSONFileType fty char path[PATH_MAX_LENGTH] = {0}; sprintf(path, "$.blocks.%d", i); JsonSaveBufAsHexCompact(root, path, &data[i * 16], 16); - + if (i == 0) { JsonSaveBufAsHexCompact(root, "$.Card.UID", &data[0], 4); JsonSaveBufAsHexCompact(root, "$.Card.SAK", &data[5], 1); JsonSaveBufAsHexCompact(root, "$.Card.ATQA", &data[6], 2); } - + if (mfIsSectorTrailer(i)) { memset(path, 0x00, sizeof(path)); sprintf(path, "$.SectorKeys.%d.KeyA", mfSectorNum(i)); @@ -216,7 +216,7 @@ int saveFileJSON(const char *preferredName, const char *suffix, JSONFileType fty uint8_t uid[7] = {0}; memcpy(uid, tmp->data, 3); memcpy(uid+3, tmp->data+4, 4); - + JsonSaveBufAsHexCompact(root, "$.Card.UID", uid, sizeof(uid)); JsonSaveBufAsHexCompact(root, "$.Card.Version", tmp->version, sizeof(tmp->version)); JsonSaveBufAsHexCompact(root, "$.Card.TBO_0", tmp->tbo, sizeof(tmp->tbo)); @@ -233,7 +233,7 @@ int saveFileJSON(const char *preferredName, const char *suffix, JSONFileType fty char path[PATH_MAX_LENGTH] = {0}; sprintf(path, "$.blocks.%d", i); - JsonSaveBufAsHexCompact(root, path, tmp->data + (i * 4), 4); + JsonSaveBufAsHexCompact(root, path, tmp->data + (i * 4), 4); } break; } @@ -248,7 +248,7 @@ int saveFileJSON(const char *preferredName, const char *suffix, JSONFileType fty PrintAndLogDevice(SUCCESS, "saved to json file " _YELLOW_(%s), fileName); json_decref(root); -out: +out: free(fileName); return retval; } @@ -270,7 +270,7 @@ int loadFile(const char *preferredName, const char *suffix, void* data, size_t* free(fileName); return 1; } - + // get filesize in order to malloc memory fseek(f, 0, SEEK_END); long fsize = ftell(f); @@ -281,14 +281,14 @@ int loadFile(const char *preferredName, const char *suffix, void* data, size_t* retval = 1; goto out; } - + uint8_t *dump = calloc(fsize, sizeof(uint8_t)); if ( !dump ) { PrintAndLogDevice(FAILED, "error, cannot allocate memory"); retval = 2; goto out; } - + size_t bytes_read = fread(dump, 1, fsize, f); if ( bytes_read != fsize ) { @@ -297,18 +297,18 @@ int loadFile(const char *preferredName, const char *suffix, void* data, size_t* retval = 3; goto out; } - + memcpy( (data), dump, bytes_read); free(dump); - + PrintAndLogDevice(SUCCESS, "loaded %d bytes from binary file " _YELLOW_(%s), bytes_read, fileName); - + *datalen = bytes_read; -out: +out: fclose(f); free(fileName); - + return retval; } @@ -330,12 +330,12 @@ int loadFileEML(const char *preferredName, const char *suffix, void* data, size_ retval = 1; goto out; } - - // 128 + 2 newline chars + 1 null terminator + + // 128 + 2 newline chars + 1 null terminator char line[131]; memset(line, 0, sizeof(line)); uint8_t buf[64] = {0x00}; - + while ( !feof(f) ) { memset(line, 0, sizeof(line)); @@ -346,10 +346,10 @@ int loadFileEML(const char *preferredName, const char *suffix, void* data, size_ retval = 2; goto out; } - + if ( line[0] == '#' ) continue; - + int res = param_gethex_to_eol(line, 0, buf, sizeof(buf), &hexlen); if (res == 0 || res == 1) { memcpy(data + counter, buf, hexlen); @@ -358,11 +358,11 @@ int loadFileEML(const char *preferredName, const char *suffix, void* data, size_ } fclose(f); PrintAndLogDevice(SUCCESS, "loaded %d bytes from text file " _YELLOW_(%s), counter, fileName); - + if ( datalen ) *datalen = counter; - -out: + +out: free(fileName); return retval; } @@ -372,7 +372,7 @@ int loadFileJSON(const char *preferredName, const char *suffix, void* data, size if ( preferredName == NULL ) return 1; if ( suffix == NULL ) return 1; if ( data == NULL ) return 1; - + *datalen = 0; json_t *root; json_error_t error; @@ -385,20 +385,20 @@ int loadFileJSON(const char *preferredName, const char *suffix, void* data, size root = json_load_file(fileName, 0, &error); if (!root) { PrintAndLog("ERROR: json " _YELLOW_(%s) " error on line %d: %s", fileName, error.line, error.text); - retval = 2; + retval = 2; goto out; } - + if (!json_is_object(root)) { PrintAndLog("ERROR: Invalid json " _YELLOW_(%s) " format. root must be an object.", fileName); - retval = 3; + retval = 3; goto out; } - + uint8_t *udata = (uint8_t *)data; char ctype[100] = {0}; JsonLoadStr(root, "$.FileType", ctype); - + if (!strcmp(ctype, "raw")) { JsonLoadBufAsHex(root, "$.raw", udata, maxdatalen, datalen); } @@ -413,15 +413,15 @@ int loadFileJSON(const char *preferredName, const char *suffix, void* data, size char path[30] = {0}; sprintf(path, "$.blocks.%d", i); - + size_t len = 0; JsonLoadBufAsHex(root, path, &udata[sptr], 16, &len); if (!len) break; - + sptr += len; } - + *datalen = sptr; } @@ -435,21 +435,21 @@ int loadFileJSON(const char *preferredName, const char *suffix, void* data, size char path[30] = {0}; sprintf(path, "$.blocks.%d", i); - + size_t len = 0; JsonLoadBufAsHex(root, path, &udata[sptr], 4, &len); if (!len) break; - + sptr += len; } - + *datalen = sptr; } - + PrintAndLog("loaded from JSON file " _YELLOW_(%s), fileName); -out: +out: json_decref(root); free(fileName); return retval; @@ -468,12 +468,12 @@ int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data if (keylen != 4 && keylen != 6 && keylen != 8) { keylen = 6; } - + // double up since its chars - keylen <<= 1; - + keylen <<= 1; + char line[255]; - + size_t counter = 0; int retval = 0; int size = sizeof(char) * (strlen(preferredName) + strlen(suffix) + 10); @@ -486,10 +486,10 @@ int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data retval = 1; goto out; } - + // read file while ( fgets(line, sizeof(line), f) ) { - + // add null terminator line[keylen] = 0; @@ -497,18 +497,18 @@ int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data if (strlen(line) < keylen) continue; - + // The line start with # is comment, skip if( line[0] == '#' ) continue; - + if (!isxdigit(line[0])){ PrintAndLogEx(FAILED, "file content error. '%s' must include " _BLUE_(%2d) "HEX symbols", line, keylen); continue; - } + } uint64_t key = strtoull(line, NULL, 16); - + num_to_bytes(key, keylen >> 1, data + counter); (*keycnt)++; memset(line, 0, sizeof(line)); @@ -516,12 +516,12 @@ int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data } fclose(f); PrintAndLogDevice(SUCCESS, "loaded " _GREEN_(%2d) "keys from dictionary file " _YELLOW_(%s), *keycnt, fileName); - - if ( datalen ) - *datalen = counter; -out: + + if ( datalen ) + *datalen = counter; +out: free(fileName); - return retval; + return retval; } #else //if we're on ARM diff --git a/client/loclass/fileutils.h b/client/loclass/fileutils.h index 9485707f1..94bc18e94 100644 --- a/client/loclass/fileutils.h +++ b/client/loclass/fileutils.h @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ #ifndef FILEUTILS_H @@ -153,7 +153,7 @@ extern int loadFileJSON(const char *preferredName, const char *suffix, void* dat extern int loadFileDICTIONARY(const char *preferredName, const char *suffix, void* data, size_t* datalen, uint8_t keylen, uint16_t* keycnt ); #define PrintAndLogDevice(level, format, args...) PrintAndLogEx(level, format , ## args) -#else +#else /** * Utility function to print to console. This is used consistently within the library instead @@ -164,7 +164,7 @@ extern int loadFileDICTIONARY(const char *preferredName, const char *suffix, voi */ #define PrintAndLogDevice(level, format, args...) { } - + #endif //ON_DEVICE #endif // FILEUTILS_H diff --git a/client/loclass/hash1_brute.c b/client/loclass/hash1_brute.c index 003a10423..d2ae822a5 100644 --- a/client/loclass/hash1_brute.c +++ b/client/loclass/hash1_brute.c @@ -38,13 +38,13 @@ void calc_score(uint8_t* csn, uint8_t* k) { score +=1; } } - + if (score >=2 && badscore < 2) { printf("CSN\t%02x%02x%02x%02x%02x%02x%02x%02x\t%02x %02x %02x %02x %02x %02x %02x %02x\t" ,csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7] ,k[0],k[1],k[2],k[3],k[4],k[5],k[6],k[7] ); - + for (i=0 ; i < score; i++) { printf("%d,", uniq_vals[i]); } @@ -62,7 +62,7 @@ void brute_hash1(void){ calc_score(testcsn,testkey); printf("Brute forcing hashones\n"); //exit(1); - + for (a=0; a < 256; a++) { //if(a > 0)printf("%d/256 done...\n", a); for (b=0; b < 256; b++) diff --git a/client/loclass/ikeys.c b/client/loclass/ikeys.c index c1265dc4d..847f90729 100644 --- a/client/loclass/ikeys.c +++ b/client/loclass/ikeys.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ /** @@ -207,7 +207,7 @@ void permute(BitstreamIn *p_in, uint64_t z,int l,int r, BitstreamOut* out) { if(bitsLeft(p_in) == 0) return; - + bool pn = tailBit(p_in); if( pn ) // pn = 1 { @@ -674,10 +674,10 @@ int doTestsWithKnownInputs() { static bool readKeyFile(uint8_t key[8]) { bool retval = false; - + //Test a few variants char filename[30] = {0}; - + if (fileExists("iclass_key.bin")){ sprintf(filename, "%s.bin", "iclass_key"); } else if (fileExists("loclass/iclass_key.bin")){ @@ -685,17 +685,17 @@ static bool readKeyFile(uint8_t key[8]) { } else if (fileExists("client/loclass/iclass_key.bin")){ sprintf(filename, "%s.bin", "client/loclass/iclass_key"); } - + if ( strlen(filename) == 0 ) return retval; - + FILE *f = fopen(filename, "rb"); if (!f) return retval; - + size_t bytes_read = fread(key, sizeof(uint8_t), 8, f); if ( bytes_read == 8) - retval = true; + retval = true; if (f) fclose(f); @@ -716,7 +716,7 @@ int doKeyTests(uint8_t debuglevel) { uint8_t j = 0; for (i = 0; i < sizeof(key); i++) j += key[i]; - + if (j != 185) { PrintAndLogDevice(INFO, "A key was loaded, but it does not seem to be the correct one. Aborting these tests"); } else { diff --git a/client/loclass/ikeys.h b/client/loclass/ikeys.h index 5b44d1796..7de3c582e 100644 --- a/client/loclass/ikeys.h +++ b/client/loclass/ikeys.h @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ #ifndef IKEYS_H diff --git a/client/loclass/main.c b/client/loclass/main.c index e0dcd48e2..e77cc8103 100644 --- a/client/loclass/main.c +++ b/client/loclass/main.c @@ -1,13 +1,13 @@ /***************************************************************************** * WARNING * - * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. - * - * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL - * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, - * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. - * - * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. + * THIS CODE IS CREATED FOR EXPERIMENTATION AND EDUCATIONAL USE ONLY. + * + * USAGE OF THIS CODE IN OTHER WAYS MAY INFRINGE UPON THE INTELLECTUAL + * PROPERTY OF OTHER PARTIES, SUCH AS INSIDE SECURE AND HID GLOBAL, + * AND MAY EXPOSE YOU TO AN INFRINGEMENT ACTION FROM THOSE PARTIES. + * + * THIS CODE SHOULD NEVER BE USED TO INFRINGE PATENTS OR INTELLECTUAL PROPERTY RIGHTS. * ***************************************************************************** * @@ -22,7 +22,7 @@ * * This is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published - * by the Free Software Foundation, or, at your option, any later version. + * by the Free Software Foundation, or, at your option, any later version. * * This file is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of @@ -31,8 +31,8 @@ * * You should have received a copy of the GNU General Public License * along with loclass. If not, see . - * - * + * + * ****************************************************************************/ diff --git a/client/mifare/mad.c b/client/mifare/mad.c index 96a4bf152..d2df7780c 100644 --- a/client/mifare/mad.c +++ b/client/mifare/mad.c @@ -15,7 +15,7 @@ // https://www.nxp.com/docs/en/application-note/AN10787.pdf static madAIDDescr madKnownAIDs[] = { - {0x0000, "free"}, + {0x0000, "free"}, {0x0001, "defect, e.g. access keys are destroyed or unknown"}, {0x0002, "reserved"}, {0x0003, "contains additional directory info"}, @@ -103,7 +103,7 @@ static const char *GetAIDDescription(uint16_t AID) { for(int i = 0; i < ARRAYLEN(madKnownClusterCodes); i++) if (madKnownClusterCodes[i].AID == (AID >> 8)) // high byte - cluster code return madKnownClusterCodes[i].Description; - + return unknownAID; } @@ -121,33 +121,33 @@ int madCRCCheck(uint8_t *sector, bool verbose, int MADver) { return 3; }; } - + return 0; } uint16_t madGetAID(uint8_t *sector, int MADver, int sectorNo) { if (MADver == 1) - return (sector[16 + 2 + (sectorNo - 1) * 2] << 8) + (sector[16 + 2 + (sectorNo - 1) * 2 + 1]); + return (sector[16 + 2 + (sectorNo - 1) * 2] << 8) + (sector[16 + 2 + (sectorNo - 1) * 2 + 1]); else - return (sector[2 + (sectorNo - 1) * 2] << 8) + (sector[2 + (sectorNo - 1) * 2 + 1]); + return (sector[2 + (sectorNo - 1) * 2] << 8) + (sector[2 + (sectorNo - 1) * 2 + 1]); } int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2) { int res = 0; - + if (!sector0) return 1; - + uint8_t GPB = sector0[3 * 16 + 9]; if (verbose) PrintAndLogEx(NORMAL, "GPB: 0x%02x", GPB); - + // DA (MAD available) if (!(GPB & 0x80)) { PrintAndLogEx(ERR, "DA=0! MAD not available."); return 1; } - + // MA (multi-application card) if (verbose) { if (GPB & 0x40) @@ -155,34 +155,34 @@ int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2) else PrintAndLogEx(NORMAL, "Single application card."); } - + uint8_t MADVer = GPB & 0x03; if (verbose) PrintAndLogEx(NORMAL, "MAD version: %d", MADVer); - + // MAD version if ((MADVer != 0x01) && (MADVer != 0x02)) { PrintAndLogEx(ERR, "Wrong MAD version: 0x%02x", MADVer); return 2; }; - + if (haveMAD2) *haveMAD2 = (MADVer == 2); res = madCRCCheck(sector0, true, 1); - + if (verbose && !res) PrintAndLogEx(NORMAL, "CRC8-MAD1 OK."); - + if (MADVer == 2 && sector10) { int res2 = madCRCCheck(sector10, true, 2); if (!res) - res = res2; + res = res2; if (verbose & !res2) PrintAndLogEx(NORMAL, "CRC8-MAD2 OK."); } - + return res; } @@ -190,12 +190,12 @@ int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen *madlen = 0; bool haveMAD2 = false; MADCheck(sector0, sector10, false, &haveMAD2); - + for (int i = 1; i < 16; i++) { mad[*madlen] = madGetAID(sector0, 1, i); (*madlen)++; } - + if (haveMAD2) { // mad2 sector (0x10 == 16dec) here mad[*madlen] = 0x0005; @@ -206,7 +206,7 @@ int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen (*madlen)++; } } - + return 0; } @@ -215,7 +215,7 @@ int MAD1DecodeAndPrint(uint8_t *sector, bool verbose, bool *haveMAD2) { // check MAD1 only MADCheck(sector, NULL, verbose, haveMAD2); - + // info byte uint8_t InfoByte = sector[16 + 1] & 0x3f; if (InfoByte) { @@ -226,13 +226,13 @@ int MAD1DecodeAndPrint(uint8_t *sector, bool verbose, bool *haveMAD2) { } if (InfoByte == 0x10 || InfoByte >= 0x28) PrintAndLogEx(WARNING, "Info byte error"); - + PrintAndLogEx(NORMAL, "00 MAD1"); for(int i = 1; i < 16; i++) { uint16_t AID = madGetAID(sector, 1, i); PrintAndLogEx(NORMAL, "%02d [%04X] %s", i, AID, GetAIDDescription(AID)); }; - + return 0; }; @@ -250,7 +250,7 @@ int MAD2DecodeAndPrint(uint8_t *sector, bool verbose) { for(int i = 1; i < 8 + 8 + 7 + 1; i++) { uint16_t AID = madGetAID(sector, 2, i); PrintAndLogEx(NORMAL, "%02d [%04X] %s", i + 16, AID, GetAIDDescription(AID)); - }; - + }; + return 0; }; diff --git a/client/mifare/mad.h b/client/mifare/mad.h index 6289982d9..d9dd3ff53 100644 --- a/client/mifare/mad.h +++ b/client/mifare/mad.h @@ -18,7 +18,7 @@ typedef struct { uint16_t AID; const char *Description; -} madAIDDescr; +} madAIDDescr; extern int MADCheck(uint8_t *sector0, uint8_t *sector10, bool verbose, bool *haveMAD2); extern int MADDecode(uint8_t *sector0, uint8_t *sector10, uint16_t *mad, size_t *madlen); diff --git a/client/mifare/mfkey.c b/client/mifare/mfkey.c index b35a3104c..e463c4505 100644 --- a/client/mifare/mfkey.c +++ b/client/mifare/mfkey.c @@ -22,7 +22,7 @@ int compare_uint64(const void *a, const void *b) { uint32_t intersection(uint64_t *listA, uint64_t *listB) { if (listA == NULL || listB == NULL) return 0; - + uint64_t *p1, *p2, *p3; p1 = p3 = listA; p2 = listB; @@ -56,7 +56,7 @@ uint32_t nonce2key(uint32_t uid, uint32_t nt, uint32_t nr, uint32_t ar, uint64_t for ( pos = 0; pos < 8; pos++ ) { ks3x[7-pos] = (ks_info >> (pos*8)) & 0x0F; bt = (par_info >> (pos*8)) & 0xFF; - + par[7-pos][0] = (bt >> 0) & 1; par[7-pos][1] = (bt >> 1) & 1; par[7-pos][2] = (bt >> 2) & 1; @@ -128,15 +128,15 @@ bool mfkey32_moebius(nonces_t data, uint64_t *outputkey) { int counter = 0; uint32_t p640 = prng_successor(data.nonce, 64); uint32_t p641 = prng_successor(data.nonce2, 64); - + s = lfsr_recovery32(data.ar ^ p640, 0); - + for(t = s; t->odd | t->even; ++t) { lfsr_rollback_word(t, 0, 0); lfsr_rollback_word(t, data.nr, 1); lfsr_rollback_word(t, data.cuid ^ data.nonce, 0); crypto1_get_lfsr(t, &key); - + crypto1_word(t, data.cuid ^ data.nonce2, 0); crypto1_word(t, data.nr2, 1); if (data.ar2 == (crypto1_word(t, 0, 0) ^ p641)) { @@ -157,7 +157,7 @@ int mfkey64(nonces_t data, uint64_t *outputkey){ uint32_t ks2; // keystream used to encrypt reader response uint32_t ks3; // keystream used to encrypt tag response struct Crypto1State *revstate; - + // Extract the keystream from the messages ks2 = data.ar ^ prng_successor(data.nonce, 64); ks3 = data.at ^ prng_successor(data.nonce, 96); @@ -168,6 +168,6 @@ int mfkey64(nonces_t data, uint64_t *outputkey){ lfsr_rollback_word(revstate, data.cuid ^ data.nonce, 0); crypto1_get_lfsr(revstate, &key); crypto1_destroy(revstate); - *outputkey = key; + *outputkey = key; return 0; } diff --git a/client/mifare/mifare4.c b/client/mifare/mifare4.c index c95529a84..b829c564a 100644 --- a/client/mifare/mifare4.c +++ b/client/mifare/mifare4.c @@ -46,7 +46,7 @@ const char * mfpGetErrorDescription(uint8_t errorCode) { for(int i = 0; i < PlusErrorsLen; i++) if (errorCode == PlusErrors[i].Code) return PlusErrors[i].Description; - + return PlusErrors[0].Description; } @@ -74,11 +74,11 @@ AccessConditions_t MFAccessConditionsTrailer[] = { char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data) { static char StaticNone[] = "none"; - + uint8_t data1 = ((data[1] >> 4) & 0x0f) >> blockn; uint8_t data2 = ((data[2]) & 0x0f) >> blockn; uint8_t data3 = ((data[2] >> 4) & 0x0f) >> blockn; - + uint8_t cond = (data1 & 0x01) << 2 | (data2 & 0x01) << 1 | (data3 & 0x01); if (blockn == 3) { @@ -92,7 +92,7 @@ char *mfGetAccessConditionsDesc(uint8_t blockn, uint8_t *data) { return MFAccessConditions[i].description; } }; - + return StaticNone; }; @@ -124,9 +124,9 @@ int CalculateEncIVResponse(mf4Session *session, uint8_t *iv, bool verbose) { int CalculateMAC(mf4Session *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose) { if (!session || !session->Authenticated || !mac || !data || !datalen || datalen < 1) return 1; - + memset(mac, 0x00, 8); - + uint16_t ctr = session->R_Ctr; switch(mtype) { case mtypWriteCmd: @@ -162,23 +162,23 @@ int CalculateMAC(mf4Session *session, MACType_t mtype, uint8_t blockNum, uint8_t macdatalen = 1 + 6; break; } - + if (verbose) PrintAndLog("MAC data[%d]: %s", macdatalen, sprint_hex(macdata, macdatalen)); - + return aes_cmac8(NULL, session->Kmac, macdata, mac, macdatalen); } int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool verbose) { uint8_t data[257] = {0}; int datalen = 0; - + uint8_t RndA[17] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00}; uint8_t RndB[17] = {0}; - + if (session) - session->Authenticated = false; - + session->Authenticated = false; + uint8_t cmd1[] = {0x70, keyn[1], keyn[0], 0x00}; int res = ExchangeRAW14a(cmd1, sizeof(cmd1), activateField, true, data, sizeof(data), &datalen); if (res) { @@ -186,16 +186,16 @@ int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateF DropField(); return 2; } - + if (verbose) PrintAndLogEx(INFO, "phase2: %s", sprint_hex(cmd2, 33)); - + res = ExchangeRAW14a(cmd2, sizeof(cmd2), false, true, data, sizeof(data), &datalen); if (res) { PrintAndLogEx(ERR, "Exchande raw error: %d", res); DropField(); return 4; } - + if (verbose) PrintAndLogEx(INFO, "Kenc, kenc, 16); memmove(session->Kmac, kmac, 16); } - + if (verbose) PrintAndLogEx(INFO, "Authentication OK"); - + return 0; } int intExchangeRAW14aPlus(uint8_t *datain, int datainlen, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { if(VerboseMode) PrintAndLogEx(INFO, ">>> %s", sprint_hex(datain, datainlen)); - + int res = ExchangeRAW14a(datain, datainlen, activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); if(VerboseMode) PrintAndLogEx(INFO, "<<< %s", sprint_hex(dataout, *dataoutlen)); - + return res; } int MFPWritePerso(uint8_t *keyNum, uint8_t *key, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { uint8_t rcmd[3 + 16] = {0xa8, keyNum[1], keyNum[0], 0x00}; memmove(&rcmd[3], key, 16); - + return intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); } int MFPCommitPerso(bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen) { uint8_t rcmd[1] = {0xaa}; - + return intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); } int MFPReadBlock(mf4Session *session, bool plain, uint8_t blockNum, uint8_t blockCount, bool activateField, bool leaveSignalON, uint8_t *dataout, int maxdataoutlen, int *dataoutlen, uint8_t *mac) { - uint8_t rcmd[4 + 8] = {(plain?(0x37):(0x33)), blockNum, 0x00, blockCount}; + uint8_t rcmd[4 + 8] = {(plain?(0x37):(0x33)), blockNum, 0x00, blockCount}; if (!plain && session) CalculateMAC(session, mtypReadCmd, blockNum, blockCount, rcmd, 4, &rcmd[4], VerboseMode); - + int res = intExchangeRAW14aPlus(rcmd, plain?4:sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); if(res) return res; - if (session) + if (session) session->R_Ctr++; - + if(session && mac && *dataoutlen > 11) CalculateMAC(session, mtypReadResp, blockNum, blockCount, dataout, *dataoutlen - 8 - 2, mac, VerboseMode); - + return 0; } @@ -356,37 +356,37 @@ int MFPWriteBlock(mf4Session *session, uint8_t blockNum, uint8_t *data, bool act memmove(&rcmd[3], data, 16); if (session) CalculateMAC(session, mtypWriteCmd, blockNum, 1, rcmd, 19, &rcmd[19], VerboseMode); - + int res = intExchangeRAW14aPlus(rcmd, sizeof(rcmd), activateField, leaveSignalON, dataout, maxdataoutlen, dataoutlen); if(res) return res; - if (session) + if (session) session->W_Ctr++; - + if(session && mac && *dataoutlen > 3) CalculateMAC(session, mtypWriteResp, blockNum, 1, dataout, *dataoutlen, mac, VerboseMode); - + return 0; } int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *dataout, bool verbose){ uint8_t keyn[2] = {0}; bool plain = false; - + uint16_t uKeyNum = 0x4000 + sectorNo * 2 + (keyType ? 1 : 0); keyn[0] = uKeyNum >> 8; keyn[1] = uKeyNum & 0xff; if (verbose) PrintAndLogEx(INFO, "--sector[%d]:%02x key:%04x", mfNumBlocksPerSector(sectorNo), sectorNo, uKeyNum); - + mf4Session session; int res = MifareAuth4(&session, keyn, key, true, true, verbose); if (res) { PrintAndLogEx(ERR, "Sector %d authentication error: %d", sectorNo, res); return res; } - + uint8_t data[250] = {0}; int datalen = 0; uint8_t mac[8] = {0}; @@ -398,7 +398,7 @@ int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data DropField(); return res; } - + if (datalen && data[0] != 0x90) { PrintAndLogEx(ERR, "Sector %d card read error: %02x %s", sectorNo, data[0], mfpGetErrorDescription(data[0])); DropField(); @@ -411,31 +411,31 @@ int mfpReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data } memcpy(&dataout[(n - firstBlockNo) * 16], &data[1], 16); - + if (verbose) PrintAndLogEx(INFO, "data[%03d]: %s", n, sprint_hex(&data[1], 16)); - + if (memcmp(&data[1 + 16], mac, 8)) { PrintAndLogEx(WARNING, "WARNING: mac on block %d not equal...", n); PrintAndLogEx(WARNING, "MAC card: %s", sprint_hex(&data[1 + 16], 8)); PrintAndLogEx(WARNING, "MAC reader: %s", sprint_hex(mac, 8)); - + if (!verbose) - return 7; - } else { + return 7; + } else { if(verbose) PrintAndLogEx(INFO, "MAC: %s", sprint_hex(&data[1 + 16], 8)); } } DropField(); - return 0; + return 0; } // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards), // plus evtl. 8 sectors with 16 blocks each (4k cards) uint8_t mfNumBlocksPerSector(uint8_t sectorNo) { - if (sectorNo < 32) + if (sectorNo < 32) return 4; else return 16; @@ -465,5 +465,5 @@ uint8_t mfSectorNum(uint8_t blockNo) { return blockNo / 4; else return 32 + (blockNo - 32 * 4) / 16; - + } diff --git a/client/mifare/mifare4.h b/client/mifare/mifare4.h index e4bf6e386..c41c05d2e 100644 --- a/client/mifare/mifare4.h +++ b/client/mifare/mifare4.h @@ -30,7 +30,7 @@ typedef struct { uint16_t R_Ctr; uint16_t W_Ctr; }mf4Session; - + typedef enum { mtypReadCmd, mtypReadResp, @@ -45,7 +45,7 @@ typedef struct { extern void mfpSetVerboseMode(bool verbose); extern const char * mfpGetErrorDescription(uint8_t errorCode); - + extern int CalculateMAC(mf4Session *session, MACType_t mtype, uint8_t blockNum, uint8_t blockCount, uint8_t *data, int datalen, uint8_t *mac, bool verbose); extern int MifareAuth4(mf4Session *session, uint8_t *keyn, uint8_t *key, bool activateField, bool leaveSignalON, bool verbose); diff --git a/client/mifare/mifarehost.c b/client/mifare/mifarehost.c index eb89e0389..1d1da1d1c 100644 --- a/client/mifare/mifarehost.c +++ b/client/mifare/mifarehost.c @@ -17,7 +17,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { uint64_t *keylist = NULL, *last_keylist = NULL; uint32_t keycount = 0; int16_t isOK = 0; - + UsbCommand c = {CMD_READER_MIFARE, {true, blockno, key_type}}; // message @@ -31,11 +31,11 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { SendCommand(&c); //flush queue - while (ukbhit()) { - int gc = getchar(); (void)gc; + while (ukbhit()) { + int gc = getchar(); (void)gc; return -5; } - + // wait cycle while (true) { printf("."); fflush(stdout); @@ -47,9 +47,9 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { isOK = resp.arg[0]; - if (isOK < 0) + if (isOK < 0) return isOK; - + uid = (uint32_t)bytes_to_num(resp.d.asBytes + 0, 4); nt = (uint32_t)bytes_to_num(resp.d.asBytes + 4, 4); par_list = bytes_to_num(resp.d.asBytes + 8, 8); @@ -60,7 +60,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { } } PrintAndLogEx(NORMAL, "\n"); - + if (par_list == 0 && c.arg[0] == true) { PrintAndLogEx(SUCCESS, "Parity is all zero. Most likely this card sends NACK on every authentication."); } @@ -92,7 +92,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { uint8_t keyBlock[USB_CMD_DATA_SIZE]; int max_keys = USB_CMD_DATA_SIZE / 6; for (int i = 0; i < keycount; i += max_keys) { - + int size = keycount - i > max_keys ? max_keys : keycount - i; for (int j = 0; j < size; j++) { if (par_list == 0) { @@ -101,12 +101,12 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { num_to_bytes(keylist[i*max_keys + j], 6, keyBlock+(j*6)); } } - + if (!mfCheckKeys(blockno, key_type - 0x60, false, size, keyBlock, key)) { break; } } - + if (*key != -1) { break; } else { @@ -121,7 +121,7 @@ int mfDarkside(uint8_t blockno, uint8_t key_type, uint64_t *key) { return 0; } int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keycnt, uint8_t * keyBlock, uint64_t * key){ - *key = -1; + *key = -1; UsbCommand c = {CMD_MIFARE_CHKKEYS, { (blockNo | (keyType << 8)), clear_trace, keycnt}}; memcpy(c.d.asBytes, keyBlock, 6 * keycnt); clearCommandBuffer(); @@ -133,9 +133,9 @@ int mfCheckKeys(uint8_t blockNo, uint8_t keyType, bool clear_trace, uint8_t keyc return 0; } -// Sends chunks of keys to device. +// Sends chunks of keys to device. // 0 == ok all keys found -// 1 == +// 1 == // 2 == Time-out, aborting int mfCheckKeys_fast( uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t strategy, uint32_t size, uint8_t *keyBlock, sector_t *e_sector, bool use_flashmemory) { @@ -143,8 +143,8 @@ int mfCheckKeys_fast( uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint64_t t2 = msclock(); uint32_t timeout = 0; - // send keychunk - UsbCommand c = {CMD_MIFARE_CHKKEYS_FAST, { (sectorsCnt | (firstChunk << 8) | (lastChunk << 12) ), ((use_flashmemory << 8) | strategy), size}}; + // send keychunk + UsbCommand c = {CMD_MIFARE_CHKKEYS_FAST, { (sectorsCnt | (firstChunk << 8) | (lastChunk << 12) ), ((use_flashmemory << 8) | strategy), size}}; memcpy(c.d.asBytes, keyBlock, 6 * size); clearCommandBuffer(); SendCommand(&c); @@ -167,11 +167,11 @@ int mfCheckKeys_fast( uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, uint8_t curr_keys = resp.arg[0]; PrintAndLogEx(SUCCESS, "\nChunk: %.1fs | found %u/%u keys (%u)", (float)(t2/1000.0), curr_keys, (sectorsCnt<<1), size); - - // all keys? + + // all keys? if ( curr_keys == sectorsCnt*2 || lastChunk ) { - - // success array. each byte is status of key + + // success array. each byte is status of key uint8_t arr[80]; uint64_t foo = 0; uint16_t bar = 0; @@ -180,10 +180,10 @@ int mfCheckKeys_fast( uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, for (uint8_t i = 0; i < 64; i++) arr[i] = (foo >> i) & 0x1; - + for (uint8_t i = 0; i < 16; i++) arr[i+64] = (bar >> i) & 0x1; - + // initialize storage for found keys icesector_t *tmp = calloc(sectorsCnt, sizeof(icesector_t)); if (tmp == NULL) @@ -203,7 +203,7 @@ int mfCheckKeys_fast( uint8_t sectorsCnt, uint8_t firstChunk, uint8_t lastChunk, } } free(tmp); - + if ( curr_keys == sectorsCnt*2 ) return 0; if ( lastChunk ) @@ -226,11 +226,11 @@ int mfKeyBrute(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint64_t *resultk memset(candidates, 0, sizeof(candidates)); memset(keyBlock, 0, sizeof(keyBlock)); - + // Generate all possible keys for the first two unknown bytes. - for (uint16_t i = 0; i < 0xFFFF; ++i) { - uint32_t j = i * 6; - candidates[0 + j] = i >> 8; + for (uint16_t i = 0; i < 0xFFFF; ++i) { + uint32_t j = i * 6; + candidates[0 + j] = i >> 8; candidates[1 + j] = i; candidates[2 + j] = key[2]; candidates[3 + j] = key[3]; @@ -241,7 +241,7 @@ int mfKeyBrute(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint64_t *resultk for ( i = 0, counter = 1; i < CANDIDATE_SIZE; i += KEYBLOCK_SIZE, ++counter){ key64 = 0; - + // copy candidatekeys to test key block memcpy(keyBlock, candidates + i, KEYBLOCK_SIZE); @@ -251,8 +251,8 @@ int mfKeyBrute(uint8_t blockNo, uint8_t keyType, uint8_t *key, uint64_t *resultk found = true; break; } - - // progress + + // progress if ( counter % 20 == 0 ) PrintAndLogEx(SUCCESS, "tried : %s.. \t %u keys", sprint_hex(candidates + i, 6), counter * KEYS_IN_BLOCK ); } @@ -270,20 +270,20 @@ int Compare16Bits(const void * a, const void * b) { void #ifdef __has_attribute #if __has_attribute(force_align_arg_pointer) -__attribute__((force_align_arg_pointer)) +__attribute__((force_align_arg_pointer)) #endif #endif *nested_worker_thread(void *arg) { struct Crypto1State *p1; StateList_t *statelist = arg; - statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid); - + statelist->head.slhead = lfsr_recovery32(statelist->ks1, statelist->nt ^ statelist->uid); + for (p1 = statelist->head.slhead; *(uint64_t *)p1 != 0; p1++) {}; - + statelist->len = p1 - statelist->head.slhead; statelist->tail.sltail = --p1; qsort(statelist->head.slhead, statelist->len, sizeof(uint64_t), Compare16Bits); - + return statelist->head.slhead; } @@ -293,7 +293,7 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo UsbCommand resp; StateList_t statelists[2]; struct Crypto1State *p1, *p2, *p3, *p4; - + UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}}; memcpy(c.d.asBytes, key, 6); clearCommandBuffer(); @@ -302,9 +302,9 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo // error during nested if (resp.arg[0]) return resp.arg[0]; - + memcpy(&uid, resp.d.asBytes, 4); - + for (i = 0; i < 2; i++) { statelists[i].blockNo = resp.arg[2] & 0xff; statelists[i].keyType = (resp.arg[2] >> 8) & 0xff; @@ -312,10 +312,10 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo memcpy(&statelists[i].nt, (void *)(resp.d.asBytes + 4 + i * 8 + 0), 4); memcpy(&statelists[i].ks1, (void *)(resp.d.asBytes + 4 + i * 8 + 4), 4); } - - // calc keys + + // calc keys pthread_t thread_id[2]; - + // create and run worker threads for (i = 0; i < 2; i++) pthread_create(thread_id + i, NULL, nested_worker_thread, &statelists[i]); @@ -327,12 +327,12 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo // the first 16 Bits of the cryptostate already contain part of our key. // Create the intersection of the two lists based on these 16 Bits and // roll back the cryptostate - p1 = p3 = statelists[0].head.slhead; + p1 = p3 = statelists[0].head.slhead; p2 = p4 = statelists[1].head.slhead; while (p1 <= statelists[0].tail.sltail && p2 <= statelists[1].tail.sltail) { if (Compare16Bits(p1, p2) == 0) { - + struct Crypto1State savestate, *savep = &savestate; savestate = *p1; while(Compare16Bits(p1, savep) == 0 && p1 <= statelists[0].tail.sltail) { @@ -381,15 +381,15 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo uint8_t keyBlock[USB_CMD_DATA_SIZE] = {0x00}; for (int i = 0; i < keycnt; i += max_keys) { - + int size = keycnt - i > max_keys ? max_keys : keycnt - i; - + for (int j = 0; j < size; j++) { crypto1_get_lfsr(statelists[0].head.slhead + i, &key64); num_to_bytes(key64, 6, keyBlock + i * 6); } - - if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, size, keyBlock, &key64)) { + + if (!mfCheckKeys(statelists[0].blockNo, statelists[0].keyType, false, size, keyBlock, &key64)) { free(statelists[0].head.slhead); free(statelists[1].head.slhead); num_to_bytes(key64, 6, resultKey); @@ -400,14 +400,14 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo key64 ); return -5; - } + } } - + out: PrintAndLogEx(SUCCESS, "target block:%3u key type: %c", (uint16_t)resp.arg[2] & 0xff, (resp.arg[2] >> 8) ? 'B' : 'A' - ); + ); free(statelists[0].head.slhead); free(statelists[1].head.slhead); @@ -416,7 +416,7 @@ out: // MIFARE int mfReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data) { - + UsbCommand c = {CMD_MIFARE_READSC, {sectorNo, keyType, 0}}; memcpy(c.d.asBytes, key, 6); clearCommandBuffer(); @@ -436,7 +436,7 @@ int mfReadSector(uint8_t sectorNo, uint8_t keyType, uint8_t *key, uint8_t *data) PrintAndLogEx(ERR, "Command execute timeout"); return 2; } - + return 0; } @@ -457,7 +457,7 @@ int mfEmlSetMem(uint8_t *data, int blockNum, int blocksCount) { int mfEmlSetMem_xt(uint8_t *data, int blockNum, int blocksCount, int blockBtWidth) { UsbCommand c = {CMD_MIFARE_EML_MEMSET, {blockNum, blocksCount, blockBtWidth}}; - memcpy(c.d.asBytes, data, blocksCount * blockBtWidth); + memcpy(c.d.asBytes, data, blocksCount * blockBtWidth); clearCommandBuffer(); SendCommand(&c); return 0; @@ -473,27 +473,27 @@ int mfCSetUID(uint8_t *uid, uint8_t *atqa, uint8_t *sak, uint8_t *oldUID, uint8_ int old = mfCGetBlock(0, block0, params); if (old == 0) PrintAndLogEx(SUCCESS, "old block 0: %s", sprint_hex(block0, sizeof(block0))); - else - PrintAndLogEx(FAILED, "couldn't get old data. Will write over the last bytes of Block 0."); + else + PrintAndLogEx(FAILED, "couldn't get old data. Will write over the last bytes of Block 0."); // fill in the new values // UID - memcpy(block0, uid, 4); + memcpy(block0, uid, 4); // Mifare UID BCC block0[4] = block0[0] ^ block0[1] ^ block0[2] ^ block0[3]; // mifare classic SAK(byte 5) and ATQA(byte 6 and 7, reversed) if ( sak != NULL ) block0[5] = sak[0]; - + if ( atqa != NULL ) { block0[6] = atqa[1]; block0[7] = atqa[0]; } PrintAndLogEx(SUCCESS, "new block 0: %s", sprint_hex(block0,16)); - - if ( wipecard ) params |= MAGIC_WIPE; + + if ( wipecard ) params |= MAGIC_WIPE; if ( oldUID == NULL) params |= MAGIC_UID; - + return mfCSetBlock(0, block0, oldUID, params); } @@ -501,15 +501,15 @@ int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) { uint8_t isOK = 0; UsbCommand c = {CMD_MIFARE_CSETBLOCK, {params, blockNo, 0}}; - memcpy(c.d.asBytes, data, 16); + memcpy(c.d.asBytes, data, 16); clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { isOK = resp.arg[0] & 0xff; - if (uid != NULL) + if (uid != NULL) memcpy(uid, resp.d.asBytes, 4); - if (!isOK) + if (!isOK) return 2; } else { PrintAndLogEx(WARNING, "command execute timeout"); @@ -520,14 +520,14 @@ int mfCSetBlock(uint8_t blockNo, uint8_t *data, uint8_t *uid, uint8_t params) { int mfCGetBlock(uint8_t blockNo, uint8_t *data, uint8_t params) { uint8_t isOK = 0; - UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, blockNo, 0}}; + UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, blockNo, 0}}; clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { isOK = resp.arg[0] & 0xff; - if (!isOK) - return 2; + if (!isOK) + return 2; memcpy(data, resp.d.asBytes, 16); } else { PrintAndLogEx(WARNING, "command execute timeout"); @@ -567,7 +567,7 @@ int isTraceCardEmpty(void) { } int isBlockEmpty(int blockN) { - for (int i = 0; i < 16; i++) + for (int i = 0; i < 16; i++) if (traceCard[blockN * 16 + i] != 0) return 0; return 1; @@ -583,10 +583,10 @@ int loadTraceCard(uint8_t *tuid, uint8_t uidlen) { uint8_t buf8[64] = {0x00}; int i, blockNum; uint32_t tmp; - - if (!isTraceCardEmpty()) + + if (!isTraceCardEmpty()) saveTraceCard(); - + memset(traceCard, 0x00, 4096); memcpy(traceCard, tuid, uidlen); @@ -594,11 +594,11 @@ int loadTraceCard(uint8_t *tuid, uint8_t uidlen) { f = fopen(traceFileName, "r"); if (!f) return 1; - + blockNum = 0; - + while (!feof(f)){ - + memset(buf, 0, sizeof(buf)); if (fgets(buf, sizeof(buf), f) == NULL) { PrintAndLogEx(FAILED, "No trace file found or reading error."); @@ -632,19 +632,19 @@ int loadTraceCard(uint8_t *tuid, uint8_t uidlen) { } int saveTraceCard(void) { - + if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0; - + FILE * f; f = fopen(traceFileName, "w+"); if ( !f ) return 1; // given 4096 tracecard size, these loop will only match a 1024, 1kb card memory - // 4086/16 == 256blocks. + // 4086/16 == 256blocks. for (uint16_t i = 0; i < 256; i++) { // blocks for (uint8_t j = 0; j < 16; j++) // bytes - fprintf(f, "%02X", *(traceCard + i * 16 + j)); - + fprintf(f, "%02X", *(traceCard + i * 16 + j)); + // no extra line in the end if ( i < 255 ) fprintf(f, "\n"); @@ -656,14 +656,14 @@ int saveTraceCard(void) { // int mfTraceInit(uint8_t *tuid, uint8_t uidlen, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) { - if (traceCrypto1) + if (traceCrypto1) crypto1_destroy(traceCrypto1); traceCrypto1 = NULL; - if (wantSaveToEmlFile) + if (wantSaveToEmlFile) loadTraceCard(tuid, uidlen); - + traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3]; traceCard[5] = sak; memcpy(&traceCard[6], atqa, 2); @@ -676,16 +676,16 @@ int mfTraceInit(uint8_t *tuid, uint8_t uidlen, uint8_t *atqa, uint8_t sak, bool void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len, bool isEncrypted){ uint8_t bt = 0; int i; - + if (len != 1) { for (i = 0; i < len; i++) data[i] = crypto1_byte(pcs, 0x00, isEncrypted) ^ data[i]; } else { - bt = 0; + bt = 0; bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 0)) << 0; bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 1)) << 1; bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 2)) << 2; - bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 3)) << 3; + bt |= (crypto1_bit(pcs, 0, isEncrypted) ^ BIT(data[0], 3)) << 3; data[0] = bt; } } @@ -699,28 +699,28 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { traceState = TRACE_ERROR; return 1; } - + uint8_t data[255]; memset(data, 0x00, sizeof(data)); - + memcpy(data, data_src, len); - + if ((traceCrypto1) && ((traceState == TRACE_IDLE) || (traceState > TRACE_AUTH_OK))) { mf_crypto1_decrypt(traceCrypto1, data, len, 0); PrintAndLogEx(NORMAL, "DEC| %s", sprint_hex(data, len)); - AddLogHex(logHexFileName, "DEC| ", data, len); + AddLogHex(logHexFileName, "DEC| ", data, len); } - + switch (traceState) { - case TRACE_IDLE: + case TRACE_IDLE: // check packet crc16! if ((len >= 4) && (!check_crc(CRC_14443_A, data, len))) { PrintAndLogEx(NORMAL, "DEC| CRC ERROR!!!"); - AddLogLine(logHexFileName, "DEC| ", "CRC ERROR!!!"); + AddLogLine(logHexFileName, "DEC| ", "CRC ERROR!!!"); traceState = TRACE_ERROR; // do not decrypt the next commands return 1; } - + // AUTHENTICATION if ((len == 4) && ((data[0] == MIFARE_AUTH_KEYA) || (data[0] == MIFARE_AUTH_KEYB))) { traceState = TRACE_AUTH1; @@ -750,7 +750,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { } return 0; - case TRACE_READ_DATA: + case TRACE_READ_DATA: if (len == 18) { traceState = TRACE_IDLE; @@ -766,7 +766,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { return 1; } break; - case TRACE_WRITE_OK: + case TRACE_WRITE_OK: if ((len == 1) && (data[0] == 0x0a)) { traceState = TRACE_WRITE_DATA; return 0; @@ -775,7 +775,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { return 1; } break; - case TRACE_WRITE_DATA: + case TRACE_WRITE_DATA: if (len == 18) { traceState = TRACE_IDLE; memcpy(traceCard + traceCurBlock * 16, data, 16); @@ -786,7 +786,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { return 1; } break; - case TRACE_AUTH1: + case TRACE_AUTH1: if (len == 4) { traceState = TRACE_AUTH2; nt = bytes_to_num(data, 4); @@ -796,7 +796,7 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { return 1; } break; - case TRACE_AUTH2: + case TRACE_AUTH2: if (len == 8) { traceState = TRACE_AUTH_OK; nr_enc = bytes_to_num(data, 4); @@ -807,11 +807,11 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { return 1; } break; - case TRACE_AUTH_OK: + case TRACE_AUTH_OK: if (len == 4) { traceState = TRACE_IDLE; at_enc = bytes_to_num(data, 4); - + // mfkey64 recover key. ks2 = ar_enc ^ prng_successor(nt, 64); ks3 = at_enc ^ prng_successor(nt, 96); @@ -822,37 +822,37 @@ int mfTraceDecode(uint8_t *data_src, int len, bool wantSaveToEmlFile) { lfsr_rollback_word(revstate, cuid ^ nt, 0); crypto1_get_lfsr(revstate, &key); PrintAndLogEx(SUCCESS, "found Key: [%012" PRIx64 "]", key); - + //if ( tryMfk64(cuid, nt, nr_enc, ar_enc, at_enc, &key) ) - AddLogUint64(logHexFileName, "Found Key: ", key); - + AddLogUint64(logHexFileName, "Found Key: ", key); + int blockShift = ((traceCurBlock & 0xFC) + 3) * 16; - if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) + if (isBlockEmpty((traceCurBlock & 0xFC) + 3)) memcpy(traceCard + blockShift + 6, trailerAccessBytes, 4); - + // keytype A/B if (traceCurKey) num_to_bytes(key, 6, traceCard + blockShift + 10); else num_to_bytes(key, 6, traceCard + blockShift); - + if (wantSaveToEmlFile) saveTraceCard(); if (traceCrypto1) crypto1_destroy(traceCrypto1); - + // set cryptosystem state - traceCrypto1 = lfsr_recovery64(ks2, ks3); + traceCrypto1 = lfsr_recovery64(ks2, ks3); } else { PrintAndLogEx(NORMAL, "[!] nested key recovery not implemented!\n"); at_enc = bytes_to_num(data, 4); - crypto1_destroy(traceCrypto1); + crypto1_destroy(traceCrypto1); traceState = TRACE_ERROR; } break; - default: + default: traceState = TRACE_ERROR; return 1; } @@ -871,30 +871,30 @@ int tryDecryptWord(uint32_t nt, uint32_t ar_enc, uint32_t at_enc, uint8_t *data, return 0; } -/* Detect Tag Prng, +/* Detect Tag Prng, * function performs a partial AUTH, where it tries to authenticate against block0, key A, but only collects tag nonce. * the tag nonce is check to see if it has a predictable PRNG. -* @returns +* @returns * TRUE if tag uses WEAK prng (ie Now the NACK bug also needs to be present for Darkside attack) * FALSE is tag uses HARDEND prng (ie hardnested attack possible, with known key) */ int detect_classic_prng(void){ - UsbCommand resp, respA; + UsbCommand resp, respA; uint8_t cmd[] = {MIFARE_AUTH_KEYA, 0x00}; uint32_t flags = ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_RATS; - + UsbCommand c = {CMD_READER_ISO_14443a, {flags, sizeof(cmd), 0}}; memcpy(c.d.asBytes, cmd, sizeof(cmd)); clearCommandBuffer(); - SendCommand(&c); - + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK, &resp, 2000)) { PrintAndLogEx(WARNING, "PRNG UID: Reply timeout."); return -1; } - + // if select tag failed. if ( resp.arg[0] == 0 ) { PrintAndLogEx(WARNING, "error: selecting tag failed, can't detect prng\n"); @@ -909,12 +909,12 @@ int detect_classic_prng(void){ if (respA.arg[0] != 4) { PrintAndLogEx(WARNING, "PRNG data error: Wrong length: %d", respA.arg[0]); return -4; - } + } uint32_t nonce = bytes_to_num(respA.d.asBytes, respA.arg[0]); return validate_prng_nonce(nonce); } -/* Detect Mifare Classic NACK bug +/* Detect Mifare Classic NACK bug returns: 0 = error during test / aborted @@ -923,25 +923,25 @@ returns: 3 = always leak nacks (clones) */ int detect_classic_nackbug(bool verbose){ - + UsbCommand c = {CMD_MIFARE_NACK_DETECT, {0, 0, 0}}; clearCommandBuffer(); SendCommand(&c); UsbCommand resp; - + if ( verbose ) PrintAndLogEx(SUCCESS, "press pm3-button on the proxmark3 device to abort both proxmark3 and client.\n"); - - // for nice animation + + // for nice animation bool term = !isatty(STDIN_FILENO); #if defined(__linux__) || (__APPLE__) char star[] = {'-', '\\', '|', '/'}; - uint8_t staridx = 0; -#endif + uint8_t staridx = 0; +#endif while (true) { - if (term) { + if (term) { printf("."); } else { printf( @@ -958,21 +958,21 @@ int detect_classic_nackbug(bool verbose){ return -1; break; } - + if (WaitForResponseTimeout(CMD_ACK, &resp, 500)) { int32_t ok = resp.arg[0]; uint32_t nacks = resp.arg[1]; uint32_t auths = resp.arg[2]; PrintAndLogEx(NORMAL, ""); - + if ( verbose ) { PrintAndLogEx(SUCCESS, "num of auth requests : %u", auths); PrintAndLogEx(SUCCESS, "num of received NACK : %u", nacks); } switch( ok ) { case 99 : PrintAndLogEx(WARNING, "button pressed. Aborted."); return 0; - case 96 : - case 98 : { + case 96 : + case 98 : { if (verbose) PrintAndLogEx(FAILED, "card random number generator is not predictable."); PrintAndLogEx(WARNING, "detection failed"); @@ -981,10 +981,10 @@ int detect_classic_nackbug(bool verbose){ case 97 : { if (verbose) { PrintAndLogEx(FAILED, "card random number generator seems to be based on the well-known generating polynomial"); - PrintAndLogEx(NORMAL, "[- ]with 16 effective bits only, but shows unexpected behavior, try again."); + PrintAndLogEx(NORMAL, "[- ]with 16 effective bits only, but shows unexpected behavior, try again."); } return 2; - } + } case 2 : PrintAndLogEx(SUCCESS, _GREEN_(always leak NACK detected)); return 3; case 1 : PrintAndLogEx(SUCCESS, _GREEN_(NACK bug detected)); return 1; case 0 : PrintAndLogEx(SUCCESS, "No NACK bug detected"); return 2; @@ -992,12 +992,12 @@ int detect_classic_nackbug(bool verbose){ } break; } - } + } return 0; } /* try to see if card responses to "chinese magic backdoor" commands. */ void detect_classic_magic(void) { - + uint8_t isGeneration = 0; UsbCommand resp; UsbCommand c = {CMD_MIFARE_CIDENT, {0, 0, 0}}; @@ -1005,11 +1005,11 @@ void detect_classic_magic(void) { SendCommand(&c); if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) isGeneration = resp.arg[0] & 0xff; - + switch( isGeneration ){ case 1: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1a): " _GREEN_(YES)); break; case 2: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 1b): " _GREEN_(YES)); break; //case 4: PrintAndLogEx(SUCCESS, "Answers to magic commands (GEN 2): " _GREEN_(YES)); break; default: PrintAndLogEx(INFO, "Answers to magic commands: " _YELLOW_(NO)); break; - } + } } \ No newline at end of file diff --git a/client/mifare/mifarehost.h b/client/mifare/mifarehost.h index 917cf5557..e0f4eaadd 100644 --- a/client/mifare/mifarehost.h +++ b/client/mifare/mifarehost.h @@ -55,7 +55,7 @@ typedef struct { uint32_t nt; uint32_t ks1; } StateList_t; - + typedef struct { uint64_t Key[2]; uint8_t foundKey[2]; diff --git a/client/mifare/ndef.c b/client/mifare/ndef.c index 6c7e12229..e8edc19da 100644 --- a/client/mifare/ndef.c +++ b/client/mifare/ndef.c @@ -89,7 +89,7 @@ uint16_t ndefTLVGetLength(uint8_t *data, size_t *indx) { len = data[0]; *indx += 1; } - + return len; } @@ -107,12 +107,12 @@ int ndefDecodeHeader(uint8_t *data, size_t datalen, NDEFHeader_t *header) { header->len = 1 + 1 + (header->ShortRecordBit ? 1 : 4) + (header->IDLenPresent ? 1 : 0); // header + typelen + payloadlen + idlen if (header->len > datalen) return 1; - + header->TypeLen = data[1]; header->Type = data + header->len; - + header->PayloadLen = (header->ShortRecordBit ? (data[2]) : ((data[2] << 24) + (data[3] << 16) + (data[4] << 8) + data[5])); - + if (header->IDLenPresent) { header->IDLen = (header->ShortRecordBit ? (data[3]) : (data[6])); header->Payload = header->Type + header->TypeLen; @@ -121,9 +121,9 @@ int ndefDecodeHeader(uint8_t *data, size_t datalen, NDEFHeader_t *header) { } header->Payload = header->Type + header->TypeLen + header->IDLen; - + header->RecLen = header->len + header->TypeLen + header->PayloadLen + header->IDLen; - + if (header->RecLen > datalen) return 3; @@ -132,7 +132,7 @@ int ndefDecodeHeader(uint8_t *data, size_t datalen, NDEFHeader_t *header) { int ndefPrintHeader(NDEFHeader_t *header) { PrintAndLogEx(INFO, "Header:"); - + PrintAndLogEx(NORMAL, "\tMessage Begin: %s", STRBOOL(header->MessageBegin)); PrintAndLogEx(NORMAL, "\tMessage End: %s", STRBOOL(header->MessageEnd)); PrintAndLogEx(NORMAL, "\tChunk Flag: %s", STRBOOL(header->ChunkFlag)); @@ -157,21 +157,21 @@ int ndefDecodeSig(uint8_t *sig, size_t siglen) { return 1; } indx++; - + uint8_t sigType = sig[indx] & 0x7f; bool sigURI = sig[indx] & 0x80; PrintAndLogEx(NORMAL, "\tsignature type: %s", ((sigType < stNA) ? ndefSigType_s[sigType] : ndefSigType_s[stNA])); PrintAndLogEx(NORMAL, "\tsignature uri: %s", (sigURI ? "present" : "not present")); - + size_t intsiglen = (sig[indx + 1] << 8) + sig[indx + 2]; // ecdsa 0x04 if (sigType == stECDSA) { indx += 3; PrintAndLogEx(NORMAL, "\tsignature [%d]: %s", intsiglen, sprint_hex_inrow(&sig[indx], intsiglen)); - - uint8_t rval[300] = {0}; - uint8_t sval[300] = {0}; + + uint8_t rval[300] = {0}; + uint8_t sval[300] = {0}; int res = ecdsa_asn1_get_signature(&sig[indx], intsiglen, rval, sval); if (!res) { PrintAndLogEx(NORMAL ,"\t\tr: %s", sprint_hex(rval, 32)); @@ -179,28 +179,28 @@ int ndefDecodeSig(uint8_t *sig, size_t siglen) { } } indx += intsiglen; - + if (sigURI) { size_t intsigurilen = (sig[indx] << 8) + sig[indx + 1]; indx += 2; - PrintAndLogEx(NORMAL, "\tsignature uri [%d]: %.*s", intsigurilen, intsigurilen, &sig[indx]); + PrintAndLogEx(NORMAL, "\tsignature uri [%d]: %.*s", intsigurilen, intsigurilen, &sig[indx]); indx += intsigurilen; } - + uint8_t certFormat = (sig[indx] >> 4) & 0x07; uint8_t certCount = sig[indx] & 0x0f; bool certURI = sig[indx] & 0x80; - + PrintAndLogEx(NORMAL, "\tcertificate format: %s", ((certFormat < sfNA) ? ndefCertificateFormat_s[certFormat] : ndefCertificateFormat_s[sfNA])); PrintAndLogEx(NORMAL, "\tcertificates count: %d", certCount); - + // print certificates indx++; for (int i = 0; i < certCount; i++) { size_t intcertlen = (sig[indx + 1] << 8) + sig[indx + 2]; indx += 2; - - PrintAndLogEx(NORMAL, "\tcertificate %d [%d]: %s", i + 1, intcertlen, sprint_hex_inrow(&sig[indx], intcertlen)); + + PrintAndLogEx(NORMAL, "\tcertificate %d [%d]: %s", i + 1, intcertlen, sprint_hex_inrow(&sig[indx], intcertlen)); indx += intcertlen; } @@ -208,32 +208,32 @@ int ndefDecodeSig(uint8_t *sig, size_t siglen) { if ((indx <= siglen) && certURI) { size_t inturilen = (sig[indx] << 8) + sig[indx + 1]; indx += 2; - PrintAndLogEx(NORMAL, "\tcertificate uri [%d]: %.*s", inturilen, inturilen, &sig[indx]); + PrintAndLogEx(NORMAL, "\tcertificate uri [%d]: %.*s", inturilen, inturilen, &sig[indx]); indx += inturilen; } - + return 0; }; int ndefDecodePayload(NDEFHeader_t *ndef) { - + switch(ndef->TypeNameFormat) { case tnfWellKnownRecord: PrintAndLogEx(INFO, "Well Known Record"); PrintAndLogEx(NORMAL, "\ttype: %.*s", ndef->TypeLen, ndef->Type); - + if (!strncmp((char *)ndef->Type, "T", ndef->TypeLen)) { PrintAndLogEx(NORMAL, "\ttext : %.*s", ndef->PayloadLen, ndef->Payload); } - + if (!strncmp((char *)ndef->Type, "U", ndef->TypeLen)) { PrintAndLogEx(NORMAL, "\turi : %s%.*s", (ndef->Payload[0] <= 0x23 ? URI_s[ndef->Payload[0]] : "[err]"), ndef->PayloadLen, &ndef->Payload[1]); } - + if (!strncmp((char *)ndef->Type, "Sig", ndef->TypeLen)) { ndefDecodeSig(ndef->Payload, ndef->PayloadLen); } - + break; case tnfAbsoluteURIRecord: PrintAndLogEx(INFO, "Absolute URI Record"); @@ -242,7 +242,7 @@ int ndefDecodePayload(NDEFHeader_t *ndef) { break; default: break; - } + } return 0; } @@ -251,9 +251,9 @@ int ndefRecordDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen) { int res = ndefDecodeHeader(ndefRecord, ndefRecordLen, &NDEFHeader); if (res) return res; - + ndefPrintHeader(&NDEFHeader); - + if (NDEFHeader.TypeLen) { PrintAndLogEx(INFO, "Type data:"); dump_buffer(NDEFHeader.Type, NDEFHeader.TypeLen, stdout, 1); @@ -275,13 +275,13 @@ int ndefRecordDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen) { int ndefRecordsDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen) { bool firstRec = true; size_t len = 0; - + while (len < ndefRecordLen) { NDEFHeader_t NDEFHeader = {0}; int res = ndefDecodeHeader(&ndefRecord[len], ndefRecordLen - len, &NDEFHeader); if (res) return res; - + if (firstRec) { if (!NDEFHeader.MessageBegin) { PrintAndLogEx(ERR, "NDEF first record have MessageBegin=false!"); @@ -289,27 +289,27 @@ int ndefRecordsDecodeAndPrint(uint8_t *ndefRecord, size_t ndefRecordLen) { } firstRec = false; } - + if (NDEFHeader.MessageEnd && len + NDEFHeader.RecLen != ndefRecordLen) { PrintAndLogEx(ERR, "NDEF records have wrong length. Must be %d, calculated %d", ndefRecordLen, len + NDEFHeader.RecLen); return 1; } - - ndefRecordDecodeAndPrint(&ndefRecord[len], NDEFHeader.RecLen); - + + ndefRecordDecodeAndPrint(&ndefRecord[len], NDEFHeader.RecLen); + len += NDEFHeader.RecLen; - + if (NDEFHeader.MessageEnd) break; - } - + } + return 0; } int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose) { - + size_t indx = 0; - + PrintAndLogEx(INFO, "NDEF decoding:"); while (indx < ndefLen) { switch (ndef[indx]) { @@ -326,11 +326,11 @@ int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose) { indx++; uint16_t len = ndefTLVGetLength(&ndef[indx], &indx); PrintAndLogEx(INFO, "-- NDEF message. len: %d", len); - + int res = ndefRecordsDecodeAndPrint(&ndef[indx], len); if (res) return res; - + indx += len; break; } @@ -350,8 +350,8 @@ int NDEFDecodeAndPrint(uint8_t *ndef, size_t ndefLen, bool verbose) { PrintAndLogEx(ERR, "unknown tag 0x%02x", ndef[indx]); return 1; } - } + } } - + return 0; } diff --git a/client/proxguiqt.h b/client/proxguiqt.h index f01526178..dbd2a9983 100644 --- a/client/proxguiqt.h +++ b/client/proxguiqt.h @@ -115,7 +115,7 @@ class ProxGuiQT : public QObject char **argv; //void (*main_func)(void); WorkerThread *proxmarkThread; - + public: ProxGuiQT(int argc, char **argv, WorkerThread *wthread); ~ProxGuiQT(void); @@ -124,7 +124,7 @@ class ProxGuiQT : public QObject void HideGraphWindow(void); void MainLoop(void); void Exit(void); - + private slots: void _ShowGraphWindow(void); void _RepaintGraphWindow(void); diff --git a/client/proxmark3.c b/client/proxmark3.c index 072fec427..45ed2b47a 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -47,7 +47,7 @@ static void showBanner(void){ void #ifdef __has_attribute #if __has_attribute(force_align_arg_pointer) -__attribute__((force_align_arg_pointer)) +__attribute__((force_align_arg_pointer)) #endif #endif main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { @@ -57,39 +57,39 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { bool stdinOnPipe = !isatty(STDIN_FILENO); FILE *sf = NULL; char script_cmd_buf[256] = {0x00}; // iceman, needs lua script the same file_path_buffer as the rest - + PrintAndLogEx(DEBUG, "ISATTY/STDIN_FILENO == %s\n", (stdinOnPipe) ? "true" : "false"); - + if (usb_present) { SetOffline(false); // cache Version information now: if ( execCommand || script_cmds_file || stdinOnPipe) CmdVersion("s"); - else + else CmdVersion(""); } else { SetOffline(true); } if (script_cmds_file) { - - sf = fopen(script_cmds_file, "r"); + + sf = fopen(script_cmds_file, "r"); if (sf) PrintAndLogEx(SUCCESS, "executing commands from file: %s\n", script_cmds_file); } read_history(".history"); - + // loops every time enter is pressed... while (1) { - + // this should hook up the PM3 again. /* if ( IsOffline() ) { - + // sets the global variable, SP and offline) usb_present = hookUpPM3(); - + // usb and the reader_thread is NULL, create a new reader thread. if (usb_present && !IsOffline() ) { rarg.run = 1; @@ -97,7 +97,7 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { // cache Version information now: if ( execCommand || script_cmds_file || stdinOnPipe) CmdVersion("s"); - else + else CmdVersion(""); } } @@ -105,16 +105,16 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { // If there is a script file if (sf) { - + // clear array memset(script_cmd_buf, 0, sizeof(script_cmd_buf)); - + // read script file if (!fgets(script_cmd_buf, sizeof(script_cmd_buf), sf)) { fclose(sf); sf = NULL; } else { - + // remove linebreaks strcleanrn(script_cmd_buf, sizeof(script_cmd_buf)); @@ -124,7 +124,7 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { } else { // If there is a script command if (execCommand){ - + if ((cmd = strmcopy(script_cmd)) != NULL) PrintAndLogEx(NORMAL, PROXPROMPT"%s", cmd); @@ -136,10 +136,10 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { // if there is a pipe from stdin if (stdinOnPipe) { - + // clear array memset(script_cmd_buf, 0, sizeof(script_cmd_buf)); - // get + // get if (!fgets(script_cmd_buf, sizeof(script_cmd_buf), stdin)) { PrintAndLogEx(ERR, "STDIN unexpected end, exit..."); break; @@ -149,17 +149,17 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { if ((cmd = strmcopy(script_cmd_buf)) != NULL) PrintAndLogEx(NORMAL, PROXPROMPT"%s", cmd); - - } else { + + } else { cmd = readline(PROXPROMPT); fflush(NULL); } } } - + // execute command if (cmd) { - + // rtrim size_t l = strlen(cmd); if ( l > 0 && isspace(cmd[l - 1])) @@ -170,9 +170,9 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { HIST_ENTRY * entry = history_get(history_length); if ((!entry) || (strcmp(entry->line, cmd) != 0)) add_history(cmd); - + // exit or quit - if (ret == 99) + if (ret == 99) break; } free(cmd); @@ -181,17 +181,17 @@ main_loop(char *script_cmds_file, char *script_cmd, bool usb_present) { PrintAndLogEx(NORMAL, "\n"); break; } - } // end while - + } // end while + if (sf) fclose(sf); - + write_history(".history"); if (cmd) { free(cmd); cmd = NULL; - } + } } static void dumpAllHelp(int markdown) { @@ -231,7 +231,7 @@ static void set_my_executable_path(void) { static void show_help(bool showFullHelp, char *command_line){ PrintAndLogEx(NORMAL, "syntax: %s [-h | -help | -m | -f | -flush | -w | -wait | -c | -command | -l | -lua] [cmd_script_file_name] [command][lua_script_name]\n", command_line); PrintAndLogEx(NORMAL, "\texample:'%s "SERIAL_PORT_H"'\n\n", command_line); - + if (showFullHelp){ PrintAndLogEx(NORMAL, "help: <-h|-help> Dump all interactive command's help at once.\n"); PrintAndLogEx(NORMAL, "\t%s -h\n\n", command_line); @@ -252,7 +252,7 @@ static void show_help(bool showFullHelp, char *command_line){ int main(int argc, char* argv[]) { srand(time(0)); - + bool usb_present = false; bool waitCOMPort = false; bool executeCommand = false; @@ -264,35 +264,35 @@ int main(int argc, char* argv[]) { using_history(); #ifdef RL_STATE_READCMD - rl_extend_line_buffer(1024); + rl_extend_line_buffer(1024); #endif - + if (argc < 2) { show_help(true, argv[0]); return 1; } for (int i = 1; i < argc; i++) { - + // helptext if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "-help") == 0) { show_help(false, argv[0]); dumpAllHelp(0); return 0; } - + // dump markup if (strcmp(argv[i], "-m") == 0) { dumpAllHelp(1); return 0; - } + } // flush output if (strcmp(argv[i], "-f") == 0 || strcmp(argv[i], "-flush") == 0){ SetFlushAfterWrite(true); PrintAndLogEx(INFO, "Output will be flushed after every print.\n"); } - + // wait for comport if (strcmp(argv[i], "-w") == 0 || strcmp(argv[i], "-wait") == 0){ waitCOMPort = true; @@ -314,10 +314,10 @@ int main(int argc, char* argv[]) { if (argc > 2 && argv[argc - 1] && argv[argc - 1][0] != '-') { if (executeCommand){ script_cmd = argv[argc - 1]; - + while (script_cmd[strlen(script_cmd) - 1] == ' ') script_cmd[strlen(script_cmd) - 1] = 0x00; - + if (strlen(script_cmd) == 0) { script_cmd = NULL; } else { @@ -332,7 +332,7 @@ int main(int argc, char* argv[]) { script_cmd = ctmp; } } - + PrintAndLogEx(SUCCESS, "execute command from commandline: %s\n", script_cmd); } } else { @@ -347,16 +347,16 @@ int main(int argc, char* argv[]) { } #if defined(__linux__) || (__APPLE__) -// ascii art doesn't work well on mingw :( +// ascii art doesn't work well on mingw :( bool stdinOnPipe = !isatty(STDIN_FILENO); if ( !executeCommand && !script_cmds_file && !stdinOnPipe ) - showBanner(); + showBanner(); #endif - + // set global variables set_my_executable_path(); - + // try to open USB connection to Proxmark usb_present = OpenProxmark(argv[1], waitCOMPort, 20, false); @@ -375,15 +375,15 @@ int main(int argc, char* argv[]) { main_loop(script_cmds_file, script_cmd, usb_present); } # endif - + #else main_loop(script_cmds_file, script_cmd, usb_present); -#endif - +#endif + // Clean up the port if (usb_present) { CloseProxmark(); } - + exit(0); } diff --git a/client/proxmark3.h b/client/proxmark3.h index 0a69e71ba..52fe27385 100644 --- a/client/proxmark3.h +++ b/client/proxmark3.h @@ -13,7 +13,7 @@ #define PROXMARK3_H__ #include "usb_cmd.h" -#include "cmdscript.h" // CmdScriptRun +#include "cmdscript.h" // CmdScriptRun #define PROXPROMPT "pm3 --> " diff --git a/client/reveng/cli.c b/client/reveng/cli.c index 6e147ba20..562b2d084 100644 --- a/client/reveng/cli.c +++ b/client/reveng/cli.c @@ -377,7 +377,7 @@ ipqx: /* allocate argument array */ args = argc - optind; - + apolys = calloc(args * sizeof(poly_t), sizeof(char)); if ( !apolys ){ uerror("cannot allocate memory for argument list"); diff --git a/client/reveng/getopt.c b/client/reveng/getopt.c index ebea43f06..7987d8e6b 100644 --- a/client/reveng/getopt.c +++ b/client/reveng/getopt.c @@ -35,7 +35,7 @@ int getopt(int argc, char *argv[], const char *optstring) { //static int pos = 0; char *str; - + if (pos == 0) { if ((optind >= argc) || (*argv[optind] != '-')) return EOF; @@ -43,7 +43,7 @@ int getopt(int argc, char *argv[], const char *optstring) if (argv[optind][pos] == '\0') return EOF; } - + str = strchr(optstring, argv[optind][pos]); if (str == NULL) { optopt = argv[optind][pos]; @@ -52,7 +52,7 @@ int getopt(int argc, char *argv[], const char *optstring) optopt); return '?'; } - + if (str[1] == ':') { if (argv[optind][pos+1] != '\0') { optarg = &argv[optind][pos+1]; diff --git a/client/reveng/preset.c b/client/reveng/preset.c index 82a18b977..dd093a6f3 100644 --- a/client/reveng/preset.c +++ b/client/reveng/preset.c @@ -811,7 +811,7 @@ int mbynam(model_t *dest, const char *key) { if (!aliases->name) return(-1); - + ukey = calloc((size_t) 1 + strlen(key) + 1, sizeof(char)); if (!ukey) { uerror("[!] cannot allocate memory for comparison string"); @@ -863,7 +863,7 @@ char * mnames(void) { ++aptr; } if (!size) return(NULL); - + string = calloc(size, sizeof(char)); if (string) { aptr = aliases; diff --git a/client/reveng/reveng.c b/client/reveng/reveng.c index 550dc2da5..1525bb265 100644 --- a/client/reveng/reveng.c +++ b/client/reveng/reveng.c @@ -173,7 +173,7 @@ modpol(const poly_t init, int rflags, int args, const poly_t *argpolys) { unsigned long alen, blen; if(args < 2) return(NULL); - + result = calloc(((((args - 1) * args) >> 1) + 1) * sizeof(poly_t), sizeof(char)); if(!result) uerror("cannot allocate memory for codeword table"); @@ -482,7 +482,7 @@ chkres(int *resc, model_t **result, const poly_t divisor, const poly_t init, int uerror("cannot reallocate result array"); return; } - + rptr = *result + *resc - 1; rptr->spoly = pclone(divisor); rptr->init = pclone(init); diff --git a/client/scandir.c b/client/scandir.c index 619bd72c6..d7cb0e9d6 100644 --- a/client/scandir.c +++ b/client/scandir.c @@ -28,7 +28,7 @@ int scandir (const char *dir, int count = 0; int allocated = 0; int err_no = 0; - + if (!(dirp = opendir (dir))) return -1; diff --git a/client/scripting.c b/client/scripting.c index 6f6a30f53..5f01f6afe 100644 --- a/client/scripting.c +++ b/client/scripting.c @@ -1,6 +1,6 @@ //----------------------------------------------------------------------------- // Copyright (C) 2013 m h swende -// Modified 2015,2016, iceman +// Modified 2015,2016, iceman // // This code is licensed to you under the terms of the GNU GPL, version 2 or, // at your option, any later version. See the LICENSE.txt file for the text of @@ -54,9 +54,9 @@ static int l_SendCommand(lua_State *L){ * @return */ static int l_GetFromBigBuf(lua_State *L){ - + int len = 0, startindex = 0; - + //Check number of arguments int n = lua_gettop(L); if (n == 0) { @@ -81,10 +81,10 @@ static int l_GetFromBigBuf(lua_State *L){ if ( !GetFromDevice(BIG_BUF, data, len, startindex, NULL, 2500, false)) { free(data); lua_pushnil(L); - lua_pushstring(L, "command execution time out"); + lua_pushstring(L, "command execution time out"); return 2; } - + //Push it as a string lua_pushlstring(L,(const char *)data, len); free(data); @@ -103,11 +103,11 @@ static int l_GetFromFlashMem(lua_State *L){ #ifndef WITH_FLASH lua_pushnil(L); - lua_pushstring(L, "Not compiled with FLASH MEM support"); + lua_pushstring(L, "Not compiled with FLASH MEM support"); return 2; #else int len = 0, startindex = 0; - + int n = lua_gettop(L); if (n == 0) { lua_pushnil(L); @@ -123,13 +123,13 @@ static int l_GetFromFlashMem(lua_State *L){ if ( !data ) { lua_pushnil(L); lua_pushstring(L, "Allocating memory failed"); - return 2; + return 2; } - + if ( !GetFromDevice(FLASH_MEM, data, len, startindex, NULL, -1, false)) { free(data); lua_pushnil(L); - lua_pushstring(L, "command execution time out"); + lua_pushstring(L, "command execution time out"); return 2; } @@ -160,7 +160,7 @@ static int l_WaitForResponseTimeout(lua_State *L){ lua_pushstring(L, "You need to supply at least command to wait for"); return 2; } - + // extract first param. cmd byte to look for if (n >= 1) { cmd = luaL_checkunsigned(L, 1); @@ -208,7 +208,7 @@ static int l_mfDarkside(lua_State *L){ case 2:{ const char *p_keytype = luaL_checklstring(L, 2, &size); if (size != 2) return returnToLuaWithError(L,"Wrong size of keytype, got %d bytes, expected 1", (int) size); - sscanf(p_keytype, "%x", &keytype); + sscanf(p_keytype, "%x", &keytype); } case 1: { const char *p_blockno = luaL_checklstring(L, 1, &size); @@ -223,7 +223,7 @@ static int l_mfDarkside(lua_State *L){ uint8_t dest_key[8]; num_to_bytes(key, sizeof(dest_key), dest_key); - + //Push the retval on the stack lua_pushinteger(L, retval); lua_pushlstring(L, (const char *) dest_key, sizeof(dest_key)); @@ -282,16 +282,16 @@ static int l_CmdConsole(lua_State *L) { static int l_iso15693_crc(lua_State *L) { uint32_t tmp; unsigned char buf[USB_CMD_DATA_SIZE] = {0x00}; - size_t size = 0; + size_t size = 0; const char *data = luaL_checklstring(L, 1, &size); - + for (int i = 0; i < size; i += 2) { sscanf(&data[i], "%02x", &tmp); buf[i / 2] = tmp & 0xFF; } - - size /= 2; - compute_crc(CRC_15693, buf, size, &buf[size], &buf[size+1]); + + size /= 2; + compute_crc(CRC_15693, buf, size, &buf[size], &buf[size+1]); lua_pushlstring(L, (const char *)&buf, size+2); return 1; } @@ -299,16 +299,16 @@ static int l_iso15693_crc(lua_State *L) { static int l_iso14443b_crc(lua_State *L) { uint32_t tmp; unsigned char buf[USB_CMD_DATA_SIZE] = {0x00}; - size_t size = 0; + size_t size = 0; const char *data = luaL_checklstring(L, 1, &size); - + for (int i = 0; i < size; i += 2) { sscanf(&data[i], "%02x", &tmp); buf[i / 2] = tmp & 0xFF; } - - size /= 2; - compute_crc(CRC_14443_B, buf, size, &buf[size], &buf[size+1]); + + size /= 2; + compute_crc(CRC_14443_B, buf, size, &buf[size], &buf[size+1]); lua_pushlstring(L, (const char *)&buf, size+2); return 1; } @@ -388,12 +388,12 @@ static int l_aes128encrypt_cbc(lua_State *L) { if (size != 32) return returnToLuaWithError(L,"Wrong size of key, got %d bytes, expected 32", (int) size); const char *p_txt = luaL_checklstring(L, 2, &size); - + unsigned char indata[16] = {0x00}; unsigned char outdata[16] = {0x00}; unsigned char aes_key[16] = {0x00}; unsigned char iv[16] = {0x00}; - + for (i = 0; i < 32; i += 2) { sscanf(&p_txt[i], "%02x", &tmp); indata[i / 2] = tmp & 0xFF; @@ -419,17 +419,17 @@ static int l_aes128encrypt_ecb(lua_State *L) { if (size != 32) return returnToLuaWithError(L,"Wrong size of key, got %d bytes, expected 32", (int) size); const char *p_txt = luaL_checklstring(L, 2, &size); - + unsigned char indata[16] = {0x00}; unsigned char outdata[16] = {0x00}; unsigned char aes_key[16] = {0x00}; - + for (i = 0; i < 32; i += 2) { sscanf(&p_txt[i], "%02x", &tmp); indata[i / 2] = tmp & 0xFF; sscanf(&p_key[i], "%02x", &tmp); aes_key[i / 2] = tmp & 0xFF; - } + } mbedtls_aes_context ctx; mbedtls_aes_init(&ctx); mbedtls_aes_setkey_enc(&ctx, aes_key, 128); @@ -459,7 +459,7 @@ static int l_crc16(lua_State *L) { static int l_crc64(lua_State *L) { size_t size; - uint64_t crc = 0; + uint64_t crc = 0; unsigned char outdata[8] = {0x00}; const char *p_str = luaL_checklstring(L, 1, &size); @@ -480,7 +480,7 @@ static int l_crc64(lua_State *L) { static int l_crc64_ecma182(lua_State *L) { //size_t size; - uint64_t crc = 0; + uint64_t crc = 0; unsigned char outdata[8] = {0x00}; //const char *p_str = luaL_checklstring(L, 1, &size); @@ -490,7 +490,7 @@ static int l_crc64_ecma182(lua_State *L) { // calc hash //crc64_ecma182((uint8_t*) p_str, size, &crc); - + outdata[0] = (uint8_t)(crc >> 56) & 0xff; outdata[1] = (uint8_t)(crc >> 48) & 0xff; outdata[2] = (uint8_t)(crc >> 40) & 0xff; @@ -505,11 +505,11 @@ static int l_crc64_ecma182(lua_State *L) { static int l_sha1(lua_State *L) { size_t size; - const char *p_str = luaL_checklstring(L, 1, &size); - unsigned char outdata[20] = {0x00}; - mbedtls_sha1( (uint8_t*) p_str, size, outdata); + const char *p_str = luaL_checklstring(L, 1, &size); + unsigned char outdata[20] = {0x00}; + mbedtls_sha1( (uint8_t*) p_str, size, outdata); lua_pushlstring(L, (const char *)&outdata, sizeof(outdata)); - return 1; + return 1; } static int l_reveng_models(lua_State *L){ @@ -526,11 +526,11 @@ static int l_reveng_models(lua_State *L){ char *models[NMODELS]; width[0] = in_width; - + if (!GetModels(models, &count, width)) return returnToLuaWithError(L, "didn't find any models"); - - lua_newtable(L); + + lua_newtable(L); for (int i = 0; i < count; i++){ lua_pushstring(L, (const char*)models[i]); lua_rawseti(L,-2,i+1); @@ -553,19 +553,19 @@ static int l_reveng_RunModel(lua_State *L){ //reverse = reverse calc option if true //endian = {0 = calc default endian input and output, b = big endian input and output, B = big endian output, r = right justified // l = little endian input and output, L = little endian output only, t = left justified} - //result = calculated crc hex string + //result = calculated crc hex string char result[50]; - + const char *inModel = luaL_checkstring(L, 1); const char *inHexStr = luaL_checkstring(L, 2); bool reverse = lua_toboolean(L, 3); const char endian = luaL_checkstring(L, 4)[0]; int ans = RunModel( (char *)inModel, (char *)inHexStr, reverse, endian, result); - if (!ans) + if (!ans) return returnToLuaWithError(L,"Reveng failed"); - lua_pushstring(L, (const char*)result); + lua_pushstring(L, (const char*)result); return 1; } @@ -582,7 +582,7 @@ static int l_hardnested(lua_State *L){ const char *p_key = luaL_checklstring(L, 3, &size); if(size != 12) return returnToLuaWithError(L,"Wrong size of key, got %d bytes, expected 12", (int) size); - + const char *p_trg_blockno = luaL_checklstring(L, 4, &size); if(size != 2) return returnToLuaWithError(L,"Wrong size of trgBlockNo, got %d bytes, expected 2", (int) size); @@ -604,7 +604,7 @@ static int l_hardnested(lua_State *L){ const char *p_tests = luaL_checklstring(L, 10, &size); if(size != 1) return returnToLuaWithError(L,"Wrong size of tests, got %d bytes, expected 1", (int) size); - + char filename[FILE_PATH_SIZE]="nonces.bin"; const char *p_filename = luaL_checklstring(L, 11, &size); if(size != 0) @@ -634,7 +634,7 @@ static int l_hardnested(lua_State *L){ trgkey[i / 2] = tmp & 0xFF; } } - + uint64_t foundkey = 0; int retval = mfnestedhard(blockNo, keyType, key, trgBlockNo, trgKeyType, haveTarget ? trgkey : NULL, nonce_file_read, nonce_file_write, slow, tests, &foundkey, filename); DropField(); @@ -642,7 +642,7 @@ static int l_hardnested(lua_State *L){ //Push the key onto the stack uint8_t dest_key[6]; num_to_bytes(foundkey, sizeof(dest_key), dest_key); - + //Push the retval on the stack lua_pushinteger(L,retval); lua_pushlstring(L, (const char *) dest_key, sizeof(dest_key)); @@ -680,10 +680,10 @@ static int l_keygen_algoD(lua_State *L) { uint32_t pwd = ul_ev1_pwdgenD(uid); uint16_t pack = ul_ev1_packgenD(uid); - + lua_pushunsigned(L, pwd); lua_pushunsigned(L, pack); - return 2; + return 2; } /** @@ -724,7 +724,7 @@ int set_pm3_libraries(lua_State *L) { {"iso14443b_crc", l_iso14443b_crc}, {"aes128_decrypt", l_aes128decrypt_cbc}, {"aes128_decrypt_ecb", l_aes128decrypt_ecb}, - {"aes128_encrypt", l_aes128encrypt_cbc}, + {"aes128_encrypt", l_aes128encrypt_cbc}, {"aes128_encrypt_ecb", l_aes128encrypt_ecb}, {"crc8legic", l_crc8legic}, {"crc16", l_crc16}, @@ -758,7 +758,7 @@ int set_pm3_libraries(lua_State *L) { //-- remove the global environment table from the stack lua_pop(L, 1); - + //--add to the LUA_PATH (package.path in lua) // so we can load scripts from the ./scripts/ - directory char scripts_path[strlen(get_my_executable_directory()) + strlen(LUA_SCRIPTS_DIRECTORY) + strlen(LUA_LIBRARIES_WILDCARD) + 1]; @@ -766,7 +766,7 @@ int set_pm3_libraries(lua_State *L) { strcat(scripts_path, LUA_SCRIPTS_DIRECTORY); strcat(scripts_path, LUA_LIBRARIES_WILDCARD); setLuaPath(L, scripts_path); - + //-- Last but not least, add to the LUA_PATH (package.path in lua) // so we can load libraries from the ./lualib/ - directory char libraries_path[strlen(get_my_executable_directory()) + strlen(LUA_LIBRARIES_DIRECTORY) + strlen(LUA_LIBRARIES_WILDCARD) + 1]; diff --git a/client/ui.c b/client/ui.c index 71603fed6..96049f6cf 100644 --- a/client/ui.c +++ b/client/ui.c @@ -45,18 +45,18 @@ void PrintAndLogOptions(char *str[][2], size_t size, size_t space) { } void PrintAndLogEx(logLevel_t level, char *fmt, ...) { - // skip debug messages if client debugging is turned off i.e. 'DATA SETDEBUG 0' + // skip debug messages if client debugging is turned off i.e. 'DATA SETDEBUG 0' if (g_debugMode == 0 && level == DEBUG) return; - char prefix[20] = {0}; + char prefix[20] = {0}; char buffer[MAX_PRINT_BUFFER] = {0}; char buffer2[MAX_PRINT_BUFFER+20] = {0}; char *token = NULL; int size = 0; // {NORMAL, SUCCESS, INFO, FAILED, WARNING, ERR, DEBUG} static char *prefixes[7] = { "", "[+] ", "[=] ", "[-] ", "[!] ", "[!!] ", "[#] "}; - + switch( level ) { case ERR: strncpy(prefix,_RED_([!!] ), sizeof(prefix)-1); @@ -65,19 +65,19 @@ void PrintAndLogEx(logLevel_t level, char *fmt, ...) { strncpy(prefix,_RED_([-] ), sizeof(prefix)-1); break; case DEBUG: - strncpy(prefix,_BLUE_([#] ), sizeof(prefix)-1); + strncpy(prefix,_BLUE_([#] ), sizeof(prefix)-1); break; - case SUCCESS: + case SUCCESS: strncpy(prefix,_GREEN_([+] ), sizeof(prefix)-1); break; case WARNING: strncpy(prefix,_CYAN_([!] ), sizeof(prefix)-1); - break; + break; default: strncpy(prefix, prefixes[level], sizeof(prefix)-1); break; } - + va_list args; va_start(args, fmt); vsnprintf(buffer, sizeof(buffer), fmt, args); @@ -88,26 +88,26 @@ void PrintAndLogEx(logLevel_t level, char *fmt, ...) { PrintAndLog("%s", buffer); return; } - + if (strchr(buffer, '\n')) { const char delim[2] = "\n"; - + // line starts with newline - if (buffer[0] == '\n') + if (buffer[0] == '\n') PrintAndLog(""); - + token = strtok(buffer, delim); - + while (token != NULL) { - + size = strlen(buffer2); - + if (strlen(token)) snprintf(buffer2+size, sizeof(buffer2)-size, "%s%s\n", prefix, token); else snprintf(buffer2+size, sizeof(buffer2)-size, "\n"); - + token = strtok(NULL, delim); } PrintAndLog("%s", buffer2); @@ -123,10 +123,10 @@ void PrintAndLog(char *fmt, ...) { va_list argptr, argptr2; static FILE *logfile = NULL; static int logging = 1; - + // lock this section to avoid interlacing prints from different threads pthread_mutex_lock(&print_lock); - + if (logging && !logfile) { logfile = fopen(logfilename, "a"); if (!logfile) { @@ -135,10 +135,10 @@ void PrintAndLog(char *fmt, ...) { } } - + // If there is an incoming message from the hardware (eg: lf hid read) in // the background (while the prompt is displayed and accepting user input), -// stash the prompt and bring it back later. +// stash the prompt and bring it back later. #ifdef RL_STATE_READCMD // We are using GNU readline. libedit (OSX) doesn't support this flag. int need_hack = (rl_readline_state & RL_STATE_READCMD) > 0; @@ -151,7 +151,7 @@ void PrintAndLog(char *fmt, ...) { rl_redisplay(); } #endif - + va_start(argptr, fmt); va_copy(argptr2, argptr); vprintf(fmt, argptr); @@ -169,7 +169,7 @@ void PrintAndLog(char *fmt, ...) { free(saved_line); } #endif - + if (logging && logfile) { vfprintf(logfile, fmt, argptr2); fprintf(logfile, "\n"); @@ -181,13 +181,13 @@ void PrintAndLog(char *fmt, ...) { fflush(stdout); //release lock - pthread_mutex_unlock(&print_lock); + pthread_mutex_unlock(&print_lock); } void SetLogFilename(char *fn) { logfilename = fn; } - + void SetFlushAfterWrite(bool value) { flushAfterWrite = value; } @@ -195,29 +195,29 @@ void SetFlushAfterWrite(bool value) { void iceIIR_Butterworth(int *data, const size_t len){ int i,j; - - int * output = (int* ) calloc(sizeof(int) * len, sizeof(uint8_t)); + + int * output = (int* ) calloc(sizeof(int) * len, sizeof(uint8_t)); if ( !output ) return; - + // clear mem memset(output, 0x00, len); - + size_t adjustedLen = len; float fc = 0.1125f; // center frequency - + // create very simple low-pass filter to remove images (2nd-order Butterworth) float complex iir_buf[3] = {0,0,0}; float b[3] = {0.003621681514929, 0.007243363029857, 0.003621681514929}; float a[3] = {1.000000000000000, -1.822694925196308, 0.837181651256023}; - + float sample = 0; // input sample read from array float complex x_prime = 1.0f; // save sample for estimating frequency float complex x; - + for (i = 0; i < adjustedLen; ++i) { sample = data[i]; - + // remove DC offset and mix to complex baseband x = (sample - 127.5f) * cexpf( _Complex_I * 2 * M_PI * fc * i ); @@ -228,27 +228,27 @@ void SetFlushAfterWrite(bool value) { x = b[0]*iir_buf[0] + b[1]*iir_buf[1] + b[2]*iir_buf[2]; - + // compute instantaneous frequency by looking at phase difference // between adjacent samples float freq = cargf(x * conjf(x_prime)); x_prime = x; // retain this sample for next iteration output[i] =(freq > 0) ? 127 : -127; - } + } // show data //memcpy(data, output, adjustedLen); for (j=0; j #include #include -#include +#include #include #include "util.h" diff --git a/client/util.c b/client/util.c index cea42f338..99c44ff13 100644 --- a/client/util.c +++ b/client/util.c @@ -21,7 +21,7 @@ uint8_t g_debugMode = 0; #ifndef _WIN32 #include -#include +#include #include #include @@ -64,10 +64,10 @@ void AddLogLine(char *fn, char *data, char *c) { int len = 0; len = strlen(fn); - if (len > FILE_PATH_SIZE) + if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, fn, len); - + f = fopen(filename, "a"); if (!f) { printf("Could not append log file %s", filename); @@ -111,14 +111,14 @@ void FillFileNameByUID(char *filenamePrefix, uint8_t *uid, const char *ext, int printf("[!] error parameter is NULL\n"); return; } - + int len = 0; len = strlen(filenamePrefix); //memset(fn, 0x00, FILE_PATH_SIZE); - + for (int j = 0; j < uidlen; j++) - sprintf(filenamePrefix + len + j * 2, "%02X", uid[j]); - strcat(filenamePrefix, ext); + sprintf(filenamePrefix + len + j * 2, "%02X", uid[j]); + strcat(filenamePrefix, ext); } // fill buffer from structure [{uint8_t data, size_t length},...] @@ -126,25 +126,25 @@ int FillBuffer(uint8_t *data, size_t maxDataLength, size_t *dataLength, ...) { *dataLength = 0; va_list valist; va_start(valist, dataLength); - + uint8_t *vdata = NULL; size_t vlength = 0; do{ vdata = va_arg(valist, uint8_t *); if (!vdata) break; - + vlength = va_arg(valist, size_t); if (*dataLength + vlength > maxDataLength) { va_end(valist); return 1; } - + memcpy(&data[*dataLength], vdata, vlength); *dataLength += vlength; - + } while (vdata); - + va_end(valist); return 0; @@ -157,13 +157,13 @@ bool CheckStringIsHEXValue(const char *value) { if (strlen(value) % 2) return false; - + return true; } -void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex_len, const size_t hex_max_len, +void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex_len, const size_t hex_max_len, const size_t min_str_len, const size_t spaces_between, bool uppercase) { - + char *tmp = (char *)buf; size_t i; memset(tmp, 0x00, hex_max_len); @@ -171,17 +171,17 @@ void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex int maxLen = ( hex_len > hex_max_len) ? hex_max_len : hex_len; for (i = 0; i < maxLen; ++i, tmp += 2 + spaces_between) { - sprintf(tmp, (uppercase) ? "%02X" : "%02x", (unsigned int) hex_data[i]); - + sprintf(tmp, (uppercase) ? "%02X" : "%02x", (unsigned int) hex_data[i]); + for (int j = 0; j < spaces_between; j++) sprintf(tmp + 2 + j, " "); } - + i *= (2 + spaces_between); int minStrLen = min_str_len > i ? min_str_len : 0; if (minStrLen > hex_max_len) minStrLen = hex_max_len; - for(; i < minStrLen; i++, tmp += 1) + for(; i < minStrLen; i++, tmp += 1) sprintf(tmp, " "); return; @@ -201,7 +201,7 @@ void print_hex_break(const uint8_t *data, const size_t len, uint8_t breaks) { for (int i = 0; i < len; ++i) { printf("%02X ", data[i]); - + // check if a line break is needed if ( breaks > 0 && !((i+1) % breaks) && (i+1 < len) ) { ++rownum; @@ -233,17 +233,17 @@ char *sprint_hex_inrow_spaces(const uint8_t *data, const size_t len, size_t spac } char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks) { - + // make sure we don't go beyond our char array memory size_t in_index = 0, out_index = 0; - + int rowlen = (len > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len; - - if ( breaks > 0 && len % breaks != 0) + + if ( breaks > 0 && len % breaks != 0) rowlen = ( len+(len/breaks) > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len+(len/breaks); - + //printf("(sprint_bin_break) rowlen %d\n", rowlen); - + static char buf[MAX_BIN_BREAK_LENGTH]; // 3072 + end of line characters if broken at 8 bits //clear memory memset(buf, 0x00, sizeof(buf)); @@ -268,21 +268,21 @@ char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t brea void sprint_bin_break_ex(uint8_t *src, size_t srclen, char *dest , uint8_t breaks) { if ( src == NULL ) return; if ( srclen < 1 ) return; - + // make sure we don't go beyond our char array memory size_t in_index = 0, out_index = 0; - int rowlen; + int rowlen; if (breaks==0) rowlen = ( len > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len; else rowlen = ( len+(len/breaks) > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len+(len/breaks); printf("(sprint_bin_break) rowlen %d\n", rowlen); - + // 3072 + end of line characters if broken at 8 bits - dest = (char *)calloc(MAX_BIN_BREAK_LENGTH, sizeof(uint8_t)); + dest = (char *)calloc(MAX_BIN_BREAK_LENGTH, sizeof(uint8_t)); if (dest == NULL) return; - + //clear memory memset(dest, 0x00, sizeof(dest)); @@ -314,7 +314,7 @@ char *sprint_hex_ascii(const uint8_t *data, const size_t len) { size_t max_len = (len > 1010) ? 1010 : len; snprintf(tmp, UTIL_BUFFER_SIZE_SPRINT, "%s| ", sprint_hex(data, max_len) ); - + size_t i = 0; size_t pos = (max_len * 3) + 2; while (i < max_len){ @@ -338,11 +338,11 @@ char *sprint_ascii_ex(const uint8_t *data, const size_t len, const size_t min_st tmp[i] = ((c < 32) || (c == 127)) ? '.' : c; ++i; } - + int m = min_str_len > i ? min_str_len : 0; - for(; i < m; ++i) + for(; i < m; ++i) tmp[i] = ' '; - + return buf; } char *sprint_ascii(const uint8_t *data, const size_t len) { @@ -409,7 +409,7 @@ uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockS return buf; } -// takes a uint8_t src array, for len items and reverses the byte order in blocksizes (8,16,32,64), +// takes a uint8_t src array, for len items and reverses the byte order in blocksizes (8,16,32,64), // returns: the dest array contains the reordered src array. void SwapEndian64ex(const uint8_t *src, const size_t len, const uint8_t blockSize, uint8_t *dest){ for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){ @@ -432,10 +432,10 @@ int param_getptr(const char *line, int *bg, int *en, int paramnum) { int i; int len = strlen(line); - + *bg = 0; *en = 0; - + // skip spaces while (line[*bg] ==' ' || line[*bg]=='\t') (*bg)++; if (*bg >= len) { @@ -445,13 +445,13 @@ int param_getptr(const char *line, int *bg, int *en, int paramnum) for (i = 0; i < paramnum; i++) { while (line[*bg]!=' ' && line[*bg]!='\t' && line[*bg] != '\0') (*bg)++; while (line[*bg]==' ' || line[*bg]=='\t') (*bg)++; - + if (line[*bg] == '\0') return 1; } - + *en = *bg; while (line[*en] != ' ' && line[*en] != '\t' && line[*en] != '\0') (*en)++; - + (*en)--; return 0; @@ -460,7 +460,7 @@ int param_getptr(const char *line, int *bg, int *en, int paramnum) int param_getlength(const char *line, int paramnum) { int bg, en; - + if (param_getptr(line, &bg, &en, paramnum)) return 0; return en - bg + 1; @@ -472,12 +472,12 @@ char param_getchar(const char *line, int paramnum) { char param_getchar_indx(const char *line, int indx, int paramnum) { int bg, en; - + if (param_getptr(line, &bg, &en, paramnum)) return 0x00; if (bg + indx > en) return '\0'; - + return line[bg + indx]; } @@ -518,7 +518,7 @@ uint8_t param_isdec(const char *line, int paramnum) uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base) { int bg, en; - if (!param_getptr(line, &bg, &en, paramnum)) + if (!param_getptr(line, &bg, &en, paramnum)) return strtoul(&line[bg], NULL, base) & 0xff; else return deflt; @@ -527,7 +527,7 @@ uint8_t param_get8ex(const char *line, int paramnum, int deflt, int base) uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base) { int bg, en; - if (!param_getptr(line, &bg, &en, paramnum)) + if (!param_getptr(line, &bg, &en, paramnum)) return strtoul(&line[bg], NULL, base); else return deflt; @@ -536,7 +536,7 @@ uint32_t param_get32ex(const char *line, int paramnum, int deflt, int base) uint64_t param_get64ex(const char *line, int paramnum, int deflt, int base) { int bg, en; - if (!param_getptr(line, &bg, &en, paramnum)) + if (!param_getptr(line, &bg, &en, paramnum)) return strtoull(&line[bg], NULL, base); else return deflt; @@ -547,17 +547,17 @@ int param_gethex(const char *line, int paramnum, uint8_t * data, int hexcnt) { uint32_t temp; if (hexcnt & 1) return 1; - + if (param_getptr(line, &bg, &en, paramnum)) return 1; if (en - bg + 1 != hexcnt) return 1; for(i = 0; i < hexcnt; i += 2) { if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1; - + sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp); data[i / 2] = temp & 0xff; - } + } return 0; } @@ -573,10 +573,10 @@ int param_gethex_ex(const char *line, int paramnum, uint8_t * data, int *hexcnt) for(i = 0; i < *hexcnt; i += 2) { if (!(isxdigit(line[bg + i]) && isxdigit(line[bg + i + 1])) ) return 1; - + sscanf((char[]){line[bg + i], line[bg + i + 1], 0}, "%X", &temp); data[i / 2] = temp & 0xff; - } + } return 0; } @@ -589,21 +589,21 @@ int param_gethex_to_eol(const char *line, int paramnum, uint8_t * data, int maxd if (param_getptr(line, &bg, &en, paramnum)) return 1; *datalen = 0; - + int indx = bg; while (line[indx]) { if (line[indx] == '\t' || line[indx] == ' ') { indx++; continue; } - + if (isxdigit(line[indx])) { buf[strlen(buf) + 1] = 0x00; buf[strlen(buf)] = line[indx]; } else { // if we have symbols other than spaces and hex return 1; - } + } if (*datalen >= maxdatalen) { // if we dont have space in buffer and have symbols to translate @@ -616,14 +616,14 @@ int param_gethex_to_eol(const char *line, int paramnum, uint8_t * data, int maxd *buf = 0; (*datalen)++; } - + indx++; } - if (strlen(buf) > 0) + if (strlen(buf) > 0) //error when not completed hex bytes return 3; - + return 0; } @@ -631,7 +631,7 @@ int param_getstr(const char *line, int paramnum, char * str, size_t buffersize) { int bg, en; - if (param_getptr(line, &bg, &en, paramnum)) { + if (param_getptr(line, &bg, &en, paramnum)) { return 0; } @@ -640,10 +640,10 @@ int param_getstr(const char *line, int paramnum, char * str, size_t buffersize) printf("out of bounds error: want %d bytes have %zu bytes\n", en - bg + 1 + 1, buffersize); return 0; } - + memcpy(str, line + bg, en - bg + 1); str[en - bg + 1] = 0; - + return en - bg + 1; } @@ -680,7 +680,7 @@ int hextobinarray(char *target, char *source) for(i= 0 ; i < 4 ; ++i, ++count) *(target++)= (x >> (3 - i)) & 1; } - + return count; } @@ -755,11 +755,11 @@ void xor(unsigned char * dst, unsigned char * src, size_t len) { int32_t le24toh (uint8_t data[3]) { return (data[2] << 16) | (data[1] << 8) | data[0]; } -// Pack a bitarray into a uint32_t. +// Pack a bitarray into a uint32_t. uint32_t PackBits(uint8_t start, uint8_t len, uint8_t* bits) { if (len > 32) return 0; - + int i = start; int j = len-1; uint32_t tmp = 0; @@ -772,7 +772,7 @@ uint32_t PackBits(uint8_t start, uint8_t len, uint8_t* bits) { // RotateLeft - Ultralight, Desfire, works on byte level // 00-01-02 >> 01-02-00 -void rol(uint8_t *data, const size_t len){ +void rol(uint8_t *data, const size_t len){ uint8_t first = data[0]; for (size_t i = 0; i < len-1; i++) { data[i] = data[i+1]; @@ -793,7 +793,7 @@ uint8_t reflect8(uint8_t b) { } uint16_t reflect16(uint16_t b) { uint16_t v = 0; - v |= (b & 0x8000) >> 15; + v |= (b & 0x8000) >> 15; v |= (b & 0x4000) >> 13; v |= (b & 0x2000) >> 11; v |= (b & 0x1000) >> 9; @@ -814,7 +814,7 @@ uint16_t reflect16(uint16_t b) { } /* ref http://www.csm.ornl.gov/~dunigan/crc.html - Returns the value v with the bottom b [0,32] bits reflected. + Returns the value v with the bottom b [0,32] bits reflected. Example: reflect(0x3e23L,3) == 0x3e26 */ uint32_t reflect(uint32_t v, int b) { @@ -857,7 +857,7 @@ extern void str_lower(char *s ){ for(int i=0; i < strlen(s); i++) s[i] = tolower( s[i] ); } -extern bool str_startswith(const char *s, const char *pre) { +extern bool str_startswith(const char *s, const char *pre) { return strncmp(pre, s, strlen(pre)) == 0; } @@ -888,6 +888,6 @@ extern char *strmcopy(char *buf) { if (str != NULL) { memset(str, 0, strlen(buf) + 1); strcpy(str, buf); - } + } return str; } \ No newline at end of file diff --git a/client/util.h b/client/util.h index e10f06497..ec99a4903 100644 --- a/client/util.h +++ b/client/util.h @@ -199,7 +199,7 @@ extern void FillFileNameByUID(char *filenamePrefix, uint8_t * uid, const char *e extern int FillBuffer(uint8_t *data, size_t maxDataLength, size_t *dataLength, ...); extern bool CheckStringIsHEXValue(const char *value); -extern void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex_len, +extern void hex_to_buffer(const uint8_t *buf, const uint8_t *hex_data, const size_t hex_len, const size_t hex_max_len, const size_t min_str_len, const size_t spaces_between, bool uppercase); @@ -263,4 +263,4 @@ extern bool str_startswith(const char *s, const char *pre); // check for prefi extern void strcleanrn(char *buf, size_t len); extern void strcreplace(char *buf, size_t len, char from, char to); extern char *strmcopy(char *buf); -#endif \ No newline at end of file +#endif \ No newline at end of file diff --git a/client/util_posix.c b/client/util_posix.c index a45dc48e9..5ecc50d13 100644 --- a/client/util_posix.c +++ b/client/util_posix.c @@ -40,7 +40,7 @@ void msleep(uint32_t n) { #ifndef CLOCK_MONOTONIC #define CLOCK_MONOTONIC (1) #endif -#ifndef CLOCK_REALTIME +#ifndef CLOCK_REALTIME #define CLOCK_REALTIME (2) #endif @@ -72,7 +72,7 @@ void msleep(uint32_t n) { uint64_t now = mach_absolute_time(); if (clock_start_time == 0) { - + mach_timebase_info(&timebase_info); clock_start_time = now; } diff --git a/client/whereami.c b/client/whereami.c index acf3ff2e8..127e49504 100644 --- a/client/whereami.c +++ b/client/whereami.c @@ -140,7 +140,7 @@ int WAI_PREFIX(getExecutablePath)(char* out, int capacity, int* dirname_length) return WAI_PREFIX(getModulePath_)(NULL, out, capacity, dirname_length); } -// GetModuleHandleEx() is not available on old mingw environments. We don't need getModulePath() yet. +// GetModuleHandleEx() is not available on old mingw environments. We don't need getModulePath() yet. // Sacrifice it for the time being to improve backwards compatibility /* WAI_NOINLINE WAI_FUNCSPEC diff --git a/common/cmd.c b/common/cmd.c index bed968c2c..ebeaf4f7c 100644 --- a/common/cmd.c +++ b/common/cmd.c @@ -40,7 +40,7 @@ uint8_t cmd_send(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void // Compose the outgoing command frame txcmd.cmd = cmd; txcmd.arg[0] = arg0; - txcmd.arg[1] = arg1; + txcmd.arg[1] = arg1; txcmd.arg[2] = arg2; // Add the (optional) content to the frame, with a maximum size of USB_CMD_DATA_SIZE @@ -50,7 +50,7 @@ uint8_t cmd_send(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void txcmd.d.asBytes[i] = ((uint8_t*)data)[i]; } } - + uint32_t sendlen = 0; // Send frame and make sure all bytes are transmitted sendlen = usb_write( (uint8_t*)&txcmd, sizeof(UsbCommand) ); @@ -59,6 +59,6 @@ uint8_t cmd_send(uint64_t cmd, uint64_t arg0, uint64_t arg1, uint64_t arg2, void // usart_init(); // usart_writebuffer( (uint8_t*)&txcmd, sizeof(UsbCommand) ); #endif - + return sendlen; } \ No newline at end of file diff --git a/common/crapto1/crapto1.h b/common/crapto1/crapto1.h index c941879ce..5abdaeb09 100644 --- a/common/crapto1/crapto1.h +++ b/common/crapto1/crapto1.h @@ -61,7 +61,7 @@ extern bool validate_prng_nonce(uint32_t nonce); break;\ else if(__i)\ __M = prng_successor(__M, (__i == 7) ? 48 : 8);\ - else + else #define LF_POLY_ODD (0x29CE5C) #define LF_POLY_EVEN (0x870804) diff --git a/common/crc.c b/common/crc.c index 77bea0b47..4097fdd48 100644 --- a/common/crc.c +++ b/common/crc.c @@ -5,7 +5,7 @@ //----------------------------------------------------------------------------- // Generic CRC calculation code. //----------------------------------------------------------------------------- -// the Check value below in the comments is CRC of the string '123456789' +// the Check value below in the comments is CRC of the string '123456789' // #include "crc.h" @@ -29,21 +29,21 @@ void crc_init(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, u } void crc_clear(crc_t *crc) { - + crc->state = crc->initial_value & crc->mask; - if (crc->refin) + if (crc->refin) crc->state = reflect(crc->state, crc->order); } void crc_update2(crc_t *crc, uint32_t data, int data_width){ - - if (crc->refin) + + if (crc->refin) data = reflect(data, data_width); - + // Bring the next byte into the remainder. crc->state ^= data << (crc->order - data_width); - - for( uint8_t bit = data_width; bit > 0; --bit) { + + for( uint8_t bit = data_width; bit > 0; --bit) { if (crc->state & crc->topbit) crc->state = (crc->state << 1) ^ crc->polynom; @@ -54,9 +54,9 @@ void crc_update2(crc_t *crc, uint32_t data, int data_width){ void crc_update(crc_t *crc, uint32_t data, int data_width) { - if (crc->refin) + if (crc->refin) data = reflect(data, data_width); - + int i; for(i=0; istate; @@ -70,7 +70,7 @@ void crc_update(crc_t *crc, uint32_t data, int data_width) uint32_t crc_finish(crc_t *crc) { uint32_t val = crc->state; - if (crc->refout) + if (crc->refout) val = reflect(val, crc->order); return ( val ^ crc->final_xor ) & crc->mask; } @@ -94,7 +94,7 @@ static void print_crc(crc_t *crc) { // width=8 poly=0x31 init=0x00 refin=true refout=true xorout=0x00 check=0xA1 name="CRC-8/MAXIM" uint32_t CRC8Maxim(uint8_t *buff, size_t size) { crc_t crc; - crc_init_ref(&crc, 8, 0x31, 0, 0, true, true); + crc_init_ref(&crc, 8, 0x31, 0, 0, true, true); for ( int i=0; i < size; ++i) crc_update2(&crc, buff[i], 8); return crc_finish(&crc); @@ -114,7 +114,7 @@ uint32_t CRC4Legic(uint8_t *cmd, size_t size) { crc_update2(&crc, 1, 1); /* CMD_READ */ crc_update2(&crc, cmd[0], 8); crc_update2(&crc, cmd[1], 8); - return reflect(crc_finish(&crc), 4); + return reflect(crc_finish(&crc), 4); } // width=8 poly=0x63, reversed poly=0x8D init=0x55 refin=true refout=true xorout=0x0000 check=0xC6 name="CRC-8/LEGIC" // the CRC needs to be reversed before returned. diff --git a/common/crc.h b/common/crc.h index 40bdc7daf..015fbf60c 100644 --- a/common/crc.h +++ b/common/crc.h @@ -26,12 +26,12 @@ typedef struct crc { /* Initialize a crc structure. order is the order of the polynom, e.g. 32 for a CRC-32 * polynom is the CRC polynom. initial_value is the initial value of a clean state. - * final_xor is XORed onto the state before returning it from crc_result(). + * final_xor is XORed onto the state before returning it from crc_result(). * refin is the setting for reversing (bitwise) the bytes during crc * refot is the setting for reversing (bitwise) the crc byte before returning it. */ extern void crc_init_ref(crc_t *crc, int order, uint32_t polynom, uint32_t initial_value, uint32_t final_xor, bool refin, bool refout); - + /* Initialize a crc structure. order is the order of the polynom, e.g. 32 for a CRC-32 * polynom is the CRC polynom. initial_value is the initial value of a clean state. * final_xor is XORed onto the state before returning it from crc_result(). */ diff --git a/common/crc16.c b/common/crc16.c index 8110d8045..b6145013b 100644 --- a/common/crc16.c +++ b/common/crc16.c @@ -12,17 +12,17 @@ static bool crc_table_init = false; static CrcType_t crc_type = CRC_NONE; void init_table(CrcType_t ct) { - + // same crc algo, and initialised already - if ( ct == crc_type && crc_table_init) + if ( ct == crc_type && crc_table_init) return; - + // not the same crc algo. reset table. if ( ct != crc_type) reset_table(); - + crc_type = ct; - + switch (ct) { case CRC_14443_A: case CRC_14443_B: @@ -59,9 +59,9 @@ void generate_table( uint16_t polynomial, bool refin) { c = c << 1; } - if (refin) + if (refin) crc = reflect16(crc); - + crc_table[i] = crc; } crc_table_init = true; @@ -80,20 +80,20 @@ uint16_t crc16_fast(uint8_t const *d, size_t n, uint16_t initval, bool refin, bo // only usable with polynom orders of 8, 16, 24 or 32. if (n == 0) return (~initval); - + uint16_t crc = initval; - if (refin) + if (refin) crc = reflect16(crc); - if (!refin) + if (!refin) while (n--) crc = (crc << 8) ^ crc_table[ ((crc >> 8) ^ *d++) & 0xFF ]; - else + else while (n--) crc = (crc >> 8) ^ crc_table[ (crc & 0xFF) ^ *d++]; - if (refout^refin) + if (refout^refin) crc = reflect16(crc); - + return crc; } @@ -102,14 +102,14 @@ uint16_t update_crc16_ex( uint16_t crc, uint8_t c, uint16_t polynomial ) { uint16_t i, v, tmp = 0; v = (crc ^ c) & 0xff; - + for (i = 0; i < 8; i++) { - + if ( (tmp ^ v) & 1 ) tmp = ( tmp >> 1 ) ^ polynomial; else tmp >>= 1; - + v >>= 1; } return ((crc >> 8) ^ tmp) & 0xffff; @@ -130,19 +130,19 @@ uint16_t crc16(uint8_t const *d, size_t length, uint16_t remainder, uint16_t pol // xor in at msb remainder ^= (c << 8); - - // 8 iteration loop + + // 8 iteration loop for (uint8_t j = 8; j; --j) { if (remainder & 0x8000) { remainder = (remainder << 1) ^ polynomial; } else { remainder <<= 1; } - } + } } - if (refout) + if (refout) remainder = reflect16(remainder); - + return remainder; } @@ -150,9 +150,9 @@ void compute_crc(CrcType_t ct, const uint8_t *d, size_t n, uint8_t *first, uint8 // can't calc a crc on less than 1 byte if ( n == 0 ) return; - + init_table(ct); - + uint16_t crc = 0; switch (ct) { case CRC_14443_A: crc = crc16_a(d, n); break; @@ -172,7 +172,7 @@ uint16_t crc(CrcType_t ct, const uint8_t *d, size_t n) { // can't calc a crc on less than 3 byte. (1byte + 2 crc bytes) if ( n < 3 ) return 0; - + init_table(ct); switch (ct) { case CRC_14443_A: return crc16_a(d, n); @@ -192,7 +192,7 @@ uint16_t crc(CrcType_t ct, const uint8_t *d, size_t n) { // ct crc type // d buffer with data // n length (including crc) -// +// // This function uses the message + crc bytes in order to compare the "residue" afterwards. // crc16 algos like CRC-A become 0x000 // while CRC-15693 become 0x0F47 @@ -201,14 +201,14 @@ bool check_crc(CrcType_t ct, const uint8_t *d, size_t n) { // can't calc a crc on less than 3 byte. (1byte + 2 crc bytes) if ( n < 3 ) return false; - + init_table(ct); - + switch (ct) { case CRC_14443_A: return (crc16_a(d, n) == 0); case CRC_14443_B: return (crc16_x25(d, n) == X25_CRC_CHECK); case CRC_15693: return (crc16_x25(d, n) == X25_CRC_CHECK); - case CRC_ICLASS: return (crc16_iclass(d, n) == 0); + case CRC_ICLASS: return (crc16_iclass(d, n) == 0); case CRC_FELICA: return (crc16_xmodem(d, n) == 0); //case CRC_LEGIC: case CRC_CCITT: return (crc16_ccitt(d, n) == 0); @@ -222,7 +222,7 @@ uint16_t crc16_ccitt(uint8_t const *d, size_t n) { return crc16_fast(d, n, 0xffff, false, false); } -// FDX-B ISO11784/85) uses KERMIT +// FDX-B ISO11784/85) uses KERMIT // poly=0x1021 init=0x0000 refin=true refout=true xorout=0x0000 name="KERMIT" uint16_t crc16_kermit(uint8_t const *d, size_t n) { return crc16_fast(d, n, 0x0000, true, true); @@ -231,7 +231,7 @@ uint16_t crc16_kermit(uint8_t const *d, size_t n) { // FeliCa uses XMODEM // poly=0x1021 init=0x0000 refin=false refout=false xorout=0x0000 name="XMODEM" uint16_t crc16_xmodem(uint8_t const *d, size_t n) { - return crc16_fast(d, n, 0x0000, false, false); + return crc16_fast(d, n, 0x0000, false, false); } // Following standards uses X-25 @@ -239,14 +239,14 @@ uint16_t crc16_xmodem(uint8_t const *d, size_t n) { // ISO 14443 CRC-B // ISO/IEC 13239 (formerly ISO/IEC 3309) // poly=0x1021 init=0xffff refin=true refout=true xorout=0xffff name="X-25" -uint16_t crc16_x25(uint8_t const *d, size_t n) { +uint16_t crc16_x25(uint8_t const *d, size_t n) { uint16_t crc = crc16_fast(d, n, 0xffff, true, true); crc = ~crc; return crc; } // CRC-A (14443-3) // poly=0x1021 init=0xc6c6 refin=true refout=true xorout=0x0000 name="CRC-A" -uint16_t crc16_a(uint8_t const *d, size_t n) { +uint16_t crc16_a(uint8_t const *d, size_t n) { return crc16_fast(d, n, 0xC6C6, true, true); } @@ -258,7 +258,7 @@ uint16_t crc16_iclass(uint8_t const *d, size_t n) { return crc16_fast(d, n, 0x4807, true, true); } -// This CRC-16 is used in Legic Advant systems. +// This CRC-16 is used in Legic Advant systems. // poly=0xB400, init=depends refin=true refout=true xorout=0x0000 check= name="CRC-16/LEGIC" uint16_t crc16_legic(uint8_t const *d, size_t n, uint8_t uidcrc) { uint16_t initial = uidcrc << 8 | uidcrc; diff --git a/common/crc16.h b/common/crc16.h index e4c3abac2..c11cf6351 100644 --- a/common/crc16.h +++ b/common/crc16.h @@ -47,7 +47,7 @@ uint16_t crc16_kermit(uint8_t const *d, size_t n); // Calculate CRC-16/XMODEM (FeliCa) uint16_t crc16_xmodem(uint8_t const *d, size_t n); -// Calculate CRC-16/X25 (ISO15693, ISO14443 CRC-B,ISO/IEC 13239) +// Calculate CRC-16/X25 (ISO15693, ISO14443 CRC-B,ISO/IEC 13239) uint16_t crc16_x25(uint8_t const *d, size_t n); // Calculate CRC-16/CRC-A (ISO14443 CRC-A) diff --git a/common/default_version.c b/common/default_version.c index b564681c7..b143afd4c 100644 --- a/common/default_version.c +++ b/common/default_version.c @@ -1,9 +1,9 @@ #include "proxmark3.h" /* This is the default version.c file that Makefile.common falls back to if perl is not available */ -const struct version_information __attribute__((section(".version_information"))) version_information = { - VERSION_INFORMATION_MAGIC, +const struct version_information __attribute__((section(".version_information"))) version_information = { + VERSION_INFORMATION_MAGIC, 1, /* version 1 */ 0, /* version information not present */ 2, /* cleanliness couldn't be determined */ /* Remaining fields: zero */ -}; +}; diff --git a/common/desfire.h b/common/desfire.h index a2b0599e9..81ca57b92 100644 --- a/common/desfire.h +++ b/common/desfire.h @@ -91,7 +91,7 @@ struct desfire_tag { desfirekey_t session_key; enum DESFIRE_AUTH_SCHEME authentication_scheme; uint8_t authenticated_key_no; - + uint8_t ivect[MAX_CRYPTO_BLOCK_SIZE]; uint8_t cmac[16]; uint8_t *crypto_buffer; diff --git a/common/emvtags.h b/common/emvtags.h index beecd5716..72cd34ccb 100644 --- a/common/emvtags.h +++ b/common/emvtags.h @@ -1,13 +1,13 @@ //----------------------------------------------------------------------------- // Peter Fillmore 2014 // code derived off merloks mifare code -// +// // // This code is licensed to you under the terms of the GNU GPL, version 2 or, // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// structure to hold EMV card and terminal parameters +// structure to hold EMV card and terminal parameters //----------------------------------------------------------------------------- #ifndef __EMVCARD_H #define __EMVCARD_H @@ -16,133 +16,133 @@ #include //structure to hold received/set tag values -//variable data inputs have length specifiers +//variable data inputs have length specifiers typedef struct { //ISO14443-A card stuff - uint8_t ATQA[2]; //Answer to Request - uint8_t UID_len; - uint8_t UID[10]; + uint8_t ATQA[2]; //Answer to Request + uint8_t UID_len; + uint8_t UID[10]; uint8_t SAK1; //SAK for UID 1 uint8_t SAK2; //SAK for UID 2 - uint8_t ATS_len; //Answer to select - uint8_t ATS[256]; - //ATS + uint8_t ATS_len; //Answer to select + uint8_t ATS[256]; + //ATS uint8_t TL; uint8_t T0; uint8_t TA1; uint8_t TB1; uint8_t TC1; uint8_t* historicalbytes; - //PPS response + //PPS response uint8_t PPSS; - //SFI 2 record 1 - uint8_t tag_4F_len; //length of AID - uint8_t tag_4F[16]; //Application Identifier (AID) - uint8_t tag_50_len; //length of application label + //SFI 2 record 1 + uint8_t tag_4F_len; //length of AID + uint8_t tag_4F[16]; //Application Identifier (AID) + uint8_t tag_50_len; //length of application label uint8_t tag_50[16]; //Application Label - uint8_t tag_56_len; //track1 length + uint8_t tag_56_len; //track1 length uint8_t tag_56[76]; //Track 1 Data - uint8_t tag_57_len; //track2 equiv len + uint8_t tag_57_len; //track2 equiv len uint8_t tag_57[19]; //Track 2 Equivalent Data - uint8_t tag_5A_len; //PAN length + uint8_t tag_5A_len; //PAN length uint8_t tag_5A[10]; //Application Primary Account Number (PAN) //uint8_t tag_6F[]; //File Control Information (FCI) Template //uint8_t tag_70[255]; //Record Template //uint8_t tag_77[]; //Response Message Template Format 2 - //uint8_t tag_80[]; //Response Message Template Format 1 + //uint8_t tag_80[]; //Response Message Template Format 1 uint8_t tag_82[2]; //Application Interchange Profile AIP //uint8_t tag_83[]; //Command Template - uint8_t tag_84_len; + uint8_t tag_84_len; uint8_t tag_84[16]; //DF Name - uint8_t tag_86_len; + uint8_t tag_86_len; uint8_t tag_86[261]; //Issuer Script Command uint8_t tag_87[1]; //Application Priority Indicator uint8_t tag_88[1]; //Short File Identifier uint8_t tag_8A[2]; //Authorisation Response Code - uint8_t tag_8C_len; + uint8_t tag_8C_len; uint8_t tag_8C[252]; //CDOL1 - uint8_t tag_8D_len; + uint8_t tag_8D_len; uint8_t tag_8D[252]; //CDOL2 - uint8_t tag_8E_len; + uint8_t tag_8E_len; uint8_t tag_8E[252]; //Cardholder Verification Method (CVM) List uint8_t tag_8F[1]; //Certification Authority Public Key Index - uint8_t tag_90_len; + uint8_t tag_90_len; uint8_t tag_90[255]; //ssuer Public Key Certificate - uint8_t tag_92_len; + uint8_t tag_92_len; uint8_t tag_92[255]; //Issuer Public Key Remainder - uint8_t tag_93_len; + uint8_t tag_93_len; uint8_t tag_93[255]; //Signed Static Application Data - uint8_t tag_94_len; + uint8_t tag_94_len; uint8_t tag_94[252]; //Application File Locator AFL uint8_t tag_95[5]; //Terminal Verification Results - uint8_t tag_97_len; + uint8_t tag_97_len; uint8_t tag_97[252]; //Transaction Certificate Data Object List (TDOL) - uint8_t tag_98[20]; //Transaction Certificate (TC) Hash Value + uint8_t tag_98[20]; //Transaction Certificate (TC) Hash Value //assume 20 bytes, change after testing - uint8_t tag_99_len; - uint8_t tag_99[20]; //Transaction Personal Identification Number (PIN) Data - uint8_t tag_9A[3]; //Transaction Date - uint8_t tag_9B[2]; //Transaction Status Information + uint8_t tag_99_len; + uint8_t tag_99[20]; //Transaction Personal Identification Number (PIN) Data + uint8_t tag_9A[3]; //Transaction Date + uint8_t tag_9B[2]; //Transaction Status Information uint8_t tag_9C[1]; //Transaction Type uint8_t tag_9D_len; uint8_t tag_9D[16]; //Directory Definition File - + uint8_t tag_CD[3]; //Card Issuer Action Codes Paypass uint8_t tag_CE[3]; uint8_t tag_CF[3]; - + uint8_t tag_D7[3]; //Application Control (PayPass) - uint8_t tag_D8[2]; //Application Interchange Profile (PayPass) - uint8_t tag_D9_len; //Application File Locator (PayPass) - uint8_t tag_D9[16]; - uint8_t tag_DA[2]; //Static CVC3track1 - uint8_t tag_DB[2]; //Static CVC3track2 - uint8_t tag_DC[2]; //IVCVC3 CVC3track1 - uint8_t tag_DD[2]; //IVCVC3 CVC3track2 - - uint8_t tag_AF_len; - uint8_t tag_AF[255]; //Proprietary Information - - uint8_t tag_5F20_len; + uint8_t tag_D8[2]; //Application Interchange Profile (PayPass) + uint8_t tag_D9_len; //Application File Locator (PayPass) + uint8_t tag_D9[16]; + uint8_t tag_DA[2]; //Static CVC3track1 + uint8_t tag_DB[2]; //Static CVC3track2 + uint8_t tag_DC[2]; //IVCVC3 CVC3track1 + uint8_t tag_DD[2]; //IVCVC3 CVC3track2 + + uint8_t tag_AF_len; + uint8_t tag_AF[255]; //Proprietary Information + + uint8_t tag_5F20_len; uint8_t tag_5F20[26]; //Cardholder Name - uint8_t tag_5F24[3]; //Application Expiry Date + uint8_t tag_5F24[3]; //Application Expiry Date uint8_t tag_5F25[3]; //Application Effective Date YYMMDD - uint8_t tag_5F28[2]; //Issuer Country Code + uint8_t tag_5F28[2]; //Issuer Country Code uint8_t tag_5F2A[2]; //Transaction Currency Code - uint8_t tag_5F2D_len; + uint8_t tag_5F2D_len; uint8_t tag_5F2D[8]; //Language Preference uint8_t tag_5F30[2]; //Service Code uint8_t tag_5F34[1]; //Application Primary Account Number (PAN) Sequence Number uint8_t tag_5F36[2]; //ATC - uint8_t tag_5F50_len; - uint8_t tag_5F50[255]; //Issuer URL - uint8_t tag_5F54_len; - uint8_t tag_5F54[11]; //Bank Identifier Code (BIC) - uint8_t tag_9F01[6]; //Acquirer Identifier + uint8_t tag_5F50_len; + uint8_t tag_5F50[255]; //Issuer URL + uint8_t tag_5F54_len; + uint8_t tag_5F54[11]; //Bank Identifier Code (BIC) + uint8_t tag_9F01[6]; //Acquirer Identifier uint8_t tag_9F02[6]; // Amount, Authorised (Numeric) - uint8_t tag_9F03[6]; //Amount, Other (Numeric) + uint8_t tag_9F03[6]; //Amount, Other (Numeric) uint8_t tag_9F04[4]; //Amount, Other (Binary) - uint8_t tag_9F05_len; - uint8_t tag_9F05[32]; //Application Discretionary Data - uint8_t tag_9F06_len; - uint8_t tag_9F06[16]; //AID terminal - uint8_t tag_9F07[2]; //Application Usage Control - uint8_t tag_9F08[2]; //Application Version Number + uint8_t tag_9F05_len; + uint8_t tag_9F05[32]; //Application Discretionary Data + uint8_t tag_9F06_len; + uint8_t tag_9F06[16]; //AID terminal + uint8_t tag_9F07[2]; //Application Usage Control + uint8_t tag_9F08[2]; //Application Version Number uint8_t tag_9F09[2]; //Application Version Number - //uint8_t tag_9F0A[2] - uint8_t tag_9F0B_len; + //uint8_t tag_9F0A[2] + uint8_t tag_9F0B_len; uint8_t tag_9F0B[45]; //Cardholder Name Extended - uint8_t tag_9F0D[5]; //Issuer Action Code - Default - uint8_t tag_9F0E[5]; //Issuer Action Code - Denial - uint8_t tag_9F0F[5]; //Issuer Action Code - Online + uint8_t tag_9F0D[5]; //Issuer Action Code - Default + uint8_t tag_9F0E[5]; //Issuer Action Code - Denial + uint8_t tag_9F0F[5]; //Issuer Action Code - Online uint8_t tag_9F10_len; //Issuer Application Data - uint8_t tag_9F10[32]; + uint8_t tag_9F10[32]; uint8_t tag_9F11[1]; //Issuer Code Table Index - uint8_t tag_9F12_len; - uint8_t tag_9F12[255]; //Application Preferred Name - uint8_t tag_9F13[2]; //Last Online Application Transaction Counter (ATC) Registerjk + uint8_t tag_9F12_len; + uint8_t tag_9F12[255]; //Application Preferred Name + uint8_t tag_9F13[2]; //Last Online Application Transaction Counter (ATC) Registerjk uint8_t tag_9F14[1]; //Lower Consecutive Offline Limit - uint8_t tag_9F15[2]; //Merchant Category Code + uint8_t tag_9F15[2]; //Merchant Category Code uint8_t tag_9F16[15]; //Merchant Identifier uint8_t tag_9F17[1]; //Personal Identification Number (PIN) Try Counter uint8_t tag_9F18[4]; //Issuer Script Identifier @@ -150,41 +150,41 @@ typedef struct { uint8_t tag_9F1A[2]; //Terminal Country Code uint8_t tag_9F1B[4]; //Terminal Floor Limit uint8_t tag_9F1C[8]; //Terminal Identification - uint8_t tag_9F1D_len; - uint8_t tag_9F1D[8]; //Terminal Risk Management Data - uint8_t tag_9F1E[8]; //Interface Device (IFD) Serial Number + uint8_t tag_9F1D_len; + uint8_t tag_9F1D[8]; //Terminal Risk Management Data + uint8_t tag_9F1E[8]; //Interface Device (IFD) Serial Number uint8_t tag_9F1F_len; - uint8_t tag_9F1F[255]; //Track 1 Discretionary Data + uint8_t tag_9F1F[255]; //Track 1 Discretionary Data uint8_t tag_9F20_len; - uint8_t tag_9F20[255]; //Track 2 DD + uint8_t tag_9F20[255]; //Track 2 DD uint8_t tag_9F21[3]; //Transaction Time uint8_t tag_9F22[1]; //Certification Authority Public Key Index uint8_t tag_9F23[1]; //Upper Consecutive Offline Limit - //uint8_t tag_9F24 - //uint8_t tag_9F25 + //uint8_t tag_9F24 + //uint8_t tag_9F25 uint8_t tag_9F26[8]; //Application Cryptogram uint8_t tag_9F27[1]; //Cryptogram Information Data - //uint8_t tag_9F28 - //uint8_t tag_9F29 + //uint8_t tag_9F28 + //uint8_t tag_9F29 //uint8_t tag_9F2A //uint8_t tag_9F2B //uint8_t tag_9F2C - uint8_t tag_9F2D_len; + uint8_t tag_9F2D_len; uint8_t tag_9F2D[255]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Certificate uint8_t tag_9F2E[3]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Exponent - uint8_t tag_9F2F_len; - uint8_t tag_9F2F[255]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Remainder - //uint8_t tag_9F30 - //uint8_t tag_9F31 - uint8_t tag_9F32_len; + uint8_t tag_9F2F_len; + uint8_t tag_9F2F[255]; //Integrated Circuit Card (ICC) PIN Encipherment Public Key Remainder + //uint8_t tag_9F30 + //uint8_t tag_9F31 + uint8_t tag_9F32_len; uint8_t tag_9F32[3]; //Issuer Public Key Exponent uint8_t tag_9F33[3]; //Terminal Capabilities - uint8_t tag_9F34[3]; //Cardholder Verification Method (CVM) Results + uint8_t tag_9F34[3]; //Cardholder Verification Method (CVM) Results uint8_t tag_9F35[1]; //Terminal Type uint8_t tag_9F36[2]; //Application Transaction Counter (ATC) uint8_t tag_9F37[8]; //Unpredictable Number - uint8_t tag_9F38_len; - uint8_t tag_9F38[255]; //PDOL + uint8_t tag_9F38_len; + uint8_t tag_9F38[255]; //PDOL uint8_t tag_9F39[1]; //Point-of-Service (POS) Entry Mode uint8_t tag_9F40[5]; //Additional Terminal Capabilities uint8_t tag_9F41[4]; //Transaction Sequence Counter @@ -192,21 +192,21 @@ typedef struct { uint8_t tag_9F43[4]; //Application Reference Currency Exponent uint8_t tag_9F44[1]; //Application Currency Exponent uint8_t tag_9F45[2]; //Data Authentication Code - uint8_t tag_9F46_len; + uint8_t tag_9F46_len; uint8_t tag_9F46[255]; //ICC Public Key Certificate - uint8_t tag_9F47_len; + uint8_t tag_9F47_len; uint8_t tag_9F47[3]; //ICC Public Key Exponent - uint8_t tag_9F48_len; + uint8_t tag_9F48_len; uint8_t tag_9F48[255]; //ICC Public Key Remainder - uint8_t tag_9F49_len; - uint8_t tag_9F49[252]; + uint8_t tag_9F49_len; + uint8_t tag_9F49[252]; uint8_t tag_9F4A[1]; //SDA Tag list - uint8_t tag_9F4B_len; - uint8_t tag_9F4B[255]; //Signed Dynamic Application Data + uint8_t tag_9F4B_len; + uint8_t tag_9F4B[255]; //Signed Dynamic Application Data uint8_t tag_9F4C[8]; //ICC Dynamic Number uint8_t tag_9F4D[2]; //Log Entry uint8_t tag_9F4E[255]; //Merchant Name and Location - //9F50-9F7F are payment system specific + //9F50-9F7F are payment system specific uint8_t tag_9F60[2]; //CVC3 track1 uint8_t tag_9F61[2]; //CVC3 track2 uint8_t tag_9F62[6]; //Track 1 Bit Map for CVC3 (PCVC3TRACK1) @@ -215,33 +215,33 @@ typedef struct { uint8_t tag_9F65[2]; //rack 2 Bit Map for CVC3 (PCVC3TRACK2) uint8_t tag_9F66[4]; //Track 2 Bit Map for UN and ATC (PUNATCTRACK2), or VISA card type uint8_t tag_9F67[1]; //Track 2 Number of ATC Digits (NATCTRACK2) - uint8_t tag_9F68_len; + uint8_t tag_9F68_len; uint8_t tag_9F68[252]; //Mag Stripe CVM List - uint8_t tag_9F69_len; + uint8_t tag_9F69_len; uint8_t tag_9F69[255]; //Unpredictable Number Data Object List (UDOL) uint8_t tag_9F6A[8]; //Unpredictable Number (Numeric) - uint8_t tag_9F6B_len; + uint8_t tag_9F6B_len; uint8_t tag_9F6B[19]; //track 2 data uint8_t tag_9F6C[2]; //Mag Stripe Application Version Number(Card) //template holders - uint8_t tag_61_len; + uint8_t tag_61_len; uint8_t tag_61[255]; //Application template - uint8_t tag_6F_len; + uint8_t tag_6F_len; uint8_t tag_6F[255]; //6F template - uint8_t tag_A5_len; - uint8_t tag_A5[255]; //A5 template - uint8_t tag_DFNAME_len; - uint8_t tag_DFNAME[255]; //A5 template - uint8_t tag_70_len; + uint8_t tag_A5_len; + uint8_t tag_A5[255]; //A5 template + uint8_t tag_DFNAME_len; + uint8_t tag_DFNAME[255]; //A5 template + uint8_t tag_70_len; uint8_t tag_70[255]; //70 template - uint8_t tag_77_len; + uint8_t tag_77_len; uint8_t tag_77[255]; //77 template - uint8_t tag_80_len; - uint8_t tag_80[255]; //80 template - uint8_t tag_91_len; //Issuer Authentication Data - uint8_t tag_91[16]; - uint8_t tag_BF0C_len; - uint8_t tag_BF0C[222]; //File Control Information (FCI) Issuer Discretionary Data + uint8_t tag_80_len; + uint8_t tag_80[255]; //80 template + uint8_t tag_91_len; //Issuer Authentication Data + uint8_t tag_91[16]; + uint8_t tag_BF0C_len; + uint8_t tag_BF0C[222]; //File Control Information (FCI) Issuer Discretionary Data uint8_t tag_DFName[16]; uint8_t tag_DFName_len; }emvtags; diff --git a/common/i2c.c b/common/i2c.c index 53627966e..dff77a05a 100644 --- a/common/i2c.c +++ b/common/i2c.c @@ -22,7 +22,7 @@ #define SCL_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SCL) #define SDA_read (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SDA) -#define I2C_ERROR "I2C_WaitAck Error" +#define I2C_ERROR "I2C_WaitAck Error" volatile unsigned long c; @@ -42,24 +42,24 @@ void __attribute__((optimize("O0"))) I2CSpinDelayClk(uint16_t delay) { // try i2c bus recovery at 100kHz = 5uS high, 5uS low void I2C_recovery(void) { - - DbpString("Performing i2c bus recovery"); - + + DbpString("Performing i2c bus recovery"); + // reset I2C SDA_H; SCL_H; - + //9nth cycle acts as NACK for (int i = 0; i < 10; i++) { SCL_H; WaitUS(5); SCL_L; WaitUS(5); } - - //a STOP signal (SDA from low to high while CLK is high) + + //a STOP signal (SDA from low to high while CLK is high) SDA_L; WaitUS(5); SCL_H; WaitUS(2); SDA_H; WaitUS(2); - - bool isok = (SCL_read && SDA_read); + + bool isok = (SCL_read && SDA_read); if (!SDA_read) DbpString("I2C bus recovery error: SDA still LOW"); if (!SCL_read) @@ -72,7 +72,7 @@ void I2C_init(void) { // Configure reset pin, close up pull up, push-pull output, default high AT91C_BASE_PIOA->PIO_PPUDR = GPIO_RST; AT91C_BASE_PIOA->PIO_MDDR = GPIO_RST; - + // Configure I2C pin, open up, open leakage AT91C_BASE_PIOA->PIO_PPUER |= (GPIO_SCL | GPIO_SDA); AT91C_BASE_PIOA->PIO_MDER |= (GPIO_SCL | GPIO_SDA); @@ -82,12 +82,12 @@ void I2C_init(void) { AT91C_BASE_PIOA->PIO_OER |= (GPIO_SCL | GPIO_SDA | GPIO_RST); AT91C_BASE_PIOA->PIO_PER |= (GPIO_SCL | GPIO_SDA | GPIO_RST); - - - bool isok = (SCL_read && SDA_read); + + + bool isok = (SCL_read && SDA_read); if ( !isok ) I2C_recovery(); - + } // set the reset state @@ -132,7 +132,7 @@ void I2C_Reset_EnterBootloader(void) { WaitMS(10); } -// Wait for the clock to go High. +// Wait for the clock to go High. bool WaitSCL_H_delay(uint32_t delay) { while (delay--) { if (SCL_read) { @@ -154,9 +154,9 @@ bool WaitSCL_L_delay(uint32_t delay) { if (!SCL_read) { return true; } - I2C_DELAY_1CLK; + I2C_DELAY_1CLK; } - return false; + return false; } // 5000 * 3.07us = 15350us. 15.35ms bool WaitSCL_L(void) { @@ -168,25 +168,25 @@ bool WaitSCL_L(void) { // Which ever comes first bool WaitSCL_L_timeout(void){ volatile uint16_t delay = 1800; - while ( delay-- ) { + while ( delay-- ) { // exit on SCL LOW if (!SCL_read) return true; - + WaitMS(1); } return (delay == 0); } bool I2C_Start(void) { - + I2C_DELAY_XCLK(4); SDA_H; I2C_DELAY_1CLK; - SCL_H; + SCL_H; if (!WaitSCL_H()) return false; I2C_DELAY_2CLK; - + if (!SCL_read) return false; if (!SDA_read) return false; @@ -224,7 +224,7 @@ void I2C_Ack(void) { SCL_L; I2C_DELAY_2CLK; SDA_L; I2C_DELAY_2CLK; SCL_H; I2C_DELAY_2CLK; - if (!WaitSCL_H()) return; + if (!WaitSCL_H()) return; SCL_L; I2C_DELAY_2CLK; } @@ -233,7 +233,7 @@ void I2C_NoAck(void) { SCL_L; I2C_DELAY_2CLK; SDA_H; I2C_DELAY_2CLK; SCL_H; I2C_DELAY_2CLK; - if (!WaitSCL_H()) return; + if (!WaitSCL_H()) return; SCL_L; I2C_DELAY_2CLK; } @@ -259,16 +259,16 @@ void I2C_SendByte(uint8_t data) { while (bits--) { SCL_L; - + I2C_DELAY_1CLK; - + if (data & 0x80) SDA_H; else SDA_L; - + data <<= 1; - + I2C_DELAY_1CLK; SCL_H; @@ -286,11 +286,11 @@ int16_t I2C_ReadByte(void) { SDA_H; while (bits--) { b <<= 1; - SCL_L; + SCL_L; if (!WaitSCL_L()) return -2; - + I2C_DELAY_1CLK; - + SCL_H; if (!WaitSCL_H()) return -1; @@ -375,13 +375,13 @@ bool I2C_BufferWrite(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t dev break; while (len) { - + I2C_SendByte(*data); if (!I2C_WaitAck()) break; len--; - data++; + data++; } if (len == 0) @@ -393,7 +393,7 @@ bool I2C_BufferWrite(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t dev if ( MF_DBGLEVEL > 3 ) DbpString(I2C_ERROR); return false; } - return true; + return true; } // read one array of data (Data array, Readout length, command to be written , SlaveDevice address ). @@ -408,7 +408,7 @@ int16_t I2C_BufferRead(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t d WaitUS(600); bool bBreak = true; uint16_t readcount = 0; - + do { if (!I2C_Start()) return 0; @@ -421,7 +421,7 @@ int16_t I2C_BufferRead(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t d I2C_SendByte(device_cmd); if (!I2C_WaitAck()) break; - + // 0xB1 / 0xC1 == i2c read I2C_Start(); I2C_SendByte(device_address | 1); @@ -442,35 +442,35 @@ int16_t I2C_BufferRead(uint8_t *data, uint8_t len, uint8_t device_cmd, uint8_t d int16_t tmp = I2C_ReadByte(); if ( tmp < 0 ) return tmp; - + *data = (uint8_t)tmp & 0xFF; len--; - // ¶ÁÈ¡µÄµÚÒ»¸ö×Ö½ÚΪºóÐø³¤¶È + // ¶ÁÈ¡µÄµÚÒ»¸ö×Ö½ÚΪºóÐø³¤¶È // The first byte in response is the message length if (!readcount && (len > *data)) { len = *data; } else { - data++; + data++; } readcount++; - + // acknowledgements. After last byte send NACK. if (len == 0) I2C_NoAck(); else I2C_Ack(); } - + I2C_Stop(); - + // return bytecount - first byte (which is length byte) return --readcount; } int16_t I2C_ReadFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address) { - //START, 0xB0, 0x00, 0x00, START, 0xB1, xx, yy, zz, ......, STOP + //START, 0xB0, 0x00, 0x00, START, 0xB1, xx, yy, zz, ......, STOP bool bBreak = true; uint8_t readcount = 0; @@ -491,7 +491,7 @@ int16_t I2C_ReadFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t I2C_SendByte(lsb); if (!I2C_WaitAck()) break; - + // 0xB1 / 0xC1 i2c read I2C_Start(); I2C_SendByte(device_address | 1); @@ -509,30 +509,30 @@ int16_t I2C_ReadFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t // reading while (len) { - + int16_t tmp = I2C_ReadByte(); if ( tmp < 0 ) return tmp; - + *data = (uint8_t)tmp & 0xFF; data++; readcount++; len--; - // acknowledgements. After last byte send NACK. + // acknowledgements. After last byte send NACK. if (len == 0) I2C_NoAck(); else I2C_Ack(); } - + I2C_Stop(); return readcount; } bool I2C_WriteFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t device_address) { - //START, 0xB0, 0x00, 0x00, xx, yy, zz, ......, STOP + //START, 0xB0, 0x00, 0x00, xx, yy, zz, ......, STOP bool bBreak = true; do { @@ -543,7 +543,7 @@ bool I2C_WriteFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t d I2C_SendByte(device_address & 0xFE); if (!I2C_WaitAck()) break; - + I2C_SendByte(msb); if (!I2C_WaitAck()) break; @@ -558,7 +558,7 @@ bool I2C_WriteFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t d break; len--; - data++; + data++; } if (len == 0) @@ -570,7 +570,7 @@ bool I2C_WriteFW(uint8_t *data, uint8_t len, uint8_t msb, uint8_t lsb, uint8_t d if ( MF_DBGLEVEL > 3 ) DbpString(I2C_ERROR); return false; } - return true; + return true; } void I2C_print_status(void) { @@ -581,7 +581,7 @@ void I2C_print_status(void) { if ( len > 0 ) Dbprintf(" version.................v%x.%02d", resp[0], resp[1]); else - DbpString(" version.................FAILED"); + DbpString(" version.................FAILED"); } // Will read response from smart card module, retries 3 times to get the data. @@ -590,46 +590,46 @@ bool sc_rx_bytes(uint8_t* dest, uint8_t *destlen) { uint8_t i = 3; int16_t len = 0; while (i--) { - + I2C_WaitForSim(); - + len = I2C_BufferRead(dest, *destlen, I2C_DEVICE_CMD_READ, I2C_DEVICE_ADDRESS_MAIN); - + if ( len > 1 ){ break; } else if ( len == 1 ) { continue; } else if ( len <= 0 ) { - return false; - } + return false; + } } // after three if ( len <= 1 ) return false; - + *destlen = (uint8_t)len & 0xFF; return true; } bool GetATR(smart_card_atr_t *card_ptr) { - + if ( !card_ptr ) return false; - + card_ptr->atr_len = 0; memset(card_ptr->atr, 0, sizeof(card_ptr->atr)); - + // Send ATR // start [C0 01] stop start C1 len aa bb cc stop] I2C_WriteCmd(I2C_DEVICE_CMD_GENERATE_ATR, I2C_DEVICE_ADDRESS_MAIN); //wait for sim card to answer. // 1byte = 1ms , max frame 256bytes. SHould wait 256ms atleast just in case. - if (!I2C_WaitForSim()) + if (!I2C_WaitForSim()) return false; - + // read bytes from module uint8_t len = sizeof(card_ptr->atr); if ( !sc_rx_bytes(card_ptr->atr, &len) ) @@ -639,12 +639,12 @@ bool GetATR(smart_card_atr_t *card_ptr) { if ( (card_ptr->atr[1] & 0x10) == 0x10) pos_td++; if ( (card_ptr->atr[1] & 0x20) == 0x20) pos_td++; if ( (card_ptr->atr[1] & 0x40) == 0x40) pos_td++; - + // T0 indicate presence T=0 vs T=1. T=1 has checksum TCK if ( (card_ptr->atr[1] & 0x80) == 0x80) { - + pos_td++; - + // 1 == T1 , presence of checksum TCK if ( (card_ptr->atr[pos_td] & 0x01) == 0x01) { @@ -683,16 +683,16 @@ void SmartCardRaw( uint64_t arg0, uint64_t arg1, uint8_t *data ) { uint8_t len = 0; uint8_t *resp = BigBuf_malloc(ISO7618_MAX_FRAME); smartcard_command_t flags = arg0; - + if ((flags & SC_CONNECT)) clear_trace(); set_tracing(true); - - if ((flags & SC_CONNECT)) { + + if ((flags & SC_CONNECT)) { I2C_Reset_EnterMainProgram(); - + if ((flags & SC_SELECT)) { smart_card_atr_t card; bool gotATR = GetATR( &card ); @@ -703,15 +703,15 @@ void SmartCardRaw( uint64_t arg0, uint64_t arg1, uint8_t *data ) { } if ((flags & SC_RAW) || (flags & SC_RAW_T0)) { - + LogTrace(data, arg1, 0, 0, NULL, true); - + // Send raw bytes // asBytes = A0 A4 00 00 02 // arg1 = len 5 bool res = I2C_BufferWrite(data, arg1, ((flags & SC_RAW_T0) ? I2C_DEVICE_CMD_SEND_T0 : I2C_DEVICE_CMD_SEND), I2C_DEVICE_ADDRESS_MAIN); - if ( !res && MF_DBGLEVEL > 3 ) DbpString(I2C_ERROR); - + if ( !res && MF_DBGLEVEL > 3 ) DbpString(I2C_ERROR); + // read bytes from module len = ISO7618_MAX_FRAME; res = sc_rx_bytes(resp, &len); @@ -721,11 +721,11 @@ void SmartCardRaw( uint64_t arg0, uint64_t arg1, uint8_t *data ) { len = 0; } } -OUT: +OUT: cmd_send(CMD_ACK, len, 0, 0, resp, len); BigBuf_free(); set_tracing(false); - LEDsoff(); + LEDsoff(); } void SmartCardUpgrade(uint64_t arg0) { @@ -735,8 +735,8 @@ void SmartCardUpgrade(uint64_t arg0) { #define I2C_BLOCK_SIZE 128 // write. Sector0, with 11,22,33,44 // erase is 128bytes, and takes 50ms to execute - - I2C_Reset_EnterBootloader(); + + I2C_Reset_EnterBootloader(); bool isOK = true; int16_t res = 0; @@ -744,16 +744,16 @@ void SmartCardUpgrade(uint64_t arg0) { uint16_t pos = 0; uint8_t *fwdata = BigBuf_get_addr(); uint8_t *verfiydata = BigBuf_malloc(I2C_BLOCK_SIZE); - + while (length) { - + uint8_t msb = (pos >> 8) & 0xFF; uint8_t lsb = pos & 0xFF; - + Dbprintf("FW %02X%02X", msb, lsb); size_t size = MIN(I2C_BLOCK_SIZE, length); - + // write res = I2C_WriteFW(fwdata+pos, size, msb, lsb, I2C_DEVICE_ADDRESS_BOOT); if ( !res ) { @@ -761,7 +761,7 @@ void SmartCardUpgrade(uint64_t arg0) { isOK = false; break; } - + // writing takes time. WaitMS(50); @@ -769,23 +769,23 @@ void SmartCardUpgrade(uint64_t arg0) { res = I2C_ReadFW(verfiydata, size, msb, lsb, I2C_DEVICE_ADDRESS_BOOT); if ( res <= 0) { DbpString("Reading back failed"); - isOK = false; + isOK = false; break; } - + // cmp if ( 0 != memcmp(fwdata+pos, verfiydata, size)) { DbpString("not equal data"); - isOK = false; + isOK = false; break; } - + length -= size; pos += size; - } + } cmd_send(CMD_ACK, isOK, pos, 0, 0, 0); LED_C_OFF(); - BigBuf_free(); + BigBuf_free(); } void SmartCardSetBaud(uint64_t arg0) { @@ -793,13 +793,13 @@ void SmartCardSetBaud(uint64_t arg0) { void SmartCardSetClock(uint64_t arg0) { LED_D_ON(); - set_tracing(true); - I2C_Reset_EnterMainProgram(); + set_tracing(true); + I2C_Reset_EnterMainProgram(); // Send SIM CLC // start [C0 05 xx] stop I2C_WriteByte(arg0, I2C_DEVICE_CMD_SIM_CLC, I2C_DEVICE_ADDRESS_MAIN); - + cmd_send(CMD_ACK, 1, 0, 0, 0, 0); set_tracing(false); LEDsoff(); diff --git a/common/iso14443crc.c b/common/iso14443crc.c index 01e77c855..ceac3c4df 100644 --- a/common/iso14443crc.c +++ b/common/iso14443crc.c @@ -39,7 +39,7 @@ bool CheckCrc14443(uint16_t CrcType, const uint8_t *data, int length) { if (length < 3) return false; uint8_t b1, b2; ComputeCrc14443(CrcType, data, length - 2, &b1, &b2); - if ((b1 == data[length - 2]) && (b2 == data[length - 1])) + if ((b1 == data[length - 2]) && (b2 == data[length - 1])) return true; return false; } diff --git a/common/iso15693tools.c b/common/iso15693tools.c index 8d06c026c..fbd79da52 100644 --- a/common/iso15693tools.c +++ b/common/iso15693tools.c @@ -15,7 +15,7 @@ char* Iso15693sprintUID(char *target, uint8_t *uid) { static char tempbuf[2*8+1] = {0}; - if (target == NULL) + if (target == NULL) target = tempbuf; sprintf(target, "%02X %02X %02X %02X %02X %02X %02X %02X", uid[7], uid[6], uid[5], uid[4], diff --git a/common/iso15693tools.h b/common/iso15693tools.h index 70382ce04..0dd4d4444 100644 --- a/common/iso15693tools.h +++ b/common/iso15693tools.h @@ -39,7 +39,7 @@ //RESPONSE FLAGS #define ISO15_RES_ERROR 0x01 -#define ISO15_RES_EXT 0x08 // Protocol Extention +#define ISO15_RES_EXT 0x08 // Protocol Extention // RESPONSE ERROR CODES #define ISO15_NOERROR 0x00 @@ -47,7 +47,7 @@ #define ISO15_ERROR_CMD_NOT_REC 0x02 // Command not recognized (eg. parameter error) #define ISO15_ERROR_CMD_OPTION 0x03 // Command option not supported #define ISO15_ERROR_GENERIC 0x0F // No additional Info about this error -#define ISO15_ERROR_BLOCK_UNAVAILABLE 0x10 +#define ISO15_ERROR_BLOCK_UNAVAILABLE 0x10 #define ISO15_ERROR_BLOCK_LOCKED_ALREADY 0x11 // cannot lock again #define ISO15_ERROR_BLOCK_LOCKED 0x12 // cannot be changed #define ISO15_ERROR_BLOCK_WRITE 0x13 // Writing was unsuccessful diff --git a/common/legic_prng.c b/common/legic_prng.c index df711aa10..c4927b33b 100644 --- a/common/legic_prng.c +++ b/common/legic_prng.c @@ -11,7 +11,7 @@ // a is 7bit lsfr // b is 8bit lsfr // c keeps track on which step the prng is. -// legic_prng_get_bit() = gets a bit muxed from a and b. +// legic_prng_get_bit() = gets a bit muxed from a and b. struct lfsr { uint8_t a; uint8_t b; @@ -26,10 +26,10 @@ struct lfsr { // Now we have a special case with iv == 0 // it sets b to 0 aswell to make sure we get a all zero keystream out // which is used in the initialisation phase sending the IV -// +// void legic_prng_init(uint8_t iv) { lfsr.a = iv; - lfsr.b = 0; // hack to get a always 0 keystream + lfsr.b = 0; // hack to get a always 0 keystream lfsr.c = 0; if(iv) lfsr.b = (iv << 1) | 1; @@ -37,7 +37,7 @@ void legic_prng_init(uint8_t iv) { void legic_prng_forward(int count) { if (count == 0) return; - + lfsr.c += count; while(count--) { // According: http://www.proxmark.org/forum/viewtopic.php?pid=5437#p5437 diff --git a/common/lfdemod.c b/common/lfdemod.c index b9807ff8f..65999ae77 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -8,20 +8,20 @@ // Low frequency demod/decode commands - by marshmellow, holiman, iceman and // many others who came before // -// NOTES: +// NOTES: // LF Demod functions are placed here to allow the flexability to use client or -// device side. Most BUT NOT ALL of these functions are currenlty safe for +// device side. Most BUT NOT ALL of these functions are currenlty safe for // device side use currently. (DetectST for example...) // // There are likely many improvements to the code that could be made, please // make suggestions... // -// we tried to include author comments so any questions could be directed to +// we tried to include author comments so any questions could be directed to // the source. // // There are 4 main sections of code below: // -// Utilities Section: +// Utilities Section: // for general utilities used by multiple other functions // // Clock / Bitrate Detection Section: @@ -58,7 +58,7 @@ extern void Dbprintf(const char *fmt, ...); # include "cmdparser.h" # include "cmddata.h" # define prnt PrintAndLog -#else +#else uint8_t g_debugMode = 0; # define prnt Dbprintf #endif @@ -99,11 +99,11 @@ void computeSignalProperties(uint8_t *samples, uint32_t size) { // measure amplitude of signal signalprop.mean = sum / size; signalprop.amplitude = signalprop.high - signalprop.mean; - // By measuring mean and look at amplitude of signal from HIGH / LOW, + // By measuring mean and look at amplitude of signal from HIGH / LOW, // we can detect noise signalprop.isnoise = signalprop.amplitude < NOISE_AMPLITUDE_THRESHOLD; - if (g_debugMode) + if (g_debugMode) printSignal(); } @@ -136,17 +136,17 @@ void getHiLo(int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo) { *low = (signalprop.low * fuzzLo) / 100; } else { uint8_t range = signalprop.high - signalprop.low; - + *low = signalprop.low + ((range * (100-fuzzLo))/100); } - + // if fuzzing to great and overlap if ( *high < *low ) { *high = signalprop.high; *low = signalprop.low; } - - if (g_debugMode) + + if (g_debugMode) prnt("getHiLo fuzzed: High %d | Low %d", *high, *low); } @@ -159,7 +159,7 @@ bool parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType) { //by marshmellow // takes a array of binary values, start position, length of bits per parity (includes parity bit - MAX 32), -// Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run) +// Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run) size_t removeParity(uint8_t *bits, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) { uint32_t parityWd = 0; size_t bitCnt = 0; @@ -201,7 +201,7 @@ size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, u switch (pType) { case 3: dest[j++]=0; break; // marker bit which should be a 0 case 2: dest[j++]=1; break; // marker bit which should be a 1 - default: + default: dest[j++] = parityTest(parityWd, pLen-1, pType) ^ 1; break; } @@ -216,7 +216,7 @@ size_t addParity(uint8_t *src, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, u // array must be size dividable with 8 uint8_t bits_to_array(const uint8_t *bits, size_t size, uint8_t *dest) { if ( (size == 0) || (size % 8) != 0) return 0; - + for(uint32_t i = 0; i < (size / 8); i++) dest[i] = bytebits_to_byte((uint8_t *) bits + (i * 8), 8); @@ -247,14 +247,14 @@ bool preambleSearch(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, return preambleSearchEx(bits, preamble, pLen, size, startIdx, false); } //by marshmellow -// search for given preamble in given BitStream and return success=1 or fail=0 and startIndex (where it was found) and length if not fineone +// search for given preamble in given BitStream and return success=1 or fail=0 and startIndex (where it was found) and length if not fineone // fineone does not look for a repeating preamble for em4x05/4x69 sends preamble once, so look for it once in the first pLen bits //(iceman) FINDONE, only finds start index. NOT SIZE!. I see Em410xDecode (lfdemod.c) uses SIZE to determine success bool preambleSearchEx(uint8_t *bits, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx, bool findone) { // Sanity check. If preamble length is bigger than bits length. if ( *size <= pLen ) return false; - + uint8_t foundCnt = 0; for (size_t idx = 0; idx < *size - pLen; idx++) { if (memcmp(bits+idx, preamble, pLen) == 0){ @@ -284,12 +284,12 @@ size_t findModStart(uint8_t *src, size_t size, uint8_t expWaveSize) { for (; i < size-20; i++ ) { if (src[i] < signalprop.mean && isAboveThreshold) { thresholdCnt++; - if (thresholdCnt > 2 && waveSizeCnt < expWaveSize+1) break; + if (thresholdCnt > 2 && waveSizeCnt < expWaveSize+1) break; isAboveThreshold = false; waveSizeCnt = 0; } else if (src[i] >= signalprop.mean && !isAboveThreshold) { thresholdCnt++; - if (thresholdCnt > 2 && waveSizeCnt < expWaveSize+1) break; + if (thresholdCnt > 2 && waveSizeCnt < expWaveSize+1) break; isAboveThreshold = true; waveSizeCnt = 0; } else { @@ -326,13 +326,13 @@ void getNextHigh(uint8_t *samples, size_t size, int high, size_t *i) { bool loadWaveCounters(uint8_t *samples, size_t size, int lowToLowWaveLen[], int highToLowWaveLen[], int *waveCnt, int *skip, int *minClk, int *high, int *low) { size_t i = 0, firstLow, firstHigh; //size_t testsize = (size < 512) ? size : 512; - + // just noise - no super good detection. good enough if (signalprop.isnoise) { if (g_debugMode == 2) prnt("DEBUG STT: just noise detected - quitting"); return false; } - + getHiLo(high, low, 80, 80); // get to first full low to prime loop and skip incomplete first pulse @@ -354,7 +354,7 @@ bool loadWaveCounters(uint8_t *samples, size_t size, int lowToLowWaveLen[], int break; highToLowWaveLen[*waveCnt] = i - firstHigh; //first high to first low - lowToLowWaveLen[*waveCnt] = i - firstLow; + lowToLowWaveLen[*waveCnt] = i - firstLow; *waveCnt += 1; if (i-firstLow < *minClk && i < size) { *minClk = i - firstLow; @@ -399,7 +399,7 @@ void askAmp(uint8_t *bits, size_t size) { last = 255; else if ( bits[i-1] - bits[i] >= 20) //large jump down last = 0; - + bits[i] = last; } } @@ -416,7 +416,7 @@ uint32_t manchesterEncode2Bytes(uint16_t datain) { } //by marshmellow -//encode binary data into binary manchester +//encode binary data into binary manchester //NOTE: bitstream must have triple the size of "size" available in memory to do the swap int ManchesterEncode(uint8_t *bits, size_t size) { //allow up to 4096b out (means bits must be at least 2048+4096 to handle the swap) @@ -440,18 +440,18 @@ bool DetectCleanAskWave(uint8_t *dest, size_t size, uint8_t high, uint8_t low) { bool allArePeaks = true; uint16_t cntPeaks = 0; size_t loopEnd = 512 + 160; - + // sanity check if (loopEnd > size) loopEnd = size; - + for (size_t i = 160; i < loopEnd; i++){ - - if (dest[i] > low && dest[i] < high) + + if (dest[i] > low && dest[i] < high) allArePeaks = false; else cntPeaks++; } - + if (!allArePeaks){ if (cntPeaks > 250) return true; } @@ -472,11 +472,11 @@ int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clo size_t i = 100; size_t minClk = 512; int shortestWaveIdx = 0; - + // get to first full low to prime loop and skip incomplete first pulse getNextHigh(dest, size, high, &i); getNextLow(dest, size, low, &i); - + // loop through all samples (well, we don't want to go out-of-bounds) while (i < size-512) { // measure from low to low @@ -491,14 +491,14 @@ int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clo shortestWaveIdx = startwave; } } - + // set clock if (g_debugMode == 2) prnt("DEBUG ASK: DetectStrongAskClock smallest wave: %d", minClk); *clock = getClosestClock(minClk); - if (*clock == 0) + if (*clock == 0) return -1; - + return shortestWaveIdx; } @@ -509,27 +509,27 @@ int DetectStrongAskClock(uint8_t *dest, size_t size, int high, int low, int *clo int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { //don't need to loop through entire array. (cotag has clock of 384) - uint16_t loopCnt = 1500; + uint16_t loopCnt = 1500; // not enough samples if (size <= loopCnt + 60){ if (g_debugMode == 2) prnt("DEBUG DetectASKClock: not enough samples - aborting"); - return -1; + return -1; } - + // just noise - no super good detection. good enough if (signalprop.isnoise) { if (g_debugMode == 2) prnt("DEBUG DetectASKClock: just noise detected - aborting"); return -2; } - + size_t i = 1; uint16_t num_clks = 9; // first 255 value pos0 is placeholder for user inputed clock. uint16_t clk[] = {255, 8, 16, 32, 40, 50, 64, 100, 128, 255}; - + // sometimes there is a strange end wave - filter out this - size -= 60; + size -= 60; // What is purpose? // already have a valid clock? @@ -543,28 +543,28 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { // threshold 75% of high, low peak int peak_hi, peak_low; getHiLo(&peak_hi, &peak_low, 75, 75); - + // test for large clean, STRONG, CLIPPED peaks - + if (!found_clk) { - + if (DetectCleanAskWave(dest, size, peak_hi, peak_low)){ - + int idx = DetectStrongAskClock(dest, size, peak_hi, peak_low, clock); - if (g_debugMode == 2) + if (g_debugMode == 2) prnt("DEBUG ASK: DetectASKClock Clean ASK Wave detected: clk %i, Best Starting Position: %i", *clock, idx); - + // return shortest wave start position if (idx > -1) return idx; } } // test for weak peaks - + // test clock if given as cmd parameter if ( *clock > 0 ) clk[0] = *clock; - + uint8_t clkCnt, tol = 0; size_t j = 0; uint16_t bestErr[] = {1000,1000,1000,1000,1000,1000,1000,1000,1000}; @@ -586,7 +586,7 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { tol = 0; } //if no errors allowed - keep start within the first clock - if (!maxErr && size > clk[clkCnt]*2 + tol && clk[clkCnt] < 128) + if (!maxErr && size > clk[clkCnt]*2 + tol && clk[clkCnt] < 128) loopCnt = clk[clkCnt] * 2; bestErr[clkCnt] = 1000; @@ -596,7 +596,7 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { // get to first full low to prime loop and skip incomplete first pulse getNextHigh(dest, size, peak_hi, &j); getNextLow(dest, size, peak_low, &j); - + for (; j < loopCnt; j++){ errCnt = 0; // now that we have the first one lined up test rest of wave array @@ -613,11 +613,11 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { // if we found no errors then we can stop here and a low clock (common clocks) // this is correct one - return this clock // if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, err %d, startpos %d, endpos %d", clk[clkCnt], errCnt, j, i); - if (errCnt == 0 && clkCnt < 7) { - if (!found_clk) + if (errCnt == 0 && clkCnt < 7) { + if (!found_clk) *clock = clk[clkCnt]; return j; - } + } // if we found errors see if it is lowest so far and save it as best run if (errCnt < bestErr[clkCnt]) { bestErr[clkCnt] = errCnt; @@ -625,9 +625,9 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { } } } - + uint8_t k, best = 0; - + for (k=1; k < num_clks; ++k){ if (bestErr[k] < bestErr[best]){ if (bestErr[k] == 0) bestErr[k] = 1; @@ -638,10 +638,10 @@ int DetectASKClock(uint8_t *dest, size_t size, int *clock, int maxErr) { } //if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, # Errors %d, Current Best Clk %d, bestStart %d", clk[k], bestErr[k], clk[best], bestStart[best]); } - - if (!found_clk) + + if (!found_clk) *clock = clk[best]; - + return bestStart[best]; } @@ -669,16 +669,16 @@ int DetectStrongNRZClk(uint8_t *dest, size_t size, int peak, int low, bool *stro for (;i < size; i++) { if ((dest[i] >= peak && !lastWasHigh) || (dest[i] <= low && lastWasHigh)) { lastWasHigh = (dest[i] >= peak); - if (i-transition1 < lowestTransition) + if (i-transition1 < lowestTransition) lowestTransition = i-transition1; transition1 = i; } else if (dest[i] < peak && dest[i] > low) { transitionSampleCount++; } } - if (lowestTransition == 255) + if (lowestTransition == 255) lowestTransition = 0; - + if (g_debugMode == 2) prnt("DEBUG NRZ: detectstrongNRZclk smallest wave: %d", lowestTransition); // if less than 10% of the samples were not peaks (or 90% were peaks) then we have a strong wave if (transitionSampleCount / size < 10) { @@ -698,23 +698,23 @@ int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx) //if we already have a valid clock quit for (; i < 8; ++i) if (clk[i] == clock) return clock; - + if (size < 20) return 0; // size must be larger than 20 here if (size < loopCnt) loopCnt = size-20; - + // just noise - no super good detection. good enough if (signalprop.isnoise) { if (g_debugMode == 2) prnt("DEBUG DetectNZRClock: just noise detected - quitting"); return 0; } - + //get high and low peak int peak, low; //getHiLo(dest, loopCnt, &peak, &low, 90, 90); getHiLo(&peak, &low, 90, 90); - + bool strong = false; int lowestTransition = DetectStrongNRZClk(dest, size-20, peak, low, &strong); if (strong) return lowestTransition; @@ -742,10 +742,10 @@ int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx) } } if (minPeak < 8) return 0; - + bool errBitHigh = 0, bitHigh = 0, lastPeakHigh = 0; uint8_t ignoreCnt = 0, ignoreWindow = 4; - int lastBit = 0; + int lastBit = 0; size_t bestStart[] = {0,0,0,0,0,0,0,0,0}; peakcnt = 0; //test each valid clock from smallest to greatest to see which lines up @@ -758,7 +758,7 @@ int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx) peakcnt=0; bitHigh = false; ignoreCnt = 0; - lastBit = ii-clk[clkCnt]; + lastBit = ii-clk[clkCnt]; //loop through to see if this start location works for (i = ii; i < size-20; ++i) { //if we are at a clock bit @@ -781,7 +781,7 @@ int DetectNRZClock(uint8_t *dest, size_t size, int clock, size_t *clockStartIdx) } else if (dest[i] < peak && dest[i] > low){ if (ignoreCnt == 0){ bitHigh = false; - if (errBitHigh == true) + if (errBitHigh == true) peakcnt--; errBitHigh = false; } else { @@ -841,7 +841,7 @@ uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) { if (fskAdj){ //if we had 5 and now have 9 then go back to 8 (for when we get a fc 9 instead of an 8) if (lastFCcnt == 5 && fcCounter == 9) fcCounter--; - + //if fc=9 or 4 add one (for when we get a fc 9 instead of 10 or a 4 instead of a 5) if ((fcCounter == 9) || fcCounter == 4) fcCounter++; // save last field clock count (fc/xx) @@ -856,7 +856,7 @@ uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) { } } if (fcCounter>0 && fcLensFnd<15){ - //add new fc length + //add new fc length fcCnts[fcLensFnd]++; fcLens[fcLensFnd++] = fcCounter; } @@ -866,10 +866,10 @@ uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) { fcCounter++; } } - + uint8_t best1 = 14, best2 = 14, best3 = 14; uint16_t maxCnt1 = 0; - // go through fclens and find which ones are bigest 2 + // go through fclens and find which ones are bigest 2 for (i=0; i<15; i++){ // get the 3 best FC values if (fcCnts[i] > maxCnt1) { @@ -886,7 +886,7 @@ uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) { if (g_debugMode == 2) prnt("DEBUG countfc: FC %u, Cnt %u, best fc: %u, best2 fc: %u", fcLens[i], fcCnts[i], fcLens[best1], fcLens[best2]); if (fcLens[i] == 0) break; } - + if (fcLens[best1] == 0) return 0; uint8_t fcH = 0, fcL = 0; if (fcLens[best1] > fcLens[best2]){ @@ -903,7 +903,7 @@ uint16_t countFC(uint8_t *bits, size_t size, bool fskAdj) { // TODO: take top 3 answers and compare to known Field clocks to get top 2 uint16_t fcs = (((uint16_t)fcH)<<8) | fcL; - if (fskAdj) return fcs; + if (fskAdj) return fcs; return (uint16_t)fcLens[best2] << 8 | fcLens[best1]; } @@ -921,16 +921,16 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif if (size < 160+20) return 0; // size must be larger than 20 here, and 160 later on. - if (size < loopCnt) loopCnt = size-20; + if (size < loopCnt) loopCnt = size-20; uint16_t fcs = countFC(dest, size, 0); - + *fc = fcs & 0xFF; - + if (g_debugMode == 2) prnt("DEBUG PSK: FC: %d, FC2: %d",*fc, fcs>>8); - + if ((fcs >> 8) == 10 && *fc == 8) return 0; - + if (*fc != 2 && *fc != 4 && *fc != 8) return 0; @@ -941,7 +941,7 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif uint16_t bestErr[] = {1000,1000,1000,1000,1000,1000,1000,1000,1000}; uint16_t peaksdet[] = {0,0,0,0,0,0,0,0,0}; - //find start of modulating data in trace + //find start of modulating data in trace i = findModStart(dest, size, *fc); firstFullWave = pskFindFirstPhaseShift(dest, size, curPhase, i, *fc, &fullWaveLen); @@ -954,7 +954,7 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif *firstPhaseShift = firstFullWave; if (g_debugMode == 2) prnt("DEBUG PSK: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen); - + //test each valid clock from greatest to smallest to see which lines up for (clkCnt=7; clkCnt >= 1 ; clkCnt--){ tol = *fc/2; @@ -965,7 +965,7 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif if (g_debugMode == 2) prnt("DEBUG PSK: clk: %d, lastClkBit: %d", clk[clkCnt], lastClkBit); for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){ - //top edge of wave = start of new wave + //top edge of wave = start of new wave if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){ if (waveStart == 0) { waveStart = i+1; @@ -973,7 +973,7 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif } else { //waveEnd waveEnd = i+1; waveLenCnt = waveEnd-waveStart; - if (waveLenCnt > *fc){ + if (waveLenCnt > *fc){ //if this wave is a phase shift if (g_debugMode == 2) prnt("DEBUG PSK: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d", waveStart, waveLenCnt, lastClkBit + clk[clkCnt] - tol, i+1, *fc); if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit @@ -994,8 +994,8 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif if (errCnt == 0) return clk[clkCnt]; if (errCnt <= bestErr[clkCnt]) bestErr[clkCnt] = errCnt; if (peakcnt > peaksdet[clkCnt]) peaksdet[clkCnt] = peakcnt; - } - //all tested with errors + } + //all tested with errors //return the highest clk with the most peaks found uint8_t best = 7; for (i=7; i >= 1; i--){ @@ -1011,9 +1011,9 @@ int DetectPSKClock(uint8_t *dest, size_t size, int clock, size_t *firstPhaseShif //detects the bit clock for FSK given the high and low Field Clocks uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, int *firstClockEdge) { - if (size == 0) + if (size == 0) return 0; - + uint8_t clk[] = {8,16,32,40,50,64,100,128,0}; uint16_t rfLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; uint8_t rfCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; @@ -1034,14 +1034,14 @@ uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, fcCounter++; rfCounter++; - if (bits[i] <= bits[i-1] || bits[i] < bits[i+1]) - continue; - // else new peak + if (bits[i] <= bits[i-1] || bits[i] < bits[i+1]) + continue; + // else new peak // if we got less than the small fc + tolerance then set it to the small fc // if it is inbetween set it to the last counter if (fcCounter < fcHigh && fcCounter > fcLow) fcCounter = lastFCcnt; - else if (fcCounter < fcLow+fcTol) + else if (fcCounter < fcLow+fcTol) fcCounter = fcLow; else //set it to the large fc fcCounter = fcHigh; @@ -1085,14 +1085,14 @@ uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, } else if(rfCnts[i] > rfCnts[rfHighest3]){ rfHighest3 = i; } - if (g_debugMode == 2) + if (g_debugMode == 2) prnt("DEBUG FSK: RF %d, cnts %d", rfLens[i], rfCnts[i]); - } - // set allowed clock remainder tolerance to be 1 large field clock length+1 - // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off - uint8_t tol1 = fcHigh+1; - - if (g_debugMode == 2) + } + // set allowed clock remainder tolerance to be 1 large field clock length+1 + // we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off + uint8_t tol1 = fcHigh+1; + + if (g_debugMode == 2) prnt("DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d", rfLens[rfHighest], rfLens[rfHighest2], rfLens[rfHighest3]); // loop to find the highest clock that has a remainder less than the tolerance @@ -1103,7 +1103,7 @@ uint8_t detectFSKClk(uint8_t *bits, size_t size, uint8_t fcHigh, uint8_t fcLow, if (rfLens[rfHighest] % clk[m] < tol1 || rfLens[rfHighest] % clk[m] > clk[m]-tol1){ if (rfLens[rfHighest2] % clk[m] < tol1 || rfLens[rfHighest2] % clk[m] > clk[m]-tol1){ if (rfLens[rfHighest3] % clk[m] < tol1 || rfLens[rfHighest3] % clk[m] > clk[m]-tol1){ - if (g_debugMode == 2) + if (g_debugMode == 2) prnt("DEBUG FSK: clk %d divides into the 3 most rf values within tolerance", clk[m]); break; } @@ -1146,7 +1146,7 @@ bool findST(int *stStopLoc, int *stStartIdx, int lowToLowWaveLen[], int highToLo bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, size_t *stend) { size_t bufsize = *size; //need to loop through all samples and identify our clock, look for the ST pattern - int clk = 0; + int clk = 0; int tol = 0; int j=0, high, low, skip=0, start=0, end=0, minClk=255; size_t i = 0; @@ -1181,7 +1181,7 @@ bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, s phaseoff = 0; else phaseoff = clk/2; - + // skip over the remainder of ST skip += clk*7/2; //3.5 clocks from tmpbuff[i] = end of st - also aligns for ending point @@ -1212,12 +1212,12 @@ bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, s } // if datalen is less than one t55xx block - ERROR if (datalen/clk < 8*4) { - if (g_debugMode == 2) prnt("DEBUG STT: datalen is less than 1 full t55xx block - quitting"); + if (g_debugMode == 2) prnt("DEBUG STT: datalen is less than 1 full t55xx block - quitting"); return false; } size_t dataloc = start; if (buffer[dataloc-(clk*4)-(clk/4)] <= low && buffer[dataloc] <= low && buffer[dataloc-(clk*4)] >= high) { - //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start + //we have low drift (and a low just before the ST and a low just after the ST) - compensate by backing up the start for ( i=0; i <= (clk/4); ++i ) { if ( buffer[dataloc - (clk*4) - i] <= low ) { dataloc -= i; @@ -1225,10 +1225,10 @@ bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, s } } } - + size_t newloc = 0; i=0; - if (g_debugMode == 2) prnt("DEBUG STT: Starting STT trim - start: %d, datalen: %d ",dataloc, datalen); + if (g_debugMode == 2) prnt("DEBUG STT: Starting STT trim - start: %d, datalen: %d ",dataloc, datalen); bool firstrun = true; // warning - overwriting buffer given with raw wave data with ST removed... while ( dataloc < bufsize-(clk/2) ) { @@ -1253,7 +1253,7 @@ bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, s if (i+newloc < dataloc) buffer[i+newloc] = buffer[dataloc]; - dataloc++; + dataloc++; } } newloc += i; @@ -1266,17 +1266,17 @@ bool DetectST(uint8_t *buffer, size_t *size, int *foundclock, size_t *ststart, s } //by marshmellow -//take 11 10 01 11 00 and make 01100 ... miller decoding +//take 11 10 01 11 00 and make 01100 ... miller decoding //check for phase errors - should never have half a 1 or 0 by itself and should never exceed 1111 or 0000 in a row //decodes miller encoded binary //NOTE askrawdemod will NOT demod miller encoded ask unless the clock is manually set to 1/2 what it is detected as! int millerRawDecode(uint8_t *bits, size_t *size, int invert) { if (*size < 16) return -1; - + uint16_t MaxBits = 512, errCnt = 0; size_t i, bitCnt = 0; uint8_t alignCnt = 0, curBit = bits[0], alignedIdx = 0, halfClkErr = 0; - + //find alignment, needs 4 1s or 0s to properly align for (i=1; i < *size-1; i++) { alignCnt = (bits[i] == curBit) ? alignCnt+1 : 0; @@ -1311,7 +1311,7 @@ int millerRawDecode(uint8_t *bits, size_t *size, int invert) { int BiphaseRawDecode(uint8_t *bits, size_t *size, int *offset, int invert) { //sanity check if (*size < 51) return -1; - + uint16_t bitnum = 0; uint16_t errCnt = 0; size_t i = *offset; @@ -1324,7 +1324,7 @@ int BiphaseRawDecode(uint8_t *bits, size_t *size, int *offset, int invert) { if (bits[i+2] == bits[i+3]) offsetB = false; } if (!offsetA && offsetB) ++*offset; - + for (i = *offset; i < *size-3; i += 2){ //check for phase error if (bits[i+1] == bits[i+2]) { @@ -1352,7 +1352,7 @@ int manrawdecode(uint8_t *bits, size_t *size, uint8_t invert, uint8_t *alignPos) // sanity check if (*size < 16) return -1; - + int errCnt = 0, bestErr = 1000; uint16_t bitnum = 0, maxBits = 512, bestRun = 0; size_t i, k; @@ -1394,7 +1394,7 @@ int cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, uint8_t cl_4 = clk / 4; uint8_t cl_2 = clk / 2; bool waveHigh = true; - + getNextHigh(bits, *size, high, &pos); // sample counts, like clock = 32.. it tries to find 32/4 = 8, 32/2 = 16 @@ -1409,7 +1409,7 @@ int cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, // 32-8-1 = 23 // 32+8+1 = 41 if (smplCnt > clk - cl_4 - 1) { //full clock - + if (smplCnt > clk + cl_4 + 1) { //too many samples errCnt++; if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod ASK Modulation Error FULL at: %u [%u]", i, smplCnt); @@ -1423,18 +1423,18 @@ int cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, } if (*startIdx == 0) *startIdx = i - clk; - waveHigh = !waveHigh; + waveHigh = !waveHigh; smplCnt = 0; - + // 16-8-1 = 7 } else if (smplCnt > cl_2 - cl_4 - 1) { //half clock - + if (smplCnt > cl_2 + cl_4 + 1) { //too many samples errCnt++; if (g_debugMode == 2) prnt("DEBUG ASK: cleanAskRawDemod ASK Modulation Error HALF at: %u [%u]", i, smplCnt); bits[bitCnt++] = 7; } - + if (waveHigh) { bits[bitCnt++] = invert; } else if (!waveHigh) { @@ -1442,7 +1442,7 @@ int cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, } if (*startIdx == 0) *startIdx = i - cl_2; - waveHigh = !waveHigh; + waveHigh = !waveHigh; smplCnt = 0; } else { smplCnt++; @@ -1460,59 +1460,59 @@ int cleanAskRawDemod(uint8_t *bits, size_t *size, int clk, int invert, int high, //by marshmellow //attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType, int *startIdx) { - + if (*size == 0) return -1; - + int start = DetectASKClock(bits, *size, clk, maxErr); if (*clk == 0 || start < 0) return -3; - + if (*invert != 1) *invert = 0; - + // amplify signal data. - // ICEMAN todo, + // ICEMAN todo, if (amp == 1) askAmp(bits, *size); - + if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, beststart %d, amp %d", *clk, start, amp); - + //start pos from detect ask clock is 1/2 clock offset // NOTE: can be negative (demod assumes rest of wave was there) - *startIdx = start - (*clk/2); + *startIdx = start - (*clk/2); uint16_t initLoopMax = 1024; if (initLoopMax > *size) initLoopMax = *size; - + // just noise - no super good detection. good enough if (signalprop.isnoise) { if (g_debugMode == 2) prnt("DEBUG askdemod_ext: just noise detected - aborting"); return -2; } - + // Detect high and lows //25% clip in case highs and lows aren't clipped [marshmellow] int high, low; //getHiLo(bits, initLoopMax, &high, &low, 75, 75); getHiLo(&high, &low, 75, 75); - + size_t errCnt = 0; // if clean clipped waves detected run alternate demod if (DetectCleanAskWave(bits, *size, high, low)) { if (g_debugMode == 2) prnt("DEBUG ASK: Clean Wave Detected - using clean wave demod"); - + errCnt = cleanAskRawDemod(bits, size, *clk, *invert, high, low, startIdx); if (askType) { //ask/manchester uint8_t alignPos = 0; errCnt = manrawdecode(bits, size, 0, &alignPos); *startIdx += *clk/2 * alignPos; - - if (g_debugMode) + + if (g_debugMode) prnt("DEBUG: (askdemod_ext) CLEAN: startIdx %i, alignPos %u", *startIdx, alignPos); - } + } return errCnt; } - + if (g_debugMode) prnt("DEBUG: (askdemod_ext) Weak wave detected: startIdx %i", *startIdx); - + int lastBit; //set first clock check - can go negative size_t i, bitnum = 0; //output counter uint8_t midBit = 0; @@ -1532,7 +1532,7 @@ int askdemod_ext(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, if (g_debugMode == 2) prnt("DEBUG: (askdemod_ext) Modulation Error at: %u", i); bits[bitnum++] = 7; errCnt++; - } + } } else { //in tolerance - looking for peak continue; } @@ -1566,22 +1566,22 @@ int askdemod(uint8_t *bits, size_t *size, int *clk, int *invert, int maxErr, uin // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startIdx) { if (signalprop.isnoise) return -1; - + size_t clkStartIdx = 0; *clk = DetectNRZClock(dest, *size, *clk, &clkStartIdx); if (*clk == 0) return -2; - + size_t i, gLen = 4096; - if (gLen > *size) + if (gLen > *size) gLen = *size-20; - - + + // just noise - no super good detection. good enough if (signalprop.isnoise) { if (g_debugMode == 2) prnt("DEBUG nrzRawDemod: just noise detected - quitting"); return -3; } - + int high, low; //getHiLo(dest, gLen, &high, &low, 75, 75); getHiLo(&high, &low, 75, 75); @@ -1594,7 +1594,7 @@ int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startId if (dest[i] <= low) bit = 0; dest[i] = bit; } - //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit) + //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit) size_t lastBit = 0; size_t numBits = 0; for(i=21; i < *size-20; i++) { @@ -1615,9 +1615,9 @@ int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int *startId //translate wave to 11111100000 (1 for each short wave [higher freq] 0 for each long wave [lower freq]) size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow, int *startIdx) { - + if ( size < 1024 ) return 0; // not enough samples - + if (fchigh == 0) fchigh = 10; if (fclow == 0) fclow = 8; @@ -1629,24 +1629,24 @@ size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow, size_t idx = 1; size_t numBits = 0; - //find start of modulating data in trace + //find start of modulating data in trace idx = findModStart(dest, size, fchigh); // Need to threshold first sample dest[idx] = (dest[idx] < signalprop.mean) ? 0 : 1; - + last_transition = idx; idx++; - + // Definition: cycles between consecutive lo-hi transitions // Lets define some expected lengths. FSK1 is easier since it has bigger differences between. - // FSK1 8/5 + // FSK1 8/5 // 50/8 = 6 | 40/8 = 5 | 64/8 = 8 // 50/5 = 10 | 40/5 = 8 | 64/5 = 12 // FSK2 10/8 // 50/10 = 5 | 40/10 = 4 | 64/10 = 6 // 50/8 = 6 | 40/8 = 5 | 64/8 = 8 - + // count cycles between consecutive lo-hi transitions, // in practice due to noise etc we may end up with anywhere // To allow fuzz would mean +-1 on expected cycle width. @@ -1661,14 +1661,14 @@ size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow, // It easy to see to the overgaping, but luckily we the group value also, like 1111000001111 // to separate between which bit to demodulate to. - // process: - // count width from 0-1 transition to 1-0. + // process: + // count width from 0-1 transition to 1-0. // determine the width is withing FUZZ_min and FUZZ_max tolerances - // width should be divided with exp_one. i:e 6+7+6+2=21, 21/5 = 4, - // the 1-0 to 0-1 width should be divided with exp_zero. Ie: 3+5+6+7 = 21/6 = 3 - + // width should be divided with exp_one. i:e 6+7+6+2=21, 21/5 = 4, + // the 1-0 to 0-1 width should be divided with exp_zero. Ie: 3+5+6+7 = 21/6 = 3 + for(; idx < size-20; idx++) { - + // threshold current value dest[idx] = (dest[idx] < signalprop.mean) ? 0 : 1; @@ -1685,14 +1685,14 @@ size_t fsk_wave_demod(uint8_t *dest, size_t size, uint8_t fchigh, uint8_t fclow, dest[numBits-1]=1; } dest[numBits++]=1; - - + + if (numBits > 0 && *startIdx == 0) *startIdx = idx - fclow; - + } else if (currSample > (fchigh+1) && numBits < 3) { //12 + and first two bit = unusable garbage //do nothing with beginning garbage and reset.. should be rare.. - numBits = 0; + numBits = 0; } else if (currSample == (fclow+1) && LastSample == (fclow-1)) { // had a 7 then a 9 should be two 8's (or 4 then a 6 should be two 5's) dest[numBits++]=1; if (numBits > 0 && *startIdx == 0) { @@ -1719,21 +1719,21 @@ size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t invert, u size_t numBits = 0; uint32_t n = 1; uint8_t hclk = clk/2; - + for( i = 1; i < size; i++) { n++; if (dest[i] == lastval) continue; //skip until we hit a transition - + //find out how many bits (n) we collected (use 1/2 clk tolerance) - + if (dest[i-1] == 1) //if lastval was 1, we have a 1->0 crossing n = (n * fclow + hclk) / clk; - else - // 0->1 crossing - n = (n * fchigh + hclk) / clk; + else + // 0->1 crossing + n = (n * fchigh + hclk) / clk; - if (n == 0) + if (n == 0) n = 1; //first transition - save startidx @@ -1747,7 +1747,7 @@ size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t invert, u } } - //add to our destination the bits we collected + //add to our destination the bits we collected memset(dest+numBits, dest[i-1] ^ invert , n); numBits += n; @@ -1755,7 +1755,7 @@ size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t clk, uint8_t invert, u lastval = dest[i]; }//end for - + // if valid extra bits at the end were all the same frequency - add them in if (n > clk/fchigh) { if (dest[i-2] == 1) { @@ -1786,9 +1786,9 @@ size_t fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8 void psk1TOpsk2(uint8_t *bits, size_t size) { uint8_t lastbit = bits[0]; for (size_t i = 1; i < size; i++){ - //ignore errors + //ignore errors if (bits[i] == 7) continue; - + if (lastbit != bits[i]){ lastbit = bits[i]; bits[i] = 1; @@ -1811,11 +1811,11 @@ void psk2TOpsk1(uint8_t *bits, size_t size) { } } -//by marshmellow - demodulate PSK1 wave -//uses wave lengths (# Samples) +//by marshmellow - demodulate PSK1 wave +//uses wave lengths (# Samples) //TODO: Iceman - hard coded value 7, should be #define int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *startIdx) { - + // sanity check if (*size < 170) return -1; @@ -1830,7 +1830,7 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s //if clock detect found firstfullwave... uint16_t tol = fc/2; if (firstFullWave == 0) { - //find start of modulating data in trace + //find start of modulating data in trace i = findModStart(dest, *size, fc); //find first phase shift firstFullWave = pskFindFirstPhaseShift(dest, *size, &curPhase, i, fc, &fullWaveLen); @@ -1855,7 +1855,7 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s waveStart = 0; dest[numBits++] = curPhase; //set first read bit for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){ - //top edge of wave = start of new wave + //top edge of wave = start of new wave if (dest[i]+fc < dest[i+1] && dest[i+1] >= dest[i+2]){ if (waveStart == 0) { waveStart = i+1; @@ -1864,7 +1864,7 @@ int pskRawDemod_ext(uint8_t *dest, size_t *size, int *clock, int *invert, int *s } else { //waveEnd waveEnd = i+1; waveLenCnt = waveEnd-waveStart; - if (waveLenCnt > fc){ + if (waveLenCnt > fc){ //this wave is a phase shift //prnt("DEBUG: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+*clock-tol,i+1,fc); if (i+1 >= lastClkBit + *clock - tol){ //should be a clock bit @@ -1925,10 +1925,10 @@ int detectAWID(uint8_t *dest, size_t *size, int *waveStartIdx) { uint8_t preamble[] = {0,0,0,0,0,0,0,1}; if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx)) return -4; //preamble not found - + // wrong size? (between to preambles) if (*size != 96) return -5; - + return (int)start_idx; } @@ -1936,12 +1936,12 @@ int detectAWID(uint8_t *dest, size_t *size, int *waveStartIdx) { //takes 1s and 0s and searches for EM410x format - output EM ID int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, uint64_t *lo) { // sanity check - if (bits[1] > 1) return -1; - if (*size < 64) return -2; + if (bits[1] > 1) return -1; + if (*size < 64) return -2; uint8_t fmtlen; *start_idx = 0; - + // preamble 0111111111 // include 0 in front to help get start pos uint8_t preamble[] = {0,1,1,1,1,1,1,1,1,1}; @@ -1952,22 +1952,22 @@ int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, u fmtlen = (*size == 128) ? 22 : 10; //skip last 4bit parity row for simplicity - *size = removeParity(bits, *start_idx + sizeof(preamble), 5, 0, fmtlen * 5); - + *size = removeParity(bits, *start_idx + sizeof(preamble), 5, 0, fmtlen * 5); + switch (*size) { - case 40: { + case 40: { // std em410x format *hi = 0; *lo = ((uint64_t)(bytebits_to_byte(bits, 8)) << 32) | (bytebits_to_byte(bits + 8, 32)); break; - } - case 88: { + } + case 88: { // long em format - *hi = (bytebits_to_byte(bits, 24)); + *hi = (bytebits_to_byte(bits, 24)); *lo = ((uint64_t)(bytebits_to_byte(bits + 24, 32)) << 32) | (bytebits_to_byte(bits + 24 + 32, 32)); break; - } - default: return -6; + } + default: return -6; } return 1; } @@ -1977,7 +1977,7 @@ int Em410xDecode(uint8_t *bits, size_t *size, size_t *start_idx, uint32_t *hi, u int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo, int *waveStartIdx) { //make sure buffer has data if (*size < 96*50) return -1; - + if (signalprop.isnoise) return -2; // FSK demodulator fsk2a so invert and fc/10/8 @@ -1987,14 +1987,14 @@ int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32 if (*size < 96*2) return -3; // 00011101 bit pattern represent start of frame, 01 pattern represents a 0 and 10 represents a 1 - size_t start_idx = 0; + size_t start_idx = 0; uint8_t preamble[] = {0,0,0,1,1,1,0,1}; - if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx)) + if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx)) return -4; //preamble not found // wrong size? (between to preambles) //if (*size != 96) return -5; - + size_t num_start = start_idx + sizeof(preamble); // final loop, go over previously decoded FSK data and manchester decode into usable tag ID for (size_t idx = num_start; (idx - num_start) < *size - sizeof(preamble); idx += 2) { @@ -2017,17 +2017,17 @@ int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32 // by iceman int detectIdteck(uint8_t *dest, size_t *size) { //make sure buffer has data - if (*size < 64*2) return -1; - + if (*size < 64*2) return -1; + if (signalprop.isnoise) return -2; - + size_t start_idx = 0; uint8_t preamble[] = {0,1,0,0,1,0,0,1,0,1,0,0,0,1,0,0,0,1,0,1,0,1,0,0,0,1,0,0,1,0,1,1}; - + //preamble not found if (!preambleSearch(dest, preamble, sizeof(preamble), size, &start_idx)) - return -3; - + return -3; + // wrong demoded size if (*size != 64) return -4; return (int)start_idx; @@ -2036,15 +2036,15 @@ int detectIdteck(uint8_t *dest, size_t *size) { int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx) { //make sure buffer has data if (*size < 66*64) return -1; - + if (signalprop.isnoise) return -2; - + // FSK demodulator RF/64, fsk2a so invert, and fc/10/8 *size = fskdemod(dest, *size, 64, 1, 10, 8, waveStartIdx); //io fsk2a - + //did we get enough demod data? if (*size < 64) return -3; - + //Index map //0 10 20 30 40 50 60 //| | | | | | | @@ -2061,12 +2061,12 @@ int detectIOProx(uint8_t *dest, size_t *size, int *waveStartIdx) { // wrong size? (between to preambles) if (*size != 64) return -5; - - if ( !dest[start_idx + 8] - && dest[start_idx + 17] == 1 - && dest[start_idx + 26] == 1 + + if ( !dest[start_idx + 8] + && dest[start_idx + 17] == 1 + && dest[start_idx + 26] == 1 && dest[start_idx + 35] == 1 - && dest[start_idx + 44] == 1 + && dest[start_idx + 44] == 1 && dest[start_idx + 53] == 1) { //confirmed proper separator bits found //return start position diff --git a/common/lfdemod.h b/common/lfdemod.h index a6542059e..222495a99 100644 --- a/common/lfdemod.h +++ b/common/lfdemod.h @@ -7,8 +7,8 @@ // Low frequency demod related commands // marshmellow // note that many of these demods are not the slickest code and they often rely -// on peaks and clock instead of converting to clean signal. -// +// on peaks and clock instead of converting to clean signal. +// //----------------------------------------------------------------------------- #ifndef LFDEMOD_H__ diff --git a/common/parity.h b/common/parity.h index fe1c2504f..9aaf936ed 100644 --- a/common/parity.h +++ b/common/parity.h @@ -6,7 +6,7 @@ // Parity functions //----------------------------------------------------------------------------- -// all functions defined in header file by purpose. Allows compiler optimizations. +// all functions defined in header file by purpose. Allows compiler optimizations. #ifndef __PARITY_H #define __PARITY_H @@ -31,7 +31,7 @@ static inline bool evenparity8(const uint8_t x) { } -static inline bool evenparity32(uint32_t x) +static inline bool evenparity32(uint32_t x) { #if !defined __GNUC__ x ^= x >> 16; @@ -43,7 +43,7 @@ static inline bool evenparity32(uint32_t x) } -static inline bool oddparity32(uint32_t x) +static inline bool oddparity32(uint32_t x) { #if !defined __GNUC__ x ^= x >> 16; diff --git a/common/prng.c b/common/prng.c index 170550edf..b1a608d7e 100644 --- a/common/prng.c +++ b/common/prng.c @@ -24,7 +24,7 @@ void burtle_init_mod(prng_ctx *x, uint32_t seed ) { } void burtle_init(prng_ctx *x, uint32_t seed ) { - uint32_t i; + uint32_t i; x->a = 0xf1ea5eed, x->b = x->c = x->d = seed; for (i=0; i < 20; ++i) { (void)burtle_get_mod(x); diff --git a/common/prng.h b/common/prng.h index 4aa890927..f7a875b6c 100644 --- a/common/prng.h +++ b/common/prng.h @@ -8,11 +8,11 @@ #define __PRNG_H #include #include -typedef struct prng_ctx { - uint32_t a; - uint32_t b; - uint32_t c; - uint32_t d; +typedef struct prng_ctx { + uint32_t a; + uint32_t b; + uint32_t c; + uint32_t d; } prng_ctx; //uint32_t burtle_get( prng_ctx *x ); diff --git a/common/protocols.c b/common/protocols.c index 96ecdab51..9649c51d9 100644 --- a/common/protocols.c +++ b/common/protocols.c @@ -30,17 +30,17 @@ uint8_t notset(uint8_t val, uint8_t mask){ void fuse_config(const picopass_hdr *hdr) { uint8_t fuses = hdr->conf.fuses; - if (isset(fuses,FUSE_FPERS)) + if (isset(fuses,FUSE_FPERS)) PrintAndLogDevice(SUCCESS, "\tMode: Personalization [Programmable]"); - else + else PrintAndLogDevice(NORMAL, "\tMode: Application [Locked]"); if (isset(fuses, FUSE_CODING1)) { PrintAndLogDevice(NORMAL, "\tCoding: RFU"); } else { - if( isset( fuses , FUSE_CODING0)) + if( isset( fuses , FUSE_CODING0)) PrintAndLogDevice(NORMAL, "\tCoding: ISO 14443-2 B/ISO 15693"); - else + else PrintAndLogDevice(NORMAL, "\tCoding: ISO 14443B only"); } // 1 1 @@ -54,7 +54,7 @@ void fuse_config(const picopass_hdr *hdr) { if( isset( fuses, FUSE_RA)) PrintAndLogDevice(NORMAL, "\tRA: Read access enabled"); - else + else PrintAndLogDevice(WARNING, "\tRA: Read access not enabled"); } @@ -63,7 +63,7 @@ void getMemConfig(uint8_t mem_cfg, uint8_t chip_cfg, uint8_t *max_blk, uint8_t * uint8_t k16 = isset(mem_cfg, 0x80); //uint8_t k2 = isset(mem_cfg, 0x08); uint8_t book = isset(mem_cfg, 0x20); - + if(isset(chip_cfg, 0x10) && !k16 && !book) { *kb = 2; *app_areas = 2; @@ -100,10 +100,10 @@ void mem_app_config(const picopass_hdr *hdr) { uint8_t max_blk = 31; getMemConfig(mem, chip, &max_blk, &app_areas, &kb); - + if (applimit < 6) applimit = 26; if (kb == 2 && (applimit > 0x1f) ) applimit = 26; - + PrintAndLogDevice(NORMAL, " Mem: %u KBits/%u App Areas (%u * 8 bytes) [%02X]", kb, app_areas, max_blk, mem); PrintAndLogDevice(NORMAL, "\tAA1: blocks 06-%02X", applimit); PrintAndLogDevice(NORMAL, "\tAA2: blocks %02X-%02X", applimit+1, max_blk); diff --git a/common/protocols.h b/common/protocols.h index 73355c85d..ce56b3175 100644 --- a/common/protocols.h +++ b/common/protocols.h @@ -36,7 +36,7 @@ ISO14443B 05 = REQB 1D = ATTRIB 50 = HALT - + BA = PING (reader -> tag) AB = PONG (tag -> reader) SRIX4K (tag does not respond to 05) @@ -132,7 +132,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. #define ICLASS_CMD_READ4 0x06 #define ICLASS_CMD_READ_OR_IDENTIFY 0x0C -#define ICLASS_CMD_SELECT 0x81 +#define ICLASS_CMD_SELECT 0x81 #define ICLASS_CMD_PAGESEL 0x84 #define ICLASS_CMD_UPDATE 0x87 #define ICLASS_CMD_READCHECK_KC 0x18 @@ -309,7 +309,7 @@ ISO 7816-4 Basic interindustry commands. For command APDU's. // ISO7816-4 For response APDU's #define ISO7816_OK 0x9000 // 6x xx = ERROR - + // MIFARE DESFire command set: #define MFDES_CREATE_APPLICATION 0xca #define MFDES_DELETE_APPLICATION 0xda @@ -417,7 +417,7 @@ void getMemConfig(uint8_t mem_cfg, uint8_t chip_cfg, uint8_t *max_blk, uint8_t * #define T55XX_WRITE_TIMEOUT 1500 uint32_t GetT55xxClockBit(uint32_t clock); - + // em4x05 & em4x69 chip configuration register definitions #define EM4x05_GET_BITRATE(x) (((x & 0x3F)*2)+2) @@ -515,7 +515,7 @@ uint32_t GetT55xxClockBit(uint32_t clock); #define SYSTEMCODE_CYBERNE 0x0003 // Cyberne #define SYSTEMCODE_SUICA 0x0003 // Suica #define SYSTEMCODE_PASMO 0x0003 // Pasmo - + //FeliCa Service list Suica/pasmo (little endian) #define SERVICE_SUICA_INOUT 0x108f // SUICA/PASMO #define SERVICE_SUICA_HISTORY 0x090f // SUICA/PASMO @@ -569,5 +569,5 @@ typedef struct { } picopass_hdr; -#endif +#endif // PROTOCOLS_H diff --git a/common/radixsort.c b/common/radixsort.c index 981c19191..fa0643216 100644 --- a/common/radixsort.c +++ b/common/radixsort.c @@ -44,13 +44,13 @@ uint64_t * radixSort(uint64_t * array, uint32_t size) { counts.c3[x] = o3; counts.c2[x] = o2; counts.c1[x] = o1; - o8 = t8; - o7 = t7; - o6 = t6; - o5 = t5; - o4 = t4; - o3 = t3; - o2 = t2; + o8 = t8; + o7 = t7; + o6 = t6; + o5 = t5; + o4 = t4; + o3 = t3; + o2 = t2; o1 = t1; } // radix diff --git a/common/random.c b/common/random.c index 5658683de..96cdbb628 100644 --- a/common/random.c +++ b/common/random.c @@ -6,20 +6,20 @@ static uint32_t g_nextrandom; * * We don't have an implementation of the "rand" function. Instead we use a * method of seeding with the time it took to call "autoseed" from first run. - * + * * https://github.com/Proxmark/proxmark3/pull/209/commits/f9c1dcd9f6e68a8c07cffed697a9c4c8caed6015 * * Iceman, rand needs to be fast. * https://software.intel.com/en-us/articles/fast-random-number-generator-on-the-intel-pentiumr-4-processor/ */ - + inline void fast_prand(){ fast_prandEx(GetTickCount()); } inline void fast_prandEx(uint32_t seed) { g_nextrandom = seed; } - + uint32_t prand() { // g_nextrandom *= 6364136223846793005; // g_nextrandom += 1; diff --git a/common/random.h b/common/random.h index 800ad8103..315794f8d 100644 --- a/common/random.h +++ b/common/random.h @@ -6,7 +6,7 @@ // the license. //----------------------------------------------------------------------------- // pseudo rng generator. To be used when PM3 simulates Mifare tag. -// i.e. 'hf mf sim' +// i.e. 'hf mf sim' // 'hf 14a sim' //----------------------------------------------------------------------------- diff --git a/common/tea.c b/common/tea.c index 616b4043b..b3e1a39c1 100644 --- a/common/tea.c +++ b/common/tea.c @@ -16,17 +16,17 @@ void tea_encrypt(uint8_t *v, uint8_t *key) { uint32_t a=0,b=0,c=0,d=0,y=0,z=0; uint32_t sum = 0; uint8_t n = ROUNDS; - + //key a = bytes_to_num(key, 4); b = bytes_to_num(key+4, 4); c = bytes_to_num(key+8, 4); d = bytes_to_num(key+12, 4); - + //input y = bytes_to_num(v, 4); z = bytes_to_num(v+4, 4); - + while ( n-- > 0 ) { sum += DELTA; y += ((z << 4) + a) ^ (z + sum) ^ ((z >> 5) + b); @@ -48,7 +48,7 @@ void tea_decrypt(uint8_t *v, uint8_t *key) { b = bytes_to_num(key+4, 4); c = bytes_to_num(key+8, 4); d = bytes_to_num(key+12, 4); - + //input y = bytes_to_num(v, 4); z = bytes_to_num(v+4, 4); diff --git a/common/usart.c b/common/usart.c index 32ccb5ca1..c62e3c8f6 100644 --- a/common/usart.c +++ b/common/usart.c @@ -1,7 +1,7 @@ //----------------------------------------------------------------------------- // Iceman, July 2018 // edits by - Anticat, August 2018 -// +// // This code is licensed to you under the terms of the GNU GPL, version 2 or, // at your option, any later version. See the LICENSE.txt file for the text of // the license. @@ -24,7 +24,7 @@ void usart_close(void) { // Reset the baud rate divisor register pUS1->US_BRGR = 0; - + // Reset the Timeguard Register pUS1->US_TTGR = 0; @@ -96,20 +96,20 @@ void usart_init(void) { // disable & reset receiver / transmitter for configuration pUS1->US_CR = (AT91C_US_RSTRX | AT91C_US_RSTTX | AT91C_US_RXDIS | AT91C_US_TXDIS); - + //enable the USART1 Peripheral clock AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_US1); // disable PIO control of receive / transmit pins - pPIO->PIO_PDR |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1); - + pPIO->PIO_PDR |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1); + // enable peripheral mode A on receive / transmit pins pPIO->PIO_ASR |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1); pPIO->PIO_BSR = 0; // enable pull-up on receive / transmit pins (see 31.5.1 I/O Lines) pPIO->PIO_PPUER |= (AT91C_PA21_RXD1 | AT91C_PA22_TXD1); - + // set mode pUS1->US_MR = AT91C_US_USMODE_NORMAL | // normal mode AT91C_US_CLKS_CLOCK | // MCK (48MHz) @@ -126,18 +126,18 @@ void usart_init(void) { // For a nice detailed sample, interrupt driven but still relevant. // See https://www.sparkfun.com/datasheets/DevTools/SAM7/at91sam7%20serial%20communications.pdf - // set baudrate to 115200 + // set baudrate to 115200 // 115200 * 16 == 1843200 // //pUS1->US_BRGR = (48UL*1000*1000) / (9600*16); pUS1->US_BRGR = 48054841 / (9600 << 4); - + // Write the Timeguard Register pUS1->US_TTGR = 0; pUS1->US_RTOR = 0; pUS1->US_FIDI = 0; pUS1->US_IF = 0; - + // re-enable receiver / transmitter pUS1->US_CR = (AT91C_US_RXEN | AT91C_US_TXEN); } \ No newline at end of file diff --git a/common/usb_cdc.c b/common/usb_cdc.c index a0005017e..b1acff692 100644 --- a/common/usb_cdc.c +++ b/common/usb_cdc.c @@ -36,14 +36,14 @@ /* AT91SAM7S256 USB Device Port • Embedded 328-byte dual-port RAM for endpoints -• Four endpoints +• Four endpoints – Endpoint 0: 8 bytes – Endpoint 1 and 2: 64 bytes ping-pong – Endpoint 3: 64 bytes – Ping-pong Mode (two memory banks) for bulk endpoints */ -// +// #define AT91C_EP_CONTROL 0 #define AT91C_EP_OUT 1 // cfg bulk out #define AT91C_EP_IN 2 // cfg bulk in @@ -79,7 +79,7 @@ AT91SAM7S256 USB Device Port #define _ISO 0x01 //Isochronous Transfer #define _BULK 0x02 //Bulk Transfer #define _INTERRUPT 0x03 //Interrupt Transfer - + // (bit7 | 0 = OUT, 1 = IN) #define _EP_IN 0x80 #define _EP_OUT 0x00 @@ -92,7 +92,7 @@ AT91SAM7S256 USB Device Port /* WCID specific Request Code */ -#define MS_OS_DESCRIPTOR_INDEX 0xEE +#define MS_OS_DESCRIPTOR_INDEX 0xEE #define MS_VENDOR_CODE 0x1C #define MS_EXTENDED_COMPAT_ID 0x04 #define MS_EXTENDED_PROPERTIES 0x05 @@ -143,10 +143,10 @@ static const char devDescriptor[] = { 0xc4,0x9a, // Vendor ID [0x9ac4 = J. Westhues] 0x8f,0x4b, // Product ID [0x4b8f = Proxmark-3 RFID Instrument] 0x00,0x01, // BCD Device release number (1.00) - 1, // index Manufacturer + 1, // index Manufacturer 2, // index Product 3, // index SerialNumber - 1 // Number of Configs + 1 // Number of Configs }; static const char cfgDescriptor[] = { @@ -154,8 +154,8 @@ static const char cfgDescriptor[] = { /* Configuration 1 descriptor */ // ----------------------------- 9, // Length - USB_DESCRIPTOR_CONFIGURATION, // Descriptor Type - (9+9+5+5+4+5+7+9+7+7), 0, // Total Length 2 EP + Control + USB_DESCRIPTOR_CONFIGURATION, // Descriptor Type + (9+9+5+5+4+5+7+9+7+7), 0, // Total Length 2 EP + Control 2, // Number of Interfaces 1, // Index value of this Configuration (used in SetConfiguration from Host) 0, // Configuration string index @@ -174,7 +174,7 @@ static const char cfgDescriptor[] = { 1, // Function Protocol: v.25term 0, // iInterface */ - + /* Interface 0 Descriptor */ /* CDC Communication Class Interface Descriptor Requirement for Notification*/ // ----------------------------------------------------------- @@ -192,7 +192,7 @@ static const char cfgDescriptor[] = { 5, // Function Length 0x24, // Descriptor type: CS_INTERFACE 0, // Descriptor subtype: Header Functional Descriptor - 0x10,0x01, // bcd CDC:1.1 + 0x10,0x01, // bcd CDC:1.1 /* ACM Functional Descriptor */ 4, // Function Length @@ -206,23 +206,23 @@ static const char cfgDescriptor[] = { 6, // Descriptor Subtype: Union Functional Descriptor 0, // MasterInterface: Communication Class Interface 1, // SlaveInterface0: Data Class Interface - + /* Call Management Functional Descriptor */ 5, // Function Length 0x24, // Descriptor Type: CS_INTERFACE - 1, // Descriptor Subtype: Call Management Functional Descriptor + 1, // Descriptor Subtype: Call Management Functional Descriptor 0, // Capabilities: Device sends/receives call management information only over the Communication Class interface. Device does not handle call management itself 1, // Data Interface: Data Class Interface - + /* Protocol Functional Descriptor */ /* 6, 0x24, // Descriptor Type: CS_INTERFACE 0x0B, // Descriptor Subtype: Protocol Unit functional Descriptor 0xDD, // constant uniq ID of unit - 0xFE, // protocol + 0xFE, // protocol */ - + /* CDC Notification Endpoint descriptor */ // --------------------------------------- 7, // Length @@ -232,7 +232,7 @@ static const char cfgDescriptor[] = { AT91C_EP_CONTROL_SIZE, 0x00, // MaxPacket Size: EP0 - 8 0xFF, // Interval polling - + /* Interface 1 Descriptor */ /* CDC Data Class Interface 1 Descriptor Requirement */ 9, // Length @@ -283,10 +283,10 @@ static const char bosDescriptor[] = { static const char CompatIDFeatureDescriptor[] = { 0x28, 0x00, 0x00, 0x00, // Descriptor Length 40bytes (0x28) 0x00, 0x01, // Version ('1.0') - MS_EXTENDED_COMPAT_ID, 0x00, // Compatibility ID Descriptor Index 0x0004 + MS_EXTENDED_COMPAT_ID, 0x00, // Compatibility ID Descriptor Index 0x0004 0x01, // Number of sections. 0x1 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Reserved (7bytes) - //-----function section 1------ + //-----function section 1------ 0x00, // Interface Number #0 0x01, // reserved (0x1) 0x57, 0x49, 0x4E, 0x55, 0x53, 0x42, 0x00, 0x00, // Compatible ID ('WINUSB\0\0') (8bytes) @@ -306,7 +306,7 @@ static const char OSprop[] = { MS_EXTENDED_PROPERTIES, 0, // u16 wCount -- three section 3, 0, - + //-----property section 1------ // u32 size ( 14+40+78 == 132) 132, 0, 0, 0, @@ -321,7 +321,7 @@ static const char OSprop[] = { // data {4D36E978-E325-11CE-BFC1-08002BE10318} '{',0,'4',0,'d',0,'3',0,'6',0,'e',0,'9',0,'7',0,'8',0,'-',0,'e',0,'3',0,'2',0,'5',0, '-',0,'1',0,'1',0,'c',0,'e',0,'-',0,'b',0,'f',0,'c',0,'1',0,'-',0,'0',0,'8',0,'0',0, - '0',0,'2',0,'b',0,'e',0,'1',0,'0',0,'3',0,'1',0,'8',0,'}',0,0,0, + '0',0,'2',0,'b',0,'e',0,'1',0,'0',0,'3',0,'1',0,'8',0,'}',0,0,0, //-----property section 2------ // u32 size ( 14+12+38 == 64) @@ -343,7 +343,7 @@ static const char OSprop[] = { // u32 type 2, 0, 0, 0, //Unicode string with environment variables // u16 namelen (12) - 12, 0, + 12, 0, // name Icons 'I',0,'c',0,'o',0,'n',0,'s',0,0,0, // u32 datalen ( 38*2 == 76) @@ -393,12 +393,12 @@ static const char StrMS_OSDescriptor[] = { const char* getStringDescriptor(uint8_t idx) { switch(idx) { - case 0: return StrLanguageCodes; + case 0: return StrLanguageCodes; case 1: return StrManufacturer; case 2: return StrProduct; case 3: return StrSerialNumber; case MS_OS_DESCRIPTOR_INDEX: return StrMS_OSDescriptor; - default: + default: return(NULL); } } @@ -446,7 +446,7 @@ static void SpinDelay(int ms) { // Borrow a PWM unit for my real-time clock AT91C_BASE_PWMC->PWMC_ENA = PWM_CHANNEL(0); - + // 48 MHz / 1024 gives 46.875 kHz AT91C_BASE_PWMC_CH0->PWMC_CMR = PWM_CH_MODE_PRESCALER(10); AT91C_BASE_PWMC_CH0->PWMC_CDTYR = 0; @@ -489,7 +489,7 @@ void usb_enable() { // Enables the 48MHz USB clock UDPCK and System Peripheral USB Clock AT91C_BASE_PMC->PMC_SCER |= AT91C_PMC_UDP; AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_UDP); - + AT91C_BASE_UDP->UDP_FADDR = 0; AT91C_BASE_UDP->UDP_GLBSTATE = 0; @@ -507,7 +507,7 @@ void usb_enable() { SpinDelay(100); // Wait for a short while //for (volatile size_t i=0; i<0x100000; i++) {}; - + // Reconnect USB reconnect AT91C_BASE_PIOA->PIO_SODR = GPIO_USB_PU; AT91C_BASE_PIOA->PIO_OER = GPIO_USB_PU; @@ -533,23 +533,23 @@ int GetUSBconfigured(void){ } bool usb_check() { - + /* - // reconnected ONCE and + // reconnected ONCE and if ( !USB_ATTACHED() ){ usb_reconnect = 1; return false; } - - // only one time after USB been disengaged and re-engaged + + // only one time after USB been disengaged and re-engaged if ( USB_ATTACHED() && usb_reconnect == 1 ) { - - if ( usb_configured == 0) { + + if ( usb_configured == 0) { usb_disable(); - usb_enable(); + usb_enable(); AT91F_CDC_Enumerate(); - + usb_configured = 1; return false; } @@ -573,7 +573,7 @@ bool usb_check() { else if (isr & AT91C_UDP_EPINT0) { pUdp->UDP_ICR = AT91C_UDP_EPINT0; AT91F_CDC_Enumerate(); - } + } /* else if (isr & AT91C_UDP_EPINT3 ) { pUdp->UDP_ICR = AT91C_UDP_EPINT3; @@ -608,20 +608,20 @@ bool usb_poll_validate_length() { //* \brief Read available data from Endpoint 1 OUT (host to device) //*---------------------------------------------------------------------------- uint32_t usb_read(byte_t* data, size_t len) { - + if ( len == 0 ) return 0; - + uint8_t bank = btReceiveBank; uint32_t packetSize, nbBytesRcv = 0; uint32_t time_out = 0; - + while (len) { if (!usb_check()) break; if ( pUdp->UDP_CSR[AT91C_EP_OUT] & bank ) { - + packetSize = (pUdp->UDP_CSR[AT91C_EP_OUT] & AT91C_UDP_RXBYTECNT) >> 16; - packetSize = MIN( packetSize, len); + packetSize = MIN( packetSize, len); len -= packetSize; while (packetSize--) data[nbBytesRcv++] = pUdp->UDP_FDR[AT91C_EP_OUT]; @@ -632,7 +632,7 @@ uint32_t usb_read(byte_t* data, size_t len) { if (bank == AT91C_UDP_RX_DATA_BK0) bank = AT91C_UDP_RX_DATA_BK1; else - bank = AT91C_UDP_RX_DATA_BK0; + bank = AT91C_UDP_RX_DATA_BK0; } if (time_out++ == 0x1fff) break; } @@ -652,20 +652,20 @@ uint32_t usb_write(const byte_t* data, const size_t len) { // can we write? if ( (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXPKTRDY) != 0 ) return 0; - + size_t length = len; uint32_t cpt = 0; - - + + // send first chunk cpt = MIN(length, AT91C_EP_IN_SIZE); length -= cpt; while (cpt--) { pUdp->UDP_FDR[AT91C_EP_IN] = *data++; } - + UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY); - + while (length) { // Send next chunk cpt = MIN(length, AT91C_EP_IN_SIZE); @@ -673,19 +673,19 @@ uint32_t usb_write(const byte_t* data, const size_t len) { while (cpt--) { pUdp->UDP_FDR[AT91C_EP_IN] = *data++; } - + // Wait for previous chunk to be sent // (iceman) when is the bankswapping done? while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) { if (!usb_check()) return length; } - + UDP_CLEAR_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXCOMP); while (pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP); UDP_SET_EP_FLAGS(AT91C_EP_IN, AT91C_UDP_TXPKTRDY); - + } - + // Wait for the end of transfer while (!(pUdp->UDP_CSR[AT91C_EP_IN] & AT91C_UDP_TXCOMP)) { if (!usb_check()) return length; @@ -704,7 +704,7 @@ uint32_t usb_write(const byte_t* data, const size_t len) { void AT91F_USB_SendData(AT91PS_UDP pUdp, const char *pData, uint32_t length) { uint32_t cpt = 0; AT91_REG csr; - + do { cpt = MIN(length, AT91C_EP_CONTROL_SIZE); length -= cpt; @@ -723,7 +723,7 @@ void AT91F_USB_SendData(AT91PS_UDP pUdp, const char *pData, uint32_t length) { csr = pUdp->UDP_CSR[AT91C_EP_CONTROL]; // Data IN stage has been stopped by a status OUT if ( csr & AT91C_UDP_RX_DATA_BK0) { - + UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_RX_DATA_BK0) return; } @@ -736,14 +736,14 @@ void AT91F_USB_SendData(AT91PS_UDP pUdp, const char *pData, uint32_t length) { while (pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP); } } - + //*---------------------------------------------------------------------------- //* \fn AT91F_USB_SendZlp //* \brief Send zero length packet through the control endpoint //*---------------------------------------------------------------------------- void AT91F_USB_SendZlp(AT91PS_UDP pUdp) { - UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXPKTRDY); + UDP_SET_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXPKTRDY); while ( !(pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP) ); UDP_CLEAR_EP_FLAGS(AT91C_EP_CONTROL, AT91C_UDP_TXCOMP); while (pUdp->UDP_CSR[AT91C_EP_CONTROL] & AT91C_UDP_TXCOMP); @@ -763,7 +763,7 @@ void AT91F_USB_SendStall(AT91PS_UDP pUdp) { //*---------------------------------------------------------------------------- //* \fn AT91F_CDC_Enumerate //* \brief This function is a callback invoked when a SETUP packet is received -//* problem: +//* problem: //* 1. this is for USB endpoint0. the control endpoint. //* 2. mixed with CDC ACM endpoint3 , interrupt, control endpoint //*---------------------------------------------------------------------------- @@ -796,22 +796,22 @@ void AT91F_CDC_Enumerate() { if ( wIndex == MS_EXTENDED_COMPAT_ID ) { // 4 //AT91F_USB_SendData(pUdp, CompatIDFeatureDescriptor, MIN(sizeof(CompatIDFeatureDescriptor), wLength)); //return; - } + } } if ( bmRequestType == MS_WCID_GET_FEATURE_DESCRIPTOR ) { //C1 // if ( wIndex == MS_EXTENDED_PROPERTIES ) { // 5 - winusb bug with wIndex == interface index, so I just send it always) //AT91F_USB_SendData(pUdp, OSprop, MIN(sizeof(OSprop), wLength)); //return; - // } + // } } } */ - + // Handle supported standard device request Cf Table 9-3 in USB specification Rev 1.1 switch ((bRequest << 8) | bmRequestType) { case STD_GET_DESCRIPTOR: { - + if ( wValue == 0x100 ) // Return Device Descriptor AT91F_USB_SendData(pUdp, devDescriptor, MIN(sizeof(devDescriptor), wLength)); else if ( wValue == 0x200 ) // Return Configuration Descriptor @@ -837,25 +837,25 @@ void AT91F_CDC_Enumerate() { pUdp->UDP_GLBSTATE = (wValue) ? AT91C_UDP_FADDEN : 0; break; case STD_SET_CONFIGURATION: - - /* - * Set or clear the device "configured" state. - * The LSB of wValue is the "Configuration Number". If this value is non-zero, - * it should be the same number as defined in the Configuration Descriptor; - * otherwise an error must have occurred. - * This device has only one configuration and its Config Number is CONF_NB (= 1). - */ + + /* + * Set or clear the device "configured" state. + * The LSB of wValue is the "Configuration Number". If this value is non-zero, + * it should be the same number as defined in the Configuration Descriptor; + * otherwise an error must have occurred. + * This device has only one configuration and its Config Number is CONF_NB (= 1). + */ AT91F_USB_SendZlp(pUdp); btConfiguration = wValue; pUdp->UDP_GLBSTATE = (wValue) ? AT91C_UDP_CONFG : AT91C_UDP_FADDEN; - + // make sure we are not stalled /* UDP_CLEAR_EP_FLAGS(AT91C_EP_OUT , AT91C_UDP_FORCESTALL); UDP_CLEAR_EP_FLAGS(AT91C_EP_IN , AT91C_UDP_FORCESTALL); UDP_CLEAR_EP_FLAGS(AT91C_EP_NOTIFY, AT91C_UDP_FORCESTALL); */ - + // enable endpoints pUdp->UDP_CSR[AT91C_EP_OUT] = (wValue) ? (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_OUT) : 0; pUdp->UDP_CSR[AT91C_EP_IN] = (wValue) ? (AT91C_UDP_EPEDS | AT91C_UDP_EPTYPE_BULK_IN) : 0; @@ -924,8 +924,8 @@ void AT91F_CDC_Enumerate() { // handle CDC class requests case SET_LINE_CODING: { /* - uint8_t i; - for ( i = 0 ; i < 7 ; i++ ) { + uint8_t i; + for ( i = 0 ; i < 7 ; i++ ) { ((uint8_t*)&line)[i] = pUdp->UDP_FDR[AT91C_EP_CONTROL]; } */ // ignore SET_LINE_CODING... diff --git a/common/usb_cdc.h b/common/usb_cdc.h index fcac556fd..aad046cc1 100644 --- a/common/usb_cdc.h +++ b/common/usb_cdc.h @@ -37,7 +37,7 @@ #include #include "at91sam7s512.h" -#include "config_gpio.h" +#include "config_gpio.h" #include "proxmark3.h" // USB_CONNECT() #include "common.h" diff --git a/common/wiegand.c b/common/wiegand.c index c9d5fbed1..730cb0206 100644 --- a/common/wiegand.c +++ b/common/wiegand.c @@ -17,7 +17,7 @@ */ uint8_t getParity( uint8_t *bits, uint8_t len, uint8_t type ) { uint8_t x = 0; - for(; len > 0; --len) + for(; len > 0; --len) x += bits[len - 1]; return (x & 1 ) ^ type; @@ -35,7 +35,7 @@ uint8_t checkParity(uint32_t bits, uint8_t len, uint8_t type); // by marshmellow // takes a array of binary values, start position, length of bits per parity (includes parity bit), -// Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run) +// Parity Type (1 for odd; 0 for even; 2 for Always 1's; 3 for Always 0's), and binary Length (length to run) size_t removeParity(uint8_t *bitstream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen) { uint32_t parityWd = 0; size_t j = 0, bitcount = 0; @@ -69,10 +69,10 @@ size_t removeParity(uint8_t *bitstream, size_t startIdx, uint8_t pLen, uint8_t p * @brief addParity * @param bits pointer to the source bitstream of binary values * @param dest pointer to the destination where parities together with bits are added. -* @param sourceLen number of +* @param sourceLen number of * @param pLen length bits to be checked * @param pType EVEN|ODD|2 (always 1's)|3 (always 0's) -* @return +* @return */ size_t addParity(uint8_t *bits, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType) { @@ -83,12 +83,12 @@ size_t addParity(uint8_t *bits, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, parityWd = (parityWd << 1) | bits[word+bit]; dest[j++] = (bits[word+bit]); } - + // if parity fails then return 0 switch (pType) { case 3: dest[j++] = 0; break; // marker bit which should be a 0 case 2: dest[j++] = 1; break; // marker bit which should be a 1 - default: + default: dest[j++] = parityTest(parityWd, pLen-1, pType) ^ 1; break; } @@ -115,34 +115,34 @@ void wiegand_add_parity(uint8_t *source, uint8_t *dest, uint8_t len) { // half length, Even and Odd is calculated to the middle. uint8_t len_h2 = length >> 1; - + // add EVEN parity at the beginning *(dest) = GetParity(source, EVEN, len_h2); - + dest += length + 1; - + // add ODD parity at the very end *(dest) = GetParity(source + len_h2, ODD, len_h2); } //uint32_t bytebits_to_byte(uint8_t* src, size_t numbits); #define MAX_BITS_TXX55 6*4*8 -#define MAX_BYTES_TXX55 6*4 +#define MAX_BYTES_TXX55 6*4 /* * @brief num_to_wiegand_bytes * @param oem Sometimes call FF Fixfield, SiteCode. Used in a few formats -* @param fc Facility code +* @param fc Facility code * @param cn Card number * @param dest pointer to the destination where wiegand bytes will be stored -* @param formatlen +* @param formatlen */ void num_to_wiegand_bytes(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint8_t formatlen){ uint8_t data[MAX_BITS_TXX55] = {0}; memset(data, 0, sizeof(data)); - + num_to_wiegand_bits(oem, fc, cn, data, formatlen); - + // loop // (formatlen / 32 ) + 1 // (formatlen >> 5) + 1 @@ -150,15 +150,15 @@ void num_to_wiegand_bytes(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint32_t value = bytebits_to_byte( data + (i * 32), 32); num_to_bytes(value, 32, dest + (i*4) ); } - + } /* * @brief num_to_wiegand_bits * @param oem Sometimes call FF Fixfield, SiteCode. Used in a few formats -* @param fc Facility code +* @param fc Facility code * @param cn Card number * @param dest pointer to the destination where wiegand bits will be stored -* @param formatlen +* @param formatlen */ void num_to_wiegand_bits(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, uint8_t formatlen){ @@ -166,8 +166,8 @@ void num_to_wiegand_bits(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, memset(bits, 0, sizeof(bits)); uint8_t *temp = bits; uint64_t value = 0; - - switch ( formatlen ){ + + switch ( formatlen ){ case 26 : // 26bit HID H10301 fc &= 0xFF; // 8bits cn &= 0xFFFF; // 16bits @@ -175,26 +175,26 @@ void num_to_wiegand_bits(uint64_t oem, uint64_t fc, uint64_t cn, uint8_t *dest, num_to_bytebits(value, 24, temp); wiegand_add_parity(temp, dest, 24); break; - case 261: // 26bit Indala + case 261: // 26bit Indala fc &= 0xFFF; // 12bits cn &= 0xFFF; // 12bits value = fc << 12 | cn; num_to_bytebits(value, 24, temp); - wiegand_add_parity(temp, dest, 24); + wiegand_add_parity(temp, dest, 24); break; case 34 : // 34bits HID fc &= 0xFFFF; // 16bits cn &= 0xFFFF; // 16bits value = fc << 16 | cn; num_to_bytebits(value, 32, temp); - wiegand_add_parity(temp, dest, 32); + wiegand_add_parity(temp, dest, 32); break; case 35 : // 35bits HID fc &= 0xFFF; // 12bits cn &= 0xFFFFFF; // 20bits value = fc << 20 | cn; num_to_bytebits(value, 32, temp); - wiegand_add_parity(temp, dest, 32); + wiegand_add_parity(temp, dest, 32); break; case 37 : // H10304 fc &= 0xFFFF; // 16bits diff --git a/include/common.h b/include/common.h index d3da792aa..8c73100ff 100644 --- a/include/common.h +++ b/include/common.h @@ -24,7 +24,7 @@ typedef unsigned char byte_t; // debug // 0 - no debug messages 1 - error messages 2 - all messages 4 - extended debug mode -#define MF_DBG_NONE 0 +#define MF_DBG_NONE 0 #define MF_DBG_ERROR 1 #define MF_DBG_ALL 2 #define MF_DBG_EXTENDED 4 @@ -51,7 +51,7 @@ extern uint32_t FLASHMEM_SPIBAUDRATE; // RDV40 Section // 256kb divided into 4k sectors. -// +// // last 4k sector = signature // second last 4k sector = settings // third last 4k sector = default MF keys dictionary @@ -94,11 +94,11 @@ extern uint32_t FLASHMEM_SPIBAUDRATE; #ifndef DEFAULT_T55XX_KEYS_OFFSET # define DEFAULT_T55XX_KEYS_OFFSET (FLASH_MEM_MAX_4K_SECTOR - 0x3000) #endif - + #ifndef DEFAULT_MF_KEYS_OFFSET # define DEFAULT_MF_KEYS_OFFSET (FLASH_MEM_MAX_4K_SECTOR - 0x4000) #endif - + #ifndef DEFAULT_ICLASS_KEYS_OFFSET # define DEFAULT_ICLASS_KEYS_OFFSET (FLASH_MEM_MAX_4K_SECTOR - 0x5000) #endif @@ -114,5 +114,5 @@ typedef struct { #ifdef __cplusplus } -#endif +#endif #endif \ No newline at end of file diff --git a/include/hitag2.h b/include/hitag2.h index a2d592410..2eeb48f6f 100644 --- a/include/hitag2.h +++ b/include/hitag2.h @@ -7,7 +7,7 @@ //----------------------------------------------------------------------------- // Hitag2 type prototyping //----------------------------------------------------------------------------- -// HitagS added +// HitagS added //----------------------------------------------------------------------------- #ifndef _HITAG2_H_ diff --git a/include/hitagS.h b/include/hitagS.h index 11b4fccb3..d74463f20 100644 --- a/include/hitagS.h +++ b/include/hitagS.h @@ -34,7 +34,7 @@ typedef enum TAG_STATE { HT_WRITING_PAGE_DATA, HT_WRITING_BLOCK_DATA} TSATE; -//number of start-of-frame bits +//number of start-of-frame bits typedef enum SOF_TYPE { HT_STANDARD=0, HT_ADVANCED, diff --git a/include/legic.h b/include/legic.h index 246af0e8b..d5ba8f166 100644 --- a/include/legic.h +++ b/include/legic.h @@ -21,7 +21,7 @@ typedef struct { uint32_t tagtype; uint8_t cmdsize; uint8_t addrsize; - uint16_t cardsize; + uint16_t cardsize; } legic_card_select_t; #endif // _LEGIC_H_ diff --git a/include/mifare.h b/include/mifare.h index 90077f60d..eec72c26f 100644 --- a/include/mifare.h +++ b/include/mifare.h @@ -91,7 +91,7 @@ typedef struct { uint32_t nonce; uint32_t ar; uint32_t nr; - uint32_t at; + uint32_t at; uint32_t nonce2; uint32_t ar2; uint32_t nr2; @@ -105,7 +105,7 @@ typedef struct { } nonces_t; //----------------------------------------------------------------------------- -// ISO 7618 Smart Card +// ISO 7618 Smart Card //----------------------------------------------------------------------------- typedef struct { uint8_t atr_len; @@ -127,7 +127,7 @@ typedef enum SMARTCARD_COMMAND { // mc = manufactureCode // mc1 mc2 u1 u2 u3 u4 u5 u6 // PMm = Product manufacturer -// icCode = +// icCode = // ic1 = ROM // ic2 = IC // maximum response time = @@ -136,7 +136,7 @@ typedef enum SMARTCARD_COMMAND { // B5(authenticate) // B6(read) // B7(write) -// B8() +// B8() // ServiceCode 2bytes (access-rights) // FileSystem = 1 Block = 16 bytes @@ -147,7 +147,7 @@ typedef struct { uint8_t PMm[8]; uint8_t iccode[2]; uint8_t mrt[6]; - uint8_t servicecode[2]; + uint8_t servicecode[2]; } __attribute__((__packed__)) felica_card_select_t; typedef enum FELICA_COMMAND { diff --git a/include/proxmark3.h b/include/proxmark3.h index 4532baf09..4b16f4eed 100644 --- a/include/proxmark3.h +++ b/include/proxmark3.h @@ -86,9 +86,9 @@ #define LED_D_OFF() LOW(GPIO_LED_D) #define LED_D_INV() INVBIT(GPIO_LED_D) -// SPI -#define SCK_LOW LOW(GPIO_SPCK) -#define SCK_HIGH HIGH(GPIO_SPCK) +// SPI +#define SCK_LOW LOW(GPIO_SPCK) +#define SCK_HIGH HIGH(GPIO_SPCK) #define MOSI_HIGH HIGH(GPIO_MOSI) #define MOSI_LOW LOW(GPIO_MOSI) #define MISO_VALUE (AT91C_BASE_PIOA->PIO_PDSR & GPIO_MISO) @@ -106,7 +106,7 @@ #define BUTTON_PRESS() !((AT91C_BASE_PIOA->PIO_PDSR & GPIO_BUTTON) == GPIO_BUTTON) //NVDD goes LOW when USB is attached. -#define USB_ATTACHED() !((AT91C_BASE_PIOA->PIO_PDSR & GPIO_NVDD_ON) == GPIO_NVDD_ON) +#define USB_ATTACHED() !((AT91C_BASE_PIOA->PIO_PDSR & GPIO_NVDD_ON) == GPIO_NVDD_ON) #define VERSION_INFORMATION_MAGIC 0x56334d50 struct version_information { diff --git a/include/usb_cmd.h b/include/usb_cmd.h index a54b27e0f..0680b443a 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -48,7 +48,7 @@ typedef struct{ uint16_t write_gap; uint16_t write_0; uint16_t write_1; - uint16_t read_gap; + uint16_t read_gap; } t55xx_config; // For the bootloader @@ -161,7 +161,7 @@ typedef struct{ #define CMD_SIMULATE_HITAG 0x0371 #define CMD_READER_HITAG 0x0372 -// For HitagS +// For HitagS #define CMD_TEST_HITAGS_TRACES 0x0367 #define CMD_SIMULATE_HITAG_S 0x0368 #define CMD_READ_HITAG_S 0x0373 @@ -202,7 +202,7 @@ typedef struct{ #define CMD_ICLASS_AUTHENTICATION 0x0399 #define CMD_ICLASS_CHECK_KEYS 0x039A -// For ISO1092 / FeliCa +// For ISO1092 / FeliCa #define CMD_FELICA_SIMULATE_TAG 0x03A0 #define CMD_FELICA_SNOOP 0x03A1 #define CMD_FELICA_COMMAND 0x03A2 @@ -253,7 +253,7 @@ typedef struct{ #define CMD_MIFARE_SNIFFER 0x0630 //ultralightC #define CMD_MIFAREUC_AUTH 0x0724 -//0x0725 and 0x0726 no longer used +//0x0725 and 0x0726 no longer used #define CMD_MIFAREUC_SETPWD 0x0727 // mifare desfire diff --git a/liblua/lgc.c b/liblua/lgc.c index 535e988ae..af001682c 100644 --- a/liblua/lgc.c +++ b/liblua/lgc.c @@ -1053,7 +1053,7 @@ static lu_mem singlestep (lua_State *L) { g->gcstate = GCSatomic; /* finish mark phase */ g->GCestimate = g->GCmemtrav; /* save what was counted */; work = atomic(L); /* add what was traversed by 'atomic' */ - g->GCestimate += work; /* estimate of total memory traversed */ + g->GCestimate += work; /* estimate of total memory traversed */ sw = entersweep(L); return work + sw * GCSWEEPCOST; } diff --git a/tools/mfkey/crapto1.c b/tools/mfkey/crapto1.c index 203efeb4f..9b2b58085 100755 --- a/tools/mfkey/crapto1.c +++ b/tools/mfkey/crapto1.c @@ -222,7 +222,7 @@ struct Crypto1State* lfsr_recovery32(uint32_t ks2, uint32_t in) // allocate memory for out of place bucket_sort bucket_array_t bucket; - + for (uint32_t i = 0; i < 2; i++) { for (uint32_t j = 0; j <= 0xff; j++) { bucket[i][j].head = malloc(sizeof(uint32_t)<<14); @@ -424,7 +424,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb) ret |= lfsr_rollback_bit(s, BEBIT(in, 18), fb) << (18 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 17), fb) << (17 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 16), fb) << (16 ^ 24); - + ret |= lfsr_rollback_bit(s, BEBIT(in, 15), fb) << (15 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 14), fb) << (14 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 13), fb) << (13 ^ 24); @@ -433,7 +433,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb) ret |= lfsr_rollback_bit(s, BEBIT(in, 10), fb) << (10 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 9), fb) << (9 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 8), fb) << (8 ^ 24); - + ret |= lfsr_rollback_bit(s, BEBIT(in, 7), fb) << (7 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 6), fb) << (6 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 5), fb) << (5 ^ 24); @@ -483,7 +483,7 @@ uint32_t *lfsr_prefix_ks(uint8_t ks[8], int isodd) { uint32_t *candidates = malloc(4 << 10); if(!candidates) return 0; - + uint32_t c, entry; int size = 0, i, good; @@ -531,7 +531,7 @@ static struct Crypto1State* check_pfx_parity(uint32_t prefix, uint32_t rresp, ui } return sl + good; -} +} /** lfsr_common_prefix * Implentation of the common prefix attack. diff --git a/tools/mfkey/crapto1.h b/tools/mfkey/crapto1.h index 65c570216..875ffdaab 100755 --- a/tools/mfkey/crapto1.h +++ b/tools/mfkey/crapto1.h @@ -44,7 +44,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State* s, uint32_t in, int fb); int nonce_distance(uint32_t from, uint32_t to); #define SWAPENDIAN(x)\ (x = (x >> 8 & 0xff00ff) | (x & 0xff00ff) << 8, x = x >> 16 | x << 16) - + #define FOREACH_VALID_NONCE(N, FILTER, FSIZE)\ uint32_t __n = 0,__M = 0, N = 0;\ int __i;\ @@ -54,7 +54,7 @@ int nonce_distance(uint32_t from, uint32_t to); break;\ else if(__i)\ __M = prng_successor(__M, (__i == 7) ? 48 : 8);\ - else + else #define LF_POLY_ODD (0x29CE5C) #define LF_POLY_EVEN (0x870804) diff --git a/tools/mfkey/crypto1.c b/tools/mfkey/crypto1.c index f49a07225..14e2cc829 100755 --- a/tools/mfkey/crypto1.c +++ b/tools/mfkey/crypto1.c @@ -25,8 +25,8 @@ struct Crypto1State * crypto1_create(uint64_t key) struct Crypto1State *s = malloc(sizeof(*s)); if ( !s ) return NULL; - s->odd = s->even = 0; - + s->odd = s->even = 0; + int i; //for(i = 47;s && i > 0; i -= 2) { for(i = 47; i > 0; i -= 2) { @@ -103,7 +103,7 @@ uint32_t crypto1_word(struct Crypto1State *s, uint32_t in, int is_encrypted) ret |= crypto1_bit(s, BEBIT(in, 5), is_encrypted) << (5 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 6), is_encrypted) << (6 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 7), is_encrypted) << (7 ^ 24); - + ret |= crypto1_bit(s, BEBIT(in, 8), is_encrypted) << (8 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 9), is_encrypted) << (9 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 10), is_encrypted) << (10 ^ 24); diff --git a/tools/mfkey/mfkey32.c b/tools/mfkey/mfkey32.c index 1196868d4..2761a063b 100755 --- a/tools/mfkey/mfkey32.c +++ b/tools/mfkey/mfkey32.c @@ -43,14 +43,14 @@ int main (int argc, char *argv[]) { uint32_t p64 = prng_successor(nt, 64); printf(" nt': %08x\n", p64); printf(" nt'': %08x\n", prng_successor(p64, 32)); - + // Extract the keystream from the messages printf("\nKeystream used to generate {ar} and {at}:\n"); ks2 = ar0_enc ^ p64; printf(" ks2: %08x\n", ks2); s = lfsr_recovery32(ar0_enc ^ p64, 0); - + for(t = s; t->odd | t->even; ++t) { lfsr_rollback_word(t, 0, 0); lfsr_rollback_word(t, nr0_enc, 1); diff --git a/tools/mfkey/mfkey32v2.c b/tools/mfkey/mfkey32v2.c index 9c04e9c18..03189aa73 100644 --- a/tools/mfkey/mfkey32v2.c +++ b/tools/mfkey/mfkey32v2.c @@ -3,7 +3,7 @@ #include "crapto1.h" #include #include - + int main (int argc, char *argv[]) { struct Crypto1State *s,*t; uint64_t key; // recovered key @@ -46,7 +46,7 @@ int main (int argc, char *argv[]) { printf("\nLFSR succesors of the tag challenge:\n"); uint32_t p64 = prng_successor(nt0, 64); uint32_t p64b = prng_successor(nt1, 64); - + printf(" nt': %08x\n", p64); printf(" nt'': %08x\n", prng_successor(p64, 32)); @@ -56,13 +56,13 @@ int main (int argc, char *argv[]) { printf(" ks2: %08x\n",ks2); s = lfsr_recovery32(ar0_enc ^ p64, 0); - + for(t = s; t->odd | t->even; ++t) { lfsr_rollback_word(t, 0, 0); lfsr_rollback_word(t, nr0_enc, 1); lfsr_rollback_word(t, uid ^ nt0, 0); crypto1_get_lfsr(t, &key); - + crypto1_word(t, uid ^ nt1, 0); crypto1_word(t, nr1_enc, 1); if (ar1_enc == (crypto1_word(t, 0, 0) ^ p64b)) { diff --git a/tools/mfkey/mfkey64.c b/tools/mfkey/mfkey64.c index bf1226ba8..a05cd223e 100755 --- a/tools/mfkey/mfkey64.c +++ b/tools/mfkey/mfkey64.c @@ -26,7 +26,7 @@ int main (int argc, char *argv[]) { int encc = argc - 6; int enclen[encc]; - uint8_t enc[encc][120]; + uint8_t enc[encc][120]; sscanf(argv[1],"%x",&uid); sscanf(argv[2],"%x",&nt); @@ -39,7 +39,7 @@ int main (int argc, char *argv[]) { sscanf(argv[i+6] + i2*2, "%2x", (unsigned int *)&enc[i][i2]); } } - + printf("Recovering key for:\n"); printf(" uid: %08x\n",uid); @@ -60,7 +60,7 @@ int main (int argc, char *argv[]) { printf("\nLFSR succesors of the tag challenge:\n"); printf(" nt': %08x\n",prng_successor(nt, 64)); printf(" nt'': %08x\n",prng_successor(nt, 96)); - + // Extract the keystream from the messages printf("\nKeystream used to generate {ar} and {at}:\n"); ks2 = ar_enc ^ prng_successor(nt, 64); @@ -73,11 +73,11 @@ int main (int argc, char *argv[]) { // Decrypting communication using keystream if presented if (argc > 6 ) { printf("\nDecrypted communication:\n"); - uint8_t ks4; + uint8_t ks4; int rollb = 0; for (int i = 0; i < encc; i++) { printf("{dec%d}: ", i); - for (int i2 = 0; i2 < enclen[i]; i2++) { + for (int i2 = 0; i2 < enclen[i]; i2++) { ks4 = crypto1_byte(revstate, 0, 0); printf("%02x", ks4 ^ enc[i][i2]); rollb += 1; @@ -87,7 +87,7 @@ int main (int argc, char *argv[]) { for (int i = 0; i < rollb; i++) lfsr_rollback_byte(revstate, 0, 0); } - + lfsr_rollback_word(revstate, 0, 0); lfsr_rollback_word(revstate, 0, 0); lfsr_rollback_word(revstate, nr_enc, 1); diff --git a/tools/nonce2key/crapto1.c b/tools/nonce2key/crapto1.c index fcfa931c4..5412ca8f6 100644 --- a/tools/nonce2key/crapto1.c +++ b/tools/nonce2key/crapto1.c @@ -221,7 +221,7 @@ struct Crypto1State* lfsr_recovery32(uint32_t ks2, uint32_t in) // allocate memory for out of place bucket_sort bucket_array_t bucket; - + for (uint32_t i = 0; i < 2; i++) { for (uint32_t j = 0; j <= 0xff; j++) { bucket[i][j].head = malloc(sizeof(uint32_t)<<14); @@ -423,7 +423,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb) ret |= lfsr_rollback_bit(s, BEBIT(in, 18), fb) << (18 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 17), fb) << (17 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 16), fb) << (16 ^ 24); - + ret |= lfsr_rollback_bit(s, BEBIT(in, 15), fb) << (15 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 14), fb) << (14 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 13), fb) << (13 ^ 24); @@ -432,7 +432,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State *s, uint32_t in, int fb) ret |= lfsr_rollback_bit(s, BEBIT(in, 10), fb) << (10 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 9), fb) << (9 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 8), fb) << (8 ^ 24); - + ret |= lfsr_rollback_bit(s, BEBIT(in, 7), fb) << (7 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 6), fb) << (6 ^ 24); ret |= lfsr_rollback_bit(s, BEBIT(in, 5), fb) << (5 ^ 24); @@ -482,7 +482,7 @@ uint32_t *lfsr_prefix_ks(uint8_t ks[8], int isodd) { uint32_t *candidates = malloc(4 << 10); if(!candidates) return 0; - + uint32_t c, entry; int size = 0, i, good; @@ -530,7 +530,7 @@ static struct Crypto1State* check_pfx_parity(uint32_t prefix, uint32_t rresp, ui } return sl + good; -} +} /** lfsr_common_prefix * Implentation of the common prefix attack. diff --git a/tools/nonce2key/crapto1.h b/tools/nonce2key/crapto1.h index 3eaf88b72..2fd6600ec 100644 --- a/tools/nonce2key/crapto1.h +++ b/tools/nonce2key/crapto1.h @@ -44,7 +44,7 @@ uint32_t lfsr_rollback_word(struct Crypto1State* s, uint32_t in, int fb); int nonce_distance(uint32_t from, uint32_t to); #define SWAPENDIAN(x)\ (x = (x >> 8 & 0xff00ff) | (x & 0xff00ff) << 8, x = x >> 16 | x << 16) - + #define FOREACH_VALID_NONCE(N, FILTER, FSIZE)\ uint32_t __n = 0,__M = 0, N = 0;\ int __i;\ @@ -54,7 +54,7 @@ int nonce_distance(uint32_t from, uint32_t to); break;\ else if(__i)\ __M = prng_successor(__M, (__i == 7) ? 48 : 8);\ - else + else #define LF_POLY_ODD (0x29CE5C) #define LF_POLY_EVEN (0x870804) diff --git a/tools/nonce2key/crypto1.c b/tools/nonce2key/crypto1.c index f49a07225..14e2cc829 100644 --- a/tools/nonce2key/crypto1.c +++ b/tools/nonce2key/crypto1.c @@ -25,8 +25,8 @@ struct Crypto1State * crypto1_create(uint64_t key) struct Crypto1State *s = malloc(sizeof(*s)); if ( !s ) return NULL; - s->odd = s->even = 0; - + s->odd = s->even = 0; + int i; //for(i = 47;s && i > 0; i -= 2) { for(i = 47; i > 0; i -= 2) { @@ -103,7 +103,7 @@ uint32_t crypto1_word(struct Crypto1State *s, uint32_t in, int is_encrypted) ret |= crypto1_bit(s, BEBIT(in, 5), is_encrypted) << (5 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 6), is_encrypted) << (6 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 7), is_encrypted) << (7 ^ 24); - + ret |= crypto1_bit(s, BEBIT(in, 8), is_encrypted) << (8 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 9), is_encrypted) << (9 ^ 24); ret |= crypto1_bit(s, BEBIT(in, 10), is_encrypted) << (10 ^ 24); diff --git a/tools/nonce2key/nonce2key.c b/tools/nonce2key/nonce2key.c index fffa5a2ac..f7bbc43b7 100644 --- a/tools/nonce2key/nonce2key.c +++ b/tools/nonce2key/nonce2key.c @@ -20,7 +20,7 @@ int main(const int argc, const char* argv[]) { sscanf(argv[2],"%08x", &nt); sscanf(argv[3],"%016" SCNx64 ,&par_info); sscanf(argv[4],"%016" SCNx64 ,&ks_info); - + // Reset the last three significant bits of the reader nonce nr &= 0xffffff1f; @@ -47,7 +47,7 @@ int main(const int argc, const char* argv[]) { printf("%01x|\n", par[i][7]); } printf("+----+--------+---+-----+---------------+\n"); - + state = lfsr_common_prefix(nr,rr,ks3x,par); lfsr_rollback_word(state,uid^nt,0); crypto1_get_lfsr(state,&key_recovered); diff --git a/uart/uart.h b/uart/uart.h index a1521a58d..d724831be 100644 --- a/uart/uart.h +++ b/uart/uart.h @@ -86,7 +86,7 @@ void uart_close(const serial_port sp); * * Returns FALSE if there was an error reading from the device. Note that a * partial read may have completed into the buffer by the corresponding - * implementation, so pszRxLen should be checked to see if any data was written. + * implementation, so pszRxLen should be checked to see if any data was written. */ bool uart_receive(const serial_port sp, uint8_t* pbtRx, size_t pszMaxRxLen, size_t* pszRxLen); diff --git a/uart/uart_posix.c b/uart/uart_posix.c index c3ff7dcca..58f24298d 100644 --- a/uart/uart_posix.c +++ b/uart/uart_posix.c @@ -34,7 +34,7 @@ */ // Test if we are dealing with posix operating systems -#ifndef _WIN32 +#ifndef _WIN32 #define _DEFAULT_SOURCE #include "uart.h" @@ -88,7 +88,7 @@ serial_port uart_open(const char* pcPortName) { } timeout.tv_usec = 300000; // 300 000 micro seconds - + char *colon = strrchr(addrstr, ':'); char *portstr; if (colon) { @@ -142,7 +142,7 @@ serial_port uart_open(const char* pcPortName) { return sp; } - + sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK); if (sp->fd == -1) { uart_close(sp); @@ -196,12 +196,12 @@ serial_port uart_open(const char* pcPortName) { #ifdef WITH_FPC if ( uart_set_speed(sp, 115200) ) { - printf("[=] UART Setting serial baudrate 115200 [FPC enabled]\n"); + printf("[=] UART Setting serial baudrate 115200 [FPC enabled]\n"); } else { uart_set_speed(sp, 9600); - printf("[=] UART Setting serial baudrate 9600 [FPC enabled]\n"); + printf("[=] UART Setting serial baudrate 9600 [FPC enabled]\n"); } -#else +#else // set speed, works for UBUNTU 14.04 bool success = uart_set_speed(sp, 460800); if (success) { @@ -210,7 +210,7 @@ serial_port uart_open(const char* pcPortName) { uart_set_speed(sp, 115200); printf("[=] UART Setting serial baudrate 115200\n"); } -#endif +#endif return sp; } @@ -229,7 +229,7 @@ void uart_close(const serial_port sp) { int err = fcntl(spu->fd, F_SETLK, &fl); if ( err == -1) { //perror("fcntl"); - } + } close(spu->fd); free(sp); } @@ -242,7 +242,7 @@ bool uart_receive(const serial_port sp, uint8_t* pbtRx, size_t pszMaxRxLen, size // Reset the output count *pszRxLen = 0; - + do { // Reset file descriptor FD_ZERO(&rfds); @@ -365,11 +365,11 @@ bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { # endif default: return false; }; - + struct termios ti; - if (tcgetattr(spu->fd,&ti) == -1) + if (tcgetattr(spu->fd,&ti) == -1) return false; - + // Set port speed (Input and Output) cfsetispeed(&ti, stPortSpeed); cfsetospeed(&ti, stPortSpeed); @@ -380,10 +380,10 @@ uint32_t uart_get_speed(const serial_port sp) { struct termios ti; uint32_t uiPortSpeed; const serial_port_unix* spu = (serial_port_unix*)sp; - - if (tcgetattr(spu->fd, &ti) == -1) + + if (tcgetattr(spu->fd, &ti) == -1) return 0; - + // Set port speed (Input) speed_t stPortSpeed = cfgetispeed(&ti); switch (stPortSpeed) { diff --git a/uart/uart_win32.c b/uart/uart_win32.c index 438f586c8..5f269c677 100644 --- a/uart/uart_win32.c +++ b/uart/uart_win32.c @@ -67,8 +67,8 @@ serial_port uart_open(const char* pcPortName) { uart_close(sp); return INVALID_SERIAL_PORT; } - - // Prepare the device control + + // Prepare the device control // doesn't matter since PM3 device ignors this CDC command: set_line_coding in usb_cdc.c memset(&sp->dcb, 0, sizeof(DCB)); sp->dcb.DCBlength = sizeof(DCB); @@ -77,7 +77,7 @@ serial_port uart_open(const char* pcPortName) { printf("[!] UART error cdc setup\n"); return INVALID_SERIAL_PORT; } - + // Update the active serial port if (!SetCommState(sp->hPort, &sp->dcb)) { uart_close(sp); @@ -92,20 +92,20 @@ serial_port uart_open(const char* pcPortName) { sp->ct.ReadTotalTimeoutConstant = 1500; sp->ct.WriteTotalTimeoutMultiplier = 1000; sp->ct.WriteTotalTimeoutConstant = 0; -#else +#else sp->ct.ReadIntervalTimeout = 30; sp->ct.ReadTotalTimeoutMultiplier = 0; sp->ct.ReadTotalTimeoutConstant = 30; sp->ct.WriteTotalTimeoutMultiplier = 30; sp->ct.WriteTotalTimeoutConstant = 0; -#endif - +#endif + if (!SetCommTimeouts(sp->hPort, &sp->ct)) { uart_close(sp); printf("[!] UART error while setting comm time outs\n"); return INVALID_SERIAL_PORT; } - + PurgeComm(sp->hPort, PURGE_RXABORT | PURGE_RXCLEAR); #ifdef WITH_FPC @@ -113,7 +113,7 @@ serial_port uart_open(const char* pcPortName) { printf("[=] UART Setting serial baudrate 115200 [FPC enabled]\n"); } else { uart_set_speed(sp, 9600); - printf("[=] UART Setting serial baudrate 9600 [FPC enabled]\n"); + printf("[=] UART Setting serial baudrate 9600 [FPC enabled]\n"); } #else bool success = uart_set_speed(sp, 460800); @@ -123,7 +123,7 @@ serial_port uart_open(const char* pcPortName) { uart_set_speed(sp, 115200); printf("[=] UART Setting serial baudrate 115200\n"); } -#endif +#endif return sp; } @@ -149,7 +149,7 @@ bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) { default: return false; }; - + spw = (serial_port_windows*)sp; spw->dcb.BaudRate = uiPortSpeed; bool result = SetCommState(spw->hPort, &spw->dcb); @@ -170,7 +170,7 @@ bool uart_receive(const serial_port sp, uint8_t* p_rx, size_t pszMaxRxLen, size_ } bool uart_send(const serial_port sp, const uint8_t* p_tx, const size_t len) { - DWORD txlen = 0; + DWORD txlen = 0; return WriteFile(((serial_port_windows*)sp)->hPort, p_tx, len, &txlen, NULL); } diff --git a/zlib/deflate.c b/zlib/deflate.c index 8e9a3e653..593f5ebd3 100644 --- a/zlib/deflate.c +++ b/zlib/deflate.c @@ -61,14 +61,14 @@ const char deflate_copyright[] = */ //----------------------------------------------------------------------------- -// This version of zlib is modified for use within the Proxmark3 project. +// This version of zlib is modified for use within the Proxmark3 project. // Files from the original distribution which are not required for this // purpose are not included. All modifications can easily be found // by searching for #ifdef ZLIB_PM3_TUNED and #ifndef ZLIB_PM3_TUNED. //----------------------------------------------------------------------------- - + /* =========================================================================== * Function prototypes. */ @@ -1776,7 +1776,7 @@ local uInt try_harder(s, strstart, lookahead, hash_head) } else { combined_gain = s->strstart - strstart + 1 - MIN_MATCH; // (possibly truncated) previous_length - 3 literals } - if (match_length < MIN_MATCH) { + if (match_length < MIN_MATCH) { combined_gain += 0; // no gain } else { combined_gain += match_length - MIN_MATCH; // match_length bytes are coded as three literals @@ -1791,7 +1791,7 @@ local uInt try_harder(s, strstart, lookahead, hash_head) hash_head = s->head[s->ins_h]; } while (s->strstart <= strstart-1 + prev_length // try to truncate the previous match to 1, 3, ... prev_length && s->strstart <= s->window_size - MIN_LOOKAHEAD); // watch out for the end of the input - + s->strstart = strstart_save; s->lookahead = lookahead_save; s->ins_h = ins_h_save; diff --git a/zlib/inflate.c b/zlib/inflate.c index 656cd6464..1b3003370 100644 --- a/zlib/inflate.c +++ b/zlib/inflate.c @@ -81,14 +81,14 @@ */ //----------------------------------------------------------------------------- -// This version of zlib is modified for use within the Proxmark3 project. +// This version of zlib is modified for use within the Proxmark3 project. // Files from the original distribution which are not required for this // purpose are not included. All modifications can easily be found // by searching for #ifdef ZLIB_PM3_TUNED and #ifndef ZLIB_PM3_TUNED. //----------------------------------------------------------------------------- - + #include "zutil.h" #include "inftrees.h" #include "inflate.h" @@ -858,7 +858,7 @@ int flush; #ifdef ZLIB_PM3_TUNED strm->msg = (char *)"fixed block coding not supported"; state->mode = BAD; -#else +#else fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); diff --git a/zlib/trees.c b/zlib/trees.c index df83f56a3..9d032bf9c 100644 --- a/zlib/trees.c +++ b/zlib/trees.c @@ -33,7 +33,7 @@ /* @(#) $Id$ */ //----------------------------------------------------------------------------- -// This version of zlib is modified for use within the Proxmark3 project. +// This version of zlib is modified for use within the Proxmark3 project. // Files from the original distribution which are not required for this // purpose are not included. All modifications can easily be found // by searching for #ifdef ZLIB_PM3_TUNED and #ifndef ZLIB_PM3_TUNED. @@ -997,9 +997,9 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) #ifdef DEBUG s->compressed_len += 3 + s->opt_len; #endif -#ifndef ZLIB_PM3_TUNED +#ifndef ZLIB_PM3_TUNED } -#endif +#endif Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. diff --git a/zlib/zlib.h b/zlib/zlib.h index b2aa55728..d62758aaf 100644 --- a/zlib/zlib.h +++ b/zlib/zlib.h @@ -29,7 +29,7 @@ */ //----------------------------------------------------------------------------- -// This version of zlib is modified for use within the Proxmark3 project. +// This version of zlib is modified for use within the Proxmark3 project. // Files from the original distribution which are not required for this // purpose are not included. All modifications can easily be found // by searching for #ifdef ZLIB_PM3_TUNED and #ifndef ZLIB_PM3_TUNED.