From 23f0a7d862fb41d21dd90403cb657e91705bf886 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 2 Apr 2015 12:48:52 -0400 Subject: [PATCH 001/132] lfem4x cleanup/add/fix changed spacing to tabs for cmdlfem4x.c finished the partially built lf em em4x50read function added save/restore GraphBuffer function in graph.c adjusted some tolerances in lfdemod.c added a maxLen argument to the askmandemod --- client/cmddata.c | 13 +- client/cmddata.h | 3 +- client/cmdlf.c | 5 + client/cmdlfem4x.c | 666 ++++++++++++++++++++++++++------------------- client/cmdlfem4x.h | 3 +- client/graph.c | 18 +- client/graph.h | 1 + common/lfdemod.c | 150 +++++----- 8 files changed, 505 insertions(+), 354 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 55959984..84a450f8 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -96,7 +96,7 @@ int CmdPrintDemodBuff(const char *Cmd) { char hex; char printBuff[512]={0x00}; - uint8_t numBits = DemodBufferLen & 0xFFF0; + uint8_t numBits = DemodBufferLen & 0xFFFC; sscanf(Cmd, "%c", &hex); if (hex == 'h'){ PrintAndLog("Usage: data printdemodbuffer [x]"); @@ -414,12 +414,13 @@ int ASKmanDemod(const char *Cmd, bool verbose, bool emSearch) int invert=0; int clk=0; int maxErr=100; + int maxLen=512*64; //param_getdec(Cmd, 0, &clk); //param_getdec(Cmd, 1, &invert); //maxErr = param_get32ex(Cmd, 2, 0xFFFFFFFF, 10); //if (maxErr == 0xFFFFFFFF) maxErr=100; uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - sscanf(Cmd, "%i %i %i", &clk, &invert, &maxErr); + sscanf(Cmd, "%i %i %i %i", &clk, &invert, &maxErr, &maxLen); if (invert != 0 && invert != 1) { PrintAndLog("Invalid argument: %s", Cmd); return 0; @@ -432,6 +433,7 @@ int ASKmanDemod(const char *Cmd, bool verbose, bool emSearch) if (g_debugMode==1) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen); if (BitLen==0) return 0; int errCnt=0; + if (maxLen 10 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data rawdemod am [clock] <0|1> [maxError]"); + if (strlen(Cmd) > 20 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: data rawdemod am [clock] <0|1> [maxError] [setSmplLen]"); PrintAndLog(" [set clock as integer] optional, if not set, autodetect."); PrintAndLog(" , 1 for invert output"); PrintAndLog(" [set maximum allowed errors], default = 100."); + PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)."); PrintAndLog(""); PrintAndLog(" sample: data rawdemod am = demod an ask/manchester tag from GraphBuffer"); PrintAndLog(" : data rawdemod am 32 = demod an ask/manchester tag from GraphBuffer using a clock of RF/32"); @@ -2065,7 +2068,7 @@ int CmdRawDemod(const char *Cmd) { char cmdp = Cmd[0]; //param_getchar(Cmd, 0); - if (strlen(Cmd) > 14 || cmdp == 'h' || cmdp == 'H' || strlen(Cmd)<2) { + if (strlen(Cmd) > 20 || cmdp == 'h' || cmdp == 'H' || strlen(Cmd)<2) { PrintAndLog("Usage: data rawdemod [modulation] |"); PrintAndLog(" [modulation] as 2 char, 'ab' for ask/biphase, 'am' for ask/manchester, 'ar' for ask/raw, 'fs' for fsk, ..."); PrintAndLog(" 'nr' for nrz/direct, 'p1' for psk1, 'p2' for psk2"); diff --git a/client/cmddata.h b/client/cmddata.h index f6b4b950..97bfdbcc 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -54,6 +54,7 @@ int CmdManchesterMod(const char *Cmd); int CmdNorm(const char *Cmd); int CmdNRZrawDemod(const char *Cmd); int CmdPlot(const char *Cmd); +int CmdPrintDemodBuff(const char *Cmd); int CmdRawDemod(const char *Cmd); int CmdSamples(const char *Cmd); int CmdTuneSamples(const char *Cmd); @@ -77,7 +78,7 @@ int getSamples(const char *Cmd, bool silent); #define MAX_DEMOD_BUF_LEN (1024*128) extern uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; extern int DemodBufferLen; - +extern uint8_t g_debugMode; #define BIGBUF_SIZE 40000 #endif diff --git a/client/cmdlf.c b/client/cmdlf.c index 54f396fd..3d29fc07 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -1094,6 +1094,11 @@ int CmdLFfind(const char *Cmd) return 1; } + ans=EM4x50Read("", false); + if (ans>0) { + PrintAndLog("\nValid EM4x50 ID Found!"); + return 1; + } PrintAndLog("\nNo Known Tags Found!\n"); if (testRaw=='u' || testRaw=='U'){ //test unknown tag formats (raw mode) diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index b915aa5a..79e8a8fe 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -19,6 +19,7 @@ #include "cmddata.h" #include "cmdlf.h" #include "cmdlfem4x.h" +#include "lfdemod.h" char *global_em410xId; static int CmdHelp(const char *Cmd); @@ -27,10 +28,10 @@ int CmdEMdemodASK(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); int findone = (cmdp == '1') ? 1 : 0; - UsbCommand c={CMD_EM410X_DEMOD}; - c.arg[0]=findone; - SendCommand(&c); - return 0; + UsbCommand c={CMD_EM410X_DEMOD}; + c.arg[0]=findone; + SendCommand(&c); + return 0; } /* Read the ID of an EM410x tag. @@ -43,21 +44,21 @@ int CmdEMdemodASK(const char *Cmd) */ int CmdEM410xRead(const char *Cmd) { - uint32_t hi=0; - uint64_t lo=0; + uint32_t hi=0; + uint64_t lo=0; - if(!AskEm410xDemod("", &hi, &lo)) return 0; - PrintAndLog("EM410x pattern found: "); - printEM410x(hi, lo); - if (hi){ - PrintAndLog ("EM410x XL pattern found"); - return 0; - } - char id[12] = {0x00}; - sprintf(id, "%010llx",lo); - - global_em410xId = id; - return 1; + if(!AskEm410xDemod("", &hi, &lo)) return 0; + PrintAndLog("EM410x pattern found: "); + printEM410x(hi, lo); + if (hi){ + PrintAndLog ("EM410x XL pattern found"); + return 0; + } + char id[12] = {0x00}; + sprintf(id, "%010llx",lo); + + global_em410xId = id; + return 1; } // emulate an EM410X tag @@ -83,52 +84,52 @@ int CmdEM410xSim(const char *Cmd) PrintAndLog("Starting simulating UID %02X%02X%02X%02X%02X", uid[0],uid[1],uid[2],uid[3],uid[4]); PrintAndLog("Press pm3-button to about simulation"); - /* clock is 64 in EM410x tags */ - int clock = 64; + /* clock is 64 in EM410x tags */ + int clock = 64; - /* clear our graph */ - ClearGraph(0); + /* clear our graph */ + ClearGraph(0); - /* write 9 start bits */ - for (i = 0; i < 9; i++) - AppendGraph(0, clock, 1); + /* write 9 start bits */ + for (i = 0; i < 9; i++) + AppendGraph(0, clock, 1); - /* for each hex char */ - parity[0] = parity[1] = parity[2] = parity[3] = 0; - for (i = 0; i < 10; i++) - { - /* read each hex char */ - sscanf(&Cmd[i], "%1x", &n); - for (j = 3; j >= 0; j--, n/= 2) - binary[j] = n % 2; + /* for each hex char */ + parity[0] = parity[1] = parity[2] = parity[3] = 0; + for (i = 0; i < 10; i++) + { + /* read each hex char */ + sscanf(&Cmd[i], "%1x", &n); + for (j = 3; j >= 0; j--, n/= 2) + binary[j] = n % 2; - /* append each bit */ - AppendGraph(0, clock, binary[0]); - AppendGraph(0, clock, binary[1]); - AppendGraph(0, clock, binary[2]); - AppendGraph(0, clock, binary[3]); + /* append each bit */ + AppendGraph(0, clock, binary[0]); + AppendGraph(0, clock, binary[1]); + AppendGraph(0, clock, binary[2]); + AppendGraph(0, clock, binary[3]); - /* append parity bit */ - AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); + /* append parity bit */ + AppendGraph(0, clock, binary[0] ^ binary[1] ^ binary[2] ^ binary[3]); - /* keep track of column parity */ - parity[0] ^= binary[0]; - parity[1] ^= binary[1]; - parity[2] ^= binary[2]; - parity[3] ^= binary[3]; - } + /* keep track of column parity */ + parity[0] ^= binary[0]; + parity[1] ^= binary[1]; + parity[2] ^= binary[2]; + parity[3] ^= binary[3]; + } - /* parity columns */ - AppendGraph(0, clock, parity[0]); - AppendGraph(0, clock, parity[1]); - AppendGraph(0, clock, parity[2]); - AppendGraph(0, clock, parity[3]); + /* parity columns */ + AppendGraph(0, clock, parity[0]); + AppendGraph(0, clock, parity[1]); + AppendGraph(0, clock, parity[2]); + AppendGraph(0, clock, parity[3]); - /* stop bit */ - AppendGraph(1, clock, 0); + /* stop bit */ + AppendGraph(1, clock, 0); - CmdLFSim("0"); //240 start_gap. - return 0; + CmdLFSim("0"); //240 start_gap. + return 0; } /* Function is equivalent of lf read + data samples + em410xread @@ -156,6 +157,7 @@ int CmdEM410xWatch(const char *Cmd) return 0; } +//currently only supports manchester modulations int CmdEM410xWatchnSpoof(const char *Cmd) { CmdEM410xWatch(Cmd); @@ -164,6 +166,65 @@ int CmdEM410xWatchnSpoof(const char *Cmd) return 0; } +bool EM_EndParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType) +{ + if (rows*cols>size) return false; + uint8_t colP=0; + //assume last row is a parity row and do not test + for (uint8_t colNum = 0; colNum < cols-1; colNum++) { + for (uint8_t rowNum = 0; rowNum < rows; rowNum++) { + colP ^= BitStream[(rowNum*cols)+colNum]; + } + if (colP != pType) return false; + } + return true; +} + +bool EM_ByteParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType) +{ + if (rows*cols>size) return false; + uint8_t rowP=0; + //assume last row is a parity row and do not test + for (uint8_t rowNum = 0; rowNum < rows-1; rowNum++) { + for (uint8_t colNum = 0; colNum < cols; colNum++) { + rowP ^= BitStream[(rowNum*cols)+colNum]; + } + if (rowP != pType) return false; + } + return true; +} + +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) PrintAndLog(""); + PrintAndLog("%d%d%d%d%d%d%d%d %d -> 0x%02x", + BitStream[i*9], + BitStream[i*9+1], + BitStream[i*9+2], + BitStream[i*9+3], + BitStream[i*9+4], + BitStream[i*9+5], + BitStream[i*9+6], + BitStream[i*9+7], + BitStream[i*9+8], + bytebits_to_byte(BitStream+i*9,8) + ); + } + if (pTest) + PrintAndLog("Parity Passed"); + else + PrintAndLog("Parity Failed"); + } + //PrintAndLog("Code: %08x",code); + return code; +} /* Read the transmitted data of an EM4x50 tag * Format: * @@ -183,135 +244,192 @@ int CmdEM410xWatchnSpoof(const char *Cmd) * is stored in the blocks defined in the control word First and Last * Word Read values. UID is stored in block 32. */ +int EM4x50Read(const char *Cmd, bool verbose) +{ + uint8_t fndClk[]={0,8,16,32,40,50,64}; + int clk = 0; + int invert = 0; + sscanf(Cmd, "%i %i", &clk, &invert); + int tol = 0; + int i, j, startblock, skip, block, start, end, low, high, minClk; + bool complete= false; + int tmpbuff[MAX_GRAPH_TRACE_LEN / 64]; + save_restoreGB(1); + uint32_t Code[6]; + char tmp[6]; + + char tmp2[20]; + high= low= 0; + memset(tmpbuff, 0, MAX_GRAPH_TRACE_LEN / 64); + + // first get high and low values + for (i = 0; i < GraphTraceLen; i++) + { + if (GraphBuffer[i] > high) + high = GraphBuffer[i]; + else if (GraphBuffer[i] < low) + low = GraphBuffer[i]; + } + + // populate a buffer with pulse lengths + i= 0; + j= 0; + minClk= 255; + while (i < GraphTraceLen) + { + // measure from low to low + while ((GraphBuffer[i] > low) && (i low) && (i=(MAX_GRAPH_TRACE_LEN/64)) { + break; + } + tmpbuff[j++]= i - start; + if (i-start < minClk) minClk = i-start; + } + // set clock + if (!clk){ + for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) { + tol = fndClk[clkCnt]/8; + if (fndClk[clkCnt]-tol >= minClk) { + clk=fndClk[clkCnt]; + break; + } + } + } + + // look for data start - should be 2 pairs of LW (pulses of clk*3,clk*2) + start= -1; + skip= 0; + for (i= 0; i < j - 4 ; ++i) + { + skip += tmpbuff[i]; + if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) + if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) + if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) + if (tmpbuff[i+3] >= clk-tol) + { + start= i + 4; + break; + } + } + startblock= i + 4; + + // skip over the remainder of LW + skip += tmpbuff[i+1] + tmpbuff[i+2] + clk + clk/8; + + int phaseoff = tmpbuff[i+3]-clk; + + // now do it again to find the end + end = skip; + for (i += 3; i < j - 4 ; ++i) + { + end += tmpbuff[i]; + if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3 + tol) + if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2 + tol) + if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3 + tol) + if (tmpbuff[i+3] >= clk-tol) + { + complete= true; + break; + } + } + end = i; + // report back + if (verbose || g_debugMode) { + if (start >= 0) { + PrintAndLog("\nNote: should print 45 bits then 0177 (end of block)"); + PrintAndLog(" for each block"); + PrintAndLog(" Also, sometimes the demod gets out of sync and "); + PrintAndLog(" inverts the output - when this happens the 0177"); + PrintAndLog(" will be 3 extra 1's at the end"); + PrintAndLog(" 'data askedge' command may fix that"); + } else { + PrintAndLog("No data found!"); + PrintAndLog("Try again with more samples."); + return 0; + } + if (!complete) + { + PrintAndLog("*** Warning!"); + PrintAndLog("Partial data - no end found!"); + PrintAndLog("Try again with more samples."); + } + } else if (start < 0) return 0; + start=skip; + snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk*47); + // get rid of leading crap + snprintf(tmp, sizeof(tmp),"%i",skip); + CmdLtrim(tmp); + bool pTest; + bool AllPTest=true; + // now work through remaining buffer printing out data blocks + block = 0; + i = startblock; + while (block < 6) + { + if (verbose || g_debugMode) PrintAndLog("\nBlock %i:", block); + skip = phaseoff; + + // look for LW before start of next block + for ( ; i < j - 4 ; ++i) + { + skip += tmpbuff[i]; + if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) + if (tmpbuff[i+1] >= clk-tol) + break; + } + skip += clk; + phaseoff = tmpbuff[i+1]-clk; + i += 2; + if (ASKmanDemod(tmp2, false, false)<1) return 0; + //set DemodBufferLen to just one block + DemodBufferLen = skip/clk; + //test parities + pTest = EM_ByteParityTest(DemodBuffer,DemodBufferLen,5,9,0); + pTest &= EM_EndParityTest(DemodBuffer,DemodBufferLen,5,9,0); + AllPTest &= pTest; + //get output + Code[block]=OutputEM4x50_Block(DemodBuffer,DemodBufferLen,verbose, pTest); + if (g_debugMode) PrintAndLog("\nskipping %d samples, bits:%d",start, skip/clk); + //skip to start of next block + snprintf(tmp,sizeof(tmp),"%i",skip); + CmdLtrim(tmp); + block++; + if (i>=end) break; //in case chip doesn't output 6 blocks + } + //print full code: + if (verbose || g_debugMode || AllPTest){ + PrintAndLog("Found data at sample: %i - using clock: %i",skip,clk); + //PrintAndLog("\nSummary:"); + end=block; + for (block=0; block high) - high = GraphBuffer[i]; - else if (GraphBuffer[i] < low) - low = GraphBuffer[i]; - } - - /* populate a buffer with pulse lengths */ - i= 0; - j= 0; - while (i < GraphTraceLen) - { - // measure from low to low - while ((GraphBuffer[i] > low) && (i low) && (i=(MAX_GRAPH_TRACE_LEN/64)) { - break; - } - tmpbuff[j++]= i - start; - } - - /* look for data start - should be 2 pairs of LW (pulses of 192,128) */ - start= -1; - skip= 0; - for (i= 0; i < j - 4 ; ++i) - { - skip += tmpbuff[i]; - if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194) - if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130) - if (tmpbuff[i+2] >= 190 && tmpbuff[i+2] <= 194) - if (tmpbuff[i+3] >= 126 && tmpbuff[i+3] <= 130) - { - start= i + 3; - break; - } - } - startblock= i + 3; - - /* skip over the remainder of the LW */ - skip += tmpbuff[i+1]+tmpbuff[i+2]; - while (skip < MAX_GRAPH_TRACE_LEN && GraphBuffer[skip] > low) - ++skip; - skip += 8; - - /* now do it again to find the end */ - end= start; - for (i += 3; i < j - 4 ; ++i) - { - end += tmpbuff[i]; - if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194) - if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130) - if (tmpbuff[i+2] >= 190 && tmpbuff[i+2] <= 194) - if (tmpbuff[i+3] >= 126 && tmpbuff[i+3] <= 130) - { - complete= true; - break; - } - } - - if (start >= 0) - PrintAndLog("Found data at sample: %i",skip); - else - { - PrintAndLog("No data found!"); - PrintAndLog("Try again with more samples."); - return 0; - } - - if (!complete) - { - PrintAndLog("*** Warning!"); - PrintAndLog("Partial data - no end found!"); - PrintAndLog("Try again with more samples."); - } - - /* get rid of leading crap */ - sprintf(tmp,"%i",skip); - CmdLtrim(tmp); - - /* now work through remaining buffer printing out data blocks */ - block= 0; - i= startblock; - while (block < 6) - { - PrintAndLog("Block %i:", block); - // mandemod routine needs to be split so we can call it for data - // just print for now for debugging - CmdManchesterDemod("i 64"); - skip= 0; - /* look for LW before start of next block */ - for ( ; i < j - 4 ; ++i) - { - skip += tmpbuff[i]; - if (tmpbuff[i] >= 190 && tmpbuff[i] <= 194) - if (tmpbuff[i+1] >= 126 && tmpbuff[i+1] <= 130) - break; - } - while (GraphBuffer[skip] > low) - ++skip; - skip += 8; - sprintf(tmp,"%i",skip); - CmdLtrim(tmp); - start += skip; - block++; - } - return 0; + return EM4x50Read(Cmd, true); } int CmdEM410xWrite(const char *Cmd) { - uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value - int card = 0xFF; // invalid card value + uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value + int card = 0xFF; // invalid card value unsigned int clock = 0; // invalid clock value sscanf(Cmd, "%" PRIx64 " %d %d", &id, &card, &clock); @@ -370,133 +488,133 @@ int CmdEM410xWrite(const char *Cmd) return 0; } - UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}}; - SendCommand(&c); + UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}}; + SendCommand(&c); - return 0; + return 0; } int CmdReadWord(const char *Cmd) { int Word = -1; //default to invalid word - UsbCommand c; - - sscanf(Cmd, "%d", &Word); - + UsbCommand c; + + sscanf(Cmd, "%d", &Word); + if ( (Word > 15) | (Word < 0) ) { - PrintAndLog("Word must be between 0 and 15"); - return 1; - } - - PrintAndLog("Reading word %d", Word); - - c.cmd = CMD_EM4X_READ_WORD; - c.d.asBytes[0] = 0x0; //Normal mode - c.arg[0] = 0; - c.arg[1] = Word; - c.arg[2] = 0; - SendCommand(&c); - return 0; + PrintAndLog("Word must be between 0 and 15"); + return 1; + } + + PrintAndLog("Reading word %d", Word); + + c.cmd = CMD_EM4X_READ_WORD; + c.d.asBytes[0] = 0x0; //Normal mode + c.arg[0] = 0; + c.arg[1] = Word; + c.arg[2] = 0; + SendCommand(&c); + return 0; } int CmdReadWordPWD(const char *Cmd) { int Word = -1; //default to invalid word - int Password = 0xFFFFFFFF; //default to blank password - UsbCommand c; - - sscanf(Cmd, "%d %x", &Word, &Password); - + int Password = 0xFFFFFFFF; //default to blank password + UsbCommand c; + + sscanf(Cmd, "%d %x", &Word, &Password); + if ( (Word > 15) | (Word < 0) ) { - PrintAndLog("Word must be between 0 and 15"); - return 1; - } - - PrintAndLog("Reading word %d with password %08X", Word, Password); - - c.cmd = CMD_EM4X_READ_WORD; - c.d.asBytes[0] = 0x1; //Password mode - c.arg[0] = 0; - c.arg[1] = Word; - c.arg[2] = Password; - SendCommand(&c); - return 0; + PrintAndLog("Word must be between 0 and 15"); + return 1; + } + + PrintAndLog("Reading word %d with password %08X", Word, Password); + + c.cmd = CMD_EM4X_READ_WORD; + c.d.asBytes[0] = 0x1; //Password mode + c.arg[0] = 0; + c.arg[1] = Word; + c.arg[2] = Password; + SendCommand(&c); + return 0; } int CmdWriteWord(const char *Cmd) { - int Word = 16; //default to invalid block - int Data = 0xFFFFFFFF; //default to blank data - UsbCommand c; - - sscanf(Cmd, "%x %d", &Data, &Word); - - if (Word > 15) { - PrintAndLog("Word must be between 0 and 15"); - return 1; - } - - PrintAndLog("Writing word %d with data %08X", Word, Data); - - c.cmd = CMD_EM4X_WRITE_WORD; - c.d.asBytes[0] = 0x0; //Normal mode - c.arg[0] = Data; - c.arg[1] = Word; - c.arg[2] = 0; - SendCommand(&c); - return 0; + int Word = 16; //default to invalid block + int Data = 0xFFFFFFFF; //default to blank data + UsbCommand c; + + sscanf(Cmd, "%x %d", &Data, &Word); + + if (Word > 15) { + PrintAndLog("Word must be between 0 and 15"); + return 1; + } + + PrintAndLog("Writing word %d with data %08X", Word, Data); + + c.cmd = CMD_EM4X_WRITE_WORD; + c.d.asBytes[0] = 0x0; //Normal mode + c.arg[0] = Data; + c.arg[1] = Word; + c.arg[2] = 0; + SendCommand(&c); + return 0; } int CmdWriteWordPWD(const char *Cmd) { - int Word = 16; //default to invalid word - int Data = 0xFFFFFFFF; //default to blank data - int Password = 0xFFFFFFFF; //default to blank password - UsbCommand c; - - sscanf(Cmd, "%x %d %x", &Data, &Word, &Password); - - if (Word > 15) { - PrintAndLog("Word must be between 0 and 15"); - return 1; - } - - PrintAndLog("Writing word %d with data %08X and password %08X", Word, Data, Password); - - c.cmd = CMD_EM4X_WRITE_WORD; - c.d.asBytes[0] = 0x1; //Password mode - c.arg[0] = Data; - c.arg[1] = Word; - c.arg[2] = Password; - SendCommand(&c); - return 0; + int Word = 16; //default to invalid word + int Data = 0xFFFFFFFF; //default to blank data + int Password = 0xFFFFFFFF; //default to blank password + UsbCommand c; + + sscanf(Cmd, "%x %d %x", &Data, &Word, &Password); + + if (Word > 15) { + PrintAndLog("Word must be between 0 and 15"); + return 1; + } + + PrintAndLog("Writing word %d with data %08X and password %08X", Word, Data, Password); + + c.cmd = CMD_EM4X_WRITE_WORD; + c.d.asBytes[0] = 0x1; //Password mode + c.arg[0] = Data; + c.arg[1] = Word; + c.arg[2] = Password; + SendCommand(&c); + return 0; } static command_t CommandTable[] = { - {"help", CmdHelp, 1, "This help"}, - {"em410xdemod", CmdEMdemodASK, 0, "[findone] -- Extract ID from EM410x tag (option 0 for continuous loop, 1 for only 1 tag)"}, - {"em410xread", CmdEM410xRead, 1, "[clock rate] -- Extract ID from EM410x tag"}, - {"em410xsim", CmdEM410xSim, 0, " -- Simulate EM410x tag"}, - {"em410xwatch", CmdEM410xWatch, 0, "['h'] -- Watches for EM410x 125/134 kHz tags (option 'h' for 134)"}, - {"em410xspoof", CmdEM410xWatchnSpoof, 0, "['h'] --- Watches for EM410x 125/134 kHz tags, and replays them. (option 'h' for 134)" }, - {"em410xwrite", CmdEM410xWrite, 1, " <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"}, - {"em4x50read", CmdEM4x50Read, 1, "Extract data from EM4x50 tag"}, - {"readword", CmdReadWord, 1, " -- Read EM4xxx word data"}, - {"readwordPWD", CmdReadWordPWD, 1, " -- Read EM4xxx word data in password mode"}, - {"writeword", CmdWriteWord, 1, " -- Write EM4xxx word data"}, - {"writewordPWD", CmdWriteWordPWD, 1, " -- Write EM4xxx word data in password mode"}, - {NULL, NULL, 0, NULL} + {"help", CmdHelp, 1, "This help"}, + {"em410xdemod", CmdEMdemodASK, 0, "[findone] -- Extract ID from EM410x tag (option 0 for continuous loop, 1 for only 1 tag)"}, + {"em410xread", CmdEM410xRead, 1, "[clock rate] -- Extract ID from EM410x tag"}, + {"em410xsim", CmdEM410xSim, 0, " -- Simulate EM410x tag"}, + {"em410xwatch", CmdEM410xWatch, 0, "['h'] -- Watches for EM410x 125/134 kHz tags (option 'h' for 134)"}, + {"em410xspoof", CmdEM410xWatchnSpoof, 0, "['h'] --- Watches for EM410x 125/134 kHz tags, and replays them. (option 'h' for 134)" }, + {"em410xwrite", CmdEM410xWrite, 1, " <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"}, + {"em4x50read", CmdEM4x50Read, 1, "Extract data from EM4x50 tag"}, + {"readword", CmdReadWord, 1, " -- Read EM4xxx word data"}, + {"readwordPWD", CmdReadWordPWD, 1, " -- Read EM4xxx word data in password mode"}, + {"writeword", CmdWriteWord, 1, " -- Write EM4xxx word data"}, + {"writewordPWD", CmdWriteWordPWD, 1, " -- Write EM4xxx word data in password mode"}, + {NULL, NULL, 0, NULL} }; int CmdLFEM4X(const char *Cmd) { - CmdsParse(CommandTable, Cmd); - return 0; + CmdsParse(CommandTable, Cmd); + return 0; } int CmdHelp(const char *Cmd) { - CmdsHelp(CommandTable); - return 0; + CmdsHelp(CommandTable); + return 0; } diff --git a/client/cmdlfem4x.h b/client/cmdlfem4x.h index baea50a4..400536d3 100644 --- a/client/cmdlfem4x.h +++ b/client/cmdlfem4x.h @@ -11,7 +11,6 @@ #ifndef CMDLFEM4X_H__ #define CMDLFEM4X_H__ -int CmdLFEM4X(const char *Cmd); int CmdEMdemodASK(const char *Cmd); int CmdEM410xRead(const char *Cmd); int CmdEM410xSim(const char *Cmd); @@ -19,9 +18,11 @@ int CmdEM410xWatch(const char *Cmd); int CmdEM410xWatchnSpoof(const char *Cmd); int CmdEM410xWrite(const char *Cmd); int CmdEM4x50Read(const char *Cmd); +int CmdLFEM4X(const char *Cmd); int CmdReadWord(const char *Cmd); int CmdReadWordPWD(const char *Cmd); int CmdWriteWord(const char *Cmd); int CmdWriteWordPWD(const char *Cmd); +int EM4x50Read(const char *Cmd, bool verbose); #endif diff --git a/client/graph.c b/client/graph.c index f4acc579..ae318ddf 100644 --- a/client/graph.c +++ b/client/graph.c @@ -17,7 +17,6 @@ int GraphBuffer[MAX_GRAPH_TRACE_LEN]; int GraphTraceLen; - /* write a manchester bit to the graph */ void AppendGraph(int redraw, int clock, int bit) { @@ -46,6 +45,23 @@ int ClearGraph(int redraw) return gtl; } +// option '1' to save GraphBuffer any other to restore +void save_restoreGB(uint8_t saveOpt) +{ + static int SavedGB[MAX_GRAPH_TRACE_LEN]; + static int SavedGBlen; + static bool GB_Saved = false; + + if (saveOpt==1) { //save + memcpy(SavedGB,GraphBuffer, sizeof(GraphBuffer)); + SavedGBlen = GraphTraceLen; + GB_Saved=true; + } else if (GB_Saved){ + memcpy(GraphBuffer,SavedGB, sizeof(GraphBuffer)); + GraphTraceLen = SavedGBlen; + } + return; +} // DETECT CLOCK NOW IN LFDEMOD.C diff --git a/client/graph.h b/client/graph.h index 8f810669..8deeb386 100644 --- a/client/graph.h +++ b/client/graph.h @@ -23,6 +23,7 @@ uint8_t GetNrzClock(const char str[], bool printAns, bool verbose); uint8_t GetFskClock(const char str[], bool printAns, bool verbose); uint8_t fskClocks(uint8_t *fc1, uint8_t *fc2, uint8_t *rf1, bool verbose); void setGraphBuf(uint8_t *buff, size_t size); +void save_restoreGB(uint8_t saveOpt); bool HasGraphData(); void DetectHighLowInGraph(int *high, int *low, bool addFuzz); diff --git a/common/lfdemod.c b/common/lfdemod.c index ffa807fe..df30aba4 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -114,6 +114,57 @@ uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_ return 0; } +// demodulates strong heavily clipped samples +int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low) +{ + size_t bitCnt=0, smplCnt=0, errCnt=0; + uint8_t waveHigh = 0; + //PrintAndLog("clk: %d", clk); + for (size_t i=0; i < *size; i++){ + if (BinStream[i] >= high && waveHigh){ + smplCnt++; + } else if (BinStream[i] <= low && !waveHigh){ + smplCnt++; + } else { //transition + if ((BinStream[i] >= high && !waveHigh) || (BinStream[i] <= low && waveHigh)){ + if (smplCnt > clk-(clk/4)-1) { //full clock + if (smplCnt > clk + (clk/4)+1) { //too many samples + errCnt++; + BinStream[bitCnt++]=77; + } else if (waveHigh) { + BinStream[bitCnt++] = invert; + BinStream[bitCnt++] = invert; + } else if (!waveHigh) { + BinStream[bitCnt++] = invert ^ 1; + BinStream[bitCnt++] = invert ^ 1; + } + waveHigh ^= 1; + smplCnt = 0; + } else if (smplCnt > (clk/2) - (clk/4)-1) { + if (waveHigh) { + BinStream[bitCnt++] = invert; + } else if (!waveHigh) { + BinStream[bitCnt++] = invert ^ 1; + } + waveHigh ^= 1; + smplCnt = 0; + } else if (!bitCnt) { + //first bit + waveHigh = (BinStream[i] >= high); + smplCnt = 1; + } else { + smplCnt++; + //transition bit oops + } + } else { //haven't hit new high or new low yet + smplCnt++; + } + } + } + *size = bitCnt; + return errCnt; +} + //by marshmellow //takes 3 arguments - clock, invert, maxErr as integers //attempts to demodulate ask while decoding manchester @@ -131,6 +182,13 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max int high, low; if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) return -2; //just noise + // if clean clipped waves detected run alternate demod + if (DetectCleanAskWave(BinStream, *size, high, low)) { + cleanAskRawDemod(BinStream, size, *clk, *invert, high, low); + return manrawdecode(BinStream, size); + } + + // PrintAndLog("DEBUG - valid high: %d - valid low: %d",high,low); int lastBit = 0; //set first clock check uint16_t bitnum = 0; //output counter @@ -138,7 +196,7 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max if (*clk <= 32) tol=1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely size_t iii = 0; //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance - if (!maxErr) initLoopMax = *clk * 2; + if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3; uint16_t errCnt = 0, MaxBits = 512; uint16_t bestStart = start; uint16_t bestErrCnt = 0; @@ -147,7 +205,7 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max if (start <= 0 || start > initLoopMax){ bestErrCnt = maxErr+1; // loop to find first wave that works - for (iii=0; iii < initLoopMax; ++iii){ + for (iii=0; iii < initLoopMax-tol-*clk; ++iii){ // if no peak skip if (BinStream[iii] < high && BinStream[iii] > low) continue; @@ -163,7 +221,7 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max if ((i-iii) > (MaxBits * *clk) || errCnt > maxErr) break; //got plenty of bits or too many errors } //we got more than 64 good bits and not all errors - if ((((i-iii)/ *clk) > (64)) && (errCnt<=maxErr)) { + if ((((i-iii)/ *clk) > (32)) && (errCnt<=maxErr)) { //possible good read if (!errCnt || errCnt < bestErrCnt){ bestStart = iii; //set this as new best run @@ -242,19 +300,17 @@ int manrawdecode(uint8_t * BitStream, size_t *size) } errCnt=0; } - if (bestErr<20){ - for (i=bestRun; i < *size-2; i+=2){ - if(BitStream[i] == 1 && (BitStream[i+1] == 0)){ - BitStream[bitnum++]=0; - } else if((BitStream[i] == 0) && BitStream[i+1] == 1){ - BitStream[bitnum++]=1; - } else { - BitStream[bitnum++]=77; - } - if(bitnum>MaxBits) break; + for (i=bestRun; i < *size-2; i+=2){ + if(BitStream[i] == 1 && (BitStream[i+1] == 0)){ + BitStream[bitnum++]=0; + } else if((BitStream[i] == 0) && BitStream[i+1] == 1){ + BitStream[bitnum++]=1; + } else { + BitStream[bitnum++]=77; } - *size=bitnum; + if(bitnum>MaxBits) break; } + *size=bitnum; return bestErr; } @@ -319,57 +375,6 @@ void askAmp(uint8_t *BitStream, size_t size) return; } -// demodulates strong heavily clipped samples -int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low) -{ - size_t bitCnt=0, smplCnt=0, errCnt=0; - uint8_t waveHigh = 0; - //PrintAndLog("clk: %d", clk); - for (size_t i=0; i < *size; i++){ - if (BinStream[i] >= high && waveHigh){ - smplCnt++; - } else if (BinStream[i] <= low && !waveHigh){ - smplCnt++; - } else { //transition - if ((BinStream[i] >= high && !waveHigh) || (BinStream[i] <= low && waveHigh)){ - if (smplCnt > clk-(clk/4)-1) { //full clock - if (smplCnt > clk + (clk/4)+1) { //too many samples - errCnt++; - BinStream[bitCnt++]=77; - } else if (waveHigh) { - BinStream[bitCnt++] = invert; - BinStream[bitCnt++] = invert; - } else if (!waveHigh) { - BinStream[bitCnt++] = invert ^ 1; - BinStream[bitCnt++] = invert ^ 1; - } - waveHigh ^= 1; - smplCnt = 0; - } else if (smplCnt > (clk/2) - (clk/4)-1) { - if (waveHigh) { - BinStream[bitCnt++] = invert; - } else if (!waveHigh) { - BinStream[bitCnt++] = invert ^ 1; - } - waveHigh ^= 1; - smplCnt = 0; - } else if (!bitCnt) { - //first bit - waveHigh = (BinStream[i] >= high); - smplCnt = 1; - } else { - smplCnt++; - //transition bit oops - } - } else { //haven't hit new high or new low yet - smplCnt++; - } - } - } - *size = bitCnt; - return errCnt; -} - //by marshmellow //takes 3 arguments - clock, invert and maxErr as integers //attempts to demodulate ask only @@ -401,13 +406,13 @@ int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max size_t MaxBits = 1024; //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance - if (!maxErr) initLoopMax = *clk * 2; + if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3; //if best start not already found by detectclock if (start <= 0 || start > initLoopMax){ bestErrCnt = maxErr+1; //PrintAndLog("DEBUG - lastbit - %d",lastBit); //loop to find first wave that works - for (iii=0; iii < initLoopMax; ++iii){ + for (iii=0; iii < initLoopMax - *clk; ++iii){ if ((BinStream[iii] >= high) || (BinStream[iii] <= low)){ lastBit = iii - *clk; //loop through to see if this start location works @@ -427,8 +432,8 @@ int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max } if ((i-iii)>(MaxBits * *clk)) break; //got enough bits } - //we got more than 64 good bits and not all errors - if ((((i-iii)/ *clk) > 64) && (errCnt<=maxErr)) { + //we got more than 32 good bits and not all errors + if ((((i-iii)/ *clk) > 32) && (errCnt<=maxErr)) { //possible good read if (errCnt==0){ bestStart=iii; @@ -859,7 +864,8 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) size_t i=0; uint8_t clk[]={8,16,32,40,50,64,100,128,255}; uint8_t loopCnt = 255; //don't need to loop through entire array... - if (size <= loopCnt) return -1; //not enough samples + if (size==0) return -1; + if (size <= loopCnt) loopCnt = size-1; //not enough samples //if we already have a valid clock quit for (;i<8;++i) @@ -892,10 +898,10 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) }else{ tol=0; } - if (!maxErr) loopCnt=clk[clkCnt]*2; + if (!maxErr && loopCnt>clk[clkCnt]*2) loopCnt=clk[clkCnt]*2; bestErr[clkCnt]=1000; //try lining up the peaks by moving starting point (try first 256) - for (ii=0; ii < loopCnt; ii++){ + for (ii=0; ii < loopCnt-tol-clk[clkCnt]; ii++){ if (dest[ii] < peak && dest[ii] > low) continue; errCnt=0; From 6e98444637baaa183812fad93cd7c03d645ba95e Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 2 Apr 2015 23:55:12 -0400 Subject: [PATCH 002/132] lfdemod reduce duplicate code remove check for best start position in demods and adjust the clock detect to always return best start position to the demods also small bug fix in lf em em4x50read --- client/cmdlfem4x.c | 138 ++++++++++++++++++++--------------------- common/lfdemod.c | 150 +++++++++------------------------------------ 2 files changed, 98 insertions(+), 190 deletions(-) diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index 79e8a8fe..47a5ac3e 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -166,6 +166,74 @@ int CmdEM410xWatchnSpoof(const char *Cmd) return 0; } +int CmdEM410xWrite(const char *Cmd) +{ + uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value + int card = 0xFF; // invalid card value + unsigned int clock = 0; // invalid clock value + + sscanf(Cmd, "%" PRIx64 " %d %d", &id, &card, &clock); + + // Check ID + if (id == 0xFFFFFFFFFFFFFFFF) { + PrintAndLog("Error! ID is required.\n"); + return 0; + } + if (id >= 0x10000000000) { + PrintAndLog("Error! Given EM410x ID is longer than 40 bits.\n"); + return 0; + } + + // Check Card + if (card == 0xFF) { + PrintAndLog("Error! Card type required.\n"); + return 0; + } + if (card < 0) { + PrintAndLog("Error! Bad card type selected.\n"); + return 0; + } + + // Check Clock + if (card == 1) + { + // Default: 64 + if (clock == 0) + clock = 64; + + // Allowed clock rates: 16, 32 and 64 + if ((clock != 16) && (clock != 32) && (clock != 64)) { + PrintAndLog("Error! Clock rate %d not valid. Supported clock rates are 16, 32 and 64.\n", clock); + return 0; + } + } + else if (clock != 0) + { + PrintAndLog("Error! Clock rate is only supported on T55x7 tags.\n"); + return 0; + } + + if (card == 1) { + PrintAndLog("Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock); + // NOTE: We really should pass the clock in as a separate argument, but to + // provide for backwards-compatibility for older firmware, and to avoid + // having to add another argument to CMD_EM410X_WRITE_TAG, we just store + // the clock rate in bits 8-15 of the card value + card = (card & 0xFF) | (((uint64_t)clock << 8) & 0xFF00); + } + else if (card == 0) + PrintAndLog("Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock); + else { + PrintAndLog("Error! Bad card type selected.\n"); + return 0; + } + + UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}}; + SendCommand(&c); + + return 0; +} + bool EM_EndParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t cols, uint8_t pType) { if (rows*cols>size) return false; @@ -300,7 +368,7 @@ int EM4x50Read(const char *Cmd, bool verbose) break; } } - } + } else tol = clk/8; // look for data start - should be 2 pairs of LW (pulses of clk*3,clk*2) start= -1; @@ -426,74 +494,6 @@ int CmdEM4x50Read(const char *Cmd) return EM4x50Read(Cmd, true); } -int CmdEM410xWrite(const char *Cmd) -{ - uint64_t id = 0xFFFFFFFFFFFFFFFF; // invalid id value - int card = 0xFF; // invalid card value - unsigned int clock = 0; // invalid clock value - - sscanf(Cmd, "%" PRIx64 " %d %d", &id, &card, &clock); - - // Check ID - if (id == 0xFFFFFFFFFFFFFFFF) { - PrintAndLog("Error! ID is required.\n"); - return 0; - } - if (id >= 0x10000000000) { - PrintAndLog("Error! Given EM410x ID is longer than 40 bits.\n"); - return 0; - } - - // Check Card - if (card == 0xFF) { - PrintAndLog("Error! Card type required.\n"); - return 0; - } - if (card < 0) { - PrintAndLog("Error! Bad card type selected.\n"); - return 0; - } - - // Check Clock - if (card == 1) - { - // Default: 64 - if (clock == 0) - clock = 64; - - // Allowed clock rates: 16, 32 and 64 - if ((clock != 16) && (clock != 32) && (clock != 64)) { - PrintAndLog("Error! Clock rate %d not valid. Supported clock rates are 16, 32 and 64.\n", clock); - return 0; - } - } - else if (clock != 0) - { - PrintAndLog("Error! Clock rate is only supported on T55x7 tags.\n"); - return 0; - } - - if (card == 1) { - PrintAndLog("Writing %s tag with UID 0x%010" PRIx64 " (clock rate: %d)", "T55x7", id, clock); - // NOTE: We really should pass the clock in as a separate argument, but to - // provide for backwards-compatibility for older firmware, and to avoid - // having to add another argument to CMD_EM410X_WRITE_TAG, we just store - // the clock rate in bits 8-15 of the card value - card = (card & 0xFF) | (((uint64_t)clock << 8) & 0xFF00); - } - else if (card == 0) - PrintAndLog("Writing %s tag with UID 0x%010" PRIx64, "T5555", id, clock); - else { - PrintAndLog("Error! Bad card type selected.\n"); - return 0; - } - - UsbCommand c = {CMD_EM410X_WRITE_TAG, {card, (uint32_t)(id >> 32), (uint32_t)id}}; - SendCommand(&c); - - return 0; -} - int CmdReadWord(const char *Cmd) { int Word = -1; //default to invalid word diff --git a/common/lfdemod.c b/common/lfdemod.c index df30aba4..c00222b3 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -172,7 +172,7 @@ int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr) { size_t i; - int start = DetectASKClock(BinStream, *size, clk, 20); //clock default + int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default if (*clk==0 || start < 0) return -3; if (*invert != 1) *invert=0; uint8_t initLoopMax = 255; @@ -188,59 +188,14 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max return manrawdecode(BinStream, size); } - // PrintAndLog("DEBUG - valid high: %d - valid low: %d",high,low); - int lastBit = 0; //set first clock check + int lastBit; //set first clock check uint16_t bitnum = 0; //output counter uint8_t tol = 0; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave if (*clk <= 32) tol=1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely - size_t iii = 0; - //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance - if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3; uint16_t errCnt = 0, MaxBits = 512; - uint16_t bestStart = start; - uint16_t bestErrCnt = 0; - // PrintAndLog("DEBUG - lastbit - %d",lastBit); - // if best start position not already found by detect clock then - if (start <= 0 || start > initLoopMax){ - bestErrCnt = maxErr+1; - // loop to find first wave that works - for (iii=0; iii < initLoopMax-tol-*clk; ++iii){ - // if no peak skip - if (BinStream[iii] < high && BinStream[iii] > low) continue; - - lastBit = iii - *clk; - // loop through to see if this start location works - for (i = iii; i < *size; ++i) { - if ((i-lastBit) > (*clk-tol) && (BinStream[i] >= high || BinStream[i] <= low)) { - lastBit += *clk; - } else if ((i-lastBit) > (*clk+tol)) { - errCnt++; - lastBit += *clk; - } - if ((i-iii) > (MaxBits * *clk) || errCnt > maxErr) break; //got plenty of bits or too many errors - } - //we got more than 64 good bits and not all errors - if ((((i-iii)/ *clk) > (32)) && (errCnt<=maxErr)) { - //possible good read - if (!errCnt || errCnt < bestErrCnt){ - bestStart = iii; //set this as new best run - bestErrCnt = errCnt; - if (!errCnt) break; //great read - finish - } - } - errCnt = 0; - } - } - if (bestErrCnt > maxErr){ - *invert = bestStart; - *clk = iii; - return -1; - } - //best run is good enough set to best run and set overwrite BinStream - lastBit = bestStart - *clk; - errCnt = 0; - for (i = bestStart; i < *size; ++i) { + lastBit = start - *clk; + for (i = start; i < *size; ++i) { if ((BinStream[i] >= high) && ((i-lastBit) > (*clk-tol))){ //high found and we are expecting a bar lastBit += *clk; @@ -261,7 +216,7 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max if (bitnum >= MaxBits) break; } *size = bitnum; - return bestErrCnt; + return errCnt; } //by marshmellow @@ -381,13 +336,13 @@ void askAmp(uint8_t *BitStream, size_t size) int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp) { if (*size==0) return -1; - int start = DetectASKClock(BinStream, *size, clk, 20); //clock default + int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default if (*clk==0 || start < 0) return -1; if (*invert != 1) *invert = 0; if (amp==1) askAmp(BinStream, *size); uint8_t initLoopMax = 255; - if (initLoopMax > *size) initLoopMax=*size; + if (initLoopMax > *size) initLoopMax = *size; // Detect high and lows //25% clip in case highs and lows aren't clipped [marshmellow] int high, low; @@ -398,67 +353,13 @@ int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max if (DetectCleanAskWave(BinStream, *size, high, low)) return cleanAskRawDemod(BinStream, size, *clk, *invert, high, low); - int lastBit = 0; //set first clock check - can go negative - size_t i, iii = 0; - size_t errCnt = 0, bitnum = 0; //output counter + int lastBit; //set first clock check - can go negative + size_t i, errCnt = 0, bitnum = 0; //output counter uint8_t midBit = 0; - size_t bestStart = start, bestErrCnt = 0; //(*size/1000); size_t MaxBits = 1024; + lastBit = start - *clk; - //if 0 errors allowed then only try first 2 clock cycles as we want a low tolerance - if (!maxErr && initLoopMax > *clk*3) initLoopMax = *clk * 3; - //if best start not already found by detectclock - if (start <= 0 || start > initLoopMax){ - bestErrCnt = maxErr+1; - //PrintAndLog("DEBUG - lastbit - %d",lastBit); - //loop to find first wave that works - for (iii=0; iii < initLoopMax - *clk; ++iii){ - if ((BinStream[iii] >= high) || (BinStream[iii] <= low)){ - lastBit = iii - *clk; - //loop through to see if this start location works - for (i = iii; i < *size; ++i) { - if (i-lastBit > *clk && (BinStream[i] >= high || BinStream[i] <= low)){ - lastBit += *clk; - midBit = 0; - } else if (i-lastBit > (*clk/2) && midBit == 0) { - midBit = 1; - } else if ((i-lastBit) > *clk) { - //should have hit a high or low based on clock!! - //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit); - errCnt++; - lastBit += *clk;//skip over until hit too many errors - if (errCnt > maxErr) - break; - } - if ((i-iii)>(MaxBits * *clk)) break; //got enough bits - } - //we got more than 32 good bits and not all errors - if ((((i-iii)/ *clk) > 32) && (errCnt<=maxErr)) { - //possible good read - if (errCnt==0){ - bestStart=iii; - bestErrCnt=errCnt; - break; //great read - finish - } - if (errCnt maxErr){ - *invert = bestStart; - *clk = iii; - return -1; - } - //best run is good enough - set to best run and overwrite BinStream - lastBit = bestStart - *clk - 1; - errCnt = 0; - - for (i = bestStart; i < *size; ++i) { + for (i = start; i < *size; ++i) { if (i - lastBit > *clk){ if (BinStream[i] >= high) { BinStream[bitnum++] = *invert; @@ -861,15 +762,17 @@ int DetectStrongAskClock(uint8_t dest[], size_t size) // return start index of best starting position for that clock and return clock (by reference) int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) { - size_t i=0; - uint8_t clk[]={8,16,32,40,50,64,100,128,255}; + size_t i=1; + uint8_t clk[]={255,8,16,32,40,50,64,100,128,255}; uint8_t loopCnt = 255; //don't need to loop through entire array... if (size==0) return -1; if (size <= loopCnt) loopCnt = size-1; //not enough samples - //if we already have a valid clock quit - - for (;i<8;++i) - if (clk[i] == *clock) return 0; + + //if we already have a valid clock + uint8_t clockFnd=0; + for (;i<9;++i) + if (clk[i] == *clock) clockFnd=i; + //clock found but continue to find best startpos //get high and low peak int peak, low; @@ -878,10 +781,11 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) //test for large clean peaks if (DetectCleanAskWave(dest, size, peak, low)==1){ int ans = DetectStrongAskClock(dest, size); - for (i=7; i>0; i--){ + for (i=8; i>1; i--){ if (clk[i] == ans) { *clock = ans; - return 0; + clockFnd = i; + break; //clock found but continue to find best startpos } } } @@ -892,15 +796,19 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) size_t errCnt = 0; size_t arrLoc, loopEnd; //test each valid clock from smallest to greatest to see which lines up - for(clkCnt=0; clkCnt < 8; clkCnt++){ + uint8_t clkEnd=9; + if (clockFnd>0) clkEnd=clockFnd+1; + else clockFnd=1; + + for(clkCnt=clockFnd; clkCnt < clkEnd; clkCnt++){ if (clk[clkCnt] == 32){ tol=1; }else{ tol=0; } - if (!maxErr && loopCnt>clk[clkCnt]*2) loopCnt=clk[clkCnt]*2; + if (!maxErr && loopCnt>clk[clkCnt]*3) loopCnt=clk[clkCnt]*3; bestErr[clkCnt]=1000; - //try lining up the peaks by moving starting point (try first 256) + //try lining up the peaks by moving starting point (try first few clocks) for (ii=0; ii < loopCnt-tol-clk[clkCnt]; ii++){ if (dest[ii] < peak && dest[ii] > low) continue; From acaeccf841f65291f5687824cb5322cc661e8183 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 3 Apr 2015 00:40:38 -0400 Subject: [PATCH 003/132] update changelog --- CHANGELOG.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f3f84ef..72674ec5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,10 +4,12 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] ### Changed +- Improved LF manchester and biphase demodulation and ask clock detection especially for reads with heavy clipping. (marshmellow) - Iclass read, `hf iclass read` now also reads tag config and prints configuration. (holiman) ### Fixed -- Fixed issue #19, problems with LF T55xx commands (marshmellow) +- Fixed EM4x50 read/demod of the tags broadcasted memory blocks. 'lf em4x em4x50read' (not page read) (marshmellow) +- Fixed issue #19, problems with LF T55xx commands (iceman1001, marshmellow) ### Added - Added changelog From 2767fc02919545bd65082b4682b2331def9a5ad5 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 5 Apr 2015 00:58:57 -0400 Subject: [PATCH 004/132] lf cleaning remove unneeded code/functions fix lfdemod askmandemod bug with maxErr=0 silence output for getting samples in lf search --- client/cmddata.c | 745 +++++--------------------------------------- client/cmddata.h | 8 - client/cmdlf.c | 54 +--- client/cmdlf.h | 1 - client/cmdlfem4x.c | 3 +- client/cmdlfhid.c | 6 +- client/cmdlfhid.h | 4 +- client/cmdlfio.c | 8 +- client/cmdlft55xx.c | 135 +++----- client/graph.c | 4 +- client/util.c | 15 +- client/util.h | 1 + common/lfdemod.c | 38 +-- 13 files changed, 169 insertions(+), 853 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 84a450f8..e2e2ca6d 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -58,37 +58,16 @@ int CmdSetDebugMode(const char *Cmd) //by marshmellow void printDemodBuff(void) { - uint32_t i = 0; int bitLen = DemodBufferLen; - if (bitLen<16) { + if (bitLen<1) { PrintAndLog("no bits found in demod buffer"); return; } if (bitLen>512) bitLen=512; //max output to 512 bits if we have more - should be plenty - // ensure equally divided by 16 - bitLen &= 0xfff0; + char *bin = sprint_bin_break(DemodBuffer,bitLen,16); + PrintAndLog("%s",bin); - for (i = 0; i <= (bitLen-16); i+=16) { - PrintAndLog("%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i", - DemodBuffer[i], - DemodBuffer[i+1], - DemodBuffer[i+2], - DemodBuffer[i+3], - DemodBuffer[i+4], - DemodBuffer[i+5], - DemodBuffer[i+6], - DemodBuffer[i+7], - DemodBuffer[i+8], - DemodBuffer[i+9], - DemodBuffer[i+10], - DemodBuffer[i+11], - DemodBuffer[i+12], - DemodBuffer[i+13], - DemodBuffer[i+14], - DemodBuffer[i+15] - ); - } return; } @@ -114,105 +93,8 @@ int CmdPrintDemodBuff(const char *Cmd) } return 1; } -int CmdAmp(const char *Cmd) -{ - int i, rising, falling; - int max = INT_MIN, min = INT_MAX; - - for (i = 10; i < GraphTraceLen; ++i) { - if (GraphBuffer[i] > max) - max = GraphBuffer[i]; - if (GraphBuffer[i] < min) - min = GraphBuffer[i]; - } - - if (max != min) { - rising = falling= 0; - for (i = 0; i < GraphTraceLen; ++i) { - if (GraphBuffer[i + 1] < GraphBuffer[i]) { - if (rising) { - GraphBuffer[i] = max; - rising = 0; - } - falling = 1; - } - if (GraphBuffer[i + 1] > GraphBuffer[i]) { - if (falling) { - GraphBuffer[i] = min; - falling = 0; - } - rising= 1; - } - } - } - RepaintGraphWindow(); - return 0; -} - -/* - * Generic command to demodulate ASK. - * - * Argument is convention: positive or negative (High mod means zero - * or high mod means one) - * - * Updates the Graph trace with 0/1 values - * - * Arguments: - * c : 0 or 1 (or invert) - */ - //this method ignores the clock - - //this function strictly converts highs and lows to 1s and 0s for each sample in the graphbuffer -int Cmdaskdemod(const char *Cmd) -{ - int i; - int c, high = 0, low = 0; - - sscanf(Cmd, "%i", &c); - - /* Detect high and lows */ - for (i = 0; i < GraphTraceLen; ++i) - { - if (GraphBuffer[i] > high) - high = GraphBuffer[i]; - else if (GraphBuffer[i] < low) - low = GraphBuffer[i]; - } - high=abs(high*.75); - low=abs(low*.75); - if (c != 0 && c != 1) { - PrintAndLog("Invalid argument: %s", Cmd); - return 0; - } - //prime loop - if (GraphBuffer[0] > 0) { - GraphBuffer[0] = 1-c; - } else { - GraphBuffer[0] = c; - } - for (i = 1; i < GraphTraceLen; ++i) { - /* Transitions are detected at each peak - * Transitions are either: - * - we're low: transition if we hit a high - * - we're high: transition if we hit a low - * (we need to do it this way because some tags keep high or - * low for long periods, others just reach the peak and go - * down) - */ - //[marhsmellow] change == to >= for high and <= for low for fuzz - if ((GraphBuffer[i] >= high) && (GraphBuffer[i - 1] == c)) { - GraphBuffer[i] = 1 - c; - } else if ((GraphBuffer[i] <= low) && (GraphBuffer[i - 1] == (1 - c))){ - GraphBuffer[i] = c; - } else { - /* No transition */ - GraphBuffer[i] = GraphBuffer[i - 1]; - } - } - RepaintGraphWindow(); - return 0; -} +//by marshmellow //this function strictly converts >1 to 1 and <1 to 0 for each sample in the graphbuffer int CmdGetBitStream(const char *Cmd) { @@ -229,43 +111,6 @@ int CmdGetBitStream(const char *Cmd) return 0; } - -//by marshmellow -void printBitStream(uint8_t BitStream[], uint32_t bitLen) -{ - uint32_t i = 0; - if (bitLen<16) { - PrintAndLog("Too few bits found: %d",bitLen); - return; - } - if (bitLen>512) bitLen=512; - - // ensure equally divided by 16 - bitLen &= 0xfff0; - - - for (i = 0; i <= (bitLen-16); i+=16) { - PrintAndLog("%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i%i", - BitStream[i], - BitStream[i+1], - BitStream[i+2], - BitStream[i+3], - BitStream[i+4], - BitStream[i+5], - BitStream[i+6], - BitStream[i+7], - BitStream[i+8], - BitStream[i+9], - BitStream[i+10], - BitStream[i+11], - BitStream[i+12], - BitStream[i+13], - BitStream[i+14], - BitStream[i+15] - ); - } - return; -} //by marshmellow //print 64 bit EM410x ID in multiple formats void printEM410x(uint32_t hi, uint64_t id) @@ -282,11 +127,11 @@ void printEM410x(uint32_t hi, uint64_t id) } if (hi){ //output 88 bit em id - PrintAndLog("\nEM TAG ID : %06x%016llx", hi, id); + PrintAndLog("\nEM TAG ID : %06X%016llX", hi, id); } else{ //output 40 bit em id - PrintAndLog("\nEM TAG ID : %010llx", id); - PrintAndLog("Unique TAG ID : %010llx", id2lo); + PrintAndLog("\nEM TAG ID : %010llX", id); + PrintAndLog("Unique TAG ID : %010llX", id2lo); PrintAndLog("\nPossible de-scramble patterns"); PrintAndLog("HoneyWell IdentKey {"); PrintAndLog("DEZ 8 : %08lld",id & 0xFFFFFF); @@ -311,7 +156,7 @@ void printEM410x(uint32_t hi, uint64_t id) ); uint64_t paxton = (((id>>32) << 24) | (id & 0xffffff)) + 0x143e00; PrintAndLog("}\nOther : %05lld_%03lld_%08lld",(id&0xFFFF),((id>>16LL) & 0xFF),(id & 0xFFFFFF)); - PrintAndLog("Pattern Paxton : %0d", paxton); + PrintAndLog("Pattern Paxton : %lld [0x%llX]", paxton, paxton); uint32_t p1id = (id & 0xFFFFFF); uint8_t arr[32] = {0x00}; @@ -352,12 +197,12 @@ void printEM410x(uint32_t hi, uint64_t id) p1 |= arr[2] << 4; p1 |= arr[1] << 5; p1 |= arr[0] << 9; - PrintAndLog("Pattern 1 : 0x%X - %d", p1, p1); + PrintAndLog("Pattern 1 : %d [0x%X]", p1, p1); uint16_t sebury1 = id & 0xFFFF; uint8_t sebury2 = (id >> 16) & 0x7F; uint32_t sebury3 = id & 0x7FFFFF; - PrintAndLog("Pattern Sebury : %d %d %d (hex: %X %X %X)", sebury1, sebury2, sebury3, sebury1, sebury2, sebury3); + PrintAndLog("Pattern Sebury : %d %d %d [0x%X 0x%X 0x%X]", sebury1, sebury2, sebury3, sebury1, sebury2, sebury3); } } return; @@ -430,20 +275,23 @@ int ASKmanDemod(const char *Cmd, bool verbose, bool emSearch) clk=0; } size_t BitLen = getFromGraphBuf(BitStream); - if (g_debugMode==1) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen); - if (BitLen==0) return 0; - int errCnt=0; + if (g_debugMode) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen); + if (!BitLen) return 0; if (maxLenmaxErr){ + if (g_debugMode) PrintAndLog("DEBUG: Too many errors found, errors:%d, bits:%d, clock:%d",errCnt, BitLen, clk); + return 0; + } + if (verbose || g_debugMode) PrintAndLog("\nUsing Clock:%d, Invert:%d, Bits Found:%d",clk,invert,BitLen); //output if (errCnt>0){ - if (verbose || g_debugMode) PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt); + if (verbose || g_debugMode) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); } if (verbose || g_debugMode) PrintAndLog("ASK/Manchester decoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits @@ -519,7 +367,7 @@ int Cmdmandecoderaw(const char *Cmd) BitStream[i]=DemodBuffer[i]; } if (high>1 || low <0 ){ - PrintAndLog("Error: please raw demod the wave first then mancheseter raw decode"); + PrintAndLog("Error: please raw demod the wave first then manchester raw decode"); return 0; } size=i; @@ -529,7 +377,7 @@ int Cmdmandecoderaw(const char *Cmd) return 0; } PrintAndLog("Manchester Decoded - # errors:%d - data:",errCnt); - printBitStream(BitStream, size); + PrintAndLog("%s", sprint_bin_break(BitStream, size, 16)); if (errCnt==0){ uint64_t id = 0; uint32_t hi = 0; @@ -549,11 +397,7 @@ int Cmdmandecoderaw(const char *Cmd) //take 01 or 10 = 0 and 11 or 00 = 1 //takes 2 arguments "offset" default = 0 if 1 it will shift the decode by one bit // and "invert" default = 0 if 1 it will invert output -// since it is not like manchester and doesn't have an incorrect bit pattern we -// cannot determine if our decode is correct or if it should be shifted by one bit -// the argument offset allows us to manually shift if the output is incorrect -// (better would be to demod and decode at the same time so we can distinguish large -// width waves vs small width waves to help the decode positioning) or askbiphdemod +// the argument offset allows us to manually shift if the output is incorrect - [EDIT: now auto detects] int CmdBiphaseDecodeRaw(const char *Cmd) { size_t size=0; @@ -592,39 +436,15 @@ int CmdBiphaseDecodeRaw(const char *Cmd) } if (errCnt>0){ - PrintAndLog("# Errors found during Demod (shown as 77 in bit stream): %d",errCnt); + PrintAndLog("# Errors found during Demod (shown as 7 in bit stream): %d",errCnt); } PrintAndLog("Biphase Decoded using offset: %d - # invert:%d - data:",offset,invert); - printBitStream(BitStream, size); + PrintAndLog("%s", sprint_bin_break(BitStream, size, 16)); if (offset) setDemodBuf(DemodBuffer,DemodBufferLen-offset, offset); //remove first bit from raw demod return 1; } -// set demod buffer back to raw after biphase demod -void setBiphasetoRawDemodBuf(uint8_t *BitStream, size_t size) -{ - uint8_t rawStream[512]={0x00}; - size_t i=0; - uint8_t curPhase=0; - if (size > 256) { - PrintAndLog("ERROR - Biphase Demod Buffer overrun"); - return; - } - for (size_t idx=0; idxmaxErr) { + if (g_debugMode) + PrintAndLog("Too many errors found, errCnt: %d, BitLen: %d, clk: %d, invert: %d", errCnt, BitLen, clk, invert); + return 0; + } + if (verbose || g_debugMode) + PrintAndLog("Using Clock: %d - invert: %d - Bits Found: %d", clk, invert, BitLen); //move BitStream back to DemodBuffer setDemodBuf(BitStream,BitLen,0); //output if (errCnt>0 && (verbose || g_debugMode)){ - PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d", errCnt); + PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d", errCnt); } if (verbose || g_debugMode){ PrintAndLog("ASK demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits - printBitStream(BitStream,BitLen); + printDemodBuff(); } return 1; } @@ -937,67 +762,6 @@ int CmdBitsamples(const char *Cmd) return 0; } -/* - * Convert to a bitstream - */ -int CmdBitstream(const char *Cmd) -{ - int i, j; - int bit; - int gtl; - int clock; - int low = 0; - int high = 0; - int hithigh, hitlow, first; - - /* Detect high and lows and clock */ - for (i = 0; i < GraphTraceLen; ++i) - { - if (GraphBuffer[i] > high) - high = GraphBuffer[i]; - else if (GraphBuffer[i] < low) - low = GraphBuffer[i]; - } - - /* Get our clock */ - clock = GetAskClock(Cmd, high, 1); - gtl = ClearGraph(0); - - bit = 0; - for (i = 0; i < (int)(gtl / clock); ++i) - { - hithigh = 0; - hitlow = 0; - first = 1; - /* Find out if we hit both high and low peaks */ - for (j = 0; j < clock; ++j) - { - if (GraphBuffer[(i * clock) + j] == high) - hithigh = 1; - else if (GraphBuffer[(i * clock) + j] == low) - hitlow = 1; - /* it doesn't count if it's the first part of our read - because it's really just trailing from the last sequence */ - if (first && (hithigh || hitlow)) - hithigh = hitlow = 0; - else - first = 0; - - if (hithigh && hitlow) - break; - } - - /* If we didn't hit both high and low peaks, we had a bit transition */ - if (!hithigh || !hitlow) - bit ^= 1; - - AppendGraph(0, clock, bit); - } - - RepaintGraphWindow(); - return 0; -} - int CmdBuffClear(const char *Cmd) { UsbCommand c = {CMD_BUFF_CLEAR}; @@ -1076,7 +840,7 @@ int CmdGraphShiftZero(const char *Cmd) //by marshmellow //use large jumps in read samples to identify edges of waves and then amplify that wave to max -//similar to dirtheshold, threshold, and askdemod 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) { @@ -1134,6 +898,25 @@ int CmdDetectClockRate(const char *Cmd) return ans; } +char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert) +{ + char *fskType; + if (fchigh==10 && fclow==8){ + if (invert) //fsk2a + fskType = "FSK2a"; + else //fsk2 + fskType = "FSK2"; + } else if (fchigh == 8 && fclow == 5) { + if (invert) + fskType = "FSK1"; + else + fskType = "FSK1a"; + } else { + fskType = "FSK??"; + } + return fskType; +} + //by marshmellow //fsk raw demod and print binary //takes 4 arguments - Clock, invert, fchigh, fclow @@ -1177,21 +960,20 @@ int FSKrawDemod(const char *Cmd, bool verbose) rfLen = detectFSKClk(BitStream, BitLen, fchigh, fclow); if (rfLen == 0) rfLen = 50; } - if (verbose) PrintAndLog("Args invert: %d - Clock:%d - fchigh:%d - fclow: %d",invert,rfLen,fchigh, fclow); int size = fskdemod(BitStream,BitLen,(uint8_t)rfLen,(uint8_t)invert,(uint8_t)fchigh,(uint8_t)fclow); if (size>0){ setDemodBuf(BitStream,size,0); // Now output the bitstream to the scrollback by line of 16 bits - if(size > (8*32)+2) size = (8*32)+2; //only output a max of 8 blocks of 32 bits most tags will have full bit stream inside that sample size - if (verbose) { - PrintAndLog("FSK decoded bitstream:"); - printBitStream(BitStream,size); + if (verbose || g_debugMode) { + PrintAndLog("\nUsing Clock:%d, invert:%d, fchigh:%d, fclow:%d", rfLen, invert, fchigh, fclow); + PrintAndLog("%s decoded bitstream:",GetFSKType(fchigh,fclow,invert)); + printDemodBuff(); } return 1; } else{ - if (verbose) PrintAndLog("no FSK data found"); + if (g_debugMode) PrintAndLog("no FSK data found"); } return 0; } @@ -1395,9 +1177,9 @@ int CmdFSKdemodIO(const char *Cmd) return 0; } if (idx==0){ - if (g_debugMode==1){ + if (g_debugMode){ PrintAndLog("DEBUG: IO Prox Data not found - FSK Bits: %d",BitLen); - if (BitLen > 92) printBitStream(BitStream,92); + if (BitLen > 92) PrintAndLog("%s", sprint_bin_break(BitStream,92,16)); } return 0; } @@ -1411,7 +1193,7 @@ int CmdFSKdemodIO(const char *Cmd) //XSF(version)facility:codeone+codetwo (raw) //Handle the data if (idx+64>BitLen) { - if (g_debugMode==1) PrintAndLog("not enough bits found - bitlen: %d",BitLen); + if (g_debugMode) PrintAndLog("not enough bits found - bitlen: %d",BitLen); return 0; } PrintAndLog("%d%d%d%d%d%d%d%d %d",BitStream[idx], BitStream[idx+1], BitStream[idx+2], BitStream[idx+3], BitStream[idx+4], BitStream[idx+5], BitStream[idx+6], BitStream[idx+7], BitStream[idx+8]); @@ -1432,7 +1214,6 @@ int CmdFSKdemodIO(const char *Cmd) for (uint8_t i=1; i<6; ++i){ calccrc += bytebits_to_byte(BitStream+idx+9*i,8); - //PrintAndLog("%d", calccrc); } calccrc &= 0xff; calccrc = 0xff - calccrc; @@ -1690,124 +1471,6 @@ int CmdFSKdemodPyramid(const char *Cmd) return 1; } -int CmdFSKdemod(const char *Cmd) //old CmdFSKdemod needs updating -{ - static const int LowTone[] = { - 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, -1, - 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, - 1, 1, 1, 1, 1, -1, -1, -1, -1, -1 - }; - static const int HighTone[] = { - 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, -1, -1, -1, -1, - 1, 1, 1, 1, -1, -1, -1, -1, - 1, 1, 1, 1, -1, -1, -1, -1, -1, - }; - - int lowLen = sizeof (LowTone) / sizeof (int); - int highLen = sizeof (HighTone) / sizeof (int); - int convLen = (highLen > lowLen) ? highLen : lowLen; - uint32_t hi = 0, lo = 0; - - int i, j; - int minMark = 0, maxMark = 0; - - for (i = 0; i < GraphTraceLen - convLen; ++i) { - int lowSum = 0, highSum = 0; - - for (j = 0; j < lowLen; ++j) { - lowSum += LowTone[j]*GraphBuffer[i+j]; - } - for (j = 0; j < highLen; ++j) { - highSum += HighTone[j] * GraphBuffer[i + j]; - } - lowSum = abs(100 * lowSum / lowLen); - highSum = abs(100 * highSum / highLen); - GraphBuffer[i] = (highSum << 16) | lowSum; - } - - for(i = 0; i < GraphTraceLen - convLen - 16; ++i) { - int lowTot = 0, highTot = 0; - // 10 and 8 are f_s divided by f_l and f_h, rounded - for (j = 0; j < 10; ++j) { - lowTot += (GraphBuffer[i+j] & 0xffff); - } - for (j = 0; j < 8; j++) { - highTot += (GraphBuffer[i + j] >> 16); - } - GraphBuffer[i] = lowTot - highTot; - if (GraphBuffer[i] > maxMark) maxMark = GraphBuffer[i]; - if (GraphBuffer[i] < minMark) minMark = GraphBuffer[i]; - } - - GraphTraceLen -= (convLen + 16); - RepaintGraphWindow(); - - // Find bit-sync (3 lo followed by 3 high) (HID ONLY) - int max = 0, maxPos = 0; - for (i = 0; i < 6000; ++i) { - int dec = 0; - for (j = 0; j < 3 * lowLen; ++j) { - dec -= GraphBuffer[i + j]; - } - for (; j < 3 * (lowLen + highLen ); ++j) { - dec += GraphBuffer[i + j]; - } - if (dec > max) { - max = dec; - maxPos = i; - } - } - - // place start of bit sync marker in graph - GraphBuffer[maxPos] = maxMark; - GraphBuffer[maxPos + 1] = minMark; - - maxPos += j; - - // place end of bit sync marker in graph - GraphBuffer[maxPos] = maxMark; - GraphBuffer[maxPos+1] = minMark; - - PrintAndLog("actual data bits start at sample %d", maxPos); - PrintAndLog("length %d/%d", highLen, lowLen); - - uint8_t bits[46] = {0x00}; - - // find bit pairs and manchester decode them - for (i = 0; i < arraylen(bits) - 1; ++i) { - int dec = 0; - for (j = 0; j < lowLen; ++j) { - dec -= GraphBuffer[maxPos + j]; - } - for (; j < lowLen + highLen; ++j) { - dec += GraphBuffer[maxPos + j]; - } - maxPos += j; - // place inter bit marker in graph - GraphBuffer[maxPos] = maxMark; - GraphBuffer[maxPos + 1] = minMark; - - // hi and lo form a 64 bit pair - hi = (hi << 1) | (lo >> 31); - lo = (lo << 1); - // store decoded bit as binary (in hi/lo) and text (in bits[]) - if(dec < 0) { - bits[i] = '1'; - lo |= 1; - } else { - bits[i] = '0'; - } - } - PrintAndLog("bits: '%s'", bits); - PrintAndLog("hex: %08x %08x", hi, lo); - return 0; -} - //by marshmellow //attempt to psk1 demod graph buffer int PSKDemod(const char *Cmd, bool verbose) @@ -1835,17 +1498,17 @@ int PSKDemod(const char *Cmd, bool verbose) int errCnt=0; errCnt = pskRawDemod(BitStream, &BitLen, &clk, &invert); if (errCnt > maxErr){ - if (g_debugMode==1 && verbose) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt); + if (g_debugMode || verbose) PrintAndLog("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==1 && verbose) PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt); + if (g_debugMode || verbose) PrintAndLog("no data found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt); return 0; } - if (verbose){ - PrintAndLog("Tried PSK Demod using Clock: %d - invert: %d - Bits Found: %d",clk,invert,BitLen); + if (verbose || g_debugMode){ + PrintAndLog("\nUsing Clock:%d, invert:%d, Bits Found:%d",clk,invert,BitLen); if (errCnt>0){ - PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt); + PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); } } //prime demod buffer for output @@ -1970,7 +1633,7 @@ int NRZrawDemod(const char *Cmd, bool verbose) //prime demod buffer for output setDemodBuf(BitStream,BitLen,0); - if (errCnt>0 && (verbose || g_debugMode)) PrintAndLog("# Errors during Demoding (shown as 77 in bit stream): %d",errCnt); + if (errCnt>0 && (verbose || g_debugMode)) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); if (verbose || g_debugMode) { PrintAndLog("NRZ demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits @@ -2026,7 +1689,7 @@ int CmdPSK1rawDemod(const char *Cmd) return 0; } - PrintAndLog("PSK demoded bitstream:"); + PrintAndLog("PSK1 demoded bitstream:"); // Now output the bitstream to the scrollback by line of 16 bits printDemodBuff(); return 1; @@ -2295,10 +1958,10 @@ int CmdTuneSamples(const char *Cmd) PrintAndLog("# LF optimal: %5.2f V @%9.2f kHz", peakv/1000.0, 12000.0/(peakf+1)); PrintAndLog("# HF antenna: %5.2f V @ 13.56 MHz", vHf/1000.0); -#define LF_UNUSABLE_V 2948 // was 2000. Changed due to bugfix in voltage measurements. LF results are now 47% higher. -#define LF_MARGINAL_V 14739 // was 10000. Changed due to bugfix bug in voltage measurements. LF results are now 47% higher. -#define HF_UNUSABLE_V 3167 // was 2000. Changed due to bugfix in voltage measurements. HF results are now 58% higher. -#define HF_MARGINAL_V 7917 // was 5000. Changed due to bugfix in voltage measurements. HF results are now 58% higher. + #define LF_UNUSABLE_V 2948 // was 2000. Changed due to bugfix in voltage measurements. LF results are now 47% higher. + #define LF_MARGINAL_V 14739 // was 10000. Changed due to bugfix bug in voltage measurements. LF results are now 47% higher. + #define HF_UNUSABLE_V 3167 // was 2000. Changed due to bugfix in voltage measurements. HF results are now 58% higher. + #define HF_MARGINAL_V 7917 // was 5000. Changed due to bugfix in voltage measurements. HF results are now 58% higher. if (peakv < LF_UNUSABLE_V) PrintAndLog("# Your LF antenna is unusable."); @@ -2374,245 +2037,6 @@ int CmdRtrim(const char *Cmd) return 0; } -/* - * Manchester demodulate a bitstream. The bitstream needs to be already in - * the GraphBuffer as 0 and 1 values - * - * Give the clock rate as argument in order to help the sync - the algorithm - * resyncs at each pulse anyway. - * - * Not optimized by any means, this is the 1st time I'm writing this type of - * routine, feel free to improve... - * - * 1st argument: clock rate (as number of samples per clock rate) - * Typical values can be 64, 32, 128... - */ -int CmdManchesterDemod(const char *Cmd) -{ - int i, j, invert= 0; - int bit; - int clock; - int lastval = 0; - int low = 0; - int high = 0; - int hithigh, hitlow, first; - int lc = 0; - int bitidx = 0; - int bit2idx = 0; - int warnings = 0; - - /* check if we're inverting output */ - if (*Cmd == 'i') - { - PrintAndLog("Inverting output"); - invert = 1; - ++Cmd; - do - ++Cmd; - while(*Cmd == ' '); // in case a 2nd argument was given - } - - /* Holds the decoded bitstream: each clock period contains 2 bits */ - /* later simplified to 1 bit after manchester decoding. */ - /* Add 10 bits to allow for noisy / uncertain traces without aborting */ - /* int BitStream[GraphTraceLen*2/clock+10]; */ - - /* But it does not work if compiling on WIndows: therefore we just allocate a */ - /* large array */ - uint8_t BitStream[MAX_GRAPH_TRACE_LEN] = {0}; - - /* Detect high and lows */ - for (i = 0; i < GraphTraceLen; i++) - { - if (GraphBuffer[i] > high) - high = GraphBuffer[i]; - else if (GraphBuffer[i] < low) - low = GraphBuffer[i]; - } - - /* Get our clock */ - clock = GetAskClock(Cmd, high, 1); - - int tolerance = clock/4; - - /* Detect first transition */ - /* Lo-Hi (arbitrary) */ - /* skip to the first high */ - for (i= 0; i < GraphTraceLen; i++) - if (GraphBuffer[i] == high) - break; - /* now look for the first low */ - for (; i < GraphTraceLen; i++) - { - if (GraphBuffer[i] == low) - { - lastval = i; - break; - } - } - - /* If we're not working with 1/0s, demod based off clock */ - if (high != 1) - { - bit = 0; /* We assume the 1st bit is zero, it may not be - * the case: this routine (I think) has an init problem. - * Ed. - */ - for (; i < (int)(GraphTraceLen / clock); i++) - { - hithigh = 0; - hitlow = 0; - first = 1; - - /* Find out if we hit both high and low peaks */ - for (j = 0; j < clock; j++) - { - if (GraphBuffer[(i * clock) + j] == high) - hithigh = 1; - else if (GraphBuffer[(i * clock) + j] == low) - hitlow = 1; - - /* it doesn't count if it's the first part of our read - because it's really just trailing from the last sequence */ - if (first && (hithigh || hitlow)) - hithigh = hitlow = 0; - else - first = 0; - - if (hithigh && hitlow) - break; - } - - /* If we didn't hit both high and low peaks, we had a bit transition */ - if (!hithigh || !hitlow) - bit ^= 1; - - BitStream[bit2idx++] = bit ^ invert; - } - } - - /* standard 1/0 bitstream */ - else - { - - /* Then detect duration between 2 successive transitions */ - for (bitidx = 1; i < GraphTraceLen; i++) - { - if (GraphBuffer[i-1] != GraphBuffer[i]) - { - lc = i-lastval; - lastval = i; - - // Error check: if bitidx becomes too large, we do not - // have a Manchester encoded bitstream or the clock is really - // wrong! - if (bitidx > (GraphTraceLen*2/clock+8) ) { - PrintAndLog("Error: the clock you gave is probably wrong, aborting."); - return 0; - } - // Then switch depending on lc length: - // Tolerance is 1/4 of clock rate (arbitrary) - if (abs(lc-clock/2) < tolerance) { - // Short pulse : either "1" or "0" - BitStream[bitidx++]=GraphBuffer[i-1]; - } else if (abs(lc-clock) < tolerance) { - // Long pulse: either "11" or "00" - BitStream[bitidx++]=GraphBuffer[i-1]; - BitStream[bitidx++]=GraphBuffer[i-1]; - } else { - // Error - warnings++; - PrintAndLog("Warning: Manchester decode error for pulse width detection."); - PrintAndLog("(too many of those messages mean either the stream is not Manchester encoded, or clock is wrong)"); - - if (warnings > 10) - { - PrintAndLog("Error: too many detection errors, aborting."); - return 0; - } - } - } - } - - // At this stage, we now have a bitstream of "01" ("1") or "10" ("0"), parse it into final decoded bitstream - // Actually, we overwrite BitStream with the new decoded bitstream, we just need to be careful - // to stop output at the final bitidx2 value, not bitidx - for (i = 0; i < bitidx; i += 2) { - if ((BitStream[i] == 0) && (BitStream[i+1] == 1)) { - BitStream[bit2idx++] = 1 ^ invert; - } else if ((BitStream[i] == 1) && (BitStream[i+1] == 0)) { - BitStream[bit2idx++] = 0 ^ invert; - } else { - // We cannot end up in this state, this means we are unsynchronized, - // move up 1 bit: - i++; - warnings++; - PrintAndLog("Unsynchronized, resync..."); - PrintAndLog("(too many of those messages mean the stream is not Manchester encoded)"); - - if (warnings > 10) - { - PrintAndLog("Error: too many decode errors, aborting."); - return 0; - } - } - } - } - - PrintAndLog("Manchester decoded bitstream"); - // Now output the bitstream to the scrollback by line of 16 bits - for (i = 0; i < (bit2idx-16); i+=16) { - PrintAndLog("%i %i %i %i %i %i %i %i %i %i %i %i %i %i %i %i", - BitStream[i], - BitStream[i+1], - BitStream[i+2], - BitStream[i+3], - BitStream[i+4], - BitStream[i+5], - BitStream[i+6], - BitStream[i+7], - BitStream[i+8], - BitStream[i+9], - BitStream[i+10], - BitStream[i+11], - BitStream[i+12], - BitStream[i+13], - BitStream[i+14], - BitStream[i+15]); - } - return 0; -} - -/* Modulate our data into manchester */ -int CmdManchesterMod(const char *Cmd) -{ - int i, j; - int clock; - int bit, lastbit, wave; - - /* Get our clock */ - clock = GetAskClock(Cmd, 0, 1); - - wave = 0; - lastbit = 1; - for (i = 0; i < (int)(GraphTraceLen / clock); i++) - { - bit = GraphBuffer[i * clock] ^ 1; - - for (j = 0; j < (int)(clock/2); j++) - GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave; - for (j = (int)(clock/2); j < clock; j++) - GraphBuffer[(i * clock) + j] = bit ^ lastbit ^ wave ^ 1; - - /* Keep track of how we start our wave and if we changed or not this time */ - wave ^= bit ^ lastbit; - lastbit = bit; - } - - RepaintGraphWindow(); - return 0; -} - int CmdNorm(const char *Cmd) { int i; @@ -2677,20 +2101,6 @@ int CmdScale(const char *Cmd) return 0; } -int CmdThreshold(const char *Cmd) -{ - int threshold = atoi(Cmd); - - for (int i = 0; i < GraphTraceLen; ++i) { - if (GraphBuffer[i] >= threshold) - GraphBuffer[i] = 1; - else - GraphBuffer[i] = -1; - } - RepaintGraphWindow(); - return 0; -} - int CmdDirectionalThreshold(const char *Cmd) { int8_t upThres = param_get8(Cmd, 0); @@ -2758,19 +2168,15 @@ int CmdZerocrossings(const char *Cmd) static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"amp", CmdAmp, 1, "Amplify peaks"}, - //{"askdemod", Cmdaskdemod, 1, "<0 or 1> -- Attempt to demodulate simple ASK tags"}, {"askedgedetect", CmdAskEdgeDetect, 1, "[threshold] Adjust Graph for manual ask demod using length of sample differences to detect the edge of a wave (default = 25)"}, {"askem410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"}, {"askgproxiidemod", CmdG_Prox_II_Demod, 1, "Demodulate a G Prox II tag from GraphBuffer"}, {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"}, {"biphaserawdecode",CmdBiphaseDecodeRaw,1,"[offset] [invert<0|1>] Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"}, - //{"bitstream", CmdBitstream, 1, "[clock rate] -- Convert waveform into a bitstream"}, {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"}, {"dec", CmdDec, 1, "Decimate samples"}, {"detectclock", CmdDetectClockRate, 1, "[modulation] Detect clock rate of wave in GraphBuffer (options: 'a','f','n','p' for ask, fsk, nrz, psk respectively)"}, - //{"fskdemod", CmdFSKdemod, 1, "Demodulate graph window as a HID FSK"}, {"fskawiddemod", CmdFSKdemodAWID, 1, "Demodulate an AWID FSK tag from GraphBuffer"}, //{"fskfcdetect", CmdFSKfcDetect, 1, "Try to detect the Field Clock of an FSK wave"}, {"fskhiddemod", CmdFSKdemodHID, 1, "Demodulate a HID FSK tag from GraphBuffer"}, @@ -2785,9 +2191,7 @@ static command_t CommandTable[] = {"load", CmdLoad, 1, " -- Load trace (to graph window"}, {"ltrim", CmdLtrim, 1, " -- Trim samples from left of trace"}, {"rtrim", CmdRtrim, 1, " -- Trim samples from right of trace"}, - //{"mandemod", CmdManchesterDemod, 1, "[i] [clock rate] -- Manchester demodulate binary stream (option 'i' to invert output)"}, {"manrawdecode", Cmdmandecoderaw, 1, "Manchester decode binary stream in DemodBuffer"}, - {"manmod", CmdManchesterMod, 1, "[clock rate] -- Manchester modulate a binary stream"}, {"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] -- print the data in the DemodBuffer - 'x' for hex output"}, @@ -2798,7 +2202,6 @@ static command_t CommandTable[] = {"scale", CmdScale, 1, " -- Set cursor display scale"}, {"setdebugmode", CmdSetDebugMode, 1, "<0|1> -- Turn on or off Debugging Mode for demods"}, {"shiftgraphzero", CmdGraphShiftZero, 1, " -- Shift 0 for Graphed wave + or - shift value"}, - //{"threshold", CmdThreshold, 1, " -- Maximize/minimize every value in the graph window depending on threshold"}, {"dirthreshold", CmdDirectionalThreshold, 1, " -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."}, {"tune", CmdTuneSamples, 0, "Get hw tune samples for graph window"}, {"undec", CmdUndec, 1, "Un-decimate samples by 2"}, diff --git a/client/cmddata.h b/client/cmddata.h index 97bfdbcc..0d2e32d6 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -15,10 +15,7 @@ command_t * CmdDataCommands(); int CmdData(const char *Cmd); void printDemodBuff(void); -void printBitStream(uint8_t BitStream[], uint32_t bitLen); void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx); -int CmdAmp(const char *Cmd); -int Cmdaskdemod(const char *Cmd); int CmdAskEM410xDemod(const char *Cmd); int CmdG_Prox_II_Demod(const char *Cmd); int Cmdaskrawdemod(const char *Cmd); @@ -27,12 +24,10 @@ int AutoCorrelate(int window, bool SaveGrph, bool verbose); int CmdAutoCorr(const char *Cmd); int CmdBiphaseDecodeRaw(const char *Cmd); int CmdBitsamples(const char *Cmd); -int CmdBitstream(const char *Cmd); int CmdBuffClear(const char *Cmd); int CmdDec(const char *Cmd); int CmdDetectClockRate(const char *Cmd); int CmdFSKdemodAWID(const char *Cmd); -int CmdFSKdemod(const char *Cmd); int CmdFSKdemodHID(const char *Cmd); int CmdFSKdemodIO(const char *Cmd); int CmdFSKdemodParadox(const char *Cmd); @@ -49,8 +44,6 @@ int CmdLoad(const char *Cmd); int CmdLtrim(const char *Cmd); int CmdRtrim(const char *Cmd); int Cmdmandecoderaw(const char *Cmd); -int CmdManchesterDemod(const char *Cmd); -int CmdManchesterMod(const char *Cmd); int CmdNorm(const char *Cmd); int CmdNRZrawDemod(const char *Cmd); int CmdPlot(const char *Cmd); @@ -60,7 +53,6 @@ int CmdSamples(const char *Cmd); int CmdTuneSamples(const char *Cmd); int CmdSave(const char *Cmd); int CmdScale(const char *Cmd); -int CmdThreshold(const char *Cmd); int CmdDirectionalThreshold(const char *Cmd); int CmdZerocrossings(const char *Cmd); int CmdIndalaDecode(const char *Cmd); diff --git a/client/cmdlf.c b/client/cmdlf.c index 3d29fc07..a52e1423 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -522,7 +522,8 @@ static void ChkBitstream(const char *str) } } } -//appears to attempt to simulate manchester +//Attempt to simulate any wave in buffer (one bit per output sample) +// converts GraphBuffer to bitstream (based on zero crossings) if needed. int CmdLFSim(const char *Cmd) { int i,j; @@ -530,11 +531,11 @@ int CmdLFSim(const char *Cmd) sscanf(Cmd, "%i", &gap); - /* convert to bitstream if necessary */ + // convert to bitstream if necessary ChkBitstream(Cmd); - //can send 512 bits at a time (1 byte sent per bit...) + //can send only 512 bits at a time (1 byte sent per bit...) printf("Sending [%d bytes]", GraphTraceLen); for (i = 0; i < GraphTraceLen; i += USB_CMD_DATA_SIZE) { UsbCommand c={CMD_DOWNLOADED_SIM_SAMPLES_125K, {i, 0, 0}}; @@ -606,8 +607,8 @@ int usage_lf_simpsk(void) // - allow pull data from DemodBuffer int CmdLFfskSim(const char *Cmd) { - //might be able to autodetect FC and clock from Graphbuffer if using demod buffer - //will need FChigh, FClow, Clock, and bitstream + //might be able to autodetect FCs and clock from Graphbuffer if using demod buffer + // otherwise will need FChigh, FClow, Clock, and bitstream uint8_t fcHigh=0, fcLow=0, clk=0; uint8_t invert=0; bool errors = FALSE; @@ -682,6 +683,8 @@ int CmdLFfskSim(const char *Cmd) } else { setDemodBuf(data, dataLen, 0); } + + //default if not found if (clk == 0) clk = 50; if (fcHigh == 0) fcHigh = 10; if (fcLow == 0) fcLow = 8; @@ -706,9 +709,8 @@ int CmdLFfskSim(const char *Cmd) int CmdLFaskSim(const char *Cmd) { //autodetect clock from Graphbuffer if using demod buffer - //will need clock, invert, manchester/raw as m or r, separator as s, and bitstream + // needs clock, invert, manchester/raw as m or r, separator as s, and bitstream uint8_t encoding = 1, separator = 0; - //char cmdp = Cmd[0], par3='m', par4=0; uint8_t clk=0, invert=0; bool errors = FALSE; char hexData[32] = {0x00}; @@ -913,30 +915,6 @@ int CmdLFSimBidir(const char *Cmd) return 0; } -/* simulate an LF Manchester encoded tag with specified bitstream, clock rate and inter-id gap */ -/* -int CmdLFSimManchester(const char *Cmd) -{ - static int clock, gap; - static char data[1024], gapstring[8]; - - sscanf(Cmd, "%i %s %i", &clock, &data[0], &gap); - - ClearGraph(0); - - for (int i = 0; i < strlen(data) ; ++i) - AppendGraph(0, clock, data[i]- '0'); - - CmdManchesterMod(""); - - RepaintGraphWindow(); - - sprintf(&gapstring[0], "%i", gap); - CmdLFSim(gapstring); - return 0; -} -*/ - int CmdVchDemod(const char *Cmd) { // Is this the entire sync pattern, or does this also include some @@ -1033,8 +1011,8 @@ int CmdLFfind(const char *Cmd) } if (!offline && (cmdp != '1')){ - ans=CmdLFRead(""); - ans=CmdSamples("20000"); + CmdLFRead("s"); + getSamples("30000",false); } else if (GraphTraceLen < 1000) { PrintAndLog("Data in Graphbuffer was too small."); return 0; @@ -1105,20 +1083,18 @@ int CmdLFfind(const char *Cmd) PrintAndLog("\nChecking for Unknown tags:\n"); ans=AutoCorrelate(4000, FALSE, FALSE); if (ans > 0) PrintAndLog("Possible Auto Correlation of %d repeating samples",ans); - ans=GetFskClock("",FALSE,FALSE); //CmdDetectClockRate("F"); // + ans=GetFskClock("",FALSE,FALSE); if (ans != 0){ //fsk - ans=FSKrawDemod("",FALSE); + ans=FSKrawDemod("",TRUE); if (ans>0) { PrintAndLog("\nUnknown FSK Modulated Tag Found!"); - printDemodBuff(); return 1; } } - ans=ASKmanDemod("",FALSE,FALSE); + ans=ASKmanDemod("0 0 0",TRUE,FALSE); if (ans>0) { PrintAndLog("\nUnknown ASK Modulated and Manchester encoded Tag Found!"); PrintAndLog("\nif it does not look right it could instead be ASK/Biphase - try 'data rawdemod ab'"); - printDemodBuff(); return 1; } ans=CmdPSK1rawDemod(""); @@ -1126,7 +1102,6 @@ int CmdLFfind(const char *Cmd) PrintAndLog("Possible unknown PSK1 Modulated Tag Found above!\n\nCould also be PSK2 - try 'data rawdemod p2'"); PrintAndLog("\nCould also be PSK3 - [currently not supported]"); PrintAndLog("\nCould also be NRZ - try 'data nrzrawdemod"); - printDemodBuff(); return 1; } PrintAndLog("\nNo Data Found!\n"); @@ -1152,7 +1127,6 @@ static command_t CommandTable[] = {"simfsk", CmdLFfskSim, 0, "[c ] [i] [H ] [L ] [d ] -- Simulate LF FSK tag from demodbuffer or input"}, {"simpsk", CmdLFpskSim, 0, "[1|2|3] [c ] [i] [r ] [d ] -- Simulate LF PSK tag from demodbuffer or input"}, {"simbidir", CmdLFSimBidir, 0, "Simulate LF tag (with bidirectional data transmission between reader and tag)"}, - //{"simman", CmdLFSimManchester, 0, " [GAP] Simulate arbitrary Manchester LF tag"}, {"snoop", CmdLFSnoop, 0, "['l'|'h'|] [trigger threshold]-- Snoop LF (l:125khz, h:134khz)"}, {"ti", CmdLFTI, 1, "{ TI RFIDs... }"}, {"hitag", CmdLFHitag, 1, "{ Hitag tags and transponders... }"}, diff --git a/client/cmdlf.h b/client/cmdlf.h index 254d8807..7dd1b044 100644 --- a/client/cmdlf.h +++ b/client/cmdlf.h @@ -23,7 +23,6 @@ int CmdLFaskSim(const char *Cmd); int CmdLFfskSim(const char *Cmd); int CmdLFpskSim(const char *Cmd); int CmdLFSimBidir(const char *Cmd); -//int CmdLFSimManchester(const char *Cmd); int CmdLFSnoop(const char *Cmd); int CmdVchDemod(const char *Cmd); int CmdLFfind(const char *Cmd); diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index 47a5ac3e..552c256e 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -140,7 +140,6 @@ int CmdEM410xSim(const char *Cmd) * rate gets lower, then grow the number of samples * Changed by martin, 4000 x 4 = 16000, * see http://www.proxmark.org/forum/viewtopic.php?pid=7235#p7235 - */ int CmdEM410xWatch(const char *Cmd) { @@ -151,7 +150,7 @@ int CmdEM410xWatch(const char *Cmd) } CmdLFRead("s"); - getSamples("8192",true); //capture enough to get 2 full messages + getSamples("8201",true); //capture enough to get 2 complete preambles (4096*2+9) } while (!CmdEM410xRead("")); return 0; diff --git a/client/cmdlfhid.c b/client/cmdlfhid.c index c6d54e78..4e103f1a 100644 --- a/client/cmdlfhid.c +++ b/client/cmdlfhid.c @@ -17,7 +17,7 @@ #include "cmdlfhid.h" static int CmdHelp(const char *Cmd); - +/* int CmdHIDDemod(const char *Cmd) { if (GraphTraceLen < 4800) { @@ -36,7 +36,7 @@ int CmdHIDDemod(const char *Cmd) RepaintGraphWindow(); return 0; } - +*/ int CmdHIDDemodFSK(const char *Cmd) { int findone=0; @@ -106,7 +106,7 @@ int CmdHIDClone(const char *Cmd) static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdHIDDemod, 1, "Demodulate HID Prox Card II (not optimal)"}, + //{"demod", CmdHIDDemod, 1, "Demodulate HID Prox Card II (not optimal)"}, {"fskdemod", CmdHIDDemodFSK, 0, "['1'] Realtime HID FSK demodulator (option '1' for one tag only)"}, {"sim", CmdHIDSim, 0, " -- HID tag simulator"}, {"clone", CmdHIDClone, 0, " ['l'] -- Clone HID to T55x7 (tag must be in antenna)(option 'l' for 84bit ID)"}, diff --git a/client/cmdlfhid.h b/client/cmdlfhid.h index 328f3b13..7021492b 100644 --- a/client/cmdlfhid.h +++ b/client/cmdlfhid.h @@ -12,9 +12,9 @@ #define CMDLFHID_H__ int CmdLFHID(const char *Cmd); - -int CmdHIDDemod(const char *Cmd); +//int CmdHIDDemod(const char *Cmd); int CmdHIDDemodFSK(const char *Cmd); int CmdHIDSim(const char *Cmd); +int CmdHIDClone(const char *Cmd); #endif diff --git a/client/cmdlfio.c b/client/cmdlfio.c index 14ce5498..aa21c44b 100644 --- a/client/cmdlfio.c +++ b/client/cmdlfio.c @@ -24,7 +24,7 @@ int CmdIODemodFSK(const char *Cmd) SendCommand(&c); return 0; } - +/* int CmdIOProxDemod(const char *Cmd){ if (GraphTraceLen < 4800) { PrintAndLog("too short; need at least 4800 samples"); @@ -37,7 +37,7 @@ int CmdIOProxDemod(const char *Cmd){ RepaintGraphWindow(); return 0; } - +*/ int CmdIOClone(const char *Cmd) { unsigned int hi = 0, lo = 0; @@ -67,7 +67,7 @@ int CmdIOClone(const char *Cmd) static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdIOProxDemod, 1, "Demodulate Stream"}, + //{"demod", CmdIOProxDemod, 1, "Demodulate Stream"}, {"fskdemod", CmdIODemodFSK, 0, "['1'] Realtime IO FSK demodulator (option '1' for one tag only)"}, {"clone", CmdIOClone, 0, "Clone ioProx Tag"}, {NULL, NULL, 0, NULL} @@ -83,4 +83,4 @@ int CmdHelp(const char *Cmd) { CmdsHelp(CommandTable); return 0; -} \ No newline at end of file +} diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index b6b29c05..64c999d6 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -147,31 +147,37 @@ int CmdT55xxSetConfig(const char *Cmd) { param_getstr(Cmd, cmdp+1, modulation); cmdp += 2; - if ( strcmp(modulation, "FSK" ) == 0) + if ( strcmp(modulation, "FSK" ) == 0) { config.modulation = DEMOD_FSK; - else if ( strcmp(modulation, "FSK1" ) == 0) + } else if ( strcmp(modulation, "FSK1" ) == 0) { config.modulation = DEMOD_FSK1; - else if ( strcmp(modulation, "FSK1a" ) == 0) + config.inverted=1; + } else if ( strcmp(modulation, "FSK1a" ) == 0) { config.modulation = DEMOD_FSK1a; - else if ( strcmp(modulation, "FSK2" ) == 0) + config.inverted=0; + } else if ( strcmp(modulation, "FSK2" ) == 0) { config.modulation = DEMOD_FSK2; - else if ( strcmp(modulation, "FSK2a" ) == 0) + config.inverted=0; + } else if ( strcmp(modulation, "FSK2a" ) == 0) { config.modulation = DEMOD_FSK2a; - else if ( strcmp(modulation, "ASK" ) == 0) + config.inverted=1; + } else if ( strcmp(modulation, "ASK" ) == 0) { config.modulation = DEMOD_ASK; - else if ( strcmp(modulation, "NRZ" ) == 0) + } else if ( strcmp(modulation, "NRZ" ) == 0) { config.modulation = DEMOD_NRZ; - else if ( strcmp(modulation, "PSK1" ) == 0) + } else if ( strcmp(modulation, "PSK1" ) == 0) { config.modulation = DEMOD_PSK1; - else if ( strcmp(modulation, "PSK2" ) == 0) + } else if ( strcmp(modulation, "PSK2" ) == 0) { config.modulation = DEMOD_PSK2; - else if ( strcmp(modulation, "PSK3" ) == 0) + } else if ( strcmp(modulation, "PSK3" ) == 0) { config.modulation = DEMOD_PSK3; - else if ( strcmp(modulation, "BIa" ) == 0) + } else if ( strcmp(modulation, "BIa" ) == 0) { config.modulation = DEMOD_BIa; - else if ( strcmp(modulation, "BI" ) == 0) + config.inverted=1; + } else if ( strcmp(modulation, "BI" ) == 0) { config.modulation = DEMOD_BI; - else { + config.inverted=0; + } else { PrintAndLog("Unknown modulation '%s'", modulation); errors = TRUE; } @@ -264,55 +270,36 @@ bool DecodeT55xxBlock(){ switch( config.modulation ){ case DEMOD_FSK: - //CmdLtrim("26"); sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); sprintf(cmdStr,"%d %d", bitRate[config.bitrate], config.inverted ); ans = FSKrawDemod(cmdStr, FALSE); break; case DEMOD_FSK1: - //CmdLtrim("26"); - sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); - CmdLtrim(cmdStr); - sprintf(cmdStr,"%d 1 8 5", bitRate[config.bitrate] ); - ans = FSKrawDemod(cmdStr, FALSE); - break; case DEMOD_FSK1a: - //CmdLtrim("26"); sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); - sprintf(cmdStr,"%d 0 8 5", bitRate[config.bitrate] ); + sprintf(cmdStr,"%d %d 8 5", bitRate[config.bitrate], config.inverted ); ans = FSKrawDemod(cmdStr, FALSE); break; case DEMOD_FSK2: - //CmdLtrim("26"); - sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); - CmdLtrim(cmdStr); - sprintf(cmdStr,"%d 0 10 8", bitRate[config.bitrate] ); - ans = FSKrawDemod(cmdStr, FALSE); - break; case DEMOD_FSK2a: - //CmdLtrim("26"); sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); - sprintf(cmdStr,"%d 1 10 8", bitRate[config.bitrate] ); + sprintf(cmdStr,"%d %d 10 8", bitRate[config.bitrate], config.inverted ); ans = FSKrawDemod(cmdStr, FALSE); break; case DEMOD_ASK: - sprintf(cmdStr,"%d %d 1", bitRate[config.bitrate], config.inverted ); + sprintf(cmdStr,"%d %d 0", bitRate[config.bitrate], config.inverted ); ans = ASKmanDemod(cmdStr, FALSE, FALSE); break; case DEMOD_PSK1: - sprintf(cmdStr,"%d %d 1", bitRate[config.bitrate], config.inverted ); + sprintf(cmdStr,"%d %d 0", bitRate[config.bitrate], config.inverted ); ans = PSKDemod(cmdStr, FALSE); break; - case DEMOD_PSK2: - sprintf(cmdStr,"%d 1", bitRate[config.bitrate] ); - ans = PSKDemod(cmdStr, FALSE); - psk1TOpsk2(DemodBuffer, DemodBufferLen); - break; - case DEMOD_PSK3: - sprintf(cmdStr,"%d %d 1", bitRate[config.bitrate], config.inverted ); + case DEMOD_PSK2: //inverted won't affect this + case DEMOD_PSK3: //not fully implemented + sprintf(cmdStr,"%d 0 1", bitRate[config.bitrate] ); ans = PSKDemod(cmdStr, FALSE); psk1TOpsk2(DemodBuffer, DemodBufferLen); break; @@ -321,11 +308,8 @@ bool DecodeT55xxBlock(){ ans = NRZrawDemod(cmdStr, FALSE); break; case DEMOD_BI: - sprintf(cmdStr,"0 %d 0 1", bitRate[config.bitrate] ); - ans = ASKbiphaseDemod(cmdStr, FALSE); - break; case DEMOD_BIa: - sprintf(cmdStr,"0 %d 1 1", bitRate[config.bitrate] ); + sprintf(cmdStr,"0 %d %d 0", bitRate[config.bitrate], config.inverted ); ans = ASKbiphaseDemod(cmdStr, FALSE); break; default: @@ -516,33 +500,9 @@ bool testBitRate(uint8_t readRate, uint8_t mod){ uint8_t detRate = 0; switch( mod ){ case DEMOD_FSK: - detRate = GetFskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; case DEMOD_FSK1: - detRate = GetFskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; case DEMOD_FSK1a: - detRate = GetFskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; case DEMOD_FSK2: - detRate = GetFskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; case DEMOD_FSK2a: detRate = GetFskClock("",FALSE, FALSE); if (expected[readRate] == detRate) { @@ -551,6 +511,8 @@ bool testBitRate(uint8_t readRate, uint8_t mod){ } break; case DEMOD_ASK: + case DEMOD_BI: + case DEMOD_BIa: detRate = GetAskClock("",FALSE, FALSE); if (expected[readRate] == detRate) { config.bitrate = readRate; @@ -558,19 +520,7 @@ bool testBitRate(uint8_t readRate, uint8_t mod){ } break; case DEMOD_PSK1: - detRate = GetPskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; case DEMOD_PSK2: - detRate = GetPskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; case DEMOD_PSK3: detRate = GetPskClock("",FALSE, FALSE); if (expected[readRate] == detRate) { @@ -585,13 +535,6 @@ bool testBitRate(uint8_t readRate, uint8_t mod){ return TRUE; } break; - case DEMOD_BI: - detRate = GetAskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; - return TRUE; - } - break; default: return FALSE; } @@ -606,18 +549,18 @@ bool test(uint8_t mode, uint8_t *offset){ si = idx; if ( PackBits(si, 32, DemodBuffer) == 0x00 ) continue; - uint8_t safer = PackBits(si, 4, DemodBuffer); si += 4; //master key + uint8_t safer = PackBits(si, 4, DemodBuffer); si += 4; //master key uint8_t resv = PackBits(si, 4, DemodBuffer); si += 4; //was 7 & +=7+3 //should be only 4 bits if extended mode // 2nibble must be zeroed. // moved test to here, since this gets most faults first. if ( resv > 0x00) continue; - uint8_t xtRate = PackBits(si, 3, DemodBuffer); si += 3; //new - uint8_t bitRate = PackBits(si, 3, DemodBuffer); si += 3; //new could check bit rate + uint8_t xtRate = PackBits(si, 3, DemodBuffer); si += 3; //extended mode part of rate + uint8_t bitRate = PackBits(si, 3, DemodBuffer); si += 3; //bit 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; //new - //uint8_t pskcr = PackBits(si, 2, DemodBuffer); si += 2+1; //new 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 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 @@ -628,9 +571,8 @@ bool test(uint8_t mode, uint8_t *offset){ } //test modulation if (!testModulation(mode, modread)) continue; - - *offset = idx; if (!testBitRate(bitRate, mode)) continue; + *offset = idx; return TRUE; } return FALSE; @@ -922,7 +864,7 @@ int AquireData( uint8_t block ){ } char * GetBitRateStr(uint32_t id){ - static char buf[40]; + static char buf[20]; char *retStr = buf; switch (id){ case 0: @@ -957,7 +899,6 @@ char * GetBitRateStr(uint32_t id){ return buf; } - char * GetSaferStr(uint32_t id){ static char buf[40]; char *retStr = buf; @@ -974,7 +915,7 @@ char * GetSaferStr(uint32_t id){ } char * GetModulationStr( uint32_t id){ - static char buf[40]; + static char buf[60]; char *retStr = buf; switch (id){ diff --git a/client/graph.c b/client/graph.c index ae318ddf..089119d9 100644 --- a/client/graph.c +++ b/client/graph.c @@ -53,11 +53,11 @@ void save_restoreGB(uint8_t saveOpt) static bool GB_Saved = false; if (saveOpt==1) { //save - memcpy(SavedGB,GraphBuffer, sizeof(GraphBuffer)); + memcpy(SavedGB, GraphBuffer, sizeof(GraphBuffer)); SavedGBlen = GraphTraceLen; GB_Saved=true; } else if (GB_Saved){ - memcpy(GraphBuffer,SavedGB, sizeof(GraphBuffer)); + memcpy(GraphBuffer, SavedGB, sizeof(GraphBuffer)); GraphTraceLen = SavedGBlen; } return; diff --git a/client/util.c b/client/util.c index edd9aebc..709e2014 100644 --- a/client/util.c +++ b/client/util.c @@ -121,19 +121,24 @@ char * sprint_hex(const uint8_t * data, const size_t len) { return buf; } -char * sprint_bin(const uint8_t * data, const size_t len) { +char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks) { int maxLen = ( len > 1024) ? 1024 : len; static char buf[1024]; - char * tmp = buf; - size_t i; + char *tmp = buf; - for (i=0; i < maxLen; ++i, ++tmp) - sprintf(tmp, "%u", data[i]); + for (size_t i=0; i < maxLen; ++i){ + sprintf(tmp++, "%u", data[i]); + if (breaks > 0 && !((i+1) % breaks)) + sprintf(tmp++, "%s","\n"); + } return buf; } +char *sprint_bin(const uint8_t *data, const size_t len) { + return sprint_bin_break(data, len, 0); +} void num_to_bytes(uint64_t n, size_t len, uint8_t* dest) { while (len--) { diff --git a/client/util.h b/client/util.h index 5001acdc..a6d0f49f 100644 --- a/client/util.h +++ b/client/util.h @@ -39,6 +39,7 @@ void FillFileNameByUID(char *fileName, uint8_t * uid, char *ext, int byteCount); void print_hex(const uint8_t * data, const size_t len); char * sprint_hex(const uint8_t * data, const size_t len); char * sprint_bin(const uint8_t * data, const size_t len); +char * sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks); void num_to_bytes(uint64_t n, size_t len, uint8_t* dest); uint64_t bytes_to_num(uint8_t* src, size_t len); diff --git a/common/lfdemod.c b/common/lfdemod.c index c00222b3..58221546 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -81,10 +81,8 @@ uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_ // otherwise could be a void with no arguments //set defaults uint32_t i = 0; - if (BitStream[1]>1){ //allow only 1s and 0s - // PrintAndLog("no data found"); - return 0; - } + if (BitStream[1]>1) return 0; //allow only 1s and 0s + // 111111111 bit pattern represent start of frame // include 0 in front to help get start pos uint8_t preamble[] = {0,1,1,1,1,1,1,1,1,1}; @@ -130,7 +128,7 @@ int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int if (smplCnt > clk-(clk/4)-1) { //full clock if (smplCnt > clk + (clk/4)+1) { //too many samples errCnt++; - BinStream[bitCnt++]=77; + BinStream[bitCnt++]=7; } else if (waveHigh) { BinStream[bitCnt++] = invert; BinStream[bitCnt++] = invert; @@ -208,7 +206,7 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max //should have hit a high or low based on clock!! //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit); if (bitnum > 0) { - BinStream[bitnum++] = 77; + BinStream[bitnum++] = 7; errCnt++; } lastBit += *clk;//skip over error @@ -244,6 +242,7 @@ int manrawdecode(uint8_t * BitStream, size_t *size) size_t i, ii; uint16_t bestErr = 1000, bestRun = 0; if (size == 0) return -1; + //find correct start position [alignment] for (ii=0;ii<2;++ii){ for (i=ii; i<*size-2; i+=2) if (BitStream[i]==BitStream[i+1]) @@ -255,13 +254,14 @@ int manrawdecode(uint8_t * BitStream, size_t *size) } errCnt=0; } + //decode for (i=bestRun; i < *size-2; i+=2){ if(BitStream[i] == 1 && (BitStream[i+1] == 0)){ BitStream[bitnum++]=0; } else if((BitStream[i] == 0) && BitStream[i+1] == 1){ BitStream[bitnum++]=1; } else { - BitStream[bitnum++]=77; + BitStream[bitnum++]=7; } if(bitnum>MaxBits) break; } @@ -291,7 +291,7 @@ int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert) for (i=offset; i<*size-3; i+=2){ //check for phase error if (BitStream[i+1]==BitStream[i+2]) { - BitStream[bitnum++]=77; + BitStream[bitnum++]=7; errCnt++; } if((BitStream[i]==1 && BitStream[i+1]==0) || (BitStream[i]==0 && BitStream[i+1]==1)){ @@ -299,7 +299,7 @@ int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert) } else if((BitStream[i]==0 && BitStream[i+1]==0) || (BitStream[i]==1 && BitStream[i+1]==1)){ BitStream[bitnum++]=invert; } else { - BitStream[bitnum++]=77; + BitStream[bitnum++]=7; errCnt++; } if(bitnum>MaxBits) break; @@ -367,7 +367,7 @@ int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max BinStream[bitnum++] = *invert ^ 1; } else { if (bitnum > 0) { - BinStream[bitnum++]=77; + BinStream[bitnum++]=7; errCnt++; } } @@ -784,8 +784,9 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) for (i=8; i>1; i--){ if (clk[i] == ans) { *clock = ans; - clockFnd = i; - break; //clock found but continue to find best startpos + //clockFnd = i; + return 0; // for strong waves i don't use the 'best start position' yet... + //break; //clock found but continue to find best startpos [not yet] } } } @@ -806,10 +807,11 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) }else{ tol=0; } - if (!maxErr && loopCnt>clk[clkCnt]*3) loopCnt=clk[clkCnt]*3; + //if no errors allowed - keep start within the first clock + if (!maxErr && size > clk[clkCnt]*3 + tol) loopCnt=clk[clkCnt]*2; bestErr[clkCnt]=1000; //try lining up the peaks by moving starting point (try first few clocks) - for (ii=0; ii < loopCnt-tol-clk[clkCnt]; ii++){ + for (ii=0; ii < loopCnt-clk[clkCnt]; ii++){ if (dest[ii] < peak && dest[ii] > low) continue; errCnt=0; @@ -849,7 +851,7 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) } } } - if (bestErr[best] > maxErr) return -1; + //if (bestErr[best] > maxErr) return -1; *clock = clk[best]; return bestStart[best]; } @@ -1029,7 +1031,7 @@ void psk1TOpsk2(uint8_t *BitStream, size_t size) size_t i=1; uint8_t lastBit=BitStream[0]; for (; i lastClkBit + *clock + tol + fc){ lastClkBit += *clock; //no phase shift but clock bit From 224ce36eb1037ecb48d55066ab2fe36f0a5064df Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 5 Apr 2015 16:37:41 -0400 Subject: [PATCH 005/132] lf t5xx - icemans update --- client/cmdlft55xx.c | 63 ++++++++------ client/scripts/test_t55x7_ask.lua | 3 +- client/scripts/test_t55x7_bi.lua | 9 +- client/scripts/test_t55x7_fsk.lua | 3 +- client/scripts/test_t55x7_psk.lua | 5 +- client/scripts/tnp3clone.lua | 136 ++++++++++++++++++++++++++++++ client/scripts/tnp3dump.lua | 70 +++++++++------ client/scripts/tnp3sim.lua | 128 ++++++++++++++++++++++++++-- 8 files changed, 351 insertions(+), 66 deletions(-) create mode 100644 client/scripts/tnp3clone.lua diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index 64c999d6..1a0c0f58 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -10,6 +10,7 @@ #include #include #include +#include #include "proxmark3.h" #include "ui.h" #include "graph.h" @@ -261,7 +262,7 @@ int CmdT55xxReadBlock(const char *Cmd) { bool DecodeT55xxBlock(){ - char buf[8] = {0x00}; + char buf[10] = {0x00}; char *cmdStr = buf; int ans = 0; uint8_t bitRate[8] = {8,16,32,40,50,64,100,128}; @@ -270,46 +271,46 @@ bool DecodeT55xxBlock(){ switch( config.modulation ){ case DEMOD_FSK: - sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); + snprintf(cmdStr, sizeof(buf),"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); - sprintf(cmdStr,"%d %d", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"%d %d", bitRate[config.bitrate], config.inverted ); ans = FSKrawDemod(cmdStr, FALSE); break; case DEMOD_FSK1: case DEMOD_FSK1a: - sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); + snprintf(cmdStr, sizeof(buf),"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); - sprintf(cmdStr,"%d %d 8 5", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"%d %d 8 5", bitRate[config.bitrate], config.inverted ); ans = FSKrawDemod(cmdStr, FALSE); break; case DEMOD_FSK2: case DEMOD_FSK2a: - sprintf(cmdStr,"%d", bitRate[config.bitrate]/2 ); + snprintf(cmdStr, sizeof(buf),"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); - sprintf(cmdStr,"%d %d 10 8", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"%d %d 10 8", bitRate[config.bitrate], config.inverted ); ans = FSKrawDemod(cmdStr, FALSE); break; case DEMOD_ASK: - sprintf(cmdStr,"%d %d 0", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"%d %d 0", bitRate[config.bitrate], config.inverted ); ans = ASKmanDemod(cmdStr, FALSE, FALSE); break; case DEMOD_PSK1: - sprintf(cmdStr,"%d %d 0", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"%d %d 0", bitRate[config.bitrate], config.inverted ); ans = PSKDemod(cmdStr, FALSE); break; case DEMOD_PSK2: //inverted won't affect this case DEMOD_PSK3: //not fully implemented - sprintf(cmdStr,"%d 0 1", bitRate[config.bitrate] ); + snprintf(cmdStr, sizeof(buf),"%d 0 1", bitRate[config.bitrate] ); ans = PSKDemod(cmdStr, FALSE); psk1TOpsk2(DemodBuffer, DemodBufferLen); break; case DEMOD_NRZ: - sprintf(cmdStr,"%d %d 1", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"%d %d 1", bitRate[config.bitrate], config.inverted ); ans = NRZrawDemod(cmdStr, FALSE); break; case DEMOD_BI: case DEMOD_BIa: - sprintf(cmdStr,"0 %d %d 0", bitRate[config.bitrate], config.inverted ); + snprintf(cmdStr, sizeof(buf),"0 %d %d 0", bitRate[config.bitrate], config.inverted ); ans = ASKbiphaseDemod(cmdStr, FALSE); break; default: @@ -578,7 +579,7 @@ bool test(uint8_t mode, uint8_t *offset){ return FALSE; } -void printT55xxBlock(const char *demodStr){ +void printT55xxBlock(const char *blockNum){ uint8_t i = config.offset; uint8_t endpos = 32 + i; @@ -596,7 +597,7 @@ void printT55xxBlock(const char *demodStr){ bits[i - config.offset]=DemodBuffer[i]; blockData = PackBits(0, 32, bits); - PrintAndLog("0x%08X %s [%s]", blockData, sprint_bin(bits,32), demodStr); + PrintAndLog("[%s] 0x%08X %s", blockNum, blockData, sprint_bin(bits,32)); } int special(const char *Cmd) { @@ -688,16 +689,28 @@ int CmdT55xxReadTrace(const char *Cmd) uint32_t bl0 = PackBits(si, 32, DemodBuffer); uint32_t bl1 = PackBits(si+32, 32, DemodBuffer); - uint32_t acl = PackBits(si, 8, DemodBuffer); si += 8; - uint32_t mfc = PackBits(si, 8, DemodBuffer); si += 8; - uint32_t cid = PackBits(si, 5, DemodBuffer); si += 5; - uint32_t icr = PackBits(si, 3, DemodBuffer); si += 3; - uint32_t year = PackBits(si, 4, DemodBuffer); si += 4; - uint32_t quarter = PackBits(si, 2, DemodBuffer); si += 2; - uint32_t lotid = PackBits(si, 14, DemodBuffer); si += 14; - uint32_t wafer = PackBits(si, 5, DemodBuffer); si += 5; + uint32_t acl = PackBits(si, 8, DemodBuffer); si += 8; + uint32_t mfc = PackBits(si, 8, DemodBuffer); si += 8; + uint32_t cid = PackBits(si, 5, DemodBuffer); si += 5; + uint32_t icr = PackBits(si, 3, DemodBuffer); si += 3; + uint32_t year = PackBits(si, 4, DemodBuffer); si += 4; + uint32_t quarter = PackBits(si, 2, DemodBuffer); si += 2; + uint32_t lotid = PackBits(si, 14, DemodBuffer); si += 14; + uint32_t wafer = PackBits(si, 5, DemodBuffer); si += 5; uint32_t dw = PackBits(si, 15, DemodBuffer); + time_t t = time(NULL); + struct tm tm = *localtime(&t); + if ( year > tm.tm_year-110) + year += 2000; + else + year += 2010; + + if ( acl != 0xE0 ) { + PrintAndLog("The modulation is most likely wrong since the ACL is not 0xE0. "); + return 1; + } + PrintAndLog(""); PrintAndLog("-- T55xx Trace Information ----------------------------------"); PrintAndLog("-------------------------------------------------------------"); @@ -716,8 +729,6 @@ int CmdT55xxReadTrace(const char *Cmd) PrintAndLog(" Block 1 : 0x%08X %s", bl1, sprint_bin(DemodBuffer+config.offset+repeat+32,32) ); PrintAndLog("-------------------------------------------------------------"); - if ( acl != 0xE0 ) - PrintAndLog("The modulation is most likely wrong since the ACL is not 0xE0. "); /* TRACE - BLOCK O Bits Definition HEX @@ -967,8 +978,8 @@ char * GetModelStrFromCID(uint32_t cid){ static char buf[10]; char *retStr = buf; - if (cid == 1) sprintf(retStr,"ATA5577M1"); - if (cid == 2) sprintf(retStr,"ATA5577M2"); + if (cid == 1) snprintf(retStr, sizeof(buf),"ATA5577M1"); + if (cid == 2) snprintf(retStr, sizeof(buf),"ATA5577M2"); return buf; } diff --git a/client/scripts/test_t55x7_ask.lua b/client/scripts/test_t55x7_ask.lua index 569d4260..f8990b15 100644 --- a/client/scripts/test_t55x7_ask.lua +++ b/client/scripts/test_t55x7_ask.lua @@ -95,6 +95,7 @@ end function test() local y + local block = "00" for y = 0x0, 0x1d, 0x4 do for _ = 1, #procedurecmds do local pcmd = procedurecmds[_] @@ -107,7 +108,7 @@ function test() dbg(('lf t55xx write 0 %s'):format(config)) config = tonumber(config,16) - local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK, arg1 = config} + local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK,arg1 = config, arg2 = block, arg3 = "00", data = "00"} local err = core.SendCommand(writecmd:getBytes()) if err then return oops(err) end local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) diff --git a/client/scripts/test_t55x7_bi.lua b/client/scripts/test_t55x7_bi.lua index a1793ba6..e8950ab8 100644 --- a/client/scripts/test_t55x7_bi.lua +++ b/client/scripts/test_t55x7_bi.lua @@ -89,6 +89,7 @@ end function test() local y + local block = "00" for y = 1, 0x1D, 4 do for _ = 1, #procedurecmds do local pcmd = procedurecmds[_] @@ -98,10 +99,10 @@ function test() elseif _ == 1 then local config = pcmd:format(config1, y, config2) - dbg(('lf t55xx wr 0 %s'):format(config)) - - config = tonumber(config,16) - local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK, arg1 = config} + dbg(('lf t55xx write 0 %s'):format(config)) + + config = tonumber(config,16) + local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK,arg1 = config, arg2 = block, arg3 = "00", data = "00"} local err = core.SendCommand(writecmd:getBytes()) if err then return oops(err) end local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) diff --git a/client/scripts/test_t55x7_fsk.lua b/client/scripts/test_t55x7_fsk.lua index f42dd147..c9c1f09c 100644 --- a/client/scripts/test_t55x7_fsk.lua +++ b/client/scripts/test_t55x7_fsk.lua @@ -92,6 +92,7 @@ end function test(modulation) local y + local block = "00" for y = 0x0, 0x1d, 0x4 do for _ = 1, #procedurecmds do local pcmd = procedurecmds[_] @@ -104,7 +105,7 @@ function test(modulation) dbg(('lf t55xx write 0 %s'):format(config)) config = tonumber(config,16) - local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK, arg1 = config} + local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK,arg1 = config, arg2 = block, arg3 = "00", data = "00"} local err = core.SendCommand(writecmd:getBytes()) if err then return oops(err) end local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) diff --git a/client/scripts/test_t55x7_psk.lua b/client/scripts/test_t55x7_psk.lua index cbd78e87..bdd644a7 100644 --- a/client/scripts/test_t55x7_psk.lua +++ b/client/scripts/test_t55x7_psk.lua @@ -108,6 +108,7 @@ end function test(modulation) local bitrate local clockrate + local block = "00" for bitrate = 0x0, 0x1d, 0x4 do for clockrate = 0,8,4 do @@ -125,8 +126,8 @@ function test(modulation) dbg(('lf t55xx write 0 %s'):format(config)) config = tonumber(config,16) - local writecommand = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK, arg1 = config ,arg2 = 0, arg3 = 0} - local err = core.SendCommand(writecommand:getBytes()) + local writecmd = Command:new{cmd = cmds.CMD_T55XX_WRITE_BLOCK,arg1 = config, arg2 = block, arg3 = "00", data = "00"} + local err = core.SendCommand(writecmd:getBytes()) if err then return oops(err) end local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) else diff --git a/client/scripts/tnp3clone.lua b/client/scripts/tnp3clone.lua new file mode 100644 index 00000000..8c9397a7 --- /dev/null +++ b/client/scripts/tnp3clone.lua @@ -0,0 +1,136 @@ +local cmds = require('commands') +local getopt = require('getopt') +local lib14a = require('read14a') +local utils = require('utils') +local pre = require('precalc') + +local lsh = bit32.lshift +local rsh = bit32.rshift +local bor = bit32.bor +local band = bit32.band + +example =[[ + script run tnp3dump + script run tnp3dump -h + script run tnp3dump -t aa00 + +]] +author = "Iceman" +usage = "script run tnp3clone -t " +desc =[[ +This script will try making a barebone clone of a tnp3 tag on to a magic generation1 card. + +Arguments: + -h : this help + -k : toytype id, 4 hex symbols. +]] + + +-- This is only meant to be used when errors occur +function oops(err) + print("ERROR: ",err) +end +-- Usage help +function help() + print(desc) + print("Example usage") + print(example) +end + +local function waitCmd() + local response = core.WaitForResponseTimeout(cmds.CMD_ACK,2000) + if response then + local count,cmd,arg0 = bin.unpack('LL',response) + if(arg0==1) then + local count,arg1,arg2,data = bin.unpack('LLH511',response,count) + return data:sub(1,32) + else + return nil, "Couldn't read block." + end + end + return nil, "No response from device" +end + +local function readblock( blocknum, keyA ) + -- Read block 0 + cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = blocknum, arg2 = 0, arg3 = 0, data = keyA} + err = core.SendCommand(cmd:getBytes()) + if err then return nil, err end + local block0, err = waitCmd() + if err then return nil, err end + return block0 +end +local function readmagicblock( blocknum ) + -- Read block 0 + local CSETBLOCK_SINGLE_OPERATION = 0x1F + cmd = Command:new{cmd = cmds.CMD_MIFARE_CGETBLOCK, arg1 = CSETBLOCK_SINGLE_OPERATION, arg2 = 0, arg3 = blocknum} + err = core.SendCommand(cmd:getBytes()) + if err then return nil, err end + local block0, err = waitCmd() + if err then return nil, err end + return block0 +end + +local function main(args) + + local numBlocks = 64 + local cset = 'hf mf csetbl ' + local cget = 'hf mf cgetbl ' + local empty = '00000000000000000000000000000000' + local AccAndKeyB = '7F078869000000000000' + -- Defaults to Gusto + local toytype = 'C201' + + -- Arguments for the script + for o, a in getopt.getopt(args, 'ht:') do + if o == "h" then return help() end + if o == "t" then toytype = a end + end + + if #toytype ~= 4 then return oops('Wrong size in toytype. (4hex symbols)') end + + -- find tag + result, err = lib14a.read1443a(false) + if not result then return oops(err) end + + -- Show tag info + print((' Found tag %s'):format(result.name)) + + -- load keys + local akeys = pre.GetAll(result.uid) + local keyA = akeys:sub(1, 12 ) + + local b0 = readblock(0,keyA) + if not b0 then + print('failed reading block with factorydefault key. Trying chinese magic read.') + b0, err = readmagicblock(0) + if not b0 then + oops(err) + return oops('failed reading block with chinese magic command. quitting...') + end + end + + -- wipe card. + local cmd = (cset..' %s 0004 08 w'):format( b0) + core.console(cmd) + + + local b1 = toytype..'000000000000000000000000' + local calc = utils.Crc16(b0..b1) + local calcEndian = bor(rsh(calc,8), lsh(band(calc, 0xff), 8)) + + local cmd = (cset..'1 %s%04x'):format( b1, calcEndian) + core.console(cmd) + + local pos, key + for blockNo = 2, numBlocks-1, 1 do + pos = (math.floor( blockNo / 4 ) * 12)+1 + key = akeys:sub(pos, pos + 11 ) + if blockNo%4 == 3 then + cmd = ('%s %d %s%s'):format(cset,blockNo,key,AccAndKeyB) + core.console(cmd) + end + end + core.clearCommandBuffer() +end +main(args) \ No newline at end of file diff --git a/client/scripts/tnp3dump.lua b/client/scripts/tnp3dump.lua index dedd3df1..363998fb 100644 --- a/client/scripts/tnp3dump.lua +++ b/client/scripts/tnp3dump.lua @@ -7,17 +7,20 @@ local md5 = require('md5') local dumplib = require('html_dumplib') local toyNames = require('default_toys') + example =[[ - 1. script run tnp3dump - 2. script run tnp3dump -n - 3. script run tnp3dump -k aabbccddeeff - 4. script run tnp3dump -k aabbccddeeff -n - 5. script run tnp3dump -o myfile - 6. script run tnp3dump -n -o myfile - 7. script run tnp3dump -k aabbccddeeff -n -o myfile + script run tnp3dump + script run tnp3dump -n + script run tnp3dump -p + script run tnp3dump -k aabbccddeeff + script run tnp3dump -k aabbccddeeff -n + script run tnp3dump -o myfile + script run tnp3dump -n -o myfile + script run tnp3dump -p -o myfile + script run tnp3dump -k aabbccddeeff -n -o myfile ]] author = "Iceman" -usage = "script run tnp3dump -k -n -o " +usage = "script run tnp3dump -k -n -p -o " desc =[[ This script will try to dump the contents of a Mifare TNP3xxx card. It will need a valid KeyA in order to find the other keys and decode the card. @@ -25,6 +28,7 @@ Arguments: -h : this help -k : Sector 0 Key A. -n : Use the nested cmd to find all keys + -p : Use the precalc to find all keys -o : filename for the saved dumps ]] @@ -112,15 +116,17 @@ local function main(args) local cmd local err local useNested = false + local usePreCalc = false local cmdReadBlockString = 'hf mf rdbl %d A %s' local input = "dumpkeys.bin" local outputTemplate = os.date("toydump_%Y-%m-%d_%H%M%S"); -- Arguments for the script - for o, a in getopt.getopt(args, 'hk:no:') do + for o, a in getopt.getopt(args, 'hk:npo:') do if o == "h" then return help() end if o == "k" then keyA = a end if o == "n" then useNested = true end + if o == "p" then usePreCalc = true end if o == "o" then outputTemplate = a end end @@ -142,29 +148,34 @@ local function main(args) core.clearCommandBuffer() if 0x01 ~= result.sak then -- NXP MIFARE TNP3xxx - return oops('This is not a TNP3xxx tag. aborting.') + -- return oops('This is not a TNP3xxx tag. aborting.') end -- Show tag info - print((' Found tag : %s'):format(result.name)) - print(('Using keyA : %s'):format(keyA)) + print((' Found tag %s'):format(result.name)) + + dbg(('Using keyA : %s'):format(keyA)) --Trying to find the other keys if useNested then core.console( ('hf mf nested 1 0 A %s d'):format(keyA) ) end - + core.clearCommandBuffer() - -- Loading keyfile - print('Loading dumpkeys.bin') - local hex, err = utils.ReadDumpFile(input) - if not hex then - return oops(err) + local akeys = '' + if usePreCalc then + local pre = require('precalc') + akeys = pre.GetAll(result.uid) + else + print('Loading dumpkeys.bin') + local hex, err = utils.ReadDumpFile(input) + if not hex then + return oops(err) + end + akeys = hex:sub(0,12*16) end - - local akeys = hex:sub(0,12*16) - + -- Read block 0 cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = 0,arg2 = 0,arg3 = 0, data = keyA} err = core.SendCommand(cmd:getBytes()) @@ -188,7 +199,7 @@ local function main(args) core.clearCommandBuffer() -- main loop - io.write('Decrypting blocks > ') + io.write('Reading blocks > ') for blockNo = 0, numBlocks-1, 1 do if core.ukbhit() then @@ -204,7 +215,9 @@ local function main(args) local blockdata, err = waitCmd() if err then return oops(err) end + if blockNo%4 ~= 3 then + if blockNo < 8 then -- Block 0-7 not encrypted blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) @@ -249,23 +262,28 @@ local function main(args) end end - local uid = block0:sub(1,8) local itemtype = block1:sub(1,4) + local cardidLsw = block1:sub(9,16) + local cardidMsw = block1:sub(16,24) local cardid = block1:sub(9,24) local traptype = block1:sub(25,28) -- Write dump to files if not DEBUG then local foo = dumplib.SaveAsBinary(bindata, outputTemplate..'_uid_'..uid..'.bin') - print(("Wrote a BIN dump to the file %s"):format(foo)) + print(("Wrote a BIN dump to: %s"):format(foo)) local bar = dumplib.SaveAsText(emldata, outputTemplate..'_uid_'..uid..'.eml') - print(("Wrote a EML dump to the file %s"):format(bar)) + print(("Wrote a EML dump to: %s"):format(bar)) end + local itemtypename = toyNames[itemtype] + if itemtypename == nil then + itemtypename = toyNames[utils.SwapEndiannessStr(itemtype,16)] + end -- Show info print( string.rep('--',20) ) - print( (' ITEM TYPE : 0x%s - %s'):format(itemtype, toyNames[itemtype]) ) + print( (' ITEM TYPE : 0x%s - %s'):format(itemtype, itemtypename) ) print( (' Alter ego / traptype : 0x%s'):format(traptype) ) print( (' UID : 0x%s'):format(uid) ) print( (' CARDID : 0x%s'):format(cardid ) ) diff --git a/client/scripts/tnp3sim.lua b/client/scripts/tnp3sim.lua index adc34cce..1d3dbefd 100644 --- a/client/scripts/tnp3sim.lua +++ b/client/scripts/tnp3sim.lua @@ -27,6 +27,17 @@ Arguments: local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds local DEBUG = true -- the debug flag + + +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift +local byte = string.byte +local char = string.char +local sub = string.sub +local format = string.format + --- -- A debug printout-function function dbg(args) @@ -65,7 +76,6 @@ function ExitMsg(msg) print() end - local function writedumpfile(infile) t = infile:read("*all") len = string.len(t) @@ -187,7 +197,6 @@ local function ValidateCheckSums(blocks) io.write( ('TYPE 3 area 2: %04x = %04x -- %s\n'):format(crc,calc,isOk)) end - local function LoadEmulator(blocks) local HASHCONSTANT = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20' local cmd @@ -219,6 +228,102 @@ local function LoadEmulator(blocks) io.write('\n') end +local function Num2Card(m, l) + + local k = { + 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,0x42, 0x43, 0x44, 0x46, 0x47, 0x48, 0x4A, 0x4B, + 0x4C, 0x4D, 0x4E, 0x50, 0x51, 0x52, 0x53, 0x54,0x56, 0x57, 0x58, 0x59, 0x5A, 0x00 + } + local msw = tonumber(utils.SwapEndiannessStr(m,32),16) + local lsw = tonumber(utils.SwapEndiannessStr(l,32),16) + + if msw > 0x17ea1 then + return "too big" + end + + if msw == 0x17ea1 and lsw > 0x8931fee8 then + return "out of range" + end + + local s = "" + local index + for i = 1,10 do + index, msw, lsw = DivideByK( msw, lsw) + if ( index <= 1 ) then + s = char(k[index]) .. s + else + s = char(k[index-1]) .. s + end + print (index-1, msw, lsw) + end + return s +end +--33LRT-LM9Q9 +--7, 122, 3474858630 +--20, 4, 1008436634 +--7, 0, 627182959 +--17, 0, 21626998 +--16, 0, 745758 +--23, 0, 25715 +--21, 0, 886 +--16, 0, 30 +--1, 0, 1 +--1, 0, 0 + +function DivideByK(msw, lsw) + + local lowLSW + local highLSW + local remainder = 0 + local RADIX = 29 + + --local num = 0 | band( rshift(msw,16), 0xffff) + local num = band( rshift(msw, 16), 0xffff) + + --highLSW = 0 | lshift( (num / RADIX) , 16) + highLSW = lshift( (num / RADIX) , 16) + remainder = num % RADIX + + num = bor( lshift(remainder,16), band(msw, 0xffff)) + + --highLSW |= num / RADIX + highLSW = highLSW or (num / RADIX) + remainder = num % RADIX + + num = bor( lshift(remainder,16), ( band(rshift(lsw,16), 0xffff))) + + --lowLSW = 0 | (num / RADIX) << 16 + lowLSW = 0 or (lshift( (num / RADIX), 16)) + remainder = num % RADIX + + num = bor( lshift(remainder,16) , band(lsw, 0xffff) ) + + lowLSW = bor(lowLSW, (num / RADIX)) + remainder = num % RADIX + return remainder, highLSW, lowLSW + + -- uint num = 0 | (msw >> 16) & 0xffff; + + -- highLSW = 0 | (num / RADIX) << 16; + -- remainder = num % RADIX; + + -- num = (remainder << 16) | (msw & 0xffff); + + -- highLSW |= num / RADIX; + -- remainder = num % RADIX; + + -- num = (remainder << 16) | ((lsw >> 16) & 0xffff); + + -- lowLSW = 0 | (num / RADIX) << 16; + -- remainder = num % RADIX; + + -- num = (remainder << 16) | (lsw & 0xffff); + + -- lowLSW |= num / RADIX; + -- remainder = num % RADIX; + +end + local function main(args) print( string.rep('--',20) ) @@ -278,15 +383,26 @@ local function main(args) print(' Gathering info') local uid = blocks[0]:sub(1,8) local itemtype = blocks[1]:sub(1,4) - local cardid = blocks[1]:sub(9,24) + local cardidLsw = blocks[1]:sub(9,16) + local cardidMsw = blocks[1]:sub(17,24) + local itemtypename = toyNames[itemtype] + if itemtypename == nil then + itemtypename = toyNames[utils.SwapEndiannessStr(itemtype,16)] + end + -- Show info print( string.rep('--',20) ) - print( (' ITEM TYPE : 0x%s - %s'):format(itemtype, toyNames[itemtype]) ) + print( (' ITEM TYPE : 0x%s - %s'):format(itemtype, itemtypename) ) print( (' UID : 0x%s'):format(uid) ) - print( (' CARDID : 0x%s'):format(cardid ) ) + print( (' CARDID : 0x%s %s [%s]'):format( + cardidMsw,cardidLsw, + --Num2Card(cardidMsw, cardidLsw)) + '') + ) print( string.rep('--',20) ) + -- lets do something. -- local experience = blocks[8]:sub(1,6) @@ -351,7 +467,7 @@ local function main(args) err = LoadEmulator(blocks) if err then return oops(err) end core.clearCommandBuffer() - print('The simulation is now prepared.\n --> run \"hf mf sim u '..uid..' x\" <--') + print('The simulation is now prepared.\n --> run \"hf mf sim u '..uid..'\" <--') end end main(args) \ No newline at end of file From 1f918317e2e59decbe862c3e1ad65a930e70ac52 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 5 Apr 2015 21:59:36 -0400 Subject: [PATCH 006/132] add maxErr to data manrawdecode --- client/cmddata.c | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index e2e2ca6d..d4fc997b 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -350,10 +350,11 @@ int Cmdmandecoderaw(const char *Cmd) size_t size=0; size_t maxErr = 20; char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) > 1 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data manrawdecode"); + if (strlen(Cmd) > 5 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: data manrawdecode [maxErr]"); PrintAndLog(" Takes 10 and 01 and converts to 0 and 1 respectively"); PrintAndLog(" --must have binary sequence in demodbuffer (run data askrawdemod first)"); + PrintAndLog(" [maxErr] set number of errors allowed (default = 20)"); PrintAndLog(""); PrintAndLog(" sample: data manrawdecode = decode manchester bitstream from the demodbuffer"); return 0; @@ -366,10 +367,12 @@ int Cmdmandecoderaw(const char *Cmd) else if(DemodBuffer[i]1 || low <0 ){ + if (high>7 || low <0 ){ PrintAndLog("Error: please raw demod the wave first then manchester raw decode"); return 0; } + + sscanf(Cmd, "%i", &maxErr); size=i; errCnt=manrawdecode(BitStream, &size); if (errCnt>=maxErr){ @@ -2172,7 +2175,7 @@ static command_t CommandTable[] = {"askem410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"}, {"askgproxiidemod", CmdG_Prox_II_Demod, 1, "Demodulate a G Prox II tag from GraphBuffer"}, {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"}, - {"biphaserawdecode",CmdBiphaseDecodeRaw,1,"[offset] [invert<0|1>] Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, + {"biphaserawdecode",CmdBiphaseDecodeRaw,1,"[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"}, {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"}, {"dec", CmdDec, 1, "Decimate samples"}, @@ -2191,7 +2194,7 @@ static command_t CommandTable[] = {"load", CmdLoad, 1, " -- Load trace (to graph window"}, {"ltrim", CmdLtrim, 1, " -- Trim samples from left of trace"}, {"rtrim", CmdRtrim, 1, " -- Trim samples from right of trace"}, - {"manrawdecode", Cmdmandecoderaw, 1, "Manchester decode binary stream in DemodBuffer"}, + {"manrawdecode", Cmdmandecoderaw, 1, "[maxErr] -- Manchester decode binary stream in DemodBuffer"}, {"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] -- print the data in the DemodBuffer - 'x' for hex output"}, From 2c772e6cf0f18afa7a91bc4b20443570d697a033 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Mon, 6 Apr 2015 21:47:09 +0200 Subject: [PATCH 007/132] Added info to changelog about bootroom update --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5f3f84ef..7ff77396 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] ### Changed - Iclass read, `hf iclass read` now also reads tag config and prints configuration. (holiman) +- *bootrom* needs to be flashed, due to new address boundaries between os and fpga, after a size optimization (piwi) ### Fixed - Fixed issue #19, problems with LF T55xx commands (marshmellow) From cc15a1187b698d185a42fe956c0b68b9384eafdd Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 6 Apr 2015 23:17:30 -0400 Subject: [PATCH 008/132] lf cleanup - fixes more lf em em4x50read fixes adjust heavy clipping ask clock detection clean up t55xx minor items --- client/cmddata.c | 2 +- client/cmdlfem4x.c | 130 ++++++++++++++++++++-------------------- client/cmdlft55xx.c | 14 ++--- common/lfdemod.c | 142 ++++++++++++++++++++------------------------ common/lfdemod.h | 3 +- 5 files changed, 142 insertions(+), 149 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index d4fc997b..18b59f21 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -2020,7 +2020,7 @@ int CmdLoad(const char *Cmd) int CmdLtrim(const char *Cmd) { int ds = atoi(Cmd); - + if (GraphTraceLen<=0) return 0; for (int i = ds; i < GraphTraceLen; ++i) GraphBuffer[i-ds] = GraphBuffer[i]; GraphTraceLen -= ds; diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index 552c256e..e45c788a 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -27,7 +27,7 @@ static int CmdHelp(const char *Cmd); int CmdEMdemodASK(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); - int findone = (cmdp == '1') ? 1 : 0; + int findone = (cmdp == '1') ? 1 : 0; UsbCommand c={CMD_EM410X_DEMOD}; c.arg[0]=findone; SendCommand(&c); @@ -237,7 +237,7 @@ bool EM_EndParityTest(uint8_t *BitStream, size_t size, uint8_t rows, uint8_t col { if (rows*cols>size) return false; uint8_t colP=0; - //assume last row is a parity row and do not test + //assume last col is a parity and do not test for (uint8_t colNum = 0; colNum < cols-1; colNum++) { for (uint8_t rowNum = 0; rowNum < rows; rowNum++) { colP ^= BitStream[(rowNum*cols)+colNum]; @@ -270,7 +270,7 @@ uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool code = code<<8 | bytebits_to_byte(BitStream+27,8); if (verbose || g_debugMode){ for (uint8_t i = 0; i<5; i++){ - if (i == 4) PrintAndLog(""); + if (i == 4) PrintAndLog(""); //parity byte spacer PrintAndLog("%d%d%d%d%d%d%d%d %d -> 0x%02x", BitStream[i*9], BitStream[i*9+1], @@ -289,7 +289,6 @@ uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool else PrintAndLog("Parity Failed"); } - //PrintAndLog("Code: %08x",code); return code; } /* Read the transmitted data of an EM4x50 tag @@ -311,95 +310,103 @@ uint32_t OutputEM4x50_Block(uint8_t *BitStream, size_t size, bool verbose, bool * is stored in the blocks defined in the control word First and Last * Word Read values. UID is stored in block 32. */ + //completed by Marshmellow int EM4x50Read(const char *Cmd, bool verbose) { - uint8_t fndClk[]={0,8,16,32,40,50,64}; + uint8_t fndClk[] = {8,16,32,40,50,64,128}; int clk = 0; int invert = 0; - sscanf(Cmd, "%i %i", &clk, &invert); int tol = 0; int i, j, startblock, skip, block, start, end, low, high, minClk; - bool complete= false; + bool complete = false; int tmpbuff[MAX_GRAPH_TRACE_LEN / 64]; - save_restoreGB(1); uint32_t Code[6]; char tmp[6]; - char tmp2[20]; - high= low= 0; + high = low = 0; memset(tmpbuff, 0, MAX_GRAPH_TRACE_LEN / 64); - + + // get user entry if any + sscanf(Cmd, "%i %i", &clk, &invert); + + // save GraphBuffer - to restore it later + save_restoreGB(1); + // first get high and low values - for (i = 0; i < GraphTraceLen; i++) - { + for (i = 0; i < GraphTraceLen; i++) { if (GraphBuffer[i] > high) high = GraphBuffer[i]; else if (GraphBuffer[i] < low) low = GraphBuffer[i]; } - // populate a buffer with pulse lengths - i= 0; - j= 0; - minClk= 255; - while (i < GraphTraceLen) - { + i = 0; + j = 0; + minClk = 255; + // get to first full low to prime loop and skip incomplete first pulse + while ((GraphBuffer[i] < high) && (i < GraphTraceLen)) + ++i; + while ((GraphBuffer[i] > low) && (i < GraphTraceLen)) + ++i; + skip = i; + + // populate tmpbuff buffer with pulse lengths + while (i < GraphTraceLen) { // measure from low to low - while ((GraphBuffer[i] > low) && (i low) && (i < GraphTraceLen)) ++i; start= i; - while ((GraphBuffer[i] < high) && (i low) && (i low) && (i < GraphTraceLen)) ++i; if (j>=(MAX_GRAPH_TRACE_LEN/64)) { break; } tmpbuff[j++]= i - start; - if (i-start < minClk) minClk = i-start; + if (i-start < minClk && i < GraphTraceLen) { + minClk = i - start; + } } // set clock - if (!clk){ + if (!clk) { for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) { tol = fndClk[clkCnt]/8; - if (fndClk[clkCnt]-tol >= minClk) { + if (minClk >= fndClk[clkCnt]-tol && minClk <= fndClk[clkCnt]+1) { clk=fndClk[clkCnt]; break; } } + if (!clk) return 0; } else tol = clk/8; // look for data start - should be 2 pairs of LW (pulses of clk*3,clk*2) - start= -1; - skip= 0; - for (i= 0; i < j - 4 ; ++i) - { + start = -1; + for (i= 0; i < j - 4 ; ++i) { skip += tmpbuff[i]; - if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) - if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) - if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) - if (tmpbuff[i+3] >= clk-tol) + if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) //3 clocks + if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) //2 clocks + if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) //3 clocks + if (tmpbuff[i+3] >= clk-tol) //1.5 to 2 clocks - depends on bit following { start= i + 4; break; } } - startblock= i + 4; + startblock = i + 4; // skip over the remainder of LW skip += tmpbuff[i+1] + tmpbuff[i+2] + clk + clk/8; - int phaseoff = tmpbuff[i+3]-clk; // now do it again to find the end end = skip; - for (i += 3; i < j - 4 ; ++i) - { + for (i += 3; i < j - 4 ; ++i) { end += tmpbuff[i]; - if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3 + tol) - if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2 + tol) - if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3 + tol) - if (tmpbuff[i+3] >= clk-tol) + if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) //3 clocks + if (tmpbuff[i+1] >= clk*2-tol && tmpbuff[i+1] <= clk*2+tol) //2 clocks + if (tmpbuff[i+2] >= clk*3-tol && tmpbuff[i+2] <= clk*3+tol) //3 clocks + if (tmpbuff[i+3] >= clk-tol) //1.5 to 2 clocks - depends on bit following { complete= true; break; @@ -409,15 +416,11 @@ int EM4x50Read(const char *Cmd, bool verbose) // report back if (verbose || g_debugMode) { if (start >= 0) { - PrintAndLog("\nNote: should print 45 bits then 0177 (end of block)"); - PrintAndLog(" for each block"); - PrintAndLog(" Also, sometimes the demod gets out of sync and "); - PrintAndLog(" inverts the output - when this happens the 0177"); - PrintAndLog(" will be 3 extra 1's at the end"); - PrintAndLog(" 'data askedge' command may fix that"); + PrintAndLog("\nNote: one block = 50 bits (32 data, 12 parity, 6 marker)"); } else { - PrintAndLog("No data found!"); + PrintAndLog("No data found!, clock tried:%d",clk); PrintAndLog("Try again with more samples."); + PrintAndLog(" or after a 'data askedge' command to clean up the read"); return 0; } if (!complete) @@ -427,24 +430,22 @@ int EM4x50Read(const char *Cmd, bool verbose) PrintAndLog("Try again with more samples."); } } else if (start < 0) return 0; - start=skip; + start = skip; snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk*47); // get rid of leading crap - snprintf(tmp, sizeof(tmp),"%i",skip); + snprintf(tmp, sizeof(tmp), "%i", skip); CmdLtrim(tmp); bool pTest; - bool AllPTest=true; + bool AllPTest = true; // now work through remaining buffer printing out data blocks block = 0; i = startblock; - while (block < 6) - { + while (block < 6) { if (verbose || g_debugMode) PrintAndLog("\nBlock %i:", block); skip = phaseoff; // look for LW before start of next block - for ( ; i < j - 4 ; ++i) - { + for ( ; i < j - 4 ; ++i) { skip += tmpbuff[i]; if (tmpbuff[i] >= clk*3-tol && tmpbuff[i] <= clk*3+tol) if (tmpbuff[i+1] >= clk-tol) @@ -453,7 +454,10 @@ int EM4x50Read(const char *Cmd, bool verbose) skip += clk; phaseoff = tmpbuff[i+1]-clk; i += 2; - if (ASKmanDemod(tmp2, false, false)<1) return 0; + if (ASKmanDemod(tmp2, false, false) < 1) { + save_restoreGB(0); + return 0; + } //set DemodBufferLen to just one block DemodBufferLen = skip/clk; //test parities @@ -461,26 +465,26 @@ int EM4x50Read(const char *Cmd, bool verbose) pTest &= EM_EndParityTest(DemodBuffer,DemodBufferLen,5,9,0); AllPTest &= pTest; //get output - Code[block]=OutputEM4x50_Block(DemodBuffer,DemodBufferLen,verbose, pTest); - if (g_debugMode) PrintAndLog("\nskipping %d samples, bits:%d",start, skip/clk); + Code[block] = OutputEM4x50_Block(DemodBuffer,DemodBufferLen,verbose, pTest); + if (g_debugMode) PrintAndLog("\nskipping %d samples, bits:%d", skip, skip/clk); //skip to start of next block snprintf(tmp,sizeof(tmp),"%i",skip); CmdLtrim(tmp); block++; - if (i>=end) break; //in case chip doesn't output 6 blocks + if (i >= end) break; //in case chip doesn't output 6 blocks } //print full code: if (verbose || g_debugMode || AllPTest){ - PrintAndLog("Found data at sample: %i - using clock: %i",skip,clk); - //PrintAndLog("\nSummary:"); - end=block; - for (block=0; block= high && waveHigh){ smplCnt++; @@ -360,7 +359,7 @@ int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max lastBit = start - *clk; for (i = start; i < *size; ++i) { - if (i - lastBit > *clk){ + if (i - lastBit == *clk){ if (BinStream[i] >= high) { BinStream[bitnum++] = *invert; } else if (BinStream[i] <= low) { @@ -373,13 +372,12 @@ int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max } midBit = 0; lastBit += *clk; - } else if (i-lastBit > (*clk/2) && midBit == 0){ + } else if (i-lastBit == (*clk/2) && midBit == 0){ if (BinStream[i] >= high) { BinStream[bitnum++] = *invert; } else if (BinStream[i] <= low) { BinStream[bitnum++] = *invert ^ 1; } else { - BinStream[bitnum] = BinStream[bitnum-1]; bitnum++; } @@ -687,11 +685,11 @@ int PyramiddemodFSK(uint8_t *dest, size_t *size) } -uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, int high, int low) +uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low) { uint16_t allPeaks=1; uint16_t cntPeaks=0; - size_t loopEnd = 572; + size_t loopEnd = 512+60; if (loopEnd > size) loopEnd = size; for (size_t i=60; ilow && dest[i]128) { - if (!high){ - high=1; - if (cnt > highCnt){ - if (highCnt != 0) highCnt2 = highCnt; - highCnt = cnt; - } else if (cnt > highCnt2) { - highCnt2 = cnt; - } - cnt=1; - } else { - cnt++; - } - } else if (dest[idx] <= 128){ - if (high) { - high=0; - if (cnt > highCnt) { - if (highCnt != 0) highCnt2 = highCnt; - highCnt = cnt; - } else if (cnt > highCnt2) { - highCnt2 = cnt; - } - cnt=1; - } else { - cnt++; - } - } + uint8_t fndClk[] = {8,16,32,40,50,64,128}; + size_t startwave; + size_t i = 0; + size_t minClk = 255; + // get to first full low to prime loop and skip incomplete first pulse + while ((dest[i] < high) && (i < size)) + ++i; + while ((dest[i] > low) && (i < size)) + ++i; + + // loop through all samples + while (i < size) { + // measure from low to low + while ((dest[i] > low) && (i < size)) + ++i; + startwave= i; + while ((dest[i] < high) && (i < size)) + ++i; + while ((dest[i] > low) && (i < size)) + ++i; + //get minimum measured distance + if (i-startwave < minClk && i < size) + minClk = i - startwave; } - uint8_t tol; - for (idx=8; idx>0; idx--){ - tol = clk[idx]/8; - if (clk[idx] >= highCnt - tol && clk[idx] <= highCnt + tol) - return clk[idx]; - if (clk[idx] >= highCnt2 - tol && clk[idx] <= highCnt2 + tol) - return clk[idx]; + // set clock + for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) { + if (minClk >= fndClk[clkCnt]-(fndClk[clkCnt]/8) && minClk <= fndClk[clkCnt]+1) + return fndClk[clkCnt]; } - return -1; + return 0; } // by marshmellow @@ -763,15 +747,15 @@ int DetectStrongAskClock(uint8_t dest[], size_t size) int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) { size_t i=1; - uint8_t clk[]={255,8,16,32,40,50,64,100,128,255}; + uint8_t clk[] = {255,8,16,32,40,50,64,100,128,255}; + uint8_t clkEnd = 9; uint8_t loopCnt = 255; //don't need to loop through entire array... - if (size==0) return -1; - if (size <= loopCnt) loopCnt = size-1; //not enough samples + if (size <= loopCnt) return -1; //not enough samples //if we already have a valid clock uint8_t clockFnd=0; - for (;i<9;++i) - if (clk[i] == *clock) clockFnd=i; + for (;i1; i--){ - if (clk[i] == ans) { - *clock = ans; - //clockFnd = i; - return 0; // for strong waves i don't use the 'best start position' yet... - //break; //clock found but continue to find best startpos [not yet] + if (!clockFnd){ + if (DetectCleanAskWave(dest, size, peak, low)==1){ + int ans = DetectStrongAskClock(dest, size, peak, low); + for (i=clkEnd-1; i>0; i--){ + if (clk[i] == ans) { + *clock = ans; + //clockFnd = i; + return 0; // for strong waves i don't use the 'best start position' yet... + //break; //clock found but continue to find best startpos [not yet] + } } } } + uint8_t ii; uint8_t clkCnt, tol = 0; uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000}; uint8_t bestStart[]={0,0,0,0,0,0,0,0,0}; size_t errCnt = 0; size_t arrLoc, loopEnd; - //test each valid clock from smallest to greatest to see which lines up - uint8_t clkEnd=9; - if (clockFnd>0) clkEnd=clockFnd+1; - else clockFnd=1; - for(clkCnt=clockFnd; clkCnt < clkEnd; clkCnt++){ + if (clockFnd>0) { + clkCnt = clockFnd; + clkEnd = clockFnd+1; + } + else clkCnt=1; + + //test each valid clock from smallest to greatest to see which lines up + for(; clkCnt < clkEnd; clkCnt++){ if (clk[clkCnt] == 32){ tol=1; }else{ tol=0; } //if no errors allowed - keep start within the first clock - if (!maxErr && size > clk[clkCnt]*3 + tol) loopCnt=clk[clkCnt]*2; + if (!maxErr && size > clk[clkCnt]*2 + tol && clk[clkCnt]<128) loopCnt=clk[clkCnt]*2; bestErr[clkCnt]=1000; //try lining up the peaks by moving starting point (try first few clocks) - for (ii=0; ii < loopCnt-clk[clkCnt]; ii++){ + for (ii=0; ii < loopCnt; ii++){ if (dest[ii] < peak && dest[ii] > low) continue; errCnt=0; @@ -826,11 +816,11 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) errCnt++; } } - //if we found no errors then we can stop here + //if we found no errors then we can stop here and a low clock (common clocks) // this is correct one - return this clock //PrintAndLog("DEBUG: clk %d, err %d, ii %d, i %d",clk[clkCnt],errCnt,ii,i); - if(errCnt==0 && clkCnt<6) { - *clock = clk[clkCnt]; + if(errCnt==0 && clkCnt<7) { + if (!clockFnd) *clock = clk[clkCnt]; return ii; } //if we found errors see if it is lowest so far and save it as best run @@ -840,9 +830,9 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) } } } - uint8_t iii=0; + uint8_t iii; uint8_t best=0; - for (iii=0; iii<8; ++iii){ + for (iii=1; iii maxErr) return -1; - *clock = clk[best]; + if (!clockFnd) *clock = clk[best]; return bestStart[best]; } diff --git a/common/lfdemod.h b/common/lfdemod.h index 15121cbf..0a4ceed9 100644 --- a/common/lfdemod.h +++ b/common/lfdemod.h @@ -16,7 +16,8 @@ #include int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr); -uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, int high, int low); +uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low); +int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low); int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr); uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo); int ManchesterEncode(uint8_t *BitStream, size_t size); From 49bbc60af37da26b73c71f4ff774841fc2290b72 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 7 Apr 2015 00:53:06 -0400 Subject: [PATCH 009/132] lf cleaning++ data askedgedetect - removed unneeded code lf em em4x50read bug fix / error checking graph-save/restore auto repaint after restore. --- client/cmddata.c | 17 ++++------------- client/cmdlfem4x.c | 31 +++++++++++++++++++------------ client/graph.c | 3 ++- 3 files changed, 25 insertions(+), 26 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 18b59f21..d838abd1 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -850,23 +850,14 @@ int CmdAskEdgeDetect(const char *Cmd) int thresLen = 25; sscanf(Cmd, "%i", &thresLen); int shift = 127; - int shiftedVal=0; + for(int i = 1; i=thresLen) //large jump up - shift=127; + GraphBuffer[i-1] = 127; else if(GraphBuffer[i]-GraphBuffer[i-1]<=-1*thresLen) //large jump down - shift=-127; - - shiftedVal=GraphBuffer[i]+shift; - - if (shiftedVal>127) - shiftedVal=127; - else if (shiftedVal<-127) - shiftedVal=-127; - GraphBuffer[i-1] = shiftedVal; + GraphBuffer[i-1] = -127; } RepaintGraphWindow(); - //CmdNorm(""); return 0; } @@ -2171,7 +2162,7 @@ int CmdZerocrossings(const char *Cmd) static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"askedgedetect", CmdAskEdgeDetect, 1, "[threshold] Adjust Graph for manual ask demod using length of sample differences to detect the edge of a wave (default = 25)"}, + {"askedgedetect", CmdAskEdgeDetect, 1, "[threshold] Adjust Graph for manual ask demod using the length of sample differences to detect the edge of a wave (use 20-45, def:25)"}, {"askem410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"}, {"askgproxiidemod", CmdG_Prox_II_Demod, 1, "Demodulate a G Prox II tag from GraphBuffer"}, {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"}, diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index e45c788a..909045d3 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -323,6 +323,7 @@ int EM4x50Read(const char *Cmd, bool verbose) uint32_t Code[6]; char tmp[6]; char tmp2[20]; + int phaseoff; high = low = 0; memset(tmpbuff, 0, MAX_GRAPH_TRACE_LEN / 64); @@ -396,9 +397,11 @@ int EM4x50Read(const char *Cmd, bool verbose) startblock = i + 4; // skip over the remainder of LW - skip += tmpbuff[i+1] + tmpbuff[i+2] + clk + clk/8; - int phaseoff = tmpbuff[i+3]-clk; - + skip += tmpbuff[i+1] + tmpbuff[i+2] + 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) { @@ -423,12 +426,6 @@ int EM4x50Read(const char *Cmd, bool verbose) PrintAndLog(" or after a 'data askedge' command to clean up the read"); return 0; } - if (!complete) - { - PrintAndLog("*** Warning!"); - PrintAndLog("Partial data - no end found!"); - PrintAndLog("Try again with more samples."); - } } else if (start < 0) return 0; start = skip; snprintf(tmp2, sizeof(tmp2),"%d %d 1000 %d", clk, invert, clk*47); @@ -451,8 +448,12 @@ int EM4x50Read(const char *Cmd, bool verbose) if (tmpbuff[i+1] >= clk-tol) break; } + if (i >= j-4) break; //next LW not found skip += clk; - phaseoff = tmpbuff[i+1]-clk; + if (tmpbuff[i+1]>clk) + phaseoff = tmpbuff[i+1]-clk; + else + phaseoff = 0; i += 2; if (ASKmanDemod(tmp2, false, false) < 1) { save_restoreGB(0); @@ -475,16 +476,22 @@ int EM4x50Read(const char *Cmd, bool verbose) } //print full code: if (verbose || g_debugMode || AllPTest){ + if (!complete) { + PrintAndLog("*** Warning!"); + PrintAndLog("Partial data - no end found!"); + PrintAndLog("Try again with more samples."); + } PrintAndLog("Found data at sample: %i - using clock: %i", start, clk); end = block; for (block=0; block < end; block++){ PrintAndLog("Block %d: %08x",block,Code[block]); } - if (AllPTest) + if (AllPTest) { PrintAndLog("Parities Passed"); - else + } else { PrintAndLog("Parities Failed"); PrintAndLog("Try cleaning the read samples with 'data askedge'"); + } } //restore GraphBuffer diff --git a/client/graph.c b/client/graph.c index 089119d9..3bea7881 100644 --- a/client/graph.c +++ b/client/graph.c @@ -56,9 +56,10 @@ void save_restoreGB(uint8_t saveOpt) memcpy(SavedGB, GraphBuffer, sizeof(GraphBuffer)); SavedGBlen = GraphTraceLen; GB_Saved=true; - } else if (GB_Saved){ + } else if (GB_Saved){ //restore memcpy(GraphBuffer, SavedGB, sizeof(GraphBuffer)); GraphTraceLen = SavedGBlen; + RepaintGraphWindow(); } return; } From fef74fdce43605f1710319b2b6e45969a5c62835 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 8 Apr 2015 01:07:39 -0400 Subject: [PATCH 010/132] lf ask consolidation backend: askman and askraw demods merged into askdemod (args adjusted accordingly) re-arranged lfdemod.h in alphabetical order and by category front end: data detectclock a (ask) now also reports the selected best start position for demod data manrawdecode takes an invert arg now --- armsrc/lfops.c | 2 +- client/cmddata.c | 236 +++++++++++++++++------------------------ client/cmddata.h | 6 +- client/cmdlf.c | 2 +- client/cmdlfem4x.c | 4 +- client/cmdlft55xx.c | 108 ++++++++++--------- client/graph.c | 4 +- common/lfdemod.c | 252 ++++++++++++++++++-------------------------- common/lfdemod.h | 50 ++++----- 9 files changed, 289 insertions(+), 375 deletions(-) diff --git a/armsrc/lfops.c b/armsrc/lfops.c index e5a40b2e..e45b55fc 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -861,7 +861,7 @@ void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol) size = BigBuf_max_traceLen(); //askdemod and manchester decode if (size > 16385) size = 16385; //big enough to catch 2 sequences of largest format - errCnt = askmandemod(dest, &size, &clk, &invert, maxErr); + errCnt = askdemod(dest, &size, &clk, &invert, maxErr, 0, 1); WDT_HIT(); if (errCnt<0) continue; diff --git a/client/cmddata.c b/client/cmddata.c index d838abd1..a8c809cf 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -208,22 +208,34 @@ void printEM410x(uint32_t hi, uint64_t id) return; } - -int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo) +int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) { - int ans = ASKmanDemod(Cmd, FALSE, FALSE); - if (!ans) return 0; - - size_t idx=0; - if (Em410xDecode(DemodBuffer,(size_t *) &DemodBufferLen, &idx, hi, lo)){ + size_t idx = 0; + size_t BitLen = DemodBufferLen; + uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; + memcpy(BitStream, DemodBuffer, BitLen); + if (Em410xDecode(BitStream, &BitLen, &idx, hi, lo)){ + //set GraphBuffer for clone or sim command + setDemodBuf(BitStream, BitLen, idx); if (g_debugMode){ - PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, DemodBufferLen); + PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen); printDemodBuff(); } + if (verbose){ + PrintAndLog("EM410x pattern found: "); + printEM410x(*hi, *lo); + } return 1; } return 0; } + +int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose) +{ + if (!ASKDemod(Cmd, FALSE, FALSE, 1)) return 0; + return AskEm410xDecode(verbose, hi, lo); +} + //by marshmellow //takes 3 arguments - clock, invert and maxErr as integers //attempts to demodulate ask while decoding manchester @@ -244,28 +256,28 @@ int CmdAskEM410xDemod(const char *Cmd) PrintAndLog(" : data askem410xdemod 64 1 0 = demod an EM410x Tag ID from GraphBuffer using a clock of RF/64 and inverting data and allowing 0 demod errors"); return 0; } - uint32_t hi = 0; uint64_t lo = 0; - if (AskEm410xDemod(Cmd, &hi, &lo)) { - PrintAndLog("EM410x pattern found: "); - printEM410x(hi, lo); - return 1; - } - return 0; + uint32_t hi = 0; + return AskEm410xDemod(Cmd, &hi, &lo, true); } -int ASKmanDemod(const char *Cmd, bool verbose, bool emSearch) +//by marshmellow +//Cmd Args: Clock, invert, maxErr, maxLen as integers and amplify as char == 'a' +// (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 +int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) { int invert=0; int clk=0; int maxErr=100; - int maxLen=512*64; - //param_getdec(Cmd, 0, &clk); - //param_getdec(Cmd, 1, &invert); - //maxErr = param_get32ex(Cmd, 2, 0xFFFFFFFF, 10); - //if (maxErr == 0xFFFFFFFF) maxErr=100; + int maxLen=0; + uint8_t askAmp = 0; + char amp = param_getchar(Cmd, 0); uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - sscanf(Cmd, "%i %i %i %i", &clk, &invert, &maxErr, &maxLen); + sscanf(Cmd, "%i %i %i %i %c", &clk, &invert, &maxErr, &maxLen, &); + if (!maxLen) maxLen = 512*64; if (invert != 0 && invert != 1) { PrintAndLog("Invalid argument: %s", Cmd); return 0; @@ -274,12 +286,14 @@ int ASKmanDemod(const char *Cmd, bool verbose, bool emSearch) invert=1; clk=0; } + if (amp == 'a' || amp == 'A') askAmp=1; size_t BitLen = getFromGraphBuf(BitStream); if (g_debugMode) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen); - if (!BitLen) return 0; + if (BitLen<255) return 0; if (maxLen0){ - if (verbose || g_debugMode) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); - } - if (verbose || g_debugMode) PrintAndLog("ASK/Manchester decoded bitstream:"); - // Now output the bitstream to the scrollback by line of 16 bits setDemodBuf(BitStream,BitLen,0); - if (verbose || g_debugMode) printDemodBuff(); - uint64_t lo =0; - uint32_t hi =0; - size_t idx=0; + if (verbose || g_debugMode){ + if (errCnt>0) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); + if (askType) PrintAndLog("ASK/Manchester decoded bitstream:"); + else PrintAndLog("ASK/Raw decoded bitstream:"); + // Now output the bitstream to the scrollback by line of 16 bits + printDemodBuff(); + + } + uint64_t lo = 0; + uint32_t hi = 0; if (emSearch){ - if (Em410xDecode(BitStream, &BitLen, &idx, &hi, &lo)){ - //set GraphBuffer for clone or sim command - setDemodBuf(BitStream, BitLen, idx); - if (g_debugMode){ - PrintAndLog("DEBUG: idx: %d, Len: %d, Printing Demod Buffer:", idx, BitLen); - printDemodBuff(); - } - if (verbose) PrintAndLog("EM410x pattern found: "); - if (verbose) printEM410x(hi, lo); - return 1; - } + AskEm410xDecode(true, &hi, &lo); } return 1; } //by marshmellow -//takes 3 arguments - clock, invert, maxErr as integers +//takes 5 arguments - clock, invert, maxErr, maxLen as integers and amplify as char == 'a' //attempts to demodulate ask while decoding manchester //prints binary found and saves in graphbuffer for further commands int Cmdaskmandemod(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) > 20 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data rawdemod am [clock] <0|1> [maxError] [setSmplLen]"); - PrintAndLog(" [set clock as integer] optional, if not set, autodetect."); - PrintAndLog(" , 1 for invert output"); - PrintAndLog(" [set maximum allowed errors], default = 100."); - PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)."); + if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: data rawdemod am [clock] [maxError] [maxLen] [amplify]"); + PrintAndLog(" [set clock as integer] optional, if not set, autodetect"); + PrintAndLog(" , 1 to invert output"); + PrintAndLog(" [set maximum allowed errors], default = 100"); + PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)"); + PrintAndLog(" , 'a' to attempt demod with ask amplification, default = no amp"); PrintAndLog(""); PrintAndLog(" sample: data rawdemod am = demod an ask/manchester tag from GraphBuffer"); PrintAndLog(" : data rawdemod am 32 = demod an ask/manchester tag from GraphBuffer using a clock of RF/32"); @@ -337,7 +343,7 @@ int Cmdaskmandemod(const char *Cmd) PrintAndLog(" : data rawdemod am 64 1 0 = demod an ask/manchester tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); return 0; } - return ASKmanDemod(Cmd, TRUE, TRUE); + return ASKDemod(Cmd, TRUE, TRUE, 1); } //by marshmellow @@ -348,12 +354,14 @@ int Cmdmandecoderaw(const char *Cmd) int i =0; int errCnt=0; size_t size=0; + int invert=0; size_t maxErr = 20; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 5 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data manrawdecode [maxErr]"); + PrintAndLog("Usage: data manrawdecode [invert] [maxErr]"); PrintAndLog(" Takes 10 and 01 and converts to 0 and 1 respectively"); PrintAndLog(" --must have binary sequence in demodbuffer (run data askrawdemod first)"); + PrintAndLog(" [invert] invert output"); PrintAndLog(" [maxErr] set number of errors allowed (default = 20)"); PrintAndLog(""); PrintAndLog(" sample: data manrawdecode = decode manchester bitstream from the demodbuffer"); @@ -372,9 +380,9 @@ int Cmdmandecoderaw(const char *Cmd) return 0; } - sscanf(Cmd, "%i", &maxErr); + sscanf(Cmd, "%i %i", &invert, &maxErr); size=i; - errCnt=manrawdecode(BitStream, &size); + errCnt=manrawdecode(BitStream, &size, invert); if (errCnt>=maxErr){ PrintAndLog("Too many errors: %d",errCnt); return 0; @@ -448,59 +456,6 @@ int CmdBiphaseDecodeRaw(const char *Cmd) return 1; } -//by marshmellow -//takes 4 arguments - clock, invert, maxErr as integers and amplify as char -//attempts to demodulate ask only -//prints binary found and saves in graphbuffer for further commands -int ASKrawDemod(const char *Cmd, bool verbose) -{ - int invert=0; - int clk=0; - int maxErr=100; - uint8_t askAmp = 0; - char amp = param_getchar(Cmd, 0); - uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; - sscanf(Cmd, "%i %i %i %c", &clk, &invert, &maxErr, &); - if (invert != 0 && invert != 1) { - if (verbose || g_debugMode) PrintAndLog("Invalid argument: %s", Cmd); - return 0; - } - if (clk==1){ - invert=1; - clk=0; - } - if (amp == 'a' || amp == 'A') askAmp=1; - size_t BitLen = getFromGraphBuf(BitStream); - if (BitLen==0) return 0; - int errCnt = askrawdemod(BitStream, &BitLen, &clk, &invert, maxErr, askAmp); - if (errCnt==-1||BitLen<16){ //throw away static - allow 1 and -1 (in case of threshold command first) - if (verbose || g_debugMode) PrintAndLog("no data found"); - if (g_debugMode) PrintAndLog("errCnt: %d, BitLen: %d, clk: %d, invert: %d", errCnt, BitLen, clk, invert); - return 0; - } - if (errCnt>maxErr) { - if (g_debugMode) - PrintAndLog("Too many errors found, errCnt: %d, BitLen: %d, clk: %d, invert: %d", errCnt, BitLen, clk, invert); - return 0; - } - if (verbose || g_debugMode) - PrintAndLog("Using Clock: %d - invert: %d - Bits Found: %d", clk, invert, BitLen); - - //move BitStream back to DemodBuffer - setDemodBuf(BitStream,BitLen,0); - - //output - if (errCnt>0 && (verbose || g_debugMode)){ - PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d", errCnt); - } - if (verbose || g_debugMode){ - PrintAndLog("ASK demoded bitstream:"); - // Now output the bitstream to the scrollback by line of 16 bits - printDemodBuff(); - } - return 1; -} - //by marshmellow // - ASK Demod then Biphase decode GraphBuffer samples int ASKbiphaseDemod(const char *Cmd, bool verbose) @@ -509,11 +464,11 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) int offset=0, clk=0, invert=0, maxErr=0, ans=0; ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); if (ans>0) - ans = ASKrawDemod(Cmd+1, FALSE); + ans = ASKDemod(Cmd+1, FALSE, FALSE, 0); else - ans = ASKrawDemod(Cmd, FALSE); + ans = ASKDemod(Cmd, FALSE, FALSE, 0); if (!ans) { - if (g_debugMode || verbose) PrintAndLog("Error AskrawDemod: %d", ans); + if (g_debugMode || verbose) PrintAndLog("Error AskDemod: %d", ans); return 0; } @@ -521,8 +476,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) size_t size = DemodBufferLen; uint8_t BitStream[MAX_DEMOD_BUF_LEN]; memcpy(BitStream, DemodBuffer, DemodBufferLen); - - int errCnt = BiphaseRawDecode(BitStream, &size, offset, invert); + int errCnt = BiphaseRawDecode(BitStream, &size, offset, 0); if (errCnt < 0){ if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode: %d", errCnt); return 0; @@ -543,12 +497,13 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) int Cmdaskbiphdemod(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) > 12 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data rawdemod ab [offset] [clock] [maxError] "); + if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: data rawdemod ab [offset] [clock] [maxError] [maxLen] "); PrintAndLog(" [offset], offset to begin biphase, default=0"); PrintAndLog(" [set clock as integer] optional, if not set, autodetect"); PrintAndLog(" , 1 to invert output"); PrintAndLog(" [set maximum allowed errors], default = 100"); + PrintAndLog(" [set maximum Samples to read], default = 32768 (512 bits at rf/64)"); PrintAndLog(" , 'a' to attempt demod with ask amplification, default = no amp"); PrintAndLog(" NOTE: can be entered as second or third argument"); PrintAndLog(" NOTE: can be entered as first, second or last argument"); @@ -556,13 +511,13 @@ int Cmdaskbiphdemod(const char *Cmd) PrintAndLog(""); PrintAndLog(" NOTE: --invert for Conditional Dephase Encoding (CDP) AKA Differential Manchester"); PrintAndLog(""); - PrintAndLog(" sample: data rawdemod ab = demod an ask/biph tag from GraphBuffer"); - PrintAndLog(" : data rawdemod ab a = demod an ask/biph tag from GraphBuffer, amplified"); - PrintAndLog(" : data rawdemod ab 1 32 = demod an ask/biph tag from GraphBuffer using an offset of 1 and a clock of RF/32"); - PrintAndLog(" : data rawdemod ab 0 32 1 = demod an ask/biph tag from GraphBuffer using a clock of RF/32 and inverting data"); - PrintAndLog(" : data rawdemod ab 0 1 = demod an ask/biph tag from GraphBuffer while inverting data"); - PrintAndLog(" : data rawdemod ab 0 64 1 0 = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); - PrintAndLog(" : data rawdemod ab 0 64 1 0 a = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp"); + PrintAndLog(" sample: data rawdemod ab = demod an ask/biph tag from GraphBuffer"); + PrintAndLog(" : data rawdemod ab 0 a = demod an ask/biph tag from GraphBuffer, amplified"); + PrintAndLog(" : data rawdemod ab 1 32 = demod an ask/biph tag from GraphBuffer using an offset of 1 and a clock of RF/32"); + PrintAndLog(" : data rawdemod ab 0 32 1 = demod an ask/biph tag from GraphBuffer using a clock of RF/32 and inverting data"); + PrintAndLog(" : data rawdemod ab 0 1 = demod an ask/biph tag from GraphBuffer while inverting data"); + PrintAndLog(" : data rawdemod ab 0 64 1 0 = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); + PrintAndLog(" : data rawdemod ab 0 64 1 0 0 a = demod an ask/biph tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp"); return 0; } return ASKbiphaseDemod(Cmd, TRUE); @@ -646,27 +601,28 @@ int CmdG_Prox_II_Demod(const char *Cmd) return 1; } -//by marshmellow - see ASKrawDemod +//by marshmellow - see ASKDemod int Cmdaskrawdemod(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) > 12 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data rawdemod ar [clock] [maxError] [amplify]"); + if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: data rawdemod ar [clock] [maxError] [maxLen] [amplify]"); PrintAndLog(" [set clock as integer] optional, if not set, autodetect"); PrintAndLog(" , 1 to invert output"); PrintAndLog(" [set maximum allowed errors], default = 100"); + PrintAndLog(" [set maximum Samples to read], default = 32768 (1024 bits at rf/64)"); PrintAndLog(" , 'a' to attempt demod with ask amplification, default = no amp"); PrintAndLog(""); - PrintAndLog(" sample: data rawdemod ar = demod an ask tag from GraphBuffer"); - PrintAndLog(" : data rawdemod ar a = demod an ask tag from GraphBuffer, amplified"); - PrintAndLog(" : data rawdemod ar 32 = demod an ask tag from GraphBuffer using a clock of RF/32"); - PrintAndLog(" : data rawdemod ar 32 1 = demod an ask tag from GraphBuffer using a clock of RF/32 and inverting data"); - PrintAndLog(" : data rawdemod ar 1 = demod an ask tag from GraphBuffer while inverting data"); - PrintAndLog(" : data rawdemod ar 64 1 0 = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); - PrintAndLog(" : data rawdemod ar 64 1 0 a = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp"); + PrintAndLog(" sample: data rawdemod ar = demod an ask tag from GraphBuffer"); + PrintAndLog(" : data rawdemod ar a = demod an ask tag from GraphBuffer, amplified"); + PrintAndLog(" : data rawdemod ar 32 = demod an ask tag from GraphBuffer using a clock of RF/32"); + PrintAndLog(" : data rawdemod ar 32 1 = demod an ask tag from GraphBuffer using a clock of RF/32 and inverting data"); + PrintAndLog(" : data rawdemod ar 1 = demod an ask tag from GraphBuffer while inverting data"); + PrintAndLog(" : data rawdemod ar 64 1 0 = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); + PrintAndLog(" : data rawdemod ar 64 1 0 0 a = demod an ask tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors, and amp"); return 0; } - return ASKrawDemod(Cmd, TRUE); + return ASKDemod(Cmd, TRUE, FALSE, 0); } int AutoCorrelate(int window, bool SaveGrph, bool verbose) @@ -849,7 +805,6 @@ int CmdAskEdgeDetect(const char *Cmd) { int thresLen = 25; sscanf(Cmd, "%i", &thresLen); - int shift = 127; for(int i = 1; i=thresLen) //large jump up @@ -867,9 +822,10 @@ int CmdAskEdgeDetect(const char *Cmd) int CmdDetectClockRate(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) > 3 || strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data detectclock [modulation]"); + if (strlen(Cmd) > 6 || strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: data detectclock [modulation] "); PrintAndLog(" [modulation as char], specify the modulation type you want to detect the clock of"); + PrintAndLog(" , specify the clock (optional - to get best start position only)"); PrintAndLog(" 'a' = ask, 'f' = fsk, 'n' = nrz/direct, 'p' = psk"); PrintAndLog(""); PrintAndLog(" sample: data detectclock a = detect the clock of an ask modulated wave in the GraphBuffer"); @@ -879,7 +835,7 @@ int CmdDetectClockRate(const char *Cmd) } int ans=0; if (cmdp == 'a'){ - ans = GetAskClock("", true, false); + ans = GetAskClock(Cmd+1, true, false); } else if (cmdp == 'f'){ ans = GetFskClock("", true, false); } else if (cmdp == 'n'){ @@ -2166,7 +2122,7 @@ static command_t CommandTable[] = {"askem410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"}, {"askgproxiidemod", CmdG_Prox_II_Demod, 1, "Demodulate a G Prox II tag from GraphBuffer"}, {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"}, - {"biphaserawdecode",CmdBiphaseDecodeRaw,1,"[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, + {"biphaserawdecode",CmdBiphaseDecodeRaw,1, "[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"}, {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"}, {"dec", CmdDec, 1, "Decimate samples"}, @@ -2185,7 +2141,7 @@ static command_t CommandTable[] = {"load", CmdLoad, 1, " -- Load trace (to graph window"}, {"ltrim", CmdLtrim, 1, " -- Trim samples from left of trace"}, {"rtrim", CmdRtrim, 1, " -- Trim samples from right of trace"}, - {"manrawdecode", Cmdmandecoderaw, 1, "[maxErr] -- Manchester decode binary stream in DemodBuffer"}, + {"manrawdecode", Cmdmandecoderaw, 1, "[invert] [maxErr] -- Manchester decode binary stream in DemodBuffer"}, {"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] -- print the data in the DemodBuffer - 'x' for hex output"}, diff --git a/client/cmddata.h b/client/cmddata.h index 0d2e32d6..9e179b9c 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -56,10 +56,10 @@ int CmdScale(const char *Cmd); int CmdDirectionalThreshold(const char *Cmd); int CmdZerocrossings(const char *Cmd); int CmdIndalaDecode(const char *Cmd); -int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo); +int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ); +int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose); int ASKbiphaseDemod(const char *Cmd, bool verbose); -int ASKmanDemod(const char *Cmd, bool verbose, bool emSearch); -int ASKrawDemod(const char *Cmd, bool verbose); +int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType); int FSKrawDemod(const char *Cmd, bool verbose); int PSKDemod(const char *Cmd, bool verbose); int NRZrawDemod(const char *Cmd, bool verbose); diff --git a/client/cmdlf.c b/client/cmdlf.c index a52e1423..d441574a 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -1091,7 +1091,7 @@ int CmdLFfind(const char *Cmd) return 1; } } - ans=ASKmanDemod("0 0 0",TRUE,FALSE); + ans=ASKDemod("0 0 0",TRUE,FALSE,1); if (ans>0) { PrintAndLog("\nUnknown ASK Modulated and Manchester encoded Tag Found!"); PrintAndLog("\nif it does not look right it could instead be ASK/Biphase - try 'data rawdemod ab'"); diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index 909045d3..614624a6 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -47,7 +47,7 @@ int CmdEM410xRead(const char *Cmd) uint32_t hi=0; uint64_t lo=0; - if(!AskEm410xDemod("", &hi, &lo)) return 0; + if(!AskEm410xDemod("", &hi, &lo, false)) return 0; PrintAndLog("EM410x pattern found: "); printEM410x(hi, lo); if (hi){ @@ -455,7 +455,7 @@ int EM4x50Read(const char *Cmd, bool verbose) else phaseoff = 0; i += 2; - if (ASKmanDemod(tmp2, false, false) < 1) { + if (ASKDemod(tmp2, false, false, 1) < 1) { save_restoreGB(0); return 0; } diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index e0f89153..564ad29d 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -262,11 +262,10 @@ int CmdT55xxReadBlock(const char *Cmd) { bool DecodeT55xxBlock(){ - char buf[10] = {0x00}; + char buf[30] = {0x00}; char *cmdStr = buf; int ans = 0; uint8_t bitRate[8] = {8,16,32,40,50,64,100,128}; - DemodBufferLen = 0x00; //trim 1/2 a clock from beginning @@ -290,7 +289,7 @@ bool DecodeT55xxBlock(){ break; case DEMOD_ASK: snprintf(cmdStr, sizeof(buf),"%d %d 0", bitRate[config.bitrate], config.inverted ); - ans = ASKmanDemod(cmdStr, FALSE, FALSE); + ans = ASKDemod(cmdStr, FALSE, FALSE, 1); break; case DEMOD_PSK1: snprintf(cmdStr, sizeof(buf),"%d %d 0", bitRate[config.bitrate], config.inverted ); @@ -337,72 +336,79 @@ bool tryDetectModulation(){ char cmdStr[8] = {0}; uint8_t hits = 0; t55xx_conf_block_t tests[15]; - + int bitRate=0; if (GetFskClock("", FALSE, FALSE)){ uint8_t fc1 = 0, fc2 = 0, clk=0; fskClocks(&fc1, &fc2, &clk, FALSE); sprintf(cmdStr,"%d", clk/2); CmdLtrim(cmdStr); - if ( FSKrawDemod("0 0", FALSE) && test(DEMOD_FSK, &tests[hits].offset)){ + if ( FSKrawDemod("0 0", FALSE) && test(DEMOD_FSK, &tests[hits].offset, &bitRate)){ tests[hits].modulation = DEMOD_FSK; if (fc1==8 && fc2 == 5) tests[hits].modulation = DEMOD_FSK1a; else if (fc1==10 && fc2 == 8) tests[hits].modulation = DEMOD_FSK2; - + tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( FSKrawDemod("0 1", FALSE) && test(DEMOD_FSK, &tests[hits].offset)) { + if ( FSKrawDemod("0 1", FALSE) && test(DEMOD_FSK, &tests[hits].offset, &bitRate)) { tests[hits].modulation = DEMOD_FSK; - if (fc1==8 && fc2 == 5) + if (fc1 == 8 && fc2 == 5) tests[hits].modulation = DEMOD_FSK1; - else if (fc1==10 && fc2 == 8) + else if (fc1 == 10 && fc2 == 8) tests[hits].modulation = DEMOD_FSK2a; + tests[hits].bitrate = bitRate; tests[hits].inverted = TRUE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } } else { - if ( ASKmanDemod("0 0 1", FALSE, FALSE) && test(DEMOD_ASK, &tests[hits].offset)) { + if ( ASKDemod("0 0 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { tests[hits].modulation = DEMOD_ASK; - tests[hits].inverted = FALSE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( ASKmanDemod("0 1 1", FALSE, FALSE) && test(DEMOD_ASK, &tests[hits].offset)) { - tests[hits].modulation = DEMOD_ASK; - tests[hits].inverted = TRUE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( NRZrawDemod("0 0 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset)) { - tests[hits].modulation = DEMOD_NRZ; + tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( NRZrawDemod("0 1 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset)) { - tests[hits].modulation = DEMOD_NRZ; + if ( ASKDemod("0 1 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_ASK; + tests[hits].bitrate = bitRate; tests[hits].inverted = TRUE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; - } + } - if ( PSKDemod("0 0 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset)) { + if ( NRZrawDemod("0 0 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_NRZ; + tests[hits].bitrate = bitRate; + tests[hits].inverted = FALSE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + + if ( NRZrawDemod("0 1 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_NRZ; + tests[hits].bitrate = bitRate; + tests[hits].inverted = TRUE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + + if ( PSKDemod("0 0 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) { tests[hits].modulation = DEMOD_PSK1; + tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( PSKDemod("0 1 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset)) { + if ( PSKDemod("0 1 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) { tests[hits].modulation = DEMOD_PSK1; + tests[hits].bitrate = bitRate; tests[hits].inverted = TRUE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; @@ -411,8 +417,9 @@ bool tryDetectModulation(){ // PSK2 - needs a call to psk1TOpsk2. if ( PSKDemod("0 0 1", FALSE)) { psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (test(DEMOD_PSK2, &tests[hits].offset)){ + if (test(DEMOD_PSK2, &tests[hits].offset, &bitRate)){ tests[hits].modulation = DEMOD_PSK2; + tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; @@ -422,22 +429,25 @@ bool tryDetectModulation(){ // PSK3 - needs a call to psk1TOpsk2. if ( PSKDemod("0 0 1", FALSE)) { psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (test(DEMOD_PSK3, &tests[hits].offset)){ + if (test(DEMOD_PSK3, &tests[hits].offset, &bitRate)){ tests[hits].modulation = DEMOD_PSK3; + tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } } // inverse waves does not affect this demod - if ( ASKbiphaseDemod("0 0 0 1", FALSE) && test(DEMOD_BI, &tests[hits].offset) ) { + if ( ASKbiphaseDemod("0 0 0 1", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate) ) { tests[hits].modulation = DEMOD_BI; + tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( ASKbiphaseDemod("0 0 1 1", FALSE) && test(DEMOD_BIa, &tests[hits].offset) ) { + if ( ASKbiphaseDemod("0 0 1 1", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate) ) { tests[hits].modulation = DEMOD_BIa; + tests[hits].bitrate = bitRate; tests[hits].inverted = TRUE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; @@ -445,6 +455,7 @@ bool tryDetectModulation(){ } if ( hits == 1) { config.modulation = tests[0].modulation; + config.bitrate = tests[0].bitrate; config.inverted = tests[0].inverted; config.offset = tests[0].offset; config.block0 = tests[0].block0; @@ -504,35 +515,27 @@ bool testBitRate(uint8_t readRate, uint8_t mod){ case DEMOD_FSK2: case DEMOD_FSK2a: detRate = GetFskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; + if (expected[readRate] == detRate) return TRUE; - } break; case DEMOD_ASK: case DEMOD_BI: case DEMOD_BIa: detRate = GetAskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; + if (expected[readRate] == detRate) return TRUE; - } break; case DEMOD_PSK1: case DEMOD_PSK2: case DEMOD_PSK3: detRate = GetPskClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; + if (expected[readRate] == detRate) return TRUE; - } break; case DEMOD_NRZ: detRate = GetNrzClock("",FALSE, FALSE); - if (expected[readRate] == detRate) { - config.bitrate = readRate; + if (expected[readRate] == detRate) return TRUE; - } break; default: return FALSE; @@ -540,9 +543,9 @@ bool testBitRate(uint8_t readRate, uint8_t mod){ return FALSE; } -bool test(uint8_t mode, uint8_t *offset){ +bool test(uint8_t mode, uint8_t *offset, int *fndBitRate){ - if ( !DemodBufferLen) return FALSE; + if ( DemodBufferLen < 64 ) return FALSE; uint8_t si = 0; for (uint8_t idx = 0; idx < 64; idx++){ si = idx; @@ -555,7 +558,8 @@ bool test(uint8_t mode, uint8_t *offset){ if ( resv > 0x00) continue; uint8_t xtRate = PackBits(si, 3, DemodBuffer); si += 3; //extended mode part of rate - uint8_t bitRate = PackBits(si, 3, DemodBuffer); si += 3; //bit rate + int bitRate = PackBits(si, 3, DemodBuffer); si += 3; //bit rate + if (bitRate > 7) continue; 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 pskcr = PackBits(si, 2, DemodBuffer); si += 2+1; //could check psk cr @@ -571,6 +575,7 @@ bool test(uint8_t mode, uint8_t *offset){ //test modulation if (!testModulation(mode, modread)) continue; if (!testBitRate(bitRate, mode)) continue; + *fndBitRate = bitRate; *offset = idx; return TRUE; } @@ -760,10 +765,10 @@ int CmdT55xxInfo(const char *Cmd){ if (strlen(Cmd)==0) AquireData( CONFIGURATION_BLOCK ); - + if (!DecodeT55xxBlock()) return 1; - if ( !DemodBufferLen) return 1; + if ( DemodBufferLen < 32) return 1; uint8_t si = config.offset; uint32_t bl0 = PackBits(si, 32, DemodBuffer); @@ -873,7 +878,8 @@ int AquireData( uint8_t block ){ } char * GetBitRateStr(uint32_t id){ - static char buf[20]; + static char buf[25]; + char *retStr = buf; switch (id){ case 0: diff --git a/client/graph.c b/client/graph.c index 3bea7881..06279848 100644 --- a/client/graph.c +++ b/client/graph.c @@ -143,10 +143,10 @@ int GetAskClock(const char str[], bool printAns, bool verbose) PrintAndLog("Failed to copy from graphbuffer"); return -1; } - DetectASKClock(grph, size, &clock, 20); + int start = DetectASKClock(grph, size, &clock, 20); // Only print this message if we're not looping something if (printAns){ - PrintAndLog("Auto-detected clock rate: %d", clock); + PrintAndLog("Auto-detected clock rate: %d, Best Starting Position: %d", clock, start); } return clock; } diff --git a/common/lfdemod.c b/common/lfdemod.c index 5bbf8a66..7d40d22e 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -112,7 +112,8 @@ uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_ return 0; } -// demodulates strong heavily clipped samples +//by marshmellow +//demodulates strong heavily clipped samples int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int high, int low) { size_t bitCnt=0, smplCnt=0, errCnt=0; @@ -163,52 +164,81 @@ int cleanAskRawDemod(uint8_t *BinStream, size_t *size, int clk, int invert, int } //by marshmellow -//takes 3 arguments - clock, invert, maxErr as integers -//attempts to demodulate ask while decoding manchester -//prints binary found and saves in graphbuffer for further commands -int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr) +void askAmp(uint8_t *BitStream, size_t size) { - size_t i; + for(size_t i = 1; i=30) //large jump up + BitStream[i]=127; + else if(BitStream[i]-BitStream[i-1]<=-20) //large jump down + BitStream[i]=-127; + } + return; +} + +//by marshmellow +//attempts to demodulate ask modulations, askType == 0 for ask/raw, askType==1 for ask/manchester +int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType) +{ + if (*size==0) return -1; int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default if (*clk==0 || start < 0) return -3; - if (*invert != 1) *invert=0; + if (*invert != 1) *invert = 0; + if (amp==1) askAmp(BinStream, *size); + uint8_t initLoopMax = 255; if (initLoopMax > *size) initLoopMax = *size; // Detect high and lows - // 25% fuzz in case highs and lows aren't clipped [marshmellow] + //25% clip in case highs and lows aren't clipped [marshmellow] int high, low; - if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) return -2; //just noise + if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) + return -2; //just noise + size_t errCnt = 0; // if clean clipped waves detected run alternate demod if (DetectCleanAskWave(BinStream, *size, high, low)) { - cleanAskRawDemod(BinStream, size, *clk, *invert, high, low); - return manrawdecode(BinStream, size); + errCnt = cleanAskRawDemod(BinStream, size, *clk, *invert, high, low); + if (askType) //askman + return manrawdecode(BinStream, size, 0); + else //askraw + return errCnt; } - // PrintAndLog("DEBUG - valid high: %d - valid low: %d",high,low); - int lastBit; //set first clock check - uint16_t bitnum = 0; //output counter + int lastBit; //set first clock check - can go negative + size_t i, bitnum = 0; //output counter + uint8_t midBit = 0; uint8_t tol = 0; //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave - if (*clk <= 32) tol=1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely - uint16_t errCnt = 0, MaxBits = 512; + if (*clk <= 32) tol = 1; //clock tolerance may not be needed anymore currently set to + or - 1 but could be increased for poor waves or removed entirely + size_t MaxBits = 1024; lastBit = start - *clk; + for (i = start; i < *size; ++i) { - if ((BinStream[i] >= high) && ((i-lastBit) > (*clk-tol))){ - //high found and we are expecting a bar + if (i-lastBit >= *clk-tol){ + if (BinStream[i] >= high) { + BinStream[bitnum++] = *invert; + } else if (BinStream[i] <= low) { + BinStream[bitnum++] = *invert ^ 1; + } else if (i-lastBit >= *clk+tol) { + if (bitnum > 0) { + BinStream[bitnum++]=7; + errCnt++; + } + } else { //in tolerance - looking for peak + continue; + } + midBit = 0; lastBit += *clk; - BinStream[bitnum++] = *invert; - } else if ((BinStream[i] <= low) && ((i-lastBit) > (*clk-tol))){ - //low found and we are expecting a bar - lastBit += *clk; - BinStream[bitnum++] = *invert ^ 1; - } else if ((i-lastBit)>(*clk+tol)){ - //should have hit a high or low based on clock!! - //PrintAndLog("DEBUG - no wave in expected area - location: %d, expected: %d-%d, lastBit: %d - resetting search",i,(lastBit+(clk-((int)(tol)))),(lastBit+(clk+((int)(tol)))),lastBit); - if (bitnum > 0) { - BinStream[bitnum++] = 7; - errCnt++; - } - lastBit += *clk;//skip over error + } else if (i-lastBit >= (*clk/2-tol) && !midBit && !askType){ + if (BinStream[i] >= high) { + BinStream[bitnum++] = *invert; + } else if (BinStream[i] <= low) { + BinStream[bitnum++] = *invert ^ 1; + } else if (i-lastBit >= *clk/2+tol) { + BinStream[bitnum] = BinStream[bitnum-1]; + bitnum++; + } else { //in tolerance - looking for peak + continue; + } + midBit = 1; } if (bitnum >= MaxBits) break; } @@ -216,6 +246,42 @@ int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int max return errCnt; } +//by marshmellow +//take 10 and 01 and manchester decode +//run through 2 times and take least errCnt +int manrawdecode(uint8_t * BitStream, size_t *size, uint8_t invert) +{ + uint16_t bitnum=0, MaxBits = 512, errCnt = 0; + size_t i, ii; + uint16_t bestErr = 1000, bestRun = 0; + if (*size < 16) return -1; + //find correct start position [alignment] + for (ii=0;ii<2;++ii){ + for (i=ii; i<*size-3; i+=2) + if (BitStream[i]==BitStream[i+1]) + errCnt++; + + if (bestErr>errCnt){ + bestErr=errCnt; + bestRun=ii; + } + errCnt=0; + } + //decode + for (i=bestRun; i < *size-3; i+=2){ + if(BitStream[i] == 1 && (BitStream[i+1] == 0)){ + BitStream[bitnum++]=invert; + } else if((BitStream[i] == 0) && BitStream[i+1] == 1){ + BitStream[bitnum++]=invert^1; + } else { + BitStream[bitnum++]=7; + } + if(bitnum>MaxBits) break; + } + *size=bitnum; + return bestErr; +} + //by marshmellow //encode binary data into binary manchester int ManchesterEncode(uint8_t *BitStream, size_t size) @@ -232,42 +298,6 @@ int ManchesterEncode(uint8_t *BitStream, size_t size) return i; } -//by marshmellow -//take 10 and 01 and manchester decode -//run through 2 times and take least errCnt -int manrawdecode(uint8_t * BitStream, size_t *size) -{ - uint16_t bitnum=0, MaxBits = 512, errCnt = 0; - size_t i, ii; - uint16_t bestErr = 1000, bestRun = 0; - if (size == 0) return -1; - //find correct start position [alignment] - for (ii=0;ii<2;++ii){ - for (i=ii; i<*size-2; i+=2) - if (BitStream[i]==BitStream[i+1]) - errCnt++; - - if (bestErr>errCnt){ - bestErr=errCnt; - bestRun=ii; - } - errCnt=0; - } - //decode - for (i=bestRun; i < *size-2; i+=2){ - if(BitStream[i] == 1 && (BitStream[i+1] == 0)){ - BitStream[bitnum++]=0; - } else if((BitStream[i] == 0) && BitStream[i+1] == 1){ - BitStream[bitnum++]=1; - } else { - BitStream[bitnum++]=7; - } - if(bitnum>MaxBits) break; - } - *size=bitnum; - return bestErr; -} - //by marshmellow //take 01 or 10 = 1 and 11 or 00 = 0 //check for phase errors - should never have 111 or 000 should be 01001011 or 10110100 for 1010 @@ -307,88 +337,7 @@ int BiphaseRawDecode(uint8_t *BitStream, size_t *size, int offset, int invert) return errCnt; } -//by marshmellow -void askAmp(uint8_t *BitStream, size_t size) -{ - int shift = 127; - int shiftedVal=0; - for(size_t i = 1; i=30) //large jump up - shift=127; - else if(BitStream[i]-BitStream[i-1]<=-20) //large jump down - shift=-127; - - shiftedVal=BitStream[i]+shift; - - if (shiftedVal>255) - shiftedVal=255; - else if (shiftedVal<0) - shiftedVal=0; - BitStream[i-1] = shiftedVal; - } - return; -} - -//by marshmellow -//takes 3 arguments - clock, invert and maxErr as integers -//attempts to demodulate ask only -int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp) -{ - if (*size==0) return -1; - int start = DetectASKClock(BinStream, *size, clk, maxErr); //clock default - if (*clk==0 || start < 0) return -1; - if (*invert != 1) *invert = 0; - if (amp==1) askAmp(BinStream, *size); - - uint8_t initLoopMax = 255; - if (initLoopMax > *size) initLoopMax = *size; - // Detect high and lows - //25% clip in case highs and lows aren't clipped [marshmellow] - int high, low; - if (getHiLo(BinStream, initLoopMax, &high, &low, 75, 75) < 1) - return -1; //just noise - - // if clean clipped waves detected run alternate demod - if (DetectCleanAskWave(BinStream, *size, high, low)) - return cleanAskRawDemod(BinStream, size, *clk, *invert, high, low); - - int lastBit; //set first clock check - can go negative - size_t i, errCnt = 0, bitnum = 0; //output counter - uint8_t midBit = 0; - size_t MaxBits = 1024; - lastBit = start - *clk; - - for (i = start; i < *size; ++i) { - if (i - lastBit == *clk){ - if (BinStream[i] >= high) { - BinStream[bitnum++] = *invert; - } else if (BinStream[i] <= low) { - BinStream[bitnum++] = *invert ^ 1; - } else { - if (bitnum > 0) { - BinStream[bitnum++]=7; - errCnt++; - } - } - midBit = 0; - lastBit += *clk; - } else if (i-lastBit == (*clk/2) && midBit == 0){ - if (BinStream[i] >= high) { - BinStream[bitnum++] = *invert; - } else if (BinStream[i] <= low) { - BinStream[bitnum++] = *invert ^ 1; - } else { - BinStream[bitnum] = BinStream[bitnum-1]; - bitnum++; - } - midBit = 1; - } - if (bitnum >= MaxBits) break; - } - *size = bitnum; - return errCnt; -} - +// by marshmellow // demod gProxIIDemod // error returns as -x // success returns start position in BitStream @@ -684,7 +633,8 @@ int PyramiddemodFSK(uint8_t *dest, size_t *size) return (int)startIdx; } - +// by marshmellow +// to detect a wave that has heavily clipped (clean) samples uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low) { uint16_t allPeaks=1; @@ -792,7 +742,7 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr) //test each valid clock from smallest to greatest to see which lines up for(; clkCnt < clkEnd; clkCnt++){ - if (clk[clkCnt] == 32){ + if (clk[clkCnt] <= 32){ tol=1; }else{ tol=0; diff --git a/common/lfdemod.h b/common/lfdemod.h index 0a4ceed9..ab81c34c 100644 --- a/common/lfdemod.h +++ b/common/lfdemod.h @@ -15,35 +15,37 @@ #define LFDEMOD_H__ #include -int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr); -uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low); -int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low); -int askmandemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr); -uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo); -int ManchesterEncode(uint8_t *BitStream, size_t size); -int manrawdecode(uint8_t *BitStream, size_t *size); -int BiphaseRawDecode(uint8_t * BitStream, size_t *size, int offset, int invert); -int askrawdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp); +//generic +int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType); +int BiphaseRawDecode(uint8_t * BitStream, size_t *size, int offset, int invert); +uint32_t bytebits_to_byte(uint8_t* src, size_t numbits); +uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj); +int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr); +uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low); +uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow); +int DetectNRZClock(uint8_t dest[], size_t size, int clock); +int DetectPSKClock(uint8_t dest[], size_t size, int clock); +int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low); +uint8_t Em410xDecode(uint8_t *BitStream, size_t *size, size_t *startIdx, uint32_t *hi, uint64_t *lo); +int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow); +int getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo); +int ManchesterEncode(uint8_t *BitStream, size_t size); +int manrawdecode(uint8_t *BitStream, size_t *size, uint8_t invert); +int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr); +uint8_t parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType); +uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx); +int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert); +void psk2TOpsk1(uint8_t *BitStream, size_t size); +void psk1TOpsk2(uint8_t *BitStream, size_t size); +size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen); + +//tag specific +int AWIDdemodFSK(uint8_t *dest, size_t *size); int gProxII_Demod(uint8_t BitStream[], size_t *size); int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo); int IOdemodFSK(uint8_t *dest, size_t size); -int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow); -uint32_t bytebits_to_byte(uint8_t* src, size_t numbits); -int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr); -void psk1TOpsk2(uint8_t *BitStream, size_t size); -void psk2TOpsk1(uint8_t *BitStream, size_t size); -int DetectNRZClock(uint8_t dest[], size_t size, int clock); int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert); int PyramiddemodFSK(uint8_t *dest, size_t *size); -int AWIDdemodFSK(uint8_t *dest, size_t *size); -size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen); -uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj); -uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fcLow); -int getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t fuzzHi, uint8_t fuzzLo); int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo); -uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx); -uint8_t parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType); -int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert); -int DetectPSKClock(uint8_t dest[], size_t size, int clock); #endif From 83602affe5ae7fd7fdc1b91722599c2450285929 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Wed, 8 Apr 2015 13:31:04 +0200 Subject: [PATCH 011/132] Fixed buffer initialization errors, as reported in http://www.proxmark.org/forum/viewtopic.php?pid=15337#p15337 --- armsrc/iclass.c | 3 ++- client/cmdhfmf.c | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 7b4daa36..56bc29db 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1675,7 +1675,8 @@ uint8_t handshakeIclassTag(uint8_t *card_data) // Reader iClass Anticollission void ReaderIClass(uint8_t arg0) { - uint8_t card_data[6 * 8]={0xFF}; + uint8_t card_data[6 * 8]={0}; + memset(card_data, 0xFF, sizeof(card_data)); uint8_t last_csn[8]={0}; //Read conf block CRC(0x01) => 0xfa 0x22 diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 468243fc..5f2e8dec 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -434,7 +434,7 @@ int CmdHF14AMfRestore(const char *Cmd) { uint8_t sectorNo,blockNo; uint8_t keyType = 0; - uint8_t key[6] = {0xFF}; + uint8_t key[6] = {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}; uint8_t bldata[16] = {0x00}; uint8_t keyA[40][6]; uint8_t keyB[40][6]; From 9632ecbe3da943a256b6925cae28965857383926 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 8 Apr 2015 10:12:24 -0400 Subject: [PATCH 012/132] update t5 detection test() missed this file in last commit... sorry. --- client/cmdlft55xx.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/cmdlft55xx.h b/client/cmdlft55xx.h index a64b1eda..364f0271 100644 --- a/client/cmdlft55xx.h +++ b/client/cmdlft55xx.h @@ -53,13 +53,13 @@ char * GetSaferStr(uint32_t id); char * GetModulationStr( uint32_t id); char * GetModelStrFromCID(uint32_t cid); char * GetSelectedModulationStr( uint8_t id); -uint32_t PackBits(uint8_t start, uint8_t len, uint8_t* bitstream); +uint32_t PackBits(uint8_t start, uint8_t len, uint8_t *bitstream); void printT55xxBlock(const char *demodStr); void printConfiguration( t55xx_conf_block_t b); bool DecodeT55xxBlock(); bool tryDetectModulation(); -bool test(uint8_t mode, uint8_t *offset); +bool test(uint8_t mode, uint8_t *offset, int *fndBitRate); int special(const char *Cmd); int AquireData( uint8_t block ); From 322f7eb111e0337e8a509fa104c23502081d6df5 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 8 Apr 2015 11:18:29 -0400 Subject: [PATCH 013/132] fix to lf t5 detect/read cmds i think this functions fairly well... still some issues with demod positioning for various reasons. ASK/Biph/FSK work pretty well the PSK Demod still needs a little attention to help it better demod various carriers... --- client/cmdlft55xx.c | 166 ++++++++++++++++++++++++-------------------- 1 file changed, 90 insertions(+), 76 deletions(-) diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index 564ad29d..3134dde7 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -271,7 +271,6 @@ bool DecodeT55xxBlock(){ //trim 1/2 a clock from beginning snprintf(cmdStr, sizeof(buf),"%d", bitRate[config.bitrate]/2 ); CmdLtrim(cmdStr); - switch( config.modulation ){ case DEMOD_FSK: snprintf(cmdStr, sizeof(buf),"%d %d", bitRate[config.bitrate], config.inverted ); @@ -337,8 +336,9 @@ bool tryDetectModulation(){ uint8_t hits = 0; t55xx_conf_block_t tests[15]; int bitRate=0; + uint8_t fc1 = 0, fc2 = 0, clk=0; + save_restoreGB(1); if (GetFskClock("", FALSE, FALSE)){ - uint8_t fc1 = 0, fc2 = 0, clk=0; fskClocks(&fc1, &fc2, &clk, FALSE); sprintf(cmdStr,"%d", clk/2); CmdLtrim(cmdStr); @@ -366,91 +366,105 @@ bool tryDetectModulation(){ ++hits; } } else { - if ( ASKDemod("0 0 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { - tests[hits].modulation = DEMOD_ASK; - tests[hits].bitrate = bitRate; - tests[hits].inverted = FALSE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( ASKDemod("0 1 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { - tests[hits].modulation = DEMOD_ASK; - tests[hits].bitrate = bitRate; - tests[hits].inverted = TRUE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( NRZrawDemod("0 0 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) { - tests[hits].modulation = DEMOD_NRZ; - tests[hits].bitrate = bitRate; - tests[hits].inverted = FALSE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( NRZrawDemod("0 1 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) { - tests[hits].modulation = DEMOD_NRZ; - tests[hits].bitrate = bitRate; - tests[hits].inverted = TRUE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( PSKDemod("0 0 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) { - tests[hits].modulation = DEMOD_PSK1; - tests[hits].bitrate = bitRate; - tests[hits].inverted = FALSE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - if ( PSKDemod("0 1 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) { - tests[hits].modulation = DEMOD_PSK1; - tests[hits].bitrate = bitRate; - tests[hits].inverted = TRUE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; - } - - // PSK2 - needs a call to psk1TOpsk2. - if ( PSKDemod("0 0 1", FALSE)) { - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (test(DEMOD_PSK2, &tests[hits].offset, &bitRate)){ - tests[hits].modulation = DEMOD_PSK2; + clk = GetAskClock("", FALSE, FALSE); + if (clk>0) { + sprintf(cmdStr,"%d", clk/2); + CmdLtrim(cmdStr); + if ( ASKDemod("0 0 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - } // inverse waves does not affect this demod - - // PSK3 - needs a call to psk1TOpsk2. - if ( PSKDemod("0 0 1", FALSE)) { - psk1TOpsk2(DemodBuffer, DemodBufferLen); - if (test(DEMOD_PSK3, &tests[hits].offset, &bitRate)){ - tests[hits].modulation = DEMOD_PSK3; + if ( ASKDemod("0 1 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_ASK; + tests[hits].bitrate = bitRate; + tests[hits].inverted = TRUE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + if ( ASKbiphaseDemod("0 0 0 1", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate) ) { + tests[hits].modulation = DEMOD_BI; tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - } // inverse waves does not affect this demod - - if ( ASKbiphaseDemod("0 0 0 1", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate) ) { - tests[hits].modulation = DEMOD_BI; - tests[hits].bitrate = bitRate; - tests[hits].inverted = FALSE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; + if ( ASKbiphaseDemod("0 0 1 1", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate) ) { + tests[hits].modulation = DEMOD_BIa; + tests[hits].bitrate = bitRate; + tests[hits].inverted = TRUE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } } - if ( ASKbiphaseDemod("0 0 1 1", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate) ) { - tests[hits].modulation = DEMOD_BIa; - tests[hits].bitrate = bitRate; - tests[hits].inverted = TRUE; - tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); - ++hits; + //undo trim from ask + save_restoreGB(0); + clk = GetNrzClock("", FALSE, FALSE); + if (clk>0) { + sprintf(cmdStr,"%d", clk/2); + CmdLtrim(cmdStr); + if ( NRZrawDemod("0 0 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_NRZ; + tests[hits].bitrate = bitRate; + tests[hits].inverted = FALSE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + + if ( NRZrawDemod("0 1 1", FALSE) && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_NRZ; + tests[hits].bitrate = bitRate; + tests[hits].inverted = TRUE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + } + + //undo trim from nrz + save_restoreGB(0); + clk = GetPskClock("", FALSE, FALSE); + if (clk>0) { + PrintAndLog("clk %d",clk); + sprintf(cmdStr,"%d", clk/2); + CmdLtrim(cmdStr); + if ( PSKDemod("0 0 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_PSK1; + tests[hits].bitrate = bitRate; + tests[hits].inverted = FALSE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + if ( PSKDemod("0 1 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) { + tests[hits].modulation = DEMOD_PSK1; + tests[hits].bitrate = bitRate; + tests[hits].inverted = TRUE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + // PSK2 - needs a call to psk1TOpsk2. + if ( PSKDemod("0 0 1", FALSE)) { + psk1TOpsk2(DemodBuffer, DemodBufferLen); + if (test(DEMOD_PSK2, &tests[hits].offset, &bitRate)){ + tests[hits].modulation = DEMOD_PSK2; + tests[hits].bitrate = bitRate; + tests[hits].inverted = FALSE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + } // inverse waves does not affect this demod + // PSK3 - needs a call to psk1TOpsk2. + if ( PSKDemod("0 0 1", FALSE)) { + psk1TOpsk2(DemodBuffer, DemodBufferLen); + if (test(DEMOD_PSK3, &tests[hits].offset, &bitRate)){ + tests[hits].modulation = DEMOD_PSK3; + tests[hits].bitrate = bitRate; + tests[hits].inverted = FALSE; + tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); + ++hits; + } + } // inverse waves does not affect this demod } } if ( hits == 1) { From 411105e03629542fad02902e18248288812a6f87 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 8 Apr 2015 14:19:03 -0400 Subject: [PATCH 014/132] added nexwatch demod & iceman lua added nexwatch demod (also added to lf search) added iceman's lua script adjustments --- client/cmddata.c | 41 ++- client/cmdlf.c | 7 + client/cmdlft55xx.c | 8 +- client/lualibs/commands.lua | 13 +- client/lualibs/default_toys.lua | 500 ++++++++++++++++++++------------ client/scripts/ndef_dump.lua | 2 +- client/scripts/tnp3clone.lua | 43 ++- client/scripts/tnp3dump.lua | 24 +- client/scripts/tnp3sim.lua | 20 +- 9 files changed, 431 insertions(+), 227 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index a8c809cf..556ede06 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1547,11 +1547,49 @@ int CmdIndalaDecode(const char *Cmd) return 1; } +int CmdPSKNexWatch(const char *Cmd) +{ + if (!PSKDemod("", false)) return 0; + 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}; + size_t startIdx = 0, size = DemodBufferLen; + bool invert = false; + if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)){ + // if didn't find preamble try again inverting + if (!PSKDemod("1", false)) return 0; + size = DemodBufferLen; + if (!preambleSearch(DemodBuffer, preamble, sizeof(preamble), &size, &startIdx)) return 0; + invert = true; + } + if (size != 128) return 0; + setDemodBuf(DemodBuffer, size, startIdx+4); + startIdx = 8+32; //4 = extra i added, 8 = preamble, 32 = reserved bits (always 0) + //get ID + uint32_t ID = 0; + for (uint8_t wordIdx=0; wordIdx<4; wordIdx++){ + for (uint8_t idx=0; idx<8; idx++){ + ID = (ID << 1) | DemodBuffer[startIdx+wordIdx+(idx*4)]; + } + } + //parity check (TBD) + + //checksum check (TBD) + + //output + PrintAndLog("NexWatch ID: %d", ID); + if (invert){ + PrintAndLog("Had to Invert - probably NexKey"); + for (uint8_t idx=0; idx] -- Demodulate an indala tag (PSK1) from GraphBuffer (args optional)"}, + {"psknexwatchdemod",CmdPSKNexWatch, 1, "Demodulate a NexWatch tag (nexkey, quadrakey) (PSK1) from GraphBuffer"}, {"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)"}, diff --git a/client/cmdlf.c b/client/cmdlf.c index d441574a..dfbbe992 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -1077,6 +1077,13 @@ int CmdLFfind(const char *Cmd) PrintAndLog("\nValid EM4x50 ID Found!"); return 1; } + + ans=CmdPSKNexWatch(""); + if (ans>0) { + PrintAndLog("\nValid NexWatch ID Found!"); + return 1; + } + PrintAndLog("\nNo Known Tags Found!\n"); if (testRaw=='u' || testRaw=='U'){ //test unknown tag formats (raw mode) diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index 3134dde7..d4b72b32 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -370,28 +370,28 @@ bool tryDetectModulation(){ if (clk>0) { sprintf(cmdStr,"%d", clk/2); CmdLtrim(cmdStr); - if ( ASKDemod("0 0 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { + if ( ASKDemod("0 0 0", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( ASKDemod("0 1 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { + if ( ASKDemod("0 1 0", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) { tests[hits].modulation = DEMOD_ASK; tests[hits].bitrate = bitRate; tests[hits].inverted = TRUE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( ASKbiphaseDemod("0 0 0 1", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate) ) { + if ( ASKbiphaseDemod("0 0 0 0", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate) ) { tests[hits].modulation = DEMOD_BI; tests[hits].bitrate = bitRate; tests[hits].inverted = FALSE; tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer); ++hits; } - if ( ASKbiphaseDemod("0 0 1 1", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate) ) { + if ( ASKbiphaseDemod("0 0 1 0", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate) ) { tests[hits].modulation = DEMOD_BIa; tests[hits].bitrate = bitRate; tests[hits].inverted = TRUE; diff --git a/client/lualibs/commands.lua b/client/lualibs/commands.lua index ad8f6e00..b0257ef0 100644 --- a/client/lualibs/commands.lua +++ b/client/lualibs/commands.lua @@ -138,6 +138,8 @@ local _commands = { CMD_MIFAREUC_AUTH1 = 0x0724, CMD_MIFAREUC_AUTH2 = 0x0725, CMD_MIFAREUC_READCARD = 0x0726, + CMD_MIFAREUC_SETPWD = 0x0727, + CMD_MIFAREU_SETUID = 0x0728, --// mifare desfire CMD_MIFARE_DESFIRE_READBL = 0x0728, @@ -153,10 +155,10 @@ local _commands = { local _reverse_lookup,k,v = {} -for k, v in pairs(_commands) do - _reverse_lookup[v] = k -end -_commands.tostring = function(command) + for k, v in pairs(_commands) do + _reverse_lookup[v] = k + end + _commands.tostring = function(command) if(type(command) == 'number') then return ("%s (%d)"):format(_reverse_lookup[command]or "ERROR UNDEFINED!", command) end @@ -217,7 +219,6 @@ function Command:getBytes() local data = self.data local cmd = self.cmd local arg1, arg2, arg3 = self.arg1, self.arg2, self.arg3 - - return bin.pack("LLLLH",cmd, arg1, arg2, arg3,data); + return bin.pack("LLLLH",cmd, arg1, arg2, arg3, data); end return _commands diff --git a/client/lualibs/default_toys.lua b/client/lualibs/default_toys.lua index 048a29c9..64eed9b3 100644 --- a/client/lualibs/default_toys.lua +++ b/client/lualibs/default_toys.lua @@ -1,196 +1,328 @@ local _names = { - --[[ + --[[ decimal, hexadecimal, ccc, elements, group, name --]] - ["0000"]="WHIRLWIND", - ["0100"]="SONIC BOOM", - ["0200"]="WARNADO", - ["0300"]="LIGHTNINGROD", - ["0400"]="BASH", - ["0500"]="TERRAFIN", - ["0600"]="DINORANG" , - ["0700"]="LIGHTCORE PRISM BREAK", - ["0800"]="SUNBURN", - ["0900"]="LIGHTCORE ERUPTOR", - ["0A00"]="IGNITOR", - ["0B00"]="FLAMESLINGER", - ["0C00"]="ZAP", - ["0D00"]="WHAM SHELL", - ["0E00"]="GILL GRUNT", - ["0F00"]="SLAMBAM", - ["1000"]="SPYRO", - ["1100"]="VOODOOD", - ["1200"]="DOUBLE TROUBLE", - ["1300"]="TRIGGER HAPPY", - ["1400"]="DROBOT", - ["1500"]="DRILLSERGEANT", - ["1600"]="BOOMER", - ["1700"]="WRECKING BALL", - ["1800"]="CAMO", - ["1900"]="ZOOK", - ["1A00"]="STEALTH ELF", - ["1B00"]="STUMP SMASH", - ["1D00"]="HEX", - ["1C00"]="DARK SPYRO", - ["1E00"]="CHOPCHOP", - ["1F00"]="GHOST ROASTER", - ["2000"]="CYNDER", - --[[ - GIANTS - --]] - ["6400"]="GIANT JET-VAC", - ["6500"]="GIANT SWARM", - ["6600"]="GIANT CRUSHER", - ["6700"]="GIANT FLASHWING", - ["6800"]="GIANT HOTHEAD", - ["6900"]="GIANT HOTDOG", - ["6A00"]="GIANT CHILL", - ["6B00"]="GIANT THUMPBACK", - ["6C00"]="GIANT POPFIZZ", - ["6D00"]="GIANT NINJINI", - ["6E00"]="GIANT BOUNCER", - ["6F00"]="GIANT SPROCKET", - ["7000"]="GIANT TREE REX", - ["7100"]="LIGHTCORE SHROOMBOOM", - ["7200"]="GIANT EYEBROAWL", - ["7300"]="GIANT FRIGHTRIDER", +{"0", "0000", "0030", "air", "regular", "Whirlwind"}, +--{"0", "0000", "0030", "air", "regular", "Elite Whirlwind"}, +--{"0", "0000", "0030", "air", "regular", "Polar Whirlwind"}, +{"1", "0100", "0030", "air", "regular", "Sonic Boom"}, +{"2", "0200", "0030", "air", "regular", "Warnado"}, +{"3", "0300", "0030", "air", "regular", "Lightning Rod"}, +{"4", "0400", "0030", "earth", "regular", "Bash"}, +--{"4", "0400", "0030", "earth", "regular", "Birthday Bash"}, +{"5", "0500", "0030", "earth", "regular", "Terrafin"}, +--{"5", "0500", "0030", "earth", "regular", "Elite Terrafin"}, +{"6", "0600", "0030", "earth", "regular", "Dino Rang"}, +{"7", "0700", "0030", "earth", "regular", "Prism Break"}, --lightcore +{"8", "0800", "0030", "fire", "regular", "Sunburn"}, +{"9", "0900", "0030", "fire", "regular", "Eruptor"}, --lightcore +--{"9", "0900", "0030", "fire", "regular", "Elite Eruptor"}, +--{"9", "0900", "0030", "fire", "regular", "Volcanic Eruptor"}, +{"10", "0a00", "0030", "fire", "regular", "Ignitor"}, +{"11", "0b00", "0030", "fire", "regular", "Flameslinger"}, +--{"11", "0b00", "0030", "fire", "regular", "Cupid Flameslinger"}, +{"12", "0c00", "0030", "water", "regular", "Zap"}, +{"13", "0d00", "0030", "water", "regular", "Wham Shell"}, +{"14", "0e00", "0030", "water", "regular", "Gill Grunt"}, +--{"14", "0e00", "0030", "water", "regular", "Elite Gill Grunt"}, +{"15", "0f00", "0030", "water", "regular", "Slam Bam"}, +--{"15", "0f00", "0030", "water", "regular", "Surfer Slam Bam"}, +{"16", "1000", "0030", "magic", "regular", "Spyro"}, +{"17", "1100", "0030", "magic", "regular", "Voodood"}, +{"18", "1200", "0030", "magic", "regular", "Double Trouble"}, +--{"18", "1200", "0030", "magic", "regular", "Royal Double Trouble"}, +{"19", "1300", "0030", "tech", "regular", "Trigger Happy"}, +--{"19", "1300", "0030", "tech", "regular", "Elite Trigger Happy"}, +--{"19", "1300", "0030", "tech", "regular", "Springtime Trigger Happy"}, +{"20", "1400", "0030", "tech", "regular", "Drobot"}, +{"21", "1500", "0030", "tech", "regular", "Drill Sergeant"}, +{"22", "1600", "0030", "tech", "regular", "Boomer"}, +--{"22", "1600", "0030", "tech", "regular", "Lucky Boomer"}, +{"23", "1700", "0030", "magic", "regular", "Wrecking Ball"}, +--{"23", "1700", "0030", "magic", "regular", "Buddy Wrecking Ball"}, +{"24", "1800", "0030", "life", "regular", "Camo"}, +{"25", "1900", "0030", "life", "regular", "Zook"}, +{"26", "1a00", "0030", "life", "regular", "Stealth Elf"}, +--{"26", "1a00", "0030", "life", "regular", "Elite Stealth Elf"}, +--{"26", "1a00", "0030", "life", "regular", "Dark Stealth Elf"}, +{"27", "1b00", "0030", "life", "regular", "Stump Smash"}, +--{"27", "1b00", "0030", "life", "regular", "Autumn Stump Smash"}, +{"28", "1c00", "0030", "magic", "regular", "Dark Spyro"}, +--{"28", "1c00", "0030", "magic", "regular", "Elite Spyro"}, +{"29", "1d00", "0030", "undead", "regular", "Hex"}, +--{"29", "1d00", "0030", "undead", "regular", "Hallows' Eve Hex"}, +{"30", "1e00", "0030", "undead", "regular", "Chop Chop"}, +--{"30", "1e00", "0030", "undead", "regular", "Elite Chop Chop"}, +--{"30", "1e00", "0030", "undead", "regular", "Grill Master Chop Chop"}, +{"31", "1f00", "0030", "undead", "regular", "Ghost Roaster"}, +{"32", "2000", "0030", "undead", "regular", "Cynder"}, +--{"32", "2000", "0030", "undead", "regular", "Skeletal Cynder"}, - --[[ - ITEM - --]] - ["C800"]="ANVIL", - ["C900"]="SECRET STASH", - ["CA00"]="REGENERATION", - ["CD00"]="SHIELD", - ["CB00"]="CROSSED SWORDS", - ["CC00"]="HOURGLASS", - ["CE00"]="SPEED BOOTS", - ["CF00"]="SPARX", - ["D000"]="CANNON", - ["D100"]="SCORPIONSTRIKER", +{"100", "6400", "0030", "air", "giant", "Jet Vac"}, +{"101", "6500", "0030", "air", "giant", "Swarm"}, +{"102", "6600", "0030", "earth", "giant", "Crusher"}, +{"103", "6700", "0030", "earth", "giant", "Flashwing"}, +--{"103", "6700", "0030", "earth", "giant", "Jade Flashwing"}, +{"104", "6800", "0030", "fire", "giant", "Hot Head"}, +{"105", "6900", "0030", "fire", "giant", "Hot Dog"}, +--{"105", "6900", "0030", "fire", "giant", "Molten Hot Dog"}, +{"106", "6a00", "0030", "water", "giant", "Chill"}, +{"107", "6b00", "0030", "water", "giant", "Thumpback"}, +--{"107", "6b00", "0030", "water", "giant", "Admiral Thumpback"}, +{"108", "6c00", "0030", "magic", "giant", "Pop Fizz"}, +--{"108", "6c00", "0030", "magic", "giant", "Hoppity Pop Fizz"}, +--{"108", "6c00", "0030", "magic", "giant", "Love Potion Pop Fizz"}, +--{"108", "6c00", "0030", "magic", "giant", "Punch Pop Fizz"}, +{"109", "6d00", "0030", "magic", "giant", "Nin Jini"}, +{"110", "6e00", "0030", "tech", "giant", "Bouncer"}, +{"111", "6f00", "0030", "tech", "giant", "Sprocket"}, +{"112", "7000", "0030", "life", "giant", "Tree Rex"}, +--{"112", "7000", "0030", "life", "giant", "Gnarly Tree Rex"}, +{"113", "7100", "0030", "life", "giant", "Shroomboom"}, --lightcore +{"114", "7200", "0030", "undead", "giant", "Eye Broawl"}, +{"115", "7300", "0030", "undead", "giant", "Fright Rider"}, - --[[ - ITEM TRAPS - --]] - ["D200"]="MAGIC TRAP", - ["D300"]="WATER TRAP", - ["D400"]="AIR TRAP", - ["D500"]="UNDEAD TRAP", - ["D600"]="TECH TRAP", - ["D700"]="FIRE TRAP", - ["D800"]="EARTH TRAP", - ["D900"]="LIFE TRAP", - ["DA00"]="DARK TRAP", - ["DB00"]="LIGHT TRAP", - ["DC00"]="KAOS TRAP", +{"200", "c800", "0030", "", "item", "Anvil Rain"}, +{"201", "c900", "0030", "", "item", "Platinum Treasure Chest"}, +{"202", "ca00", "0030", "", "item", "Healing Elixer"}, +{"203", "cb00", "0030", "", "item", "Ghost Pirate Swords"}, +{"204", "cc00", "0030", "", "item", "Time Twist Hourglass"}, +{"205", "cd00", "0030", "", "item", "Sky Iron Shield"}, +{"206", "ce00", "0030", "", "item", "Winged Boots"}, +{"207", "cf00", "0030", "", "item", "Sparx"}, +{"208", "d000", "0030", "", "item", "Cannon"}, +{"209", "d100", "0030", "", "item", "Scorpion Striker"}, - --[[ - ITEM - --]] - ["E600"]="HAND OF FATE", - ["E700"]="PIGGYBANK", - ["E800"]="ROCKET RAM", - ["E900"]="TIKI SPEAKY", +{"210", "d200", "0230", "magic", "trap", "Biter's Bane"}, +{"210", "d200", "0830", "magic", "trap", "Sorcerous Skull"}, +-- legendary Sorcerous Skull? +{"210", "d200", "0b30", "magic", "trap", "Axe Of Illusion"}, +{"210", "d200", "0e30", "magic", "trap", "Arcane Hourglass"}, +{"210", "d200", "1230", "magic", "trap", "Spell Slapper"}, +{"210", "d200", "1430", "magic", "trap", "Rune Rocket"}, + +{"211", "d300", "0130", "water", "trap", "Tidal Tiki"}, +{"211", "d300", "0230", "water", "trap", "Wet Walter"}, +{"211", "d300", "0630", "water", "trap", "Flood Flask"}, +-- legendary flood flask? +{"211", "d300", "0730", "water", "trap", "Soaking Staff"}, +{"211", "d300", "0b30", "water", "trap", "Aqua Axe"}, +{"211", "d300", "1630", "water", "trap", "Frost Helm"}, + +{"212", "d400", "0330", "air", "trap", "Breezy Bird"}, +{"212", "d400", "0630", "air", "trap", "Drafty Decanter"}, +{"212", "d400", "0d30", "air", "trap", "Tempest Timer"}, +{"212", "d400", "1030", "air", "trap", "Cloudy Cobra"}, +{"212", "d400", "1130", "air", "trap", "Storm Warning"}, +{"212", "d400", "1830", "air", "trap", "Cycone Saber"}, + +{"213", "d500", "0430", "undead", "trap", "Spirit Sphere"}, +{"213", "d500", "0830", "undead", "trap", "Spectral Skull"}, +{"213", "d500", "0b30", "undead", "trap", "Haunted Hatchet"}, +{"213", "d500", "0c30", "undead", "trap", "Grim Gripper"}, +{"213", "d500", "1030", "undead", "trap", "Spooky Snake"}, +{"213", "d500", "1730", "undead", "trap", "Dream Piercer"}, + +{"214", "d600", "0030", "tech", "trap", "tech Totem"}, +{"214", "d600", "0730", "tech", "trap", "Automatic Angel"}, +{"214", "d600", "0930", "tech", "trap", "Factory Flower"}, +{"214", "d600", "0c30", "tech", "trap", "Grabbing Gadget"}, +{"214", "d600", "1630", "tech", "trap", "Makers Mana"}, +{"214", "d600", "1a30", "tech", "trap", "Topsy techy"}, + +{"215", "d700", "0530", "fire", "trap", "Eternal Flame"}, +{"215", "d700", "0930", "fire", "trap", "fire Flower"}, +{"215", "d700", "1130", "fire", "trap", "Scorching Stopper"}, +{"215", "d700", "1230", "fire", "trap", "Searing Spinner"}, +{"215", "d700", "1730", "fire", "trap", "Spark Spear"}, +{"215", "d700", "1b30", "fire", "trap", "Blazing Belch"}, + +{"216", "d800", "0030", "earth", "trap", "Banded Boulder"}, +{"216", "d800", "0330", "earth", "trap", "Rock Hawk"}, +{"216", "d800", "0a30", "earth", "trap", "Slag Hammer"}, +{"216", "d800", "0e30", "earth", "trap", "Dust Of Time"}, +{"216", "d800", "1330", "earth", "trap", "Spinning Sandstorm"}, +{"216", "d800", "1a30", "earth", "trap", "Rubble Trouble"}, + +{"217", "d900", "0330", "life", "trap", "Oak Eagle"}, +{"217", "d900", "0530", "life", "trap", "Emerald Energy"}, +{"217", "d900", "0a30", "life", "trap", "Weed Whacker"}, +{"217", "d900", "1030", "life", "trap", "Seed Serpent"}, +{"217", "d900", "1830", "life", "trap", "Jade Blade"}, +{"217", "d900", "1b30", "life", "trap", "Shrub Shrieker"}, + +{"218", "da00", "0030", "dark", "trap", "dark Dagger"}, +{"218", "da00", "1430", "dark", "trap", "Shadow Spider"}, +{"218", "da00", "1a30", "dark", "trap", "Ghastly Grimace"}, + +{"219", "db00", "0030", "light", "trap", "Shining Ship"}, +{"219", "db00", "0f30", "light", "trap", "Heavenly Hawk"}, +{"219", "db00", "1b30", "light", "trap", "Beam Scream"}, + +{"220", "dc00", "3030", "kaos", "trap", "Kaos trap!"}, +--{"220", "dc00", "3130", "kaos", "trap", "Ultimate Kaos trap!"}, ? - --[[ - EXPANSION - --]] - ["012C"]="DRAGONS PEAK", - ["012D"]="EMPIRE OF ICE", - ["012E"]="PIRATE SEAS", - ["012F"]="DARKLIGHT CRYPT", - ["0130"]="VOLCANIC VAULT", - ["0131"]="MIRROR OF MYSTERY", - ["0132"]="NIGHTMARE EXPRESS", - ["0133"]="SUNSCRAPER SPIRE", - ["0134"]="MIDNIGHT MUSEUM", +{"230", "e600", "0030", "none", "item", "Hand Of Fate"}, +{"231", "e700", "0030", "none", "item", "Piggy Bank"}, +{"232", "e800", "0030", "none", "item", "Rocket Ram"}, +{"233", "e900", "0030", "none", "item", "Tiki Speaky"}, + +{"300", "2c01", "0030", "none", "location", "Dragons Peak"}, +{"301", "2d01", "0030", "none", "location", "Empire Of Ice"}, +{"302", "2e01", "0030", "none", "location", "Pirate Seas"}, +{"303", "2f01", "0030", "none", "location", "darklight Crypt"}, +{"304", "3001", "0030", "none", "location", "Volcanic Vault"}, +{"305", "3101", "0030", "none", "location", "Mirror Of Mystery"}, +{"306", "3201", "0030", "none", "location", "Nightmare Express"}, +{"307", "3301", "0030", "none", "location", "Sunscraper Spire"}, +{"308", "3401", "0030", "none", "location", "Midnight Museum"}, + +{"404", "9401", "0030", "earth", "legendary","Bash"}, +{"416", "a001", "0030", "magic", "legendary", "Spyro"}, + --{"", "", "0030", "magic", "legendary", "Deja Vu"}, +{"419", "a301", "0030", "tech", "legendary", "Trigger Happy"}, + --{"", "", "0030", "tech", "legendary", "bouncer"}, + --{"", "", "0030", "tech", "legendary", "jawbreaker"}, +{"430", "ae01", "0030", "undead", "legendary", "Chop Chop"}, + --{"", "", "0030", "undead", "legendary", "grim creeper"}, + --{"", "", "0030", "undead", "legendary", "night shift"}, - --[[ - LEGENDARY - --]] - ["0194"]="LEGENDARY BASH", - ["01A0"]="LEGENDARY SPYRO", - ["01A3"]="LEGENDARY TRIGGER HAPPY", - ["01AE"]="LEGENDARY CHOPCHOP", + --{"", "", "0030", "air", "legendary", "blades"}, + --{"", "", "0030", "air", "legendary", "jet vac"}, + --{"", "", "0030", "air", "legendary", "Free Ranger"}, + --{"", "", "0030", "life", "legendary", "stealth elf"}, + --{"", "", "0030", "life", "legendary", "Bushwhack"}, + --{"", "", "0030", "fire", "legendary", "ignitor"}, + --{"", "", "0030", "water", "legendary", "slam bam"}, + --{"", "", "0030", "water", "legendary", "chill"}, + + --{"", "", "0030", "", "legendary", "zoo lou"}, - --[[ - TRAPTEAM - --]] - ["01C2"]="TRAPTEAM GUSTO", - ["01C3"]="TRAPTEAM THUNDERBOLT", - ["01C4"]="TRAPTEAM FLING KONG", - ["01C5"]="TRAPTEAM BLADES", - ["01C6"]="TRAPTEAM WALLOP", - ["01C7"]="TRAPTEAM HEAD RUSH", - ["01C8"]="TRAPTEAM FIST BUMP", - ["01C9"]="TRAPTEAM ROCKY ROLL", - ["01CA"]="TRAPTEAM WILDFIRE", - ["01CB"]="TRAPTEAM KA BOOM", - ["01CC"]="TRAPTEAM TRAIL BLAZER", - ["01CD"]="TRAPTEAM TORCH", - ["01CE"]="TRAPTEAM SNAP SHOT", - ["01CF"]="TRAPTEAM LOB STAR", - ["01D0"]="TRAPTEAM FLIP WRECK", - ["01D1"]="TRAPTEAM ECHO", - ["01D2"]="TRAPTEAM BLASTERMIND", - ["01D3"]="TRAPTEAM ENIGMA", - ["01D4"]="TRAPTEAM DEJA VU", - ["01D5"]="TRAPTEAM COBRA CADABRA", - ["01D6"]="TRAPTEAM JAWBREAKER", - ["01D7"]="TRAPTEAM GEARSHIFT", - ["01D8"]="TRAPTEAM CHOPPER", - ["01D9"]="TRAPTEAM TREAD HEAD", - ["01DA"]="TRAPTEAM BUSHWHACK", - ["01DB"]="TRAPTEAM TUFF LUCK", - ["01DC"]="TRAPTEAM FOOD FIGHT", - ["01DD"]="TRAPTEAM HIGH FIVE", - ["01DE"]="TRAPTEAM NITRO KRYPT KING", - ["01DF"]="TRAPTEAM SHORT CUT", - ["01E0"]="TRAPTEAM BAT SPIN", - ["01E1"]="TRAPTEAM FUNNY BONE", - ["01E2"]="TRAPTEAM KNIGHT LIGHT", - ["01E3"]="TRAPTEAM SPOTLIGHT", - ["01E4"]="TRAPTEAM KNIGHT MARE", - ["01E5"]="TRAPTEAM BLACKOUT", +{"450", "c201", "0030", "air", "trapmaster", "Gusto"}, +--{"450", "c201", "0234", "air", "trapmaster", "Special Gusto"}, +{"451", "c301", "0030", "air", "trapmaster", "Thunderbolt"}, +--{"451", "c301", "0234", "air", "trapmaster", "Special Thunderbolt"}, +{"452", "c401", "0030", "air", "regular", "Fling Kong"}, +{"453", "c501", "0030", "air", "regular", "Blades"}, +{"454", "c601", "0030", "earth", "trapmaster", "Wallop"}, +--{"454", "c601", "0234", "earth", "trapmaster", "Special Wallop"}, +{"455", "c701", "0030", "earth", "trapmaster", "Head Rush"}, +{"455", "c701", "0234", "earth", "trapmaster", "Nitro Head Rush"}, +{"456", "c801", "0030", "earth", "regular", "Fist Bump"}, +{"457", "c901", "0030", "earth", "regular", "Rocky Roll"}, +--{"457", "c901", "0030", "earth", "regular", "Rocky Egg Roll"}, +{"458", "ca01", "0030", "fire", "trapmaster", "Wildfire"}, +{"458", "ca01", "0234", "fire", "trapmaster", "Dark Wildfire"}, +{"459", "cb01", "0030", "fire", "trapmaster", "Ka Boom"}, +--{"459", "cb01", "0234", "fire", "trapmaster", "Special Ka Boom"}, +{"460", "cc01", "0030", "fire", "regular", "Trail Blazer"}, +{"461", "cd01", "0030", "fire", "regular", "Torch"}, +{"462", "ce01", "0030", "water", "trapmaster", "Snap Shot"}, +{"462", "ce01", "0234", "water", "trapmaster", "Dark Snap Shot"}, +--, "water", "trapmaster", "Instant Snap Shot"}, +--, "water", "trapmaster", "Merry Snap Shot"}, +{"463", "cf01", "0030", "water", "trapmaster", "Lob Star"}, +{"463", "cf01", "0234", "water", "trapmaster", "Winterfest Lob Star"}, +{"464", "d001", "0030", "water", "regular", "Flip Wreck"}, +{"465", "d101", "0030", "water", "regular", "Echo"}, +{"466", "d201", "0030", "magic", "trapmaster", "Blastermind"}, +--{"466", "d201", "0234", "magic", "trapmaster", "Special Blastermind"}, +{"467", "d301", "0030", "magic", "trapmaster", "Enigma"}, +--{"467", "d301", "0234", "magic", "trapmaster", "Special Enigma"}, +{"468", "d401", "0030", "magic", "regular", "Deja Vu"}, +{"469", "d501", "0030", "magic", "regular", "Cobra Cadabra"}, +--{"469", "d501", "0030", "magic", "regular", "Charming Cobra Cadabra"}, +--{"469", "d501", "0030", "magic", "regular", "King Cobra Cadabra"}, +{"470", "d601", "0030", "tech", "trapmaster", "Jawbreaker"}, +--{"470", "d601", "0234", "tech", "trapmaster", "Special Jawbreaker"}, +--{"470", "d601", "0234", "tech", "trapmaster", "Knockout Jawbreaker"}, +{"471", "d701", "0030", "tech", "trapmaster", "Gearshift"}, +--{"471", "d701", "0234", "tech", "trapmaster", "Special Gearshift"}, +{"472", "d801", "0030", "tech", "regular", "Chopper"}, +{"473", "d901", "0030", "tech", "regular", "Tread Head"}, +{"474", "da01", "0030", "life", "trapmaster", "Bushwhack"}, +--{"474", "da01", "0234", "life", "trapmaster", "Special Bushwhack"}, +{"475", "db01", "0030", "life", "trapmaster", "Tuff Luck"}, +--{"475", "db01", "0234", "life", "trapmaster", "Special Tuff Luck"}, +{"476", "dc01", "0030", "life", "regular", "Food Fight"}, +--{"476", "dc01", "0030", "life", "regular", "Dark Food Fight"}, +--{"476", "dc01", "0030", "life", "regular", "Frosted Food Fight"}, +--{"476", "dc01", "0030", "life", "regular", "Instant Food Fight"}, +{"477", "dd01", "0030", "life", "regular", "High Five"}, +{"478", "de01", "0030", "undead", "trapmaster", "Krypt King"}, +{"478", "de01", "0234", "undead", "trapmaster", "Nitro Krypt King"}, +{"479", "df01", "0030", "undead", "trapmaster", "Short Cut"}, +--{"479", "df01", "0234", "undead", "trapmaster", "Special Short Cut"}, +{"480", "e001", "0030", "undead", "regular", "Bat Spin"}, +{"481", "e101", "0030", "undead", "regular", "Funny Bone"}, +--{"481", "e101", "0030", "undead", "regular", "Fortune Funny Bone"}, +{"482", "e201", "0030", "light", "trapmaster", "Knight light"}, +--{"482", "e201", "0234", "light", "trapmaster", "Special Knight light"}, +{"483", "e301", "0030", "light", "regular", "Spotlight"}, +--{"483", "e301", "0234", "light", "regular", "Special Spotlight"}, +{"484", "e401", "0030", "dark", "trapmaster", "Knight Mare"}, +--{"484", "e401", "0234", "dark", "trapmaster", "Special Knight Mare"}, +{"485", "e501", "0030", "dark", "regular", "Blackout"}, +--{"485", "e501", "0234", "dark", "regular", "Special Blackout"}, - --[[ - PET - --]] - ["01F6"]="PET BOP", - ["01F7"]="PET SPRY", - ["01F8"]="PET HIJINX", - ["01F9"]="PET TERRAFIN", - ["01FA"]="PET BREEZE", - ["01FB"]="PET WEERUPTOR", - ["01FC"]="PET PET VAC", - ["01FD"]="PET SMALL FRY", - ["01FE"]="PET DROBIT", - ["0202"]="PET GILL GRUNT", - ["0207"]="PET TRIGGER SNAPPY", - ["020E"]="PET WHISPER ELF", - ["021C"]="PET BARKLEY", - ["021D"]="PET THUMPLING", - ["021E"]="PET MINI JINI", - ["021F"]="PET EYE SMALL", +{"502", "f601", "0030", "earth", "mini", "Bop"}, +{"503", "f701", "0030", "magic", "mini", "Spry"}, +{"504", "f801", "0030", "undead", "mini", "Hijinx"}, +{"505", "f901", "0030", "earth", "mini", "Terrabite"}, +{"506", "fa01", "0030", "air", "mini", "Breeze"}, +{"507", "fb01", "0030", "fire", "mini", "Weeruptor"}, +--{"507", "fb01", "0030", "fire", "mini", "Eggsellent Weeruptor"}, +{"508", "fc01", "0030", "air", "mini", "Pet Vac"}, +--{"508", "fc01", "0030", "air", "mini", "Power Punch Pet Vac"}, +{"509", "fd01", "0030", "fire", "mini", "Small Fry"}, +{"510", "fe01", "0030", "tech", "mini", "Drobit"}, +{"514", "0202", "0030", "water", "mini", "Gill Runt"}, +{"519", "0702", "0030", "tech", "mini", "Trigger Snappy"}, +{"526", "0e02", "0030", "life", "mini", "Whisper Elf"}, +{"540", "1c02", "0030", "life", "mini", "Barkley"}, +--{"540", "1c02", "0030", "life", "mini", "Gnarly Barkley"}, +{"541", "1d02", "0030", "water", "mini", "Thumpling"}, +{"542", "1e02", "0030", "magic", "mini", "mini Jini"}, +{"543", "1f02", "0030", "undead", "mini", "Eye Small"}, - --[[ - SWAP FORCE - --]] - ["0BB8"]="SWAPFORCE SCRATCH", - ["0BB9"]="SWAPFORCE POPTHORN", - ["0BBA"]="SWAPFORCE SLOBBER TOOTH", - ["0BBB"]="SWAPFORCE SCORP", - ["0BBC"]="SWAPFORCE HOG WILD FRYNO", - ["0BBD"]="SWAPFORCE SMOLDER DASH", - ["0BBE"]="SWAPFORCE BUMBLE BLAST", - ["0BBF"]="SWAPFORCE ZOO LOU", - ["0BC0"]="SWAPFORCE DUNE BUG", - ["0BC1"]="SWAPFORCE STAR STRIKE", - ["0BC2"]="SWAPFORCE COUNTDOWN", - ["0BC3"]="SWAPFORCE WIND UP", - ["0BC4"]="SWAPFORCE ROLLER BRAWL", - ["0BC5"]="SWAPFORCE GRIM CREEPER", - ["0BC6"]="SWAPFORCE RIP TIDE", - ["0BC7"]="SWAPFORCE PUNK SHOCK", +{"3000", "b80b", "0030", "air", "SWAPFORCE", "Scratch"}, +{"3001", "b90b", "0030", "air", "SWAPFORCE", "Pop Thorn"}, +--{"3001", "b90b", "0030", "air", "SWAPFORCE", "Buttered Pop Thorn"}, +{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Slobber Tooth"}, +--{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Dark Slobber Tooth"}, +--{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Sundae Slobber Tooth"}, +{"3003", "bb0b", "0030", "earth", "SWAPFORCE", "Scorp"}, +{"3004", "bc0b", "0138", "fire", "SWAPFORCE", "Hog Wild Fryno"}, +--{"3004", "bc0b", "0138", "fire", "SWAPFORCE", "Flip flop Fryno"}, +{"3005", "bd0b", "0030", "fire", "SWAPFORCE", "Smolderdash"}, +{"3006", "be0b", "0030", "life", "SWAPFORCE", "Bumble Blast"}, +--{"3006", "be0b", "0030", "life", "SWAPFORCE", "Jolly Bumble Blast"}, +{"3007", "bf0b", "0030", "life", "SWAPFORCE", "Zoo Lou"}, +{"3008", "c00b", "0030", "magic", "SWAPFORCE", "Dune Bug"}, +{"3009", "c10b", "0030", "magic", "SWAPFORCE", "Star Strike"}, +--{"3009", "c10b", "0030", "magic", "SWAPFORCE", "Enchanted Star Strike"}, +--{"3009", "c10b", "0030", "magic", "SWAPFORCE", "Mystic Star Strike"}, +{"3010", "c20b", "0030", "tech", "SWAPFORCE", "Countdown"}, +--{"3010", "c20b", "0030", "tech", "SWAPFORCE", "Kickoff Countdown"}, +--{"3010", "c20b", "0030", "tech", "SWAPFORCE", "New Year's Countdown"}, +{"3011", "c30b", "0030", "tech", "SWAPFORCE", "Wind Up"}, +{"3012", "c40b", "0030", "undead", "SWAPFORCE", "Roller Brawl"}, +--{"3012", "c40b", "0030", "undead", "SWAPFORCE", "Snowler Roller Brawl"}, +{"3013", "c50b", "0030", "undead", "SWAPFORCE", "Grim Creeper"}, +{"3014", "c60b", "0030", "water", "SWAPFORCE", "Rip Tide"}, +{"3015", "c70b", "0030", "water", "SWAPFORCE", "Punk Shock"}, +} + +local function find( main, sub) + + for k, v in pairs(_names) do + if ( v[2] == main and v[3] == sub) then + return v + end + end + return nil +end + +return { + Find = find, } -return _names diff --git a/client/scripts/ndef_dump.lua b/client/scripts/ndef_dump.lua index da1a1ef2..3b27cac3 100644 --- a/client/scripts/ndef_dump.lua +++ b/client/scripts/ndef_dump.lua @@ -205,7 +205,7 @@ local function main( args) -- NDEF compliant? if b3chars[1] ~= 0xE1 then - return oops("This tag is not NDEF-Complian") + return oops("This tag is not NDEF-Compliant") end local ndefVersion = b3chars[2] diff --git a/client/scripts/tnp3clone.lua b/client/scripts/tnp3clone.lua index 8c9397a7..cad1ab70 100644 --- a/client/scripts/tnp3clone.lua +++ b/client/scripts/tnp3clone.lua @@ -3,6 +3,7 @@ local getopt = require('getopt') local lib14a = require('read14a') local utils = require('utils') local pre = require('precalc') +local toys = require('default_toys') local lsh = bit32.lshift local rsh = bit32.rshift @@ -10,19 +11,20 @@ local bor = bit32.bor local band = bit32.band example =[[ - script run tnp3dump - script run tnp3dump -h - script run tnp3dump -t aa00 + script run tnp3clone + script run tnp3clone -h + script run tnp3clone -t aa00 -s 0030 ]] author = "Iceman" -usage = "script run tnp3clone -t " +usage = "script run tnp3clone -t -s " desc =[[ This script will try making a barebone clone of a tnp3 tag on to a magic generation1 card. Arguments: -h : this help - -k : toytype id, 4 hex symbols. + -t : toytype id, 4hex symbols. + -s : subtype id, 4hex symbols ]] @@ -73,29 +75,45 @@ end local function main(args) + print( string.rep('--',20) ) + print( string.rep('--',20) ) + local numBlocks = 64 local cset = 'hf mf csetbl ' + local csetuid = 'hf mf csetuid ' local cget = 'hf mf cgetbl ' local empty = '00000000000000000000000000000000' local AccAndKeyB = '7F078869000000000000' -- Defaults to Gusto local toytype = 'C201' + local subtype = '0030' + local DEBUG = true -- Arguments for the script - for o, a in getopt.getopt(args, 'ht:') do + for o, a in getopt.getopt(args, 'ht:s:') do if o == "h" then return help() end if o == "t" then toytype = a end + if o == "s" then subtype = a end end - if #toytype ~= 4 then return oops('Wrong size in toytype. (4hex symbols)') end + if #toytype ~= 4 then return oops('Wrong size - toytype. (4hex symbols)') end + if #subtype ~= 4 then return oops('Wrong size - subtype. (4hex symbols)') end + + -- look up type, find & validate types + local item = toys.Find( toytype, subtype) + if item then + print( (' Looking up input: Found %s - %s (%s)'):format(item[6],item[5], item[4]) ) + else + print('Didn\'t find item type. If you are sure about it, report it in') + end + --15,16 + --13-14 + -- find tag result, err = lib14a.read1443a(false) if not result then return oops(err) end - -- Show tag info - print((' Found tag %s'):format(result.name)) - -- load keys local akeys = pre.GetAll(result.uid) local keyA = akeys:sub(1, 12 ) @@ -111,11 +129,10 @@ local function main(args) end -- wipe card. - local cmd = (cset..' %s 0004 08 w'):format( b0) + local cmd = (csetuid..'%s 0004 08 w'):format(result.uid) core.console(cmd) - - local b1 = toytype..'000000000000000000000000' + local b1 = toytype..'00000000000000000000'..subtype local calc = utils.Crc16(b0..b1) local calcEndian = bor(rsh(calc,8), lsh(band(calc, 0xff), 8)) diff --git a/client/scripts/tnp3dump.lua b/client/scripts/tnp3dump.lua index 363998fb..f93f9728 100644 --- a/client/scripts/tnp3dump.lua +++ b/client/scripts/tnp3dump.lua @@ -5,8 +5,7 @@ local lib14a = require('read14a') local utils = require('utils') local md5 = require('md5') local dumplib = require('html_dumplib') -local toyNames = require('default_toys') - +local toys = require('default_toys') example =[[ script run tnp3dump @@ -129,7 +128,7 @@ local function main(args) if o == "p" then usePreCalc = true end if o == "o" then outputTemplate = a end end - + -- validate input args. keyA = keyA or '4b0b20107ccb' if #(keyA) ~= 12 then @@ -261,13 +260,16 @@ local function main(args) bindata[#bindata+1] = c end end + + print( string.rep('--',20) ) + local uid = block0:sub(1,8) - local itemtype = block1:sub(1,4) + local toytype = block1:sub(1,4) local cardidLsw = block1:sub(9,16) local cardidMsw = block1:sub(16,24) local cardid = block1:sub(9,24) - local traptype = block1:sub(25,28) + local subtype = block1:sub(25,28) -- Write dump to files if not DEBUG then @@ -277,13 +279,15 @@ local function main(args) print(("Wrote a EML dump to: %s"):format(bar)) end - local itemtypename = toyNames[itemtype] - if itemtypename == nil then - itemtypename = toyNames[utils.SwapEndiannessStr(itemtype,16)] + local item = toys.Find(toytype, subtype) + if item then + local itemStr = ('%s - %s (%s)'):format(item[6],item[5], item[4]) + print(' ITEM TYPE : '..itemStr ) + else + print((' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype)) end + -- Show info - print( string.rep('--',20) ) - print( (' ITEM TYPE : 0x%s - %s'):format(itemtype, itemtypename) ) print( (' Alter ego / traptype : 0x%s'):format(traptype) ) print( (' UID : 0x%s'):format(uid) ) print( (' CARDID : 0x%s'):format(cardid ) ) diff --git a/client/scripts/tnp3sim.lua b/client/scripts/tnp3sim.lua index 1d3dbefd..af3d2d4c 100644 --- a/client/scripts/tnp3sim.lua +++ b/client/scripts/tnp3sim.lua @@ -4,7 +4,7 @@ local bin = require('bin') local lib14a = require('read14a') local utils = require('utils') local md5 = require('md5') -local toyNames = require('default_toys') +local toys = require('default_toys') example =[[ 1. script run tnp3sim @@ -382,18 +382,22 @@ local function main(args) print( string.rep('--',20) ) print(' Gathering info') local uid = blocks[0]:sub(1,8) - local itemtype = blocks[1]:sub(1,4) + local toytype = blocks[1]:sub(1,4) local cardidLsw = blocks[1]:sub(9,16) local cardidMsw = blocks[1]:sub(17,24) + local subtype = blocks[1]:sub(25,28) - local itemtypename = toyNames[itemtype] - if itemtypename == nil then - itemtypename = toyNames[utils.SwapEndiannessStr(itemtype,16)] - end - -- Show info print( string.rep('--',20) ) - print( (' ITEM TYPE : 0x%s - %s'):format(itemtype, itemtypename) ) + + local item = toys.Find( toytype, subtype) + if item then + local itemStr = ('%s - %s (%s)'):format(item[6],item[5], item[4]) + print(' ITEM TYPE :'..itemStr ) + else + print( (' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype) ) + end + print( (' UID : 0x%s'):format(uid) ) print( (' CARDID : 0x%s %s [%s]'):format( cardidMsw,cardidLsw, From 664f658650f466eaae758bf01088bbeaeace422f Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 8 Apr 2015 15:08:05 -0400 Subject: [PATCH 015/132] nexwatch fix .h file + icemans mf csetblk w arg forgot to include the new nexwatch command in the header... added icemans hf mf csetblk w parameter fix --- client/cmddata.h | 1 + client/cmdhfmf.c | 23 ++++++++++++----------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/client/cmddata.h b/client/cmddata.h index 9e179b9c..57f04001 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -35,6 +35,7 @@ int CmdFSKdemodPyramid(const char *Cmd); int CmdFSKrawdemod(const char *Cmd); int CmdPSK1rawDemod(const char *Cmd); int CmdPSK2rawDemod(const char *Cmd); +int CmdPSKNexWatch(const char *Cmd); int CmdGrid(const char *Cmd); int CmdGetBitStream(const char *Cmd); int CmdHexsamples(const char *Cmd); diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 5f2e8dec..b96c9c1a 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -1499,16 +1499,16 @@ int CmdHF14AMfCSetUID(const char *Cmd) int CmdHF14AMfCSetBlk(const char *Cmd) { - uint8_t uid[8] = {0x00}; uint8_t memBlock[16] = {0x00}; uint8_t blockNo = 0; + bool wipeCard = FALSE; int res; if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') { - PrintAndLog("Usage: hf mf csetblk "); + PrintAndLog("Usage: hf mf csetblk [w]"); PrintAndLog("sample: hf mf csetblk 1 01020304050607080910111213141516"); - PrintAndLog("Set block data for magic Chinese card (only works with!!!)"); - PrintAndLog("If you want wipe card then add 'w' into command line. \n"); + PrintAndLog("Set block data for magic Chinese card (only works with such cards)"); + PrintAndLog("If you also want wipe the card then add 'w' at the end of the command line"); return 0; } @@ -1519,14 +1519,15 @@ int CmdHF14AMfCSetBlk(const char *Cmd) return 1; } + char ctmp = param_getchar(Cmd, 2); + wipeCard = (ctmp == 'w' || ctmp == 'W'); PrintAndLog("--block number:%2d data:%s", blockNo, sprint_hex(memBlock, 16)); - res = mfCSetBlock(blockNo, memBlock, uid, 0, CSETBLOCK_SINGLE_OPER); + res = mfCSetBlock(blockNo, memBlock, NULL, wipeCard, CSETBLOCK_SINGLE_OPER); if (res) { - PrintAndLog("Can't write block. error=%d", res); - return 1; - } - + PrintAndLog("Can't write block. error=%d", res); + return 1; + } return 0; } @@ -1637,7 +1638,7 @@ int CmdHF14AMfCGetBlk(const char *Cmd) { if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') { PrintAndLog("Usage: hf mf cgetblk "); PrintAndLog("sample: hf mf cgetblk 1"); - PrintAndLog("Get block data from magic Chinese card (only works with!!!)\n"); + PrintAndLog("Get block data from magic Chinese card (only works with such cards)\n"); return 0; } @@ -1664,7 +1665,7 @@ int CmdHF14AMfCGetSc(const char *Cmd) { if (strlen(Cmd) < 1 || param_getchar(Cmd, 0) == 'h') { PrintAndLog("Usage: hf mf cgetsc "); PrintAndLog("sample: hf mf cgetsc 0"); - PrintAndLog("Get sector data from magic Chinese card (only works with!!!)\n"); + PrintAndLog("Get sector data from magic Chinese card (only works with such cards)\n"); return 0; } From 8e0cf02308a732bf5ddf5bd9263e2895905a9d59 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 10 Apr 2015 00:06:59 -0400 Subject: [PATCH 016/132] minor change to lf em4x menu & iceman script... ...updates --- client/cmdlfem4x.c | 4 +-- client/lualibs/default_toys.lua | 17 ++++++---- client/scripts/tnp3clone.lua | 8 +++++ client/scripts/tnp3dump.lua | 55 ++++++++++----------------------- 4 files changed, 38 insertions(+), 46 deletions(-) diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index 614624a6..c492a64d 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -604,11 +604,11 @@ static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, {"em410xdemod", CmdEMdemodASK, 0, "[findone] -- Extract ID from EM410x tag (option 0 for continuous loop, 1 for only 1 tag)"}, - {"em410xread", CmdEM410xRead, 1, "[clock rate] -- Extract ID from EM410x tag"}, + {"em410xread", CmdEM410xRead, 1, "[clock rate] -- Extract ID from EM410x tag in GraphBuffer"}, {"em410xsim", CmdEM410xSim, 0, " -- Simulate EM410x tag"}, {"em410xwatch", CmdEM410xWatch, 0, "['h'] -- Watches for EM410x 125/134 kHz tags (option 'h' for 134)"}, {"em410xspoof", CmdEM410xWatchnSpoof, 0, "['h'] --- Watches for EM410x 125/134 kHz tags, and replays them. (option 'h' for 134)" }, - {"em410xwrite", CmdEM410xWrite, 1, " <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"}, + {"em410xwrite", CmdEM410xWrite, 0, " <'0' T5555> <'1' T55x7> [clock rate] -- Write EM410x UID to T5555(Q5) or T55x7 tag, optionally setting clock rate"}, {"em4x50read", CmdEM4x50Read, 1, "Extract data from EM4x50 tag"}, {"readword", CmdReadWord, 1, " -- Read EM4xxx word data"}, {"readwordPWD", CmdReadWordPWD, 1, " -- Read EM4xxx word data in password mode"}, diff --git a/client/lualibs/default_toys.lua b/client/lualibs/default_toys.lua index 64eed9b3..f34d510d 100644 --- a/client/lualibs/default_toys.lua +++ b/client/lualibs/default_toys.lua @@ -45,6 +45,7 @@ local _names = { --{"26", "1a00", "0030", "life", "regular", "Elite Stealth Elf"}, --{"26", "1a00", "0030", "life", "regular", "Dark Stealth Elf"}, {"27", "1b00", "0030", "life", "regular", "Stump Smash"}, +{"27", "1b00", "0118", "life", "regular", "Stump Smash"}, --{"27", "1b00", "0030", "life", "regular", "Autumn Stump Smash"}, {"28", "1c00", "0030", "magic", "regular", "Dark Spyro"}, --{"28", "1c00", "0030", "magic", "regular", "Elite Spyro"}, @@ -70,7 +71,7 @@ local _names = { --{"107", "6b00", "0030", "water", "giant", "Admiral Thumpback"}, {"108", "6c00", "0030", "magic", "giant", "Pop Fizz"}, --{"108", "6c00", "0030", "magic", "giant", "Hoppity Pop Fizz"}, ---{"108", "6c00", "0030", "magic", "giant", "Love Potion Pop Fizz"}, +{"108", "6c00", "023c", "magic", "giant", "Love Potion Pop Fizz"}, --{"108", "6c00", "0030", "magic", "giant", "Punch Pop Fizz"}, {"109", "6d00", "0030", "magic", "giant", "Nin Jini"}, {"110", "6e00", "0030", "tech", "giant", "Bouncer"}, @@ -174,8 +175,8 @@ local _names = { {"304", "3001", "0030", "none", "location", "Volcanic Vault"}, {"305", "3101", "0030", "none", "location", "Mirror Of Mystery"}, {"306", "3201", "0030", "none", "location", "Nightmare Express"}, -{"307", "3301", "0030", "none", "location", "Sunscraper Spire"}, -{"308", "3401", "0030", "none", "location", "Midnight Museum"}, +{"307", "3301", "0030", "light", "location", "Sunscraper Spire"}, +{"308", "3401", "0030", "dark", "location", "Midnight Museum"}, {"404", "9401", "0030", "earth", "legendary","Bash"}, {"416", "a001", "0030", "magic", "legendary", "Spyro"}, @@ -219,7 +220,7 @@ local _names = { {"461", "cd01", "0030", "fire", "regular", "Torch"}, {"462", "ce01", "0030", "water", "trapmaster", "Snap Shot"}, {"462", "ce01", "0234", "water", "trapmaster", "Dark Snap Shot"}, ---, "water", "trapmaster", "Instant Snap Shot"}, +{"462", "6c00", "023c", "water", "trapmaster", "Instant Snap Shot"}, --, "water", "trapmaster", "Merry Snap Shot"}, {"463", "cf01", "0030", "water", "trapmaster", "Lob Star"}, {"463", "cf01", "0234", "water", "trapmaster", "Winterfest Lob Star"}, @@ -245,6 +246,7 @@ local _names = { {"475", "db01", "0030", "life", "trapmaster", "Tuff Luck"}, --{"475", "db01", "0234", "life", "trapmaster", "Special Tuff Luck"}, {"476", "dc01", "0030", "life", "regular", "Food Fight"}, +{"476", "dc01", "0612", "life", "regular", "LightCore Food Fight"}, --{"476", "dc01", "0030", "life", "regular", "Dark Food Fight"}, --{"476", "dc01", "0030", "life", "regular", "Frosted Food Fight"}, --{"476", "dc01", "0030", "life", "regular", "Instant Food Fight"}, @@ -255,6 +257,7 @@ local _names = { --{"479", "df01", "0234", "undead", "trapmaster", "Special Short Cut"}, {"480", "e001", "0030", "undead", "regular", "Bat Spin"}, {"481", "e101", "0030", "undead", "regular", "Funny Bone"}, +{"481", "e101", "0612", "undead", "regular", "LightCore Funny Bone"}, --{"481", "e101", "0030", "undead", "regular", "Fortune Funny Bone"}, {"482", "e201", "0030", "light", "trapmaster", "Knight light"}, --{"482", "e201", "0234", "light", "trapmaster", "Special Knight light"}, @@ -292,6 +295,7 @@ local _names = { --{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Dark Slobber Tooth"}, --{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Sundae Slobber Tooth"}, {"3003", "bb0b", "0030", "earth", "SWAPFORCE", "Scorp"}, +{"3004", "bc0b", "0030", "fire", "SWAPFORCE", "Fryno"}, {"3004", "bc0b", "0138", "fire", "SWAPFORCE", "Hog Wild Fryno"}, --{"3004", "bc0b", "0138", "fire", "SWAPFORCE", "Flip flop Fryno"}, {"3005", "bd0b", "0030", "fire", "SWAPFORCE", "Smolderdash"}, @@ -314,9 +318,10 @@ local _names = { } local function find( main, sub) - + main = main:lower() + sub = sub:lower() for k, v in pairs(_names) do - if ( v[2] == main and v[3] == sub) then + if ( v[2]:lower() == main and v[3]:lower() == sub) then return v end end diff --git a/client/scripts/tnp3clone.lua b/client/scripts/tnp3clone.lua index cad1ab70..6c4a148c 100644 --- a/client/scripts/tnp3clone.lua +++ b/client/scripts/tnp3clone.lua @@ -25,6 +25,14 @@ Arguments: -h : this help -t : toytype id, 4hex symbols. -s : subtype id, 4hex symbols + + For fun, try the following subtype id: + 0612 - Lightcore + 0118 - Series 1 + 0138 - Series 2 + 0234 - Special + 023c - Special + ]] diff --git a/client/scripts/tnp3dump.lua b/client/scripts/tnp3dump.lua index f93f9728..cd547e8a 100644 --- a/client/scripts/tnp3dump.lua +++ b/client/scripts/tnp3dump.lua @@ -30,9 +30,7 @@ Arguments: -p : Use the precalc to find all keys -o : filename for the saved dumps ]] - -local HASHCONSTANT = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20' - +local RANDOM = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20' local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds local DEBUG = false -- the debug flag local numBlocks = 64 @@ -96,16 +94,6 @@ local function waitCmd() return nil, "No response from device" end -local function computeCrc16(s) - local hash = core.crc16(utils.ConvertHexToAscii(s)) - return hash -end - -local function reverseCrcBytes(crc) - crc2 = crc:sub(3,4)..crc:sub(1,2) - return tonumber(crc2,16) -end - local function main(args) print( string.rep('--',20) ) @@ -146,10 +134,6 @@ local function main(args) core.clearCommandBuffer() - if 0x01 ~= result.sak then -- NXP MIFARE TNP3xxx - -- return oops('This is not a TNP3xxx tag. aborting.') - end - -- Show tag info print((' Found tag %s'):format(result.name)) @@ -189,6 +173,8 @@ local function main(args) local block1, err = waitCmd() if err then return oops(err) end + local tmpHash = block0..block1..'%02x'..RANDOM + local key local pos = 0 local blockNo @@ -221,20 +207,16 @@ local function main(args) -- Block 0-7 not encrypted blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) else - local base = ('%s%s%02x%s'):format(block0, block1, blockNo, HASHCONSTANT) - local baseStr = utils.ConvertHexToAscii(base) - local md5hash = md5.sumhexa(baseStr) - local aestest = core.aes(md5hash, blockdata) - - local hex = utils.ConvertAsciiToBytes(aestest) - hex = utils.ConvertBytesToHex(hex) - -- blocks with zero not encrypted. if string.find(blockdata, '^0+$') then blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) else - blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,hex) - io.write( blockNo..',') + local baseStr = utils.ConvertHexToAscii(tmpHash:format(blockNo)) + local key = md5.sumhexa(baseStr) + local aestest = core.aes128_decrypt(key, blockdata) + local hex = utils.ConvertAsciiToBytes(aestest) + hex = utils.ConvertBytesToHex(hex) + blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,hex) end end else @@ -258,11 +240,10 @@ local function main(args) emldata = emldata..slice..'\n' for c in (str):gmatch('.') do bindata[#bindata+1] = c - end + end end print( string.rep('--',20) ) - local uid = block0:sub(1,8) local toytype = block1:sub(1,4) @@ -273,26 +254,24 @@ local function main(args) -- Write dump to files if not DEBUG then - local foo = dumplib.SaveAsBinary(bindata, outputTemplate..'_uid_'..uid..'.bin') + local foo = dumplib.SaveAsBinary(bindata, outputTemplate..'-'..uid..'.bin') print(("Wrote a BIN dump to: %s"):format(foo)) - local bar = dumplib.SaveAsText(emldata, outputTemplate..'_uid_'..uid..'.eml') + local bar = dumplib.SaveAsText(emldata, outputTemplate..'-'..uid..'.eml') print(("Wrote a EML dump to: %s"):format(bar)) end + + print( string.rep('--',20) ) + -- Show info local item = toys.Find(toytype, subtype) if item then - local itemStr = ('%s - %s (%s)'):format(item[6],item[5], item[4]) - print(' ITEM TYPE : '..itemStr ) + print((' ITEM TYPE : %s - %s (%s)'):format(item[6],item[5], item[4]) ) else print((' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype)) end - - -- Show info - print( (' Alter ego / traptype : 0x%s'):format(traptype) ) + print( (' UID : 0x%s'):format(uid) ) print( (' CARDID : 0x%s'):format(cardid ) ) - print( string.rep('--',20) ) - end main(args) \ No newline at end of file From 0e6c7336b09102432a728796cf4903efc6d3ec5b Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Thu, 23 Apr 2015 09:50:44 +0200 Subject: [PATCH 017/132] Fixed issue with dumping iclass tags > 2KB in size --- client/cmdhficlass.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index 44b074b3..b8337196 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -345,7 +345,7 @@ int CmdHFiClassReader_Dump(const char *Cmd) if(dataLength > 0) { PrintAndLog("Got %d bytes data (total so far %d)" ,dataLength,iclass_datalen); - memcpy(iclass_data, resp.d.asBytes,dataLength); + memcpy(iclass_data+iclass_datalen, resp.d.asBytes,dataLength); iclass_datalen += dataLength; }else {//Last transfer, datalength 0 means the dump is finished From 4745afb647c96a80f3f088f2afebf9686499680d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 28 Apr 2015 15:35:23 -0400 Subject: [PATCH 018/132] Iceman's Issue #96 fix --- client/cmdhf14a.c | 49 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 40 insertions(+), 9 deletions(-) diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index d36ebb8b..200c9dcd 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -152,18 +152,43 @@ int CmdHF14AReader(const char *Cmd) return 0; } - PrintAndLog("ATQA : %02x %02x", card.atqa[1], card.atqa[0]); - PrintAndLog(" UID : %s", sprint_hex(card.uid, card.uidlen)); - PrintAndLog(" SAK : %02x [%d]", card.sak, resp.arg[0]); - - // Double & triple sized UID, can be mapped to a manufacturer. - // HACK: does this apply for Ultralight cards? - if ( card.uidlen > 4 ) { - PrintAndLog("MANUFACTURER : %s", getTagInfo(card.uid[0])); + if(select_status == 3) { + PrintAndLog("Card doesn't support standard iso14443-3 anticollision"); + PrintAndLog("ATQA : %02x %02x", card.atqa[1], card.atqa[0]); + // disconnect + c.arg[0] = 0; + c.arg[1] = 0; + c.arg[2] = 0; + SendCommand(&c); + return 0; } + PrintAndLog(" UID : %s", sprint_hex(card.uid, card.uidlen)); + PrintAndLog("ATQA : %02x %02x", card.atqa[1], card.atqa[0]); + PrintAndLog(" SAK : %02x [%d]", card.sak, resp.arg[0]); + switch (card.sak) { - case 0x00: PrintAndLog("TYPE : NXP MIFARE Ultralight | Ultralight C"); break; + case 0x00: + // check if the tag answers to GETVERSION (0x60) + c.arg[0] = ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT; + c.arg[1] = 1; + c.arg[2] = 0; + c.d.asBytes[0] = 0x60; + SendCommand(&c); + WaitForResponse(CMD_ACK,&resp); + + uint8_t version[8] = {0,0,0,0,0,0,0,0}; + memcpy(&version, resp.d.asBytes, resp.arg[0]); + uint8_t len = resp.arg[0] & 0xff; + switch ( len ){ + // todo, identify "Magic UL-C tags". // they usually have a static nonce response to 0x1A command. + // UL-EV1, size, check version[6] == 0x0b (smaller) 0x0b * 4 == 48 + case 0x0A:PrintAndLog("TYPE : NXP MIFARE Ultralight EV1 %d bytes", (version[6] == 0xB) ? 48 : 128);break; + case 0x01:PrintAndLog("TYPE : NXP MIFARE Ultralight C");break; + case 0x00:PrintAndLog("TYPE : NXP MIFARE Ultralight");break; + } + + break; case 0x01: PrintAndLog("TYPE : NXP TNP3xxx Activision Game Appliance"); break; case 0x04: PrintAndLog("TYPE : NXP MIFARE (various !DESFire !DESFire EV1)"); break; case 0x08: PrintAndLog("TYPE : NXP MIFARE CLASSIC 1k | Plus 2k SL1"); break; @@ -180,6 +205,12 @@ int CmdHF14AReader(const char *Cmd) default: ; } + // Double & triple sized UID, can be mapped to a manufacturer. + // HACK: does this apply for Ultralight cards? + if ( card.uidlen > 4 ) { + PrintAndLog("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 From e9b8d0dd6edea3ecac7d663024d38ad549c62f42 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 28 Apr 2015 15:43:58 -0400 Subject: [PATCH 019/132] Iceman's mf sim 7bt UID fix from #97 --- armsrc/iso14443a.c | 1 + 1 file changed, 1 insertion(+) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index ac839cfd..64bbcbf5 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -2270,6 +2270,7 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * if (_7BUID) { rATQA[0] = 0x44; rUIDBCC1[0] = 0x88; + rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3]; rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; } From bdfb62b405a3588e4ce72e02c5e6cee7b977efdb Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 28 Apr 2015 15:53:07 -0400 Subject: [PATCH 020/132] Iceman's script aes fix #93 Thanks Iceman (note I did not have a tag to double test this one. :) --- client/scripting.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/scripting.c b/client/scripting.c index 0ccdeeec..d7f51c23 100644 --- a/client/scripting.c +++ b/client/scripting.c @@ -261,7 +261,7 @@ static int l_aes(lua_State *L) aes_context ctx; aes_init(&ctx); - aes_setkey_enc(&ctx,(const unsigned char *)p_key,128); + aes_setkey_dec(&ctx, aes_key, 128); aes_crypt_cbc(&ctx,AES_DECRYPT,sizeof(indata), iv, indata,outdata ); //Push decrypted array as a string lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); From b0c76dd2cfd63d8a632637166a16f5f0e31a5563 Mon Sep 17 00:00:00 2001 From: Drewgoo Date: Tue, 28 Apr 2015 22:47:49 -0600 Subject: [PATCH 021/132] Update README.txt typo --- README.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.txt b/README.txt index cb2c7f3c..1a4ddb6d 100644 --- a/README.txt +++ b/README.txt @@ -40,7 +40,7 @@ your operating system. Please refer to the Wiki for details. OBTAINING HARDWARE: -The Proxmark 3 is available for purcahse (assembled and tested) from the +The Proxmark 3 is available for purchase (assembled and tested) from the following locations: * http://proxmark3.com/ From f168b2633b28e52e8ca08ace5f3e62f1767d9df2 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 29 Apr 2015 18:27:31 -0400 Subject: [PATCH 022/132] MF Ultralight - Iceman's updates + mine Beginning of Ultralight additions. detection of Ultralight Types added dump command now auto detects type can authenticate Ultralight C --- armsrc/appmain.c | 15 +- armsrc/apps.h | 3 +- armsrc/des.c | 39 ++ armsrc/des.h | 3 + armsrc/mifarecmd.c | 416 ++++++++++++++-------- armsrc/mifareutil.c | 300 ++++++++-------- armsrc/mifareutil.h | 44 +-- client/cmdhfmfu.c | 692 +++++++++++++++++++++++++++--------- client/cmdhfmfu.h | 6 + client/lualibs/commands.lua | 20 +- include/usb_cmd.h | 20 +- 11 files changed, 1040 insertions(+), 518 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 6e0b58b3..128f4063 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -738,7 +738,7 @@ void UsbPacketReceived(uint8_t *packet, int len) ReaderHitag((hitag_function)c->arg[0],(hitag_data*)c->d.asBytes); break; #endif - + #ifdef WITH_ISO15693 case CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693: AcquireRawAdcSamplesIso15693(); @@ -818,13 +818,13 @@ void UsbPacketReceived(uint8_t *packet, int len) break; case CMD_READER_MIFARE: - ReaderMifare(c->arg[0]); + ReaderMifare(c->arg[0]); break; case CMD_MIFARE_READBL: MifareReadBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; case CMD_MIFAREU_READBL: - MifareUReadBlock(c->arg[0],c->d.asBytes); + MifareUReadBlock(c->arg[0],c->arg[1], c->d.asBytes); break; case CMD_MIFAREUC_AUTH1: MifareUC_Auth1(c->arg[0],c->d.asBytes); @@ -838,6 +838,9 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_MIFAREUC_READCARD: MifareUReadCard(c->arg[0], c->arg[1], c->d.asBytes); break; + case CMD_MIFAREUC_SETPWD: + MifareUSetPwd(c->arg[0], c->d.asBytes); + break; case CMD_MIFARE_READSC: MifareReadSector(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; @@ -846,10 +849,10 @@ void UsbPacketReceived(uint8_t *packet, int len) break; case CMD_MIFAREU_WRITEBL_COMPAT: MifareUWriteBlock(c->arg[0], c->d.asBytes); - break; + break; case CMD_MIFAREU_WRITEBL: - MifareUWriteBlock_Special(c->arg[0], c->d.asBytes); - break; + MifareUWriteBlock_Special(c->arg[0], c->d.asBytes); + break; case CMD_MIFARE_NESTED: MifareNested(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; diff --git a/armsrc/apps.h b/armsrc/apps.h index 928a3075..7e4aa5e1 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -165,7 +165,7 @@ void EPA_PACE_Collect_Nonce(UsbCommand * c); void ReaderMifare(bool first_try); int32_t dist_nt(uint32_t nt1, uint32_t nt2); void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *data); -void MifareUReadBlock(uint8_t arg0,uint8_t *datain); +void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareUC_Auth1(uint8_t arg0, uint8_t *datain); void MifareUC_Auth2(uint32_t arg0, uint8_t *datain); void MifareUReadCard(uint8_t arg0, int Pages, uint8_t *datain); @@ -184,6 +184,7 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); // Work with "magic Chinese" card void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); void MifareCIdent(); // is "magic chinese" card? +void MifareUSetPwd(uint8_t arg0, uint8_t *datain); //desfire void Mifare_DES_Auth1(uint8_t arg0,uint8_t *datain); diff --git a/armsrc/des.c b/armsrc/des.c index 0a27503e..dbe62da9 100644 --- a/armsrc/des.c +++ b/armsrc/des.c @@ -378,6 +378,45 @@ void tdes_dec(void* out, void* in, const uint8_t* key){ des_dec(out, out, (uint8_t*)key + 0); } +void tdes_2key_enc(void* out, const void* in, size_t length, const void* key){ + + if( length % 8 ) return; + + uint8_t* tin = (uint8_t*) in; + uint8_t* tout = (uint8_t*) out; + + while( length > 0 ) + { + des_enc(tout, tin, (uint8_t*)key + 0); + des_dec(tout, tout, (uint8_t*)key + 8); + des_enc(tout, tout, (uint8_t*)key + 0); + + tin += 8; + tout += 8; + length -= 8; + } +} + +void tdes_2key_dec(void* out, const void* in, size_t length, const void* key){ + + if( length % 8 ) return; + + uint8_t* tin = (uint8_t*) in; + uint8_t* tout = (uint8_t*) out; + + while( length > 0 ) + { + des_dec(tout, tin, (uint8_t*)key + 0); + des_enc(tout, tout, (uint8_t*)key + 8); + des_dec(tout, tout, (uint8_t*)key + 0); + + tin += 8; + tout += 8; + length -= 8; + } +} + + /******************************************************************************/ diff --git a/armsrc/des.h b/armsrc/des.h index 652886fd..cc1d59b0 100644 --- a/armsrc/des.h +++ b/armsrc/des.h @@ -97,6 +97,9 @@ void tdes_enc(void* out, const void* in, const void* key); */ void tdes_dec(void* out, const void* in, const void* key); + void tdes_2key_enc(void* out, const void* in, size_t length, const void* key); + void tdes_2key_dec(void* out, const void* in, size_t length, const void* key); + #endif /*DES_H_*/ // Copied from des.h in desfire imp. diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index a16cbf16..3d5dcdef 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -17,8 +17,15 @@ #include "apps.h" #include "util.h" +#include "des.h" #include "crc.h" +// the block number for the ISO14443-4 PCB +uint8_t pcb_blocknum = 0; +// Deselect card by sending a s-block. the crc is precalced for speed +static uint8_t deselect_cmd[] = {0xc2,0xe0,0xb4}; + + //----------------------------------------------------------------------------- // Select, Authenticate, Read a MIFARE tag. // read block @@ -86,111 +93,164 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } - void MifareUC_Auth1(uint8_t arg0, uint8_t *datain){ - byte_t isOK = 0; byte_t dataoutbuf[16] = {0x00}; uint8_t uid[10] = {0x00}; - uint32_t cuid; + uint32_t cuid = 0x00; - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); if(!iso14443a_select_card(uid, NULL, &cuid)) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Can't select card"); - //OnError(0); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); + OnError(0); return; }; - if(mifare_ultra_auth1(cuid, dataoutbuf)){ - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Authentication part1: Fail."); - //OnError(1); + if(mifare_ultra_auth1(dataoutbuf)){ + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part1: Fail."); + OnError(1); return; } - isOK = 1; - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) - DbpString("AUTH 1 FINISHED"); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 1 FINISHED"); - cmd_send(CMD_ACK,isOK,cuid,0,dataoutbuf,11); + cmd_send(CMD_ACK,1,cuid,0,dataoutbuf,11); LEDsoff(); } void MifareUC_Auth2(uint32_t arg0, uint8_t *datain){ - uint32_t cuid = arg0; uint8_t key[16] = {0x00}; - byte_t isOK = 0; byte_t dataoutbuf[16] = {0x00}; memcpy(key, datain, 16); - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - if(mifare_ultra_auth2(cuid, key, dataoutbuf)){ - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Authentication part2: Fail..."); - //OnError(1); + if(mifare_ultra_auth2(key, dataoutbuf)){ + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part2: Fail..."); + OnError(1); return; } - isOK = 1; - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) - DbpString("AUTH 2 FINISHED"); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 2 FINISHED"); - cmd_send(CMD_ACK,isOK,0,0,dataoutbuf,11); + cmd_send(CMD_ACK,1,0,0,dataoutbuf,11); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } -void MifareUReadBlock(uint8_t arg0,uint8_t *datain) +void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; byte_t dataout[16] = {0x00}; uint8_t uid[10] = {0x00}; - uint32_t cuid; - - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); - + uint8_t key[16] = {0x00}; + bool usePwd = (arg1 == 1); + + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - - int len = iso14443a_select_card(uid, NULL, &cuid); + + int len = iso14443a_select_card(uid, NULL, NULL); if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); - //OnError(1); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%02X)",len); + OnError(1); return; - }; - - len = mifare_ultra_readblock(cuid, blockNo, dataout); - if(len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block error"); - //OnError(2); - return; - }; - - len = mifare_ultra_halt(cuid); - if(len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); - //OnError(3); - return; - }; + } + + // authenticate here. + if ( usePwd ) { + + memcpy(key, datain, 16); + + // Dbprintf("KEY: %02x %02x %02x %02x %02x %02x %02x %02x", key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7] ); + // Dbprintf("KEY: %02x %02x %02x %02x %02x %02x %02x %02x", key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15] ); + + uint8_t a[8] = {1,1,1,1,1,1,1,1 }; + uint8_t b[8] = {0x00}; + uint8_t enc_b[8] = {0x00}; + uint8_t ab[16] = {0x00}; + uint8_t enc_ab[16] = {0x00}; + uint8_t enc_key[8] = {0x00}; - cmd_send(CMD_ACK,1,0,0,dataout,16); + uint16_t len; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; + + len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); + if (len != 11) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + OnError(1); + return; + } + + // tag nonce. + memcpy(enc_b,receivedAnswer+1,8); + + // decrypt nonce. + tdes_2key_dec(b, enc_b, 8, key ); + + Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x", enc_b[0],enc_b[1],enc_b[2],enc_b[3],enc_b[4],enc_b[5],enc_b[6],enc_b[7] ); + Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x", b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7] ); + rol(b,8); + + memcpy(ab ,a,8); + memcpy(ab+8,b,8); + + Dbprintf("AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[0],ab[1],ab[2],ab[3],ab[4],ab[5],ab[6],ab[7] ); + Dbprintf("AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[8],ab[9],ab[10],ab[11],ab[12],ab[13],ab[14],ab[15] ); + + // encrypt + tdes_2key_enc(enc_ab, ab, 16, key); + + Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", enc_ab[0],enc_ab[1],enc_ab[2],enc_ab[3],enc_ab[4],enc_ab[5],enc_ab[6],enc_ab[7] ); + Dbprintf("e_enc_ab: %02x %02x %02x %02x %02x %02x %02x %02x", enc_ab[8],enc_ab[9],enc_ab[10],enc_ab[11],enc_ab[12],enc_ab[13],enc_ab[14],enc_ab[15] ); + + len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, enc_ab, receivedAnswer, receivedAnswerPar, NULL); + if (len != 11) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + OnError(1); + return; + } + + // the tags' encryption of our nonce, A. + memcpy(enc_key, receivedAnswer+1, 8); + + // clear B. + memset(b, 0x00, 8); + + // decrypt + tdes_2key_dec(b, enc_key, 8, key ); + if ( memcmp(a, b, 8) == 0 ) + Dbprintf("Verified key"); + else + Dbprintf("failed authentication"); + + Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x", a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7] ); + Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x", b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7] ); + } + + if( mifare_ultra_readblock(blockNo, dataout) ) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block error"); + OnError(2); + return; + } + + if( mifare_ultra_halt() ) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); + OnError(3); + return; + } + + cmd_send(CMD_ACK,1,0,0,dataout,16); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } - //----------------------------------------------------------------------------- // Select, Authenticate, Read a MIFARE tag. // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes) @@ -261,71 +321,58 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain) { - // params - uint8_t sectorNo = arg0; + // params + uint8_t sectorNo = arg0; int Pages = arg1; - int count_Pages = 0; + int countpages = 0; byte_t dataout[176] = {0x00};; - uint8_t uid[10] = {0x00}; - uint32_t cuid; + uint32_t cuid = 0x00; - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); - - if (MF_DBGLEVEL >= MF_DBG_ALL) - Dbprintf("Pages %d",Pages); - + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - int len = iso14443a_select_card(uid, NULL, &cuid); - + int len = iso14443a_select_card(NULL, NULL, &cuid); if (!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Can't select card"); - //OnError(1); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%d)",len); + OnError(1); return; } for (int i = 0; i < Pages; i++){ - len = mifare_ultra_readblock(cuid, sectorNo * 4 + i, dataout + 4 * i); + len = mifare_ultra_readblock(sectorNo * 4 + i, dataout + 4 * i); if (len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Read block %d error",i); - //OnError(2); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block %d error",i); + OnError(2); return; } else { - count_Pages++; + countpages++; } } - len = mifare_ultra_halt(cuid); + len = mifare_ultra_halt(); if (len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Halt error"); - //OnError(3); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); + OnError(3); return; } - if (MF_DBGLEVEL >= MF_DBG_ALL) { - Dbprintf("Pages read %d", count_Pages); - } + if (MF_DBGLEVEL >= MF_DBG_ALL) Dbprintf("Pages read %d", countpages); + +// len = 16*4; //64 bytes - len = 16*4; //64 bytes - // Read a UL-C - if (Pages == 44 && count_Pages > 16) - len = 176; +// if (Pages == 44 && countpages > 16) +// len = 176; + len = Pages * 4; cmd_send(CMD_ACK, 1, 0, 0, dataout, len); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } - //----------------------------------------------------------------------------- // Select, Authenticate, Write a MIFARE tag. // read block @@ -400,94 +447,144 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) { - // params - uint8_t blockNo = arg0; + uint8_t blockNo = arg0; byte_t blockdata[16] = {0x00}; - memcpy(blockdata, datain,16); - - // variables - byte_t isOK = 0; + memcpy(blockdata, datain, 16); + uint8_t uid[10] = {0x00}; - uint32_t cuid; - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); + clear_trace(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - while (true) { - if(!iso14443a_select_card(uid, NULL, &cuid)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); - break; - }; + if(!iso14443a_select_card(uid, NULL, NULL)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); + OnError(0); + return; + }; - if(mifare_ultra_writeblock(cuid, blockNo, blockdata)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); - break; - }; + if(mifare_ultra_writeblock(blockNo, blockdata)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); + OnError(0); + return; }; - if(mifare_ultra_halt(cuid)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); - break; - }; - - isOK = 1; - break; - } - - if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED"); + if(mifare_ultra_halt()) { + if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); + OnError(0); + return; + }; - cmd_send(CMD_ACK,isOK,0,0,0,0); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - LEDsoff(); + if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED"); + + cmd_send(CMD_ACK,1,0,0,0,0); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); } void MifareUWriteBlock_Special(uint8_t arg0, uint8_t *datain) { - // params uint8_t blockNo = arg0; byte_t blockdata[4] = {0x00}; memcpy(blockdata, datain,4); - // variables - byte_t isOK = 0; uint8_t uid[10] = {0x00}; - uint32_t cuid; - + + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); - LED_B_OFF(); - LED_C_OFF(); + if(!iso14443a_select_card(uid, NULL, NULL)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); + OnError(0); + return; + }; - while (true) { - if(!iso14443a_select_card(uid, NULL, &cuid)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); - break; - }; + if(mifare_ultra_special_writeblock(blockNo, blockdata)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); + OnError(0); + return; + }; - if(mifare_ultra_special_writeblock(cuid, blockNo, blockdata)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); - break; - }; + if(mifare_ultra_halt()) { + if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); + OnError(0); + return; + }; - if(mifare_ultra_halt(cuid)) { - if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); - break; - }; + if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED"); - isOK = 1; - break; - } + cmd_send(CMD_ACK,1,0,0,0,0); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); +} - if (MF_DBGLEVEL >= 2) DbpString("WRITE BLOCK FINISHED"); +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(); + clear_trace(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - cmd_send(CMD_ACK,isOK,0,0,0,0); + if(!iso14443a_select_card(NULL, NULL, NULL)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); + OnError(0); + return; + }; + + blockdata[0] = pwd[7]; + blockdata[1] = pwd[6]; + blockdata[2] = pwd[5]; + blockdata[3] = pwd[4]; + if(mifare_ultra_special_writeblock( 44, blockdata)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); + OnError(44); + return; + }; + + blockdata[0] = pwd[3]; + blockdata[1] = pwd[2]; + blockdata[2] = pwd[1]; + blockdata[3] = pwd[0]; + if(mifare_ultra_special_writeblock( 45, blockdata)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); + OnError(45); + return; + }; + + blockdata[0] = pwd[15]; + blockdata[1] = pwd[14]; + blockdata[2] = pwd[13]; + blockdata[3] = pwd[12]; + if(mifare_ultra_special_writeblock( 46, blockdata)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); + OnError(46); + return; + }; + + blockdata[0] = pwd[11]; + blockdata[1] = pwd[10]; + blockdata[2] = pwd[9]; + blockdata[3] = pwd[8]; + if(mifare_ultra_special_writeblock( 47, blockdata)) { + if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); + OnError(47); + return; + }; + + if(mifare_ultra_halt()) { + if (MF_DBGLEVEL >= 1) Dbprintf("Halt error"); + OnError(0); + return; + }; + + cmd_send(CMD_ACK,1,0,0,0,0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } @@ -1184,3 +1281,18 @@ void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain){ FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } + +void OnSuccess(){ + pcb_blocknum = 0; + ReaderTransmit(deselect_cmd, 3 , NULL); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); +} + +void OnError(uint8_t reason){ + pcb_blocknum = 0; + ReaderTransmit(deselect_cmd, 3 , NULL); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + cmd_send(CMD_ACK,0,reason,0,0,0); + LEDsoff(); +} diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index f79c2ede..b7408cf1 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -67,24 +67,24 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) { // send commands int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) { - return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing); -} - -int mifare_sendcmd_short_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[8]; - dcmd[0] = cmd; - dcmd[1] = data[0]; - dcmd[2] = data[1]; - dcmd[3] = data[2]; - dcmd[4] = data[3]; - dcmd[5] = data[4]; - AppendCrc14443a(dcmd, 6); - ReaderTransmit(dcmd, sizeof(dcmd), NULL); - int len = ReaderReceive(answer, answer_parity); - if(!len) { - if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout."); - return 2; + return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing); +} + +int mifare_sendcmd_short_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[8]; + dcmd[0] = cmd; + dcmd[1] = data[0]; + dcmd[2] = data[1]; + dcmd[3] = data[2]; + dcmd[4] = data[3]; + dcmd[5] = data[4]; + AppendCrc14443a(dcmd, 6); + ReaderTransmit(dcmd, sizeof(dcmd), NULL); + int len = ReaderReceive(answer, answer_parity); + if(!len) { + if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout."); + return 2; } return len; } @@ -106,13 +106,13 @@ int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uin if(len==1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); return 1; - } - return len; -} - -int mifare_sendcmd_shortex(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[4], ecmd[4]; + } + return len; +} + +int mifare_sendcmd_shortex(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[4], ecmd[4]; uint16_t pos, res; uint8_t par[1]; // 1 Byte parity is enough here dcmd[0] = cmd; @@ -284,24 +284,21 @@ int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blo } memcpy(blockData, receivedAnswer, 16); - return 0; -} - + return 0; +} + // mifare ultralight commands -int mifare_ultra_auth1(uint32_t uid, uint8_t *blockData){ +int mifare_ultra_auth1(uint8_t *blockData){ uint16_t len; - uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); - if (len == 1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if (len != 11) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); return 1; } - if (len != 11) - return 1; if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { Dbprintf("Auth1 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", @@ -313,20 +310,17 @@ int mifare_ultra_auth1(uint32_t uid, uint8_t *blockData){ return 0; } -int mifare_ultra_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){ +int mifare_ultra_auth2(uint8_t *key, uint8_t *blockData){ uint16_t len; - uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, key, receivedAnswer, receivedAnswerPar, NULL); - if (len == 1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if (len != 11) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); return 1; } - if (len != 11) - return 1; if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { Dbprintf("Auth2 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", @@ -338,43 +332,39 @@ int mifare_ultra_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){ return 0; } -int mifare_ultra_readblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData) -{ - uint16_t len; - uint8_t bt[2]; - uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; - +int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) +{ + uint16_t len; + uint8_t bt[2]; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - // command MIFARE_CLASSIC_READBLOCK - len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL); - if (len == 1) { - 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: card timeout. len: %x", len); - return 2; - } - - memcpy(bt, receivedAnswer + 16, 2); - AppendCrc14443a(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; -} - - -int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) -{ - // variables + len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL); + if (len == 1) { + 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: card timeout. len: %x", len); + return 2; + } + + memcpy(bt, receivedAnswer + 16, 2); + AppendCrc14443a(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; +} + + + +int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) +{ + // variables uint16_t len, i; uint32_t pos; uint8_t par[3] = {0}; // enough for 18 Bytes to send @@ -416,65 +406,65 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl return 2; } - return 0; -} - -int mifare_ultra_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData) -{ - uint16_t len; - uint8_t par[3] = {0}; // enough for 18 parity bits - uint8_t d_block[18] = {0x00}; + return 0; +} + +int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) +{ + uint16_t len; + uint8_t par[3] = {0}; // enough for 18 parity bits + uint8_t d_block[18] = {0x00}; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; + + // command MIFARE_CLASSIC_WRITEBLOCK + len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL); + + if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK + if (MF_DBGLEVEL >= MF_DBG_ERROR) + Dbprintf("Cmd Addr Error: %02x", receivedAnswer[0]); + return 1; + } + + memcpy(d_block, blockData, 16); + AppendCrc14443a(d_block, 16); + + ReaderTransmitPar(d_block, sizeof(d_block), par, NULL); + + len = ReaderReceive(receivedAnswer, receivedAnswerPar); + + if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK + if (MF_DBGLEVEL >= MF_DBG_ERROR) + Dbprintf("Cmd Data Error: %02x %d", receivedAnswer[0],len); + return 2; + } + return 0; +} + +int mifare_ultra_special_writeblock(uint8_t blockNo, uint8_t *blockData) +{ + uint16_t len; + uint8_t d_block[8] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; - - // command MIFARE_CLASSIC_WRITEBLOCK - len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL); - - if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK + + // command MIFARE_CLASSIC_WRITEBLOCK + d_block[0]= blockNo; + memcpy(d_block+1,blockData,4); + AppendCrc14443a(d_block, 6); + + len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL); + + if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Cmd Addr Error: %02x", receivedAnswer[0]); - return 1; - } - - memcpy(d_block, blockData, 16); - AppendCrc14443a(d_block, 16); - - ReaderTransmitPar(d_block, sizeof(d_block), par, NULL); - - len = ReaderReceive(receivedAnswer, receivedAnswerPar); - - if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Cmd Data Error: %02x %d", receivedAnswer[0],len); - return 2; - } - return 0; -} - -int mifare_ultra_special_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData) -{ - uint16_t len; - uint8_t d_block[8] = {0x00}; - uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; - - // command MIFARE_CLASSIC_WRITEBLOCK - d_block[0]= blockNo; - memcpy(d_block+1,blockData,4); - AppendCrc14443a(d_block, 6); - - len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL); - - if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0],len); - return 1; - } - return 0; -} - -int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid) -{ + Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0],len); + return 1; + } + return 0; +} + +int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid) +{ uint16_t len; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; @@ -486,24 +476,24 @@ int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid) return 1; } - return 0; -} - -int mifare_ultra_halt(uint32_t uid) -{ - uint16_t len; + return 0; +} + +int mifare_ultra_halt() +{ + uint16_t len; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; - - len = mifare_sendcmd_short(NULL, true, 0x50, 0x00, receivedAnswer, receivedAnswerPar, NULL); - if (len != 0) { + + len = mifare_sendcmd_short(NULL, true, 0x50, 0x00, receivedAnswer, receivedAnswerPar, NULL); + if (len != 0) { if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("halt error. response len: %x", len); - return 1; - } - return 0; -} - + Dbprintf("halt error. response len: %x", len); + return 1; + } + 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) @@ -525,9 +515,9 @@ uint8_t FirstBlockOfSector(uint8_t sectorNo) } -// work with emulator memory -void emlSetMem(uint8_t *data, int blockNum, int blocksCount) { - uint8_t* emCARD = BigBuf_get_EM_addr(); +// work with emulator memory +void emlSetMem(uint8_t *data, int blockNum, int blocksCount) { + uint8_t* emCARD = BigBuf_get_EM_addr(); memcpy(emCARD + blockNum * 16, data, blocksCount * 16); } @@ -706,4 +696,4 @@ int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){ return 0; } return 1; -} +} diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index 195afa53..ee3ae7c6 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -52,33 +52,33 @@ extern int MF_DBGLEVEL; #define cardSTATE_TO_IDLE() cardSTATE = MFEMUL_IDLE; LED_B_OFF(); LED_C_OFF(); -//functions -int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); +//functions +int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); +int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); - +int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); + 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_ultra_auth1(uint32_t cuid, uint8_t *blockData); -int mifare_ultra_auth2(uint32_t cuid, uint8_t *key, uint8_t *blockData); -int mifare_ultra_readblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData); -int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); -int mifare_ultra_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData); -int mifare_ultra_special_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData); -int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); -int mifare_ultra_halt(uint32_t uid); +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_ultra_auth1(uint8_t *blockData); +int mifare_ultra_auth2(uint8_t *key, uint8_t *blockData); +int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData); +int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); +int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData); +int mifare_ultra_special_writeblock(uint8_t blockNo, uint8_t *blockData); +int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); +int mifare_ultra_halt(); // desfire 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); int mifare_sendcmd_special2(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer,uint8_t *answer_parity, uint32_t *timing); int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData); int mifare_desfire_des_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData); - -// crypto functions -void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *receivedCmd, int len); + +// crypto functions +void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *receivedCmd, int len); void mf_crypto1_encrypt(struct Crypto1State *pcs, uint8_t *data, uint16_t len, uint8_t *par); uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data); @@ -93,7 +93,7 @@ void emlGetMem(uint8_t *data, int blockNum, int blocksCount); void emlGetMemBt(uint8_t *data, int bytePtr, int byteCount); uint64_t emlGetKey(int sectorNum, int keyType); int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum); -int emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum); -int emlCheckValBl(int blockNum); - -#endif +int emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum); +int emlCheckValBl(int blockNum); + +#endif diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 8dfb9a3b..1886fc3d 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -7,25 +7,67 @@ //----------------------------------------------------------------------------- // High frequency MIFARE ULTRALIGHT (C) commands //----------------------------------------------------------------------------- -//#include #include "loclass/des.h" #include "cmdhfmfu.h" #include "cmdhfmf.h" #include "cmdhf14a.h" +#include "mifare.h" +#define MAX_UL_BLOCKS 0x0f +#define MAX_ULC_BLOCKS 0x2f +#define MAX_ULEV1a_BLOCKS 0x0b; +#define MAX_ULEV1b_BLOCKS 0x20; -#define MAX_ULTRA_BLOCKS 0x0f -#define MAX_ULTRAC_BLOCKS 0x2f -//#define MAX_ULTRAC_BLOCKS 0x2c - - +uint8_t default_3des_keys[7][16] = { + { 0x42,0x52,0x45,0x41,0x4b,0x4d,0x45,0x49,0x46,0x59,0x4f,0x55,0x43,0x41,0x4e,0x21 },// 3des std key + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },// all zeroes + { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f },// 0x00-0x0F + { 0x49,0x45,0x4D,0x4B,0x41,0x45,0x52,0x42,0x21,0x4E,0x41,0x43,0x55,0x4F,0x59,0x46 },// NFC-key + { 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01 },// all ones + { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF },// all FF + { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF } // 11 22 33 + }; + static int CmdHelp(const char *Cmd); -int CmdHF14AMfUInfo(const char *Cmd){ +// return 1 if tag responded to 0x1A. +uint8_t requestAuthentication( uint8_t* nonce){ - uint8_t datatemp[7] = {0x00}; + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC ,2 ,0}}; + c.d.asBytes[0] = 0x1A; + c.d.asBytes[1] = 0x00; + SendCommand(&c); + UsbCommand resp; + WaitForResponse(CMD_ACK, &resp); // skip select answer. + + if ( !(resp.arg[0] & 0xff) ) + return 0; + + if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + + if ( resp.arg[0] & 0xff ) { + memcpy(nonce, resp.d.asBytes+1, 8); + return 1; + } + } + return 0; +} + +typedef enum TAGTYPE_UL { + UNKNOWN = 0x00, + UL = 0x01, + UL_C = 0x02, + UL_EV1_48 = 0x04, + UL_EV1_128 = 0x08, + UL_MAGIC = 0x11, + UL_C_MAGIC = 0x12, + MAGIC = 0x10, + UL_ERROR = 0xFF, +} TagTypeUL_t; + +uint8_t GetHF14AMfU_Type(uint8_t *data, uint8_t dataSize){ + TagTypeUL_t tagtype = UNKNOWN; uint8_t isOK = 0; - uint8_t *data = NULL; UsbCommand c = {CMD_MIFAREU_READCARD, {0, 4}}; SendCommand(&c); @@ -33,52 +75,127 @@ int CmdHF14AMfUInfo(const char *Cmd){ if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { isOK = resp.arg[0] & 0xff; - data = resp.d.asBytes; + memcpy(data, resp.d.asBytes, dataSize); if (!isOK) { PrintAndLog("Error reading from tag"); - return -1; + return UL_ERROR; } } else { PrintAndLog("Command execute timed out"); - return -1; + return UL_ERROR; } - PrintAndLog(""); - PrintAndLog("-- Mifare Ultralight / Ultralight-C Tag Information ---------"); - PrintAndLog("-------------------------------------------------------------"); + c.cmd = CMD_READER_ISO_14443a; + c.arg[0] = ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC; + c.arg[1] = 1; + c.arg[2] = 0; + c.d.asBytes[0] = 0x60; + SendCommand(&c); + WaitForResponse(CMD_ACK, &resp); + + if ( resp.arg[0] ) { + if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + uint8_t version[8] = {0,0,0,0,0,0,0,0}; + memcpy(&version, resp.d.asBytes, sizeof(version)); + uint8_t len = resp.arg[0] & 0xff; + + if ( len == 0x0A && version[6] == 0x0B ) + tagtype = UL_EV1_48; + else if ( len == 0x0A && version[6] != 0x0B ) + tagtype = UL_EV1_128; + else if ( len == 0x01 ) + tagtype = UL_C; + else if ( len == 0x00 ) + tagtype = UL; //| UL_MAGIC | UL_C_MAGIC + } + } + + // Magic UL-C, mine have a static nonce response to 0x1A command. + uint8_t nonce1[8] = {0,0,0,0,0,0,0,0}; + uint8_t nonce2[8] = {0,0,0,0,0,0,0,0}; + uint8_t status = requestAuthentication(nonce1); + if ( status ) { + requestAuthentication(nonce2); + if ( !memcmp(nonce1, nonce2, 8) ) + tagtype ^= MAGIC; + } else { + // Magic Ultralight test here - TODO + } + return tagtype; +} + +int CmdHF14AMfUInfo(const char *Cmd){ + + TagTypeUL_t tagtype = UNKNOWN; + + uint8_t datatemp[7] = {0x00}; + uint8_t data[16] = {0x00}; + + tagtype = GetHF14AMfU_Type(data, sizeof(data)); + if (tagtype == UL_ERROR) return -1; + + PrintAndLog("\n-- Tag Information ---------"); + PrintAndLog("-------------------------------------------------------------"); + switch(tagtype){ + case UNKNOWN : PrintAndLog(" TYPE : Unknown"); return 0; + case UL : PrintAndLog(" TYPE : MIFARE Ultralight");break; + case UL_C : PrintAndLog(" TYPE : MIFARE Ultralight C");break; + case UL_EV1_48 : PrintAndLog(" TYPE : MIFARE Ultralight EV1 48 bytes"); break; + case UL_EV1_128 : PrintAndLog(" TYPE : MIFARE Ultralight EV1 128 bytes"); break; + case UL_MAGIC : PrintAndLog(" TYPE : MIFARE Ultralight (MAGIC)");break; + case UL_C_MAGIC : PrintAndLog(" TYPE : MIFARE Ultralight-C (MAGIC)");break; + default : PrintAndLog(" TYPE : Unknown %x",tagtype);break; + } + // UID memcpy( datatemp, data, 3); memcpy( datatemp+3, data+4, 4); - PrintAndLog("MANUFACTURER : %s", getTagInfo(datatemp[0])); - PrintAndLog(" UID : %s ", sprint_hex(datatemp, 7)); + PrintAndLog(" UID : %s ", sprint_hex(datatemp, 7)); + PrintAndLog(" UID[0] : (Manufacturer Byte) = %02x, Manufacturer: %s", datatemp[0], getTagInfo(datatemp[0]) ); + // BBC // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; if ( data[3] == crc0 ) - PrintAndLog(" BCC0 : %02x - Ok", data[3]); + PrintAndLog(" BCC0 : %02x - Ok", data[3]); else - PrintAndLog(" BCC0 : %02x - crc should be %02x", data[3], crc0); + PrintAndLog(" BCC0 : %02x - crc should be %02x", data[3], crc0); int crc1 = data[4] ^ data[5] ^ data[6] ^data[7]; if ( data[8] == crc1 ) - PrintAndLog(" BCC1 : %02x - Ok", data[8]); + PrintAndLog(" BCC1 : %02x - Ok", data[8]); else - PrintAndLog(" BCC1 : %02x - crc should be %02x", data[8], crc1 ); + PrintAndLog(" BCC1 : %02x - crc should be %02x", data[8], crc1 ); - PrintAndLog(" Internal : %s ", sprint_hex(data + 9, 1)); + PrintAndLog(" Internal : %s ", sprint_hex(data + 9, 1)); memcpy(datatemp, data+10, 2); - PrintAndLog(" Lock : %s - %s", sprint_hex(datatemp, 2),printBits( 2, &datatemp) ); - PrintAndLog(" OneTimePad : %s ", sprint_hex(data + 3*4, 4)); + PrintAndLog(" Lock : %s - %s", sprint_hex(datatemp, 2),printBits( 2, &datatemp) ); + PrintAndLog("OneTimePad : %s ", sprint_hex(data + 3*4, 4)); PrintAndLog(""); - - int len = CmdHF14AMfucAuth("K 0"); -// PrintAndLog("CODE: %d",len); - PrintAndLog("Seems to be a Ultralight %s", (len==0) ? "-C" :""); + + PrintAndLog("--- "); + if ((tagtype & UL_C)){ + + PrintAndLog("Trying some default 3des keys"); + uint8_t *key; + + for (uint8_t i = 0; i < 5; ++i ){ + key = default_3des_keys[i]; + if (try3DesAuthentication(key)){ + PrintAndLog("Found default 3des key: %s", sprint_hex(key,16)); + return 0; + } + } + } + else if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { + //********** TODO ******************************** + //PrintAndLog("Trying some known EV1 passwords."); + } return 0; } @@ -105,7 +222,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ blockNo = param_get8(Cmd, 0); - if (blockNo > MAX_ULTRA_BLOCKS){ + if (blockNo > MAX_UL_BLOCKS){ PrintAndLog("Error: Maximum number of blocks is 15 for Ultralight Cards!"); return 1; } @@ -155,40 +272,41 @@ int CmdHF14AMfUWrBl(const char *Cmd){ // Mifare Ultralight Read Single Block // int CmdHF14AMfURdBl(const char *Cmd){ - - uint8_t blockNo = -1; + UsbCommand resp; + uint8_t blockNo = -1; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') { PrintAndLog("Usage: hf mfu rdbl "); PrintAndLog(" sample: hfu mfu rdbl 0"); return 0; - } - + } + blockNo = param_get8(Cmd, 0); - if (blockNo > MAX_ULTRA_BLOCKS){ - PrintAndLog("Error: Maximum number of blocks is 15 for Ultralight Cards!"); - return 1; + if (blockNo > MAX_UL_BLOCKS){ + PrintAndLog("Error: Maximum number of blocks is 15 for Ultralight"); + return 1; } - - PrintAndLog("--block no:0x%02X (%d)", (int)blockNo, blockNo); + UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; SendCommand(&c); - UsbCommand resp; + if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - uint8_t * data = resp.d.asBytes; - - PrintAndLog("isOk: %02x", isOK); - - if (isOK) - PrintAndLog("Data: %s", sprint_hex(data, 4)); + uint8_t isOK = resp.arg[0] & 0xff; + if (isOK) { + uint8_t *data = resp.d.asBytes; + PrintAndLog("Block: %0d (0x%02X) [ %s]", (int)blockNo, blockNo, sprint_hex(data, 4)); + } + else { + PrintAndLog("Failed reading block: (%02x)", isOK); + } } else { - PrintAndLog("Command execute timeout"); + PrintAndLog("Command execute time-out"); } + return 0; } @@ -224,7 +342,7 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLog("Reads all pages from Mifare Ultralight or Ultralight-C tag."); PrintAndLog("It saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("Usage: hf mfu dump "); - PrintAndLog(" optional cardtype c == Ultralight-C, if not defaults to Ultralight"); + PrintAndLog(" optional cardtype c == Ultralight-C, Defaults to Ultralight"); PrintAndLog(" sample: hf mfu dump"); PrintAndLog(" : hf mfu dump myfile"); PrintAndLog(" : hf mfu dump c myfile"); @@ -234,7 +352,36 @@ int CmdHF14AMfUDump(const char *Cmd){ // UL or UL-C? Pages = (cmdp == 'c' || cmdp == 'C') ? 44 : 16; - PrintAndLog("Dumping Ultralight%s Card Data...", (Pages ==16)?"":"-C"); + uint8_t data2[16] = {0x00}; + TagTypeUL_t tagtype = GetHF14AMfU_Type(data2, sizeof(data2)); + switch(tagtype){ + case UL_C: + Pages = 44; + PrintAndLog("Dumping Ultralight_C Card Data..."); + break; + case UL_EV1_48: + Pages = 18; + PrintAndLog("Dumping Ultralight EV1_48 Card Data..."); + break; + case UL_EV1_128: + Pages = 32; + PrintAndLog("Dumping Ultralight EV1_128 Card Data..."); + break; + case UL_MAGIC: + Pages = 16; + PrintAndLog("Dumping Ultralight (Magic) Card Data..."); + break; + case UL_C_MAGIC: + Pages = 44; + PrintAndLog("Dumping Ultralight_C (Magic) Card Data..."); + break; + case UL: + default: + Pages = 16; + PrintAndLog("Dumping Ultralight Card Data..."); + break; + } + //PrintAndLog("Dumping Ultralight%s Card Data...", (Pages ==16)?"":"-C"); UsbCommand c = {CMD_MIFAREU_READCARD, {BlockNo,Pages}}; SendCommand(&c); @@ -248,7 +395,7 @@ int CmdHF14AMfUDump(const char *Cmd){ } data = resp.d.asBytes; } else { - PrintAndLog("Command execute timeout"); + PrintAndLog("Command execute time-out"); return 0; } @@ -376,130 +523,107 @@ void rol (uint8_t *data, const size_t len){ // int CmdHF14AMfucAuth(const char *Cmd){ - uint8_t default_keys[5][16] = { - { 0x42,0x52,0x45,0x41,0x4b,0x4d,0x45,0x49,0x46,0x59,0x4f,0x55,0x43,0x41,0x4e,0x21 },// 3des std key - { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },// all zeroes - { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f },// 0x00-0x0F - { 0x49,0x45,0x4D,0x4B,0x41,0x45,0x52,0x42,0x21,0x4E,0x41,0x43,0x55,0x4F,0x59,0x46 },// NFC-key - { 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01 } // all ones - }; - - char cmdp = param_getchar(Cmd, 0); - uint8_t keyNo = 0; bool errors = false; + + char cmdp = param_getchar(Cmd, 0); + //Change key to user defined one if (cmdp == 'k' || cmdp == 'K'){ keyNo = param_get8(Cmd, 1); - if(keyNo >= 4) errors = true; + if(keyNo > 6) + errors = true; } - if (cmdp == 'h' || cmdp == 'H') { + if (cmdp == 'h' || cmdp == 'H') errors = true; - } - + if (errors) { PrintAndLog("Usage: hf mfu cauth k "); PrintAndLog(" 0 (default): 3DES standard key"); - PrintAndLog(" 1 : all zeros key"); + PrintAndLog(" 1 : all 0x00 key"); PrintAndLog(" 2 : 0x00-0x0F key"); PrintAndLog(" 3 : nfc key"); - PrintAndLog(" 4 : all ones key"); - PrintAndLog(" sample : hf mfu cauth k"); + PrintAndLog(" 4 : all 0x01 key"); + PrintAndLog(" 5 : all 0xff key"); + PrintAndLog(" 6 : 0x00-0xFF key"); + PrintAndLog("\n sample : hf mfu cauth k"); PrintAndLog(" : hf mfu cauth k 3"); return 0; } - uint8_t random_a[8] = { 1,1,1,1,1,1,1,1 }; - //uint8_t enc_random_a[8] = { 0 }; - uint8_t random_b[8] = { 0 }; - uint8_t enc_random_b[8] = { 0 }; - uint8_t random_a_and_b[16] = { 0 }; - des3_context ctx = { 0 }; - uint8_t *key = default_keys[keyNo]; + uint8_t *key = default_3des_keys[keyNo]; + if (try3DesAuthentication(key)) + PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 8)); + else + PrintAndLog("Authentication failed"); + + return 0; +} + +int try3DesAuthentication( uint8_t *key){ + uint8_t blockNo = 0; uint32_t cuid = 0; - //Auth1 + des3_context ctx = { 0 }; + + uint8_t random_a[8] = { 1,1,1,1,1,1,1,1 }; + uint8_t random_b[8] = { 0 }; + uint8_t enc_random_b[8] = { 0 }; + uint8_t rnd_ab[16] = { 0 }; + uint8_t iv[8] = { 0 }; + UsbCommand c = {CMD_MIFAREUC_AUTH1, {blockNo}}; SendCommand(&c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - cuid = resp.arg[1]; - uint8_t * data= resp.d.asBytes; - - if (isOK){ - PrintAndLog("enc(RndB):%s", sprint_hex(data+1, 8)); - memcpy(enc_random_b,data+1,8); - } else { - PrintAndLog("Auth failed"); - return 2; // auth failed. - } - } else { - PrintAndLog("Command execute timeout"); - return 1; - } - - uint8_t iv[8] = { 0 }; - // Do we need random ? Right now we use all ones, is that random enough ? -// DES_random_key(&RndA); - - PrintAndLog(" RndA :%s",sprint_hex(random_a, 8)); - PrintAndLog(" e_RndB:%s",sprint_hex(enc_random_b, 8)); + if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return -1; + if ( !(resp.arg[0] & 0xff) ) return -2; + + cuid = resp.arg[1]; + memcpy(enc_random_b,resp.d.asBytes+1,8); des3_set2key_dec(&ctx, key); - - des3_crypt_cbc(&ctx // des3_context *ctx - , DES_DECRYPT // int mode - , sizeof(random_b) // size_t length - , iv // unsigned char iv[8] - , enc_random_b // const unsigned char *input - , random_b // unsigned char *output - ); - - PrintAndLog(" RndB:%s",sprint_hex(random_b, 8)); + // context, mode, length, IV, input, output + des3_crypt_cbc( &ctx, DES_DECRYPT, sizeof(random_b), iv , enc_random_b , random_b); rol(random_b,8); - memcpy(random_a_and_b ,random_a,8); - memcpy(random_a_and_b+8,random_b,8); - - PrintAndLog(" RA+B:%s",sprint_hex(random_a_and_b, 16)); + memcpy(rnd_ab ,random_a,8); + memcpy(rnd_ab+8,random_b,8); des3_set2key_enc(&ctx, key); - - des3_crypt_cbc(&ctx // des3_context *ctx - , DES_ENCRYPT // int mode - , sizeof(random_a_and_b) // size_t length - , enc_random_b // unsigned char iv[8] - , random_a_and_b // const unsigned char *input - , random_a_and_b // unsigned char *output - ); - - PrintAndLog("enc(RA+B):%s",sprint_hex(random_a_and_b, 16)); + // context, mode, length, IV, input, output + des3_crypt_cbc(&ctx, DES_ENCRYPT, sizeof(rnd_ab), enc_random_b, rnd_ab, rnd_ab); //Auth2 - UsbCommand d = {CMD_MIFAREUC_AUTH2, {cuid}}; - memcpy(d.d.asBytes,random_a_and_b, 16); - SendCommand(&d); + c.cmd = CMD_MIFAREUC_AUTH2; + c.arg[0] = cuid; + memcpy(c.d.asBytes, rnd_ab, 16); + SendCommand(&c); - UsbCommand respb; - if (WaitForResponseTimeout(CMD_ACK,&respb,1500)) { - uint8_t isOK = respb.arg[0] & 0xff; - uint8_t * data2= respb.d.asBytes; + if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if ( !(resp.arg[0] & 0xff)) return -2; + + uint8_t enc_resp[8] = { 0 }; + uint8_t resp_random_a[8] = { 0 }; + memcpy(enc_resp, resp.d.asBytes+1, 8); - if (isOK){ - PrintAndLog("enc(RndA'):%s", sprint_hex(data2+1, 8)); - } else { - return 2; - } - - } else { - PrintAndLog("Command execute timeout"); - return 1; - } + des3_set2key_dec(&ctx, key); + // context, mode, length, IV, input, output + des3_crypt_cbc( &ctx, DES_DECRYPT, 8, enc_random_b, enc_resp, resp_random_a); + + if ( !memcmp(resp_random_a, random_a, 8)) + return 1; return 0; + + //PrintAndLog(" RndA :%s", sprint_hex(random_a, 8)); + //PrintAndLog(" enc(RndB) :%s", sprint_hex(enc_random_b, 8)); + //PrintAndLog(" RndB :%s", sprint_hex(random_b, 8)); + //PrintAndLog(" A+B :%s", sprint_hex(random_a_and_b, 16)); + //PrintAndLog(" enc(A+B) :%s", sprint_hex(random_a_and_b, 16)); + //PrintAndLog(" enc(RndA') :%s", sprint_hex(data2+1, 8)); } + /** A test function to validate that the polarssl-function works the same was as the openssl-implementation. @@ -601,12 +725,17 @@ int CmdTestDES(const char * cmd) // int CmdHF14AMfUCRdBl(const char *Cmd) { + UsbCommand resp; + bool hasPwd = FALSE; uint8_t blockNo = -1; + unsigned char key[16]; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: hf mfu crdbl "); - PrintAndLog(" sample: hf mfu crdbl 0"); + PrintAndLog("Usage: hf mfu crdbl "); + PrintAndLog(""); + PrintAndLog("sample: hf mfu crdbl 0"); + PrintAndLog(" hf mfu crdbl 0 112233445566778899AABBCCDDEEFF"); return 0; } @@ -616,27 +745,40 @@ int CmdHF14AMfUCRdBl(const char *Cmd) return 1; } - if (blockNo > MAX_ULTRAC_BLOCKS ){ - PrintAndLog("Error: Maximum number of readable blocks is 47 for Ultralight-C Cards!"); + if (blockNo > MAX_ULC_BLOCKS ){ + PrintAndLog("Error: Maximum number of blocks is 47 for Ultralight-C"); return 1; } - PrintAndLog("--block no: 0x%02X (%d)", (int)blockNo, blockNo); + // key + if ( strlen(Cmd) > 3){ + if (param_gethex(Cmd, 1, key, 32)) { + PrintAndLog("Key must include %d HEX symbols", 32); + return 1; + } else { + hasPwd = TRUE; + } + } //Read Block - UsbCommand e = {CMD_MIFAREU_READBL, {blockNo}}; - SendCommand(&e); - UsbCommand resp_c; - if (WaitForResponseTimeout(CMD_ACK,&resp_c,1500)) { - uint8_t isOK = resp_c.arg[0] & 0xff; - uint8_t *data = resp_c.d.asBytes; - - PrintAndLog("isOk: %02x", isOK); - if (isOK) - PrintAndLog("Data: %s", sprint_hex(data, 4)); - + UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; + if ( hasPwd ) { + c.arg[1] = 1; + memcpy(c.d.asBytes,key,16); + } + SendCommand(&c); + + if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + uint8_t isOK = resp.arg[0] & 0xff; + if (isOK) { + uint8_t *data = resp.d.asBytes; + PrintAndLog("Block: %0d (0x%02X) [ %s]", (int)blockNo, blockNo, sprint_hex(data, 4)); + } + else { + PrintAndLog("Failed reading block: (%02x)", isOK); + } } else { - PrintAndLog("Command execute timeout"); + PrintAndLog("Command execute time-out"); } return 0; } @@ -665,7 +807,7 @@ int CmdHF14AMfUCWrBl(const char *Cmd){ } blockNo = param_get8(Cmd, 0); - if (blockNo > MAX_ULTRAC_BLOCKS ){ + if (blockNo > MAX_ULC_BLOCKS ){ PrintAndLog("Error: Maximum number of blocks is 47 for Ultralight-C Cards!"); return 1; } @@ -711,6 +853,228 @@ int CmdHF14AMfUCWrBl(const char *Cmd){ return 0; } +// +// Mifare Ultralight C - Set password +// +int CmdHF14AMfucSetPwd(const char *Cmd){ + + uint8_t pwd[16] = {0x00}; + + char cmdp = param_getchar(Cmd, 0); + + if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: hf mfu setpwd "); + PrintAndLog(" [password] - (32 hex symbols)"); + PrintAndLog(""); + PrintAndLog("sample: hf mfu setpwd 000102030405060708090a0b0c0d0e0f"); + PrintAndLog(""); + return 0; + } + + if (param_gethex(Cmd, 0, pwd, 32)) { + PrintAndLog("Password must include 32 HEX symbols"); + return 1; + } + + UsbCommand c = {CMD_MIFAREUC_SETPWD}; + memcpy( c.d.asBytes, pwd, 16); + SendCommand(&c); + + UsbCommand resp; + + if (WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + if ( (resp.arg[0] & 0xff) == 1) + PrintAndLog("Ultralight-C new password: %s", sprint_hex(pwd,16)); + else{ + PrintAndLog("Failed writing at block %d", resp.arg[1] & 0xff); + return 1; + } + } + else { + PrintAndLog("command execution time out"); + return 1; + } + + return 0; +} + +// +// Mifare Ultraligh - Set UID +// +int CmdHF14AMfucSetUid(const char *Cmd){ + + UsbCommand c; + UsbCommand resp; + uint8_t uid[7] = {0x00}; + char cmdp = param_getchar(Cmd, 0); + + if (strlen(Cmd) == 0 || cmdp == 'h' || cmdp == 'H') { + PrintAndLog("Usage: hf mfu setuid "); + PrintAndLog(" [uid] - (14 hex symbols)"); + PrintAndLog("\nThis only works for Magic Ultralight tags."); + PrintAndLog(""); + PrintAndLog("sample: hf mfu setuid 11223344556677"); + PrintAndLog(""); + return 0; + } + + if (param_gethex(Cmd, 0, uid, 14)) { + PrintAndLog("UID must include 14 HEX symbols"); + return 1; + } + + // read block2. + c.cmd = CMD_MIFAREU_READBL; + c.arg[0] = 2; + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + PrintAndLog("Command execute timeout"); + return 2; + } + + // 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; + c.d.asBytes[0] = uid[0]; + c.d.asBytes[1] = uid[1]; + c.d.asBytes[2] = uid[2]; + c.d.asBytes[3] = 0x88 ^ uid[0] ^ uid[1] ^ uid[2]; + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + PrintAndLog("Command execute timeout"); + return 3; + } + + // block 1. + c.arg[0] = 1; + c.d.asBytes[0] = uid[3]; + c.d.asBytes[1] = uid[4]; + c.d.asBytes[2] = uid[5]; + c.d.asBytes[3] = uid[6]; + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + PrintAndLog("Command execute timeout"); + return 4; + } + + // block 2. + c.arg[0] = 2; + c.d.asBytes[0] = uid[3] ^ uid[4] ^ uid[5] ^ uid[6]; + c.d.asBytes[1] = oldblock2[1]; + c.d.asBytes[2] = oldblock2[2]; + c.d.asBytes[3] = oldblock2[3]; + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { + PrintAndLog("Command execute timeout"); + return 5; + } + + return 0; +} + +int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ + + uint8_t iv[8] = { 0x00 }; + uint8_t block = 0x07; + + // UL-EV1 + //04 57 b6 e2 05 3f 80 UID + //4a f8 4b 19 PWD + uint8_t uid[] = { 0xF4,0xEA, 0x54, 0x8E }; + 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]; + + des3_context ctx = { 0x00 }; + des3_set2key_enc(&ctx, masterkey); + + des3_crypt_cbc(&ctx // des3_context + , DES_ENCRYPT // int mode + , sizeof(mix) // length + , iv // iv[8] + , mix // input + , divkey // output + ); + + PrintAndLog("3DES version"); + PrintAndLog("Masterkey :\t %s", sprint_hex(masterkey,sizeof(masterkey))); + PrintAndLog("UID :\t %s", sprint_hex(uid, sizeof(uid))); + PrintAndLog("Sector :\t %0d", block); + PrintAndLog("Mifare key :\t %s", sprint_hex(mifarekeyA, sizeof(mifarekeyA))); + PrintAndLog("Message :\t %s", sprint_hex(mix, sizeof(mix))); + PrintAndLog("Diversified key: %s", sprint_hex(divkey+1, 6)); + + PrintAndLog("\n DES version"); + + 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}; + memcpy(dmkey, dkeyA, 8); + memcpy(dmkey+8, dkeyB, 8); + memcpy(dmkey+16, dkeyA, 8); + memset(iv, 0x00, 8); + + des3_set3key_enc(&ctx, dmkey); + + des3_crypt_cbc(&ctx // des3_context + , DES_ENCRYPT // int mode + , sizeof(newpwd) // length + , iv // iv[8] + , zeros // input + , newpwd // output + ); + + PrintAndLog("Mifare dkeyA :\t %s", sprint_hex(dkeyA, sizeof(dkeyA))); + PrintAndLog("Mifare dkeyB :\t %s", sprint_hex(dkeyB, sizeof(dkeyB))); + PrintAndLog("Mifare ABA :\t %s", sprint_hex(dmkey, sizeof(dmkey))); + PrintAndLog("Mifare Pwd :\t %s", sprint_hex(newpwd, sizeof(newpwd))); + + return 0; +} + +// static uint8_t * diversify_key(uint8_t * key){ + + // for(int i=0; i<16; i++){ + // if(i<=6) key[i]^=cuid[i]; + // if(i>6) key[i]^=cuid[i%7]; + // } + // return key; +// } + +// static void GenerateUIDe( uint8_t *uid, uint8_t len){ + // for (int i=0; i Date: Thu, 30 Apr 2015 09:28:43 -0400 Subject: [PATCH 023/132] Iceman's updates to MFU info and dump --- armsrc/mifarecmd.c | 13 +-- client/cmdhfmfu.c | 285 +++++++++++++++++++++------------------------ client/cmdhfmfu.h | 3 + 3 files changed, 143 insertions(+), 158 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 3d5dcdef..03e191e0 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -326,13 +326,13 @@ void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain) int Pages = arg1; int countpages = 0; byte_t dataout[176] = {0x00};; - uint32_t cuid = 0x00; - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + LEDsoff(); + LED_A_ON(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - int len = iso14443a_select_card(NULL, NULL, &cuid); + int len = iso14443a_select_card(NULL, NULL, NULL); if (!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%d)",len); OnError(1); @@ -359,13 +359,8 @@ void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain) return; } - if (MF_DBGLEVEL >= MF_DBG_ALL) Dbprintf("Pages read %d", countpages); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Pages read %d", countpages); -// len = 16*4; //64 bytes - - // Read a UL-C -// if (Pages == 44 && countpages > 16) -// len = 176; len = Pages * 4; cmd_send(CMD_ACK, 1, 0, 0, dataout, len); diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 1886fc3d..2f7fa2c9 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -59,57 +59,46 @@ typedef enum TAGTYPE_UL { UL_C = 0x02, UL_EV1_48 = 0x04, UL_EV1_128 = 0x08, - UL_MAGIC = 0x11, - UL_C_MAGIC = 0x12, MAGIC = 0x10, + UL_MAGIC = UL | MAGIC, + UL_C_MAGIC = UL_C | MAGIC, UL_ERROR = 0xFF, } TagTypeUL_t; -uint8_t GetHF14AMfU_Type(uint8_t *data, uint8_t dataSize){ +uint8_t GetHF14AMfU_Type(void){ + TagTypeUL_t tagtype = UNKNOWN; - uint8_t isOK = 0; + iso14a_card_select_t card; - UsbCommand c = {CMD_MIFAREU_READCARD, {0, 4}}; - SendCommand(&c); - UsbCommand resp; - - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { - isOK = resp.arg[0] & 0xff; - memcpy(data, resp.d.asBytes, dataSize); - - if (!isOK) { - PrintAndLog("Error reading from tag"); - return UL_ERROR; - } - } else { - PrintAndLog("Command execute timed out"); - return UL_ERROR; - } - - c.cmd = CMD_READER_ISO_14443a; - c.arg[0] = ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC; - c.arg[1] = 1; - c.arg[2] = 0; + // select and run 0x60 (GET_VERSION - EV1 command) + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC, 1, 0}}; c.d.asBytes[0] = 0x60; SendCommand(&c); + UsbCommand resp; WaitForResponse(CMD_ACK, &resp); - if ( resp.arg[0] ) { - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + if ( resp.arg[0] == 0 ) return UL_ERROR; + + memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); - uint8_t version[8] = {0,0,0,0,0,0,0,0}; - memcpy(&version, resp.d.asBytes, sizeof(version)); - uint8_t len = resp.arg[0] & 0xff; - - if ( len == 0x0A && version[6] == 0x0B ) - tagtype = UL_EV1_48; - else if ( len == 0x0A && version[6] != 0x0B ) - tagtype = UL_EV1_128; - else if ( len == 0x01 ) - tagtype = UL_C; - else if ( len == 0x00 ) - tagtype = UL; //| UL_MAGIC | UL_C_MAGIC - } + // Ultralight - ATQA / SAK + if ( card.atqa[1] != 0x00 && card.atqa[0] != 0x44 && card.sak != 0x00 ) return UL_ERROR; + + // EV1 GetVersion + if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + + uint8_t version[8] = {0,0,0,0,0,0,0,0}; + memcpy(&version, resp.d.asBytes, sizeof(version)); + uint8_t len = resp.arg[0] & 0xff; + + if ( len == 0x0A && version[6] == 0x0B ) + tagtype = UL_EV1_48; + else if ( len == 0x0A && version[6] != 0x0B ) + tagtype = UL_EV1_128; + else if ( len == 0x01 ) + tagtype = UL_C; + else if ( len == 0x00 ) + tagtype = UL; } // Magic UL-C, mine have a static nonce response to 0x1A command. @@ -118,8 +107,9 @@ uint8_t GetHF14AMfU_Type(uint8_t *data, uint8_t dataSize){ uint8_t status = requestAuthentication(nonce1); if ( status ) { requestAuthentication(nonce2); - if ( !memcmp(nonce1, nonce2, 8) ) - tagtype ^= MAGIC; + if ( !memcmp(nonce1, nonce2, 8) ){ + tagtype = UL_C_MAGIC; + } } else { // Magic Ultralight test here - TODO } @@ -128,27 +118,46 @@ uint8_t GetHF14AMfU_Type(uint8_t *data, uint8_t dataSize){ int CmdHF14AMfUInfo(const char *Cmd){ - TagTypeUL_t tagtype = UNKNOWN; - uint8_t datatemp[7] = {0x00}; + uint8_t isOK = 0; uint8_t data[16] = {0x00}; + uint8_t *key; - tagtype = GetHF14AMfU_Type(data, sizeof(data)); + TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; PrintAndLog("\n-- Tag Information ---------"); PrintAndLog("-------------------------------------------------------------"); - switch(tagtype){ - case UNKNOWN : PrintAndLog(" TYPE : Unknown"); return 0; - case UL : PrintAndLog(" TYPE : MIFARE Ultralight");break; - case UL_C : PrintAndLog(" TYPE : MIFARE Ultralight C");break; - case UL_EV1_48 : PrintAndLog(" TYPE : MIFARE Ultralight EV1 48 bytes"); break; - case UL_EV1_128 : PrintAndLog(" TYPE : MIFARE Ultralight EV1 128 bytes"); break; - case UL_MAGIC : PrintAndLog(" TYPE : MIFARE Ultralight (MAGIC)");break; - case UL_C_MAGIC : PrintAndLog(" TYPE : MIFARE Ultralight-C (MAGIC)");break; - default : PrintAndLog(" TYPE : Unknown %x",tagtype);break; + + if ( tagtype & UL ) + PrintAndLog(" TYPE : MIFARE Ultralight %s", (tagtype & MAGIC)?"(magic)":""); + else if ( tagtype & UL_C) + PrintAndLog(" TYPE : MIFARE Ultralight C %s", (tagtype & MAGIC)?"(magic)":"" ); + else if ( tagtype & UL_EV1_48) + PrintAndLog(" TYPE : MIFARE Ultralight EV1 48 bytes"); + else if ( tagtype & UL_EV1_128) + PrintAndLog(" TYPE : MIFARE Ultralight EV1 128 bytes"); + else + PrintAndLog(" TYPE : Unknown %x",tagtype); + + // read pages 0,1,2,4 + UsbCommand c = {CMD_MIFAREU_READCARD, {0, 4}}; + SendCommand(&c); + UsbCommand resp; + + if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + isOK = resp.arg[0] & 0xff; + memcpy(data, resp.d.asBytes, sizeof(data)); + + if (!isOK) { + PrintAndLog("Error reading from tag"); + return -1; + } + } else { + PrintAndLog("Command execute timed out"); + return -1; } - + // UID memcpy( datatemp, data, 3); memcpy( datatemp+3, data+4, 4); @@ -182,7 +191,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ((tagtype & UL_C)){ PrintAndLog("Trying some default 3des keys"); - uint8_t *key; for (uint8_t i = 0; i < 5; ++i ){ key = default_3des_keys[i]; @@ -194,6 +202,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } else if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { //********** TODO ******************************** + // --problem, there is a failed pwd tries counter in UL-EV1 //PrintAndLog("Trying some known EV1 passwords."); } return 0; @@ -310,108 +319,95 @@ int CmdHF14AMfURdBl(const char *Cmd){ return 0; } +int usage_hf_mfu_dump(void) +{ + PrintAndLog("Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); + PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); + PrintAndLog("It autodetects card type.\n"); + PrintAndLog("Usage: hf mfu dump "); + PrintAndLog(" sample : hf mfu dump"); + PrintAndLog(" : hf mfu dump myfile"); + PrintAndLog(" : hf mfu dump 1 myfile"); + return 0; +} // -// Mifare Ultralight / Ultralight-C; Read and Dump Card Contents +// Mifare Ultralight / Ultralight-C / Ultralight-EV1 +// Read and Dump Card Contents, using auto detection of tag size. // +// TODO: take a password to read UL-C / UL-EV1 tags. int CmdHF14AMfUDump(const char *Cmd){ + char cmdp = param_getchar(Cmd, 0); + if (cmdp == 'h' || cmdp == 'H') + return usage_hf_mfu_dump(); + FILE *fout; char filename[FILE_PATH_SIZE] = {0x00}; - char * fnameptr = filename; + char *fnameptr = filename; + char *str = "Dumping Ultralight%s%s Card Data..."; uint8_t *lockbytes_t = NULL; uint8_t lockbytes[2] = {0x00}; - uint8_t *lockbytes_t2 = NULL; uint8_t lockbytes2[2] = {0x00}; - bool bit[16] = {0x00}; bool bit2[16] = {0x00}; + uint8_t data[176] = {0x00}; - int i; - uint8_t BlockNo = 0; - int Pages = 16; + int i = 0; + int Pages = 16; + bool tmplockbit = false; - bool tmplockbit = false; - uint8_t isOK = 0; - uint8_t *data = NULL; + TagTypeUL_t tagtype = GetHF14AMfU_Type(); + if (tagtype == UL_ERROR) return -1; - char cmdp = param_getchar(Cmd, 0); - - if (cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Reads all pages from Mifare Ultralight or Ultralight-C tag."); - PrintAndLog("It saves binary dump into the file `filename.bin` or `cardUID.bin`"); - PrintAndLog("Usage: hf mfu dump "); - PrintAndLog(" optional cardtype c == Ultralight-C, Defaults to Ultralight"); - PrintAndLog(" sample: hf mfu dump"); - PrintAndLog(" : hf mfu dump myfile"); - PrintAndLog(" : hf mfu dump c myfile"); - return 0; + if ( tagtype & UL ) { + Pages = 16; + PrintAndLog(str,"", (tagtype & MAGIC)?" (magic)":"" ); + } + else if ( tagtype & UL_C ) { + Pages = 44; + PrintAndLog(str,"-C", (tagtype & MAGIC)?" (magic)":"" ); + } + else if ( tagtype & UL_EV1_48 ) { + Pages = 18; + PrintAndLog(str," EV1_48",""); + } + else if ( tagtype & UL_EV1_128 ) { + Pages = 32; + PrintAndLog(str," EV1_128",""); + } else { + Pages = 16; + PrintAndLog("Dumping unknown Ultralight, using default values."); } - // UL or UL-C? - Pages = (cmdp == 'c' || cmdp == 'C') ? 44 : 16; - - uint8_t data2[16] = {0x00}; - TagTypeUL_t tagtype = GetHF14AMfU_Type(data2, sizeof(data2)); - switch(tagtype){ - case UL_C: - Pages = 44; - PrintAndLog("Dumping Ultralight_C Card Data..."); - break; - case UL_EV1_48: - Pages = 18; - PrintAndLog("Dumping Ultralight EV1_48 Card Data..."); - break; - case UL_EV1_128: - Pages = 32; - PrintAndLog("Dumping Ultralight EV1_128 Card Data..."); - break; - case UL_MAGIC: - Pages = 16; - PrintAndLog("Dumping Ultralight (Magic) Card Data..."); - break; - case UL_C_MAGIC: - Pages = 44; - PrintAndLog("Dumping Ultralight_C (Magic) Card Data..."); - break; - case UL: - default: - Pages = 16; - PrintAndLog("Dumping Ultralight Card Data..."); - break; - } - //PrintAndLog("Dumping Ultralight%s Card Data...", (Pages ==16)?"":"-C"); - - UsbCommand c = {CMD_MIFAREU_READCARD, {BlockNo,Pages}}; + UsbCommand c = {CMD_MIFAREU_READCARD, {0,Pages}}; SendCommand(&c); UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - isOK = resp.arg[0] & 0xff; - if (!isOK) { - PrintAndLog("Command error"); - return 0; - } - data = resp.d.asBytes; - } else { + if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { PrintAndLog("Command execute time-out"); return 0; } - + + if (!resp.arg[0] ) { + PrintAndLog("Read command failed"); + return 0; + } + memcpy(data, resp.d.asBytes, sizeof(data)); + // Load lock bytes. int j = 0; - + lockbytes_t = data + 8; lockbytes[0] = lockbytes_t[2]; lockbytes[1] = lockbytes_t[3]; for(j = 0; j < 16; j++){ bit[j] = lockbytes[j/8] & ( 1 <<(7-j%8)); - } - + } + // Load bottom lockbytes if available if ( Pages == 44 ) { - lockbytes_t2 = data + (40*4); lockbytes2[0] = lockbytes_t2[2]; lockbytes2[1] = lockbytes_t2[3]; @@ -421,12 +417,10 @@ int CmdHF14AMfUDump(const char *Cmd){ } for (i = 0; i < Pages; ++i) { - if ( i < 3 ) { PrintAndLog("Block %02x:%s ", i,sprint_hex(data + i * 4, 4)); continue; } - switch(i){ case 3: tmplockbit = bit[4]; break; case 4: tmplockbit = bit[3]; break; @@ -473,27 +467,20 @@ int CmdHF14AMfUDump(const char *Cmd){ } PrintAndLog("Block %02x:%s [%d]", i,sprint_hex(data + i * 4, 4),tmplockbit); } - - int len = 0; - if ( Pages == 16 ) - len = param_getstr(Cmd,0,filename); - else - len = param_getstr(Cmd,1,filename); - if (len > FILE_PATH_SIZE-5) len = FILE_PATH_SIZE-5; + int len = param_getstr(Cmd,0,filename); + if (len > FILE_PATH_SIZE-5) + len = FILE_PATH_SIZE-5; // user supplied filename? if (len < 1) { - // UID = data 0-1-2 4-5-6-7 (skips a beat) sprintf(fnameptr,"%02X%02X%02X%02X%02X%02X%02X.bin", data[0],data[1], data[2], data[4],data[5],data[6], data[7]); - } else { sprintf(fnameptr + len," .bin"); } - if ((fout = fopen(filename,"wb")) == NULL) { PrintAndLog("Could not create file name %s", filename); return 1; @@ -899,7 +886,7 @@ int CmdHF14AMfucSetPwd(const char *Cmd){ } // -// Mifare Ultraligh - Set UID +// Magic UL / UL-C tags - Set UID // int CmdHF14AMfucSetUid(const char *Cmd){ @@ -1080,17 +1067,17 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ //------------------------------------ static command_t CommandTable[] = { - {"help", CmdHelp, 1,"This help"}, - {"dbg", CmdHF14AMfDbg, 0,"Set default debug mode"}, - {"info", CmdHF14AMfUInfo, 0,"Taginfo"}, - {"dump", CmdHF14AMfUDump, 0,"Dump MIFARE Ultralight / Ultralight-C tag to binary file"}, - {"rdbl", CmdHF14AMfURdBl, 0,"Read block - MIFARE Ultralight"}, - {"wrbl", CmdHF14AMfUWrBl, 0,"Write block - MIFARE Ultralight"}, - {"crdbl", CmdHF14AMfUCRdBl, 0,"Read block - MIFARE Ultralight C"}, - {"cwrbl", CmdHF14AMfUCWrBl, 0,"Write block - MIFARE Ultralight C"}, - {"cauth", CmdHF14AMfucAuth, 0,"Ultralight C Authentication"}, - {"setpwd", CmdHF14AMfucSetPwd , 1, "Set 3des password [Ultralight-C only]"}, - {"setuid", CmdHF14AMfucSetUid , 1, "Set UID"}, + {"help", CmdHelp, 1, "This help"}, + {"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"}, + {"info", CmdHF14AMfUInfo, 0, "Tag information"}, + {"dump", CmdHF14AMfUDump, 0, "Dump Ultralight / Ultralight-C tag to binary file"}, + {"rdbl", CmdHF14AMfURdBl, 0, "Read block - Ultralight"}, + {"wrbl", CmdHF14AMfUWrBl, 0, "Write block - Ultralight"}, + {"crdbl", CmdHF14AMfUCRdBl, 0, "Read block - Ultralight C"}, + {"cwrbl", CmdHF14AMfUCWrBl, 0, "Write block - Ultralight C"}, + {"cauth", CmdHF14AMfucAuth, 0, "Authentication - Ultralight C"}, + {"setpwd", CmdHF14AMfucSetPwd, 1, "Set 3des password - Ultralight-C"}, + {"setuid", CmdHF14AMfucSetUid, 1, "Set UID - MAGIC tags only"}, {"gen", CmdHF14AMfuGenDiverseKeys , 1, "Generate 3des mifare diversified keys"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 72193390..64f32a49 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -19,6 +19,9 @@ void rol (uint8_t *data, const size_t len); uint8_t requestAuthentication( uint8_t *nonce); int try3DesAuthentication( uint8_t *key); +uint8_t GetHF14AMfU_Type(void); + +int usage_hf_mfu_dump(void); int CmdHFMFUltra(const char *Cmd); int CmdHF14AMfUInfo(const char *Cmd); From 7eec1204e7ab07e2840b64c274715422af5f1393 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 30 Apr 2015 10:34:20 -0400 Subject: [PATCH 024/132] fix bug in mfu cauth --- client/cmdhfmfu.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 2f7fa2c9..8b906904 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -540,8 +540,8 @@ int CmdHF14AMfucAuth(const char *Cmd){ } uint8_t *key = default_3des_keys[keyNo]; - if (try3DesAuthentication(key)) - PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 8)); + if (try3DesAuthentication(key)>0) + PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 16)); else PrintAndLog("Authentication failed"); From b3125340f39856e7d8b3fbdcaeacc0baf0e71336 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 3 May 2015 15:41:11 -0400 Subject: [PATCH 025/132] Icemans UL-C Auth dev side fix plus a few other ... ... small UL fixes --- armsrc/des.c | 19 +++++++- armsrc/des.h | 4 +- armsrc/mifarecmd.c | 105 +++++++++++++++++++++++++++------------------ client/cmdhfmfu.c | 17 +++++--- 4 files changed, 93 insertions(+), 52 deletions(-) diff --git a/armsrc/des.c b/armsrc/des.c index dbe62da9..a81df9c8 100644 --- a/armsrc/des.c +++ b/armsrc/des.c @@ -378,38 +378,53 @@ void tdes_dec(void* out, void* in, const uint8_t* key){ des_dec(out, out, (uint8_t*)key + 0); } -void tdes_2key_enc(void* out, const void* in, size_t length, const void* key){ +void tdes_2key_enc(void* out, const void* in, size_t length, const void* key, unsigned char iv[8]){ 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){ +void tdes_2key_dec(void* out, const void* in, size_t length, const void* key, unsigned char iv[8]){ 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); + 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 cc1d59b0..90f74246 100644 --- a/armsrc/des.h +++ b/armsrc/des.h @@ -97,8 +97,8 @@ void tdes_enc(void* out, const void* in, const void* key); */ void tdes_dec(void* out, const void* in, const void* key); - void tdes_2key_enc(void* out, const void* in, size_t length, const void* key); - void tdes_2key_dec(void* out, const void* in, size_t length, const void* 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]); #endif /*DES_H_*/ diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 03e191e0..3a932409 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -171,13 +171,12 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) // Dbprintf("KEY: %02x %02x %02x %02x %02x %02x %02x %02x", key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7] ); // Dbprintf("KEY: %02x %02x %02x %02x %02x %02x %02x %02x", key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15] ); - uint8_t a[8] = {1,1,1,1,1,1,1,1 }; - uint8_t b[8] = {0x00}; - uint8_t enc_b[8] = {0x00}; - uint8_t ab[16] = {0x00}; - uint8_t enc_ab[16] = {0x00}; - uint8_t enc_key[8] = {0x00}; - + uint8_t random_a[8] = {1,1,1,1,1,1,1,1 }; + uint8_t random_b[8] = {0x00}; + uint8_t enc_random_b[8] = {0x00}; + uint8_t rnd_ab[16] = {0x00}; + uint8_t IV[8] = {0x00}; + uint16_t len; uint8_t receivedAnswer[MAX_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; @@ -188,69 +187,93 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) OnError(1); return; } - + // tag nonce. - memcpy(enc_b,receivedAnswer+1,8); + memcpy(enc_random_b,receivedAnswer+1,8); // decrypt nonce. - tdes_2key_dec(b, enc_b, 8, key ); + tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV ); - Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x", enc_b[0],enc_b[1],enc_b[2],enc_b[3],enc_b[4],enc_b[5],enc_b[6],enc_b[7] ); - Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x", b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7] ); - rol(b,8); + + rol(random_b,8); - memcpy(ab ,a,8); - memcpy(ab+8,b,8); + memcpy(rnd_ab ,random_a,8); + memcpy(rnd_ab+8,random_b,8); - Dbprintf("AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[0],ab[1],ab[2],ab[3],ab[4],ab[5],ab[6],ab[7] ); - Dbprintf("AB: %02x %02x %02x %02x %02x %02x %02x %02x", ab[8],ab[9],ab[10],ab[11],ab[12],ab[13],ab[14],ab[15] ); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { + Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x", + enc_random_b[0],enc_random_b[1],enc_random_b[2],enc_random_b[3], + enc_random_b[4],enc_random_b[5],enc_random_b[6],enc_random_b[7]); + + Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x", + random_b[0],random_b[1],random_b[2],random_b[3], + random_b[4],random_b[5],random_b[6],random_b[7]); - // encrypt - tdes_2key_enc(enc_ab, ab, 16, key); + Dbprintf("rnd_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]); + + Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x", + rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11], + rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15] ); + } + + // encrypt out, in, length, key, iv + tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", enc_ab[0],enc_ab[1],enc_ab[2],enc_ab[3],enc_ab[4],enc_ab[5],enc_ab[6],enc_ab[7] ); - Dbprintf("e_enc_ab: %02x %02x %02x %02x %02x %02x %02x %02x", enc_ab[8],enc_ab[9],enc_ab[10],enc_ab[11],enc_ab[12],enc_ab[13],enc_ab[14],enc_ab[15] ); - - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, enc_ab, receivedAnswer, receivedAnswerPar, NULL); + + len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); if (len != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); OnError(1); return; } - // the tags' encryption of our nonce, A. - memcpy(enc_key, receivedAnswer+1, 8); - - // clear B. - memset(b, 0x00, 8); - - // decrypt - tdes_2key_dec(b, enc_key, 8, key ); - if ( memcmp(a, b, 8) == 0 ) - Dbprintf("Verified key"); - else + uint8_t enc_resp[8] = { 0 }; + uint8_t resp_random_a[8] = { 0 }; + memcpy(enc_resp, receivedAnswer+1, 8); + + // 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 ) Dbprintf("failed authentication"); - - Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x", a[0],a[1],a[2],a[3],a[4],a[5],a[6],a[7] ); - Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x", b[0],b[1],b[2],b[3],b[4],b[5],b[6],b[7] ); - } + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { + 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]); + + Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", + rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11], + rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15]); + + Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x", + random_a[0],random_a[1],random_a[2],random_a[3], + random_a[4],random_a[5],random_a[6],random_a[7]); + + Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x", + resp_random_a[0],resp_random_a[1],resp_random_a[2],resp_random_a[3], + resp_random_a[4],resp_random_a[5],resp_random_a[6],resp_random_a[7]); + } + } + if( mifare_ultra_readblock(blockNo, dataout) ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block error"); OnError(2); return; } - + if( mifare_ultra_halt() ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); OnError(3); return; } - - cmd_send(CMD_ACK,1,0,0,dataout,16); + + cmd_send(CMD_ACK,1,0,0,dataout,16); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } + //----------------------------------------------------------------------------- // Select, Authenticate, Read a MIFARE tag. // read sector (data = 4 x 16 bytes = 64 bytes, or 16 x 16 bytes = 256 bytes) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 8b906904..9825f928 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -87,7 +87,7 @@ uint8_t GetHF14AMfU_Type(void){ // EV1 GetVersion if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { - uint8_t version[8] = {0,0,0,0,0,0,0,0}; + uint8_t version[10] = {0,0,0,0,0,0,0,0}; memcpy(&version, resp.d.asBytes, sizeof(version)); uint8_t len = resp.arg[0] & 0xff; @@ -722,7 +722,7 @@ int CmdHF14AMfUCRdBl(const char *Cmd) PrintAndLog("Usage: hf mfu crdbl "); PrintAndLog(""); PrintAndLog("sample: hf mfu crdbl 0"); - PrintAndLog(" hf mfu crdbl 0 112233445566778899AABBCCDDEEFF"); + PrintAndLog(" hf mfu crdbl 0 00112233445566778899AABBCCDDEEFF"); return 0; } @@ -803,14 +803,15 @@ int CmdHF14AMfUCWrBl(const char *Cmd){ PrintAndLog("Block data must include 8 HEX symbols"); return 1; } - + if (strchr(Cmd,'w') != 0 || strchr(Cmd,'W') != 0 ) { chinese_card = TRUE; } - + if ( blockNo <= 3 ) { if (!chinese_card){ - PrintAndLog("Access Denied"); + PrintAndLog("Access Denied"); + return 1; } else { PrintAndLog("--Special block no: 0x%02x", blockNo); PrintAndLog("--Data: %s", sprint_hex(bldata, 4)); @@ -822,8 +823,9 @@ int CmdHF14AMfUCWrBl(const char *Cmd){ PrintAndLog("isOk:%02x", isOK); } else { PrintAndLog("Command execute timeout"); - } - } + return 1; + } + } } else { PrintAndLog("--Block no : 0x%02x", blockNo); PrintAndLog("--Data: %s", sprint_hex(bldata, 4)); @@ -835,6 +837,7 @@ int CmdHF14AMfUCWrBl(const char *Cmd){ PrintAndLog("isOk : %02x", isOK); } else { PrintAndLog("Command execute timeout"); + return 1; } } return 0; From 4b36037948fb7f0de45ac1033e6da335810c4993 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Sun, 3 May 2015 22:09:52 +0200 Subject: [PATCH 026/132] Fixes to issue #100 --- client/cmdhf14a.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index 200c9dcd..d4285eea 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -177,8 +177,8 @@ int CmdHF14AReader(const char *Cmd) SendCommand(&c); WaitForResponse(CMD_ACK,&resp); - uint8_t version[8] = {0,0,0,0,0,0,0,0}; - memcpy(&version, resp.d.asBytes, resp.arg[0]); + uint8_t version[10] = {0}; + memcpy(version, resp.d.asBytes, resp.arg[0] < sizeof(version) ? resp.arg[0] : sizeof(version)); uint8_t len = resp.arg[0] & 0xff; switch ( len ){ // todo, identify "Magic UL-C tags". // they usually have a static nonce response to 0x1A command. @@ -221,7 +221,7 @@ int CmdHF14AReader(const char *Cmd) SendCommand(&c); WaitForResponse(CMD_ACK,&resp); - memcpy(&card.ats, resp.d.asBytes, resp.arg[0]); + memcpy(card.ats, resp.d.asBytes, resp.arg[0]); card.ats_len = resp.arg[0]; // note: ats_len includes CRC Bytes } From f9848fd647ce3c708510d8ead6d1b56b26c57ad9 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 3 May 2015 23:17:11 -0400 Subject: [PATCH 027/132] MFU dump UL-C with key adding UL-C auth and keys to dump cmd swapped endian for input of hf mfu crdbl to match output of hf mfu info cmd and tag info app --- client/cmdhfmfu.c | 115 +++++++++++++++++++++++++++++++++------------- client/util.c | 14 ++++++ client/util.h | 1 + 3 files changed, 98 insertions(+), 32 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 9825f928..620f1b0e 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -12,6 +12,7 @@ #include "cmdhfmf.h" #include "cmdhf14a.h" #include "mifare.h" +#include "util.h" #define MAX_UL_BLOCKS 0x0f #define MAX_ULC_BLOCKS 0x2f @@ -87,8 +88,8 @@ uint8_t GetHF14AMfU_Type(void){ // EV1 GetVersion if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { - uint8_t version[10] = {0,0,0,0,0,0,0,0}; - memcpy(&version, resp.d.asBytes, sizeof(version)); + uint8_t version[10] = {0,0,0,0,0,0,0,0,0,0}; + memcpy(version, resp.d.asBytes, resp.arg[0] < sizeof(version) ? resp.arg[0] : sizeof(version)); uint8_t len = resp.arg[0] & 0xff; if ( len == 0x0A && version[6] == 0x0B ) @@ -324,10 +325,9 @@ int usage_hf_mfu_dump(void) PrintAndLog("Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("It autodetects card type.\n"); - PrintAndLog("Usage: hf mfu dump "); + PrintAndLog("Usage: hf mfu dump k n "); PrintAndLog(" sample : hf mfu dump"); - PrintAndLog(" : hf mfu dump myfile"); - PrintAndLog(" : hf mfu dump 1 myfile"); + PrintAndLog(" : hf mfu dump n myfile"); return 0; } // @@ -337,26 +337,66 @@ int usage_hf_mfu_dump(void) // TODO: take a password to read UL-C / UL-EV1 tags. int CmdHF14AMfUDump(const char *Cmd){ - char cmdp = param_getchar(Cmd, 0); - if (cmdp == 'h' || cmdp == 'H') - return usage_hf_mfu_dump(); - FILE *fout; char filename[FILE_PATH_SIZE] = {0x00}; char *fnameptr = filename; char *str = "Dumping Ultralight%s%s Card Data..."; - uint8_t *lockbytes_t = NULL; uint8_t lockbytes[2] = {0x00}; uint8_t *lockbytes_t2 = NULL; uint8_t lockbytes2[2] = {0x00}; bool bit[16] = {0x00}; bool bit2[16] = {0x00}; - uint8_t data[176] = {0x00}; - + uint8_t data[1024] = {0x00}; + bool hasPwd = false; int i = 0; int Pages = 16; bool tmplockbit = false; + uint8_t dataLen=0; + uint8_t cmdp =0; + uint8_t *key= NULL; + size_t fileNlen = 0; + bool errors = FALSE; + + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_mfu_dump(); + case 'k': + case 'K': + dataLen = param_gethex(Cmd, cmdp+1, data, 32); + if (dataLen) { + errors = true; + } else { + key = SwapEndian64(data, 16); + PrintAndLog("3des key: %s",sprint_hex(key, 16)); + } + cmdp += 2; + hasPwd = true; + break; + case 'n': + case 'N': + fileNlen = param_getstr(Cmd, cmdp+1, filename); + if (!fileNlen) errors = true; + if (fileNlen > FILE_PATH_SIZE-5) fileNlen = FILE_PATH_SIZE-5; + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) break; + } + + //Validations + if(errors) + { + return usage_hf_mfu_dump(); + } TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -381,21 +421,29 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLog("Dumping unknown Ultralight, using default values."); } - UsbCommand c = {CMD_MIFAREU_READCARD, {0,Pages}}; - SendCommand(&c); - UsbCommand resp; + for (uint8_t i = 0; i FILE_PATH_SIZE-5) - len = FILE_PATH_SIZE-5; - // user supplied filename? - if (len < 1) { + if (fileNlen < 1) { // UID = data 0-1-2 4-5-6-7 (skips a beat) sprintf(fnameptr,"%02X%02X%02X%02X%02X%02X%02X.bin", data[0],data[1], data[2], data[4],data[5],data[6], data[7]); } else { - sprintf(fnameptr + len," .bin"); + sprintf(fnameptr + fileNlen," .bin"); } if ((fout = fopen(filename,"wb")) == NULL) { @@ -707,6 +756,7 @@ int CmdTestDES(const char * cmd) return 0; } **/ + // // Ultralight C Read Single Block // @@ -715,7 +765,7 @@ int CmdHF14AMfUCRdBl(const char *Cmd) UsbCommand resp; bool hasPwd = FALSE; uint8_t blockNo = -1; - unsigned char key[16]; + uint8_t key[16]; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') { @@ -746,12 +796,13 @@ int CmdHF14AMfUCRdBl(const char *Cmd) hasPwd = TRUE; } } + uint8_t *key2 = SwapEndian64(key, 16); //Read Block UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; if ( hasPwd ) { c.arg[1] = 1; - memcpy(c.d.asBytes,key,16); + memcpy(c.d.asBytes,key2,16); } SendCommand(&c); diff --git a/client/util.c b/client/util.c index 709e2014..5bb98fd7 100644 --- a/client/util.c +++ b/client/util.c @@ -158,6 +158,20 @@ uint64_t bytes_to_num(uint8_t* src, size_t len) return num; } +// aa,bb,cc,dd,ee,ff,gg,hh, ii,jj,kk,ll,mm,nn,oo,pp +// to +// hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii +// up to 64 bytes or 512 bits +uint8_t *SwapEndian64(uint8_t *src, size_t len){ + static uint8_t temp[64]={0}; + for (uint8_t block=0; block < (uint8_t)len/8; block++){ + for (size_t i = 0; i < 8; i++){ + temp[i+(8*block)] = src[(7-i)+(8*block)]; + } + } + return temp; +} + //assumes little endian char * printBits(size_t const size, void const * const ptr) { diff --git a/client/util.h b/client/util.h index a6d0f49f..fb587da0 100644 --- a/client/util.h +++ b/client/util.h @@ -44,6 +44,7 @@ char * sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t bre void num_to_bytes(uint64_t n, size_t len, uint8_t* dest); uint64_t bytes_to_num(uint8_t* src, size_t len); char * printBits(size_t const size, void const * const ptr); +uint8_t *SwapEndian64(uint8_t *src, size_t len); char param_getchar(const char *line, int paramnum); uint8_t param_get8(const char *line, int paramnum); From 75377d29d6f63cf67e427727706fe19149640861 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 6 May 2015 00:55:29 -0400 Subject: [PATCH 028/132] MFU - Icemans further improvements add UL-C device side read card with authentication add MF_UL-Annotations add ntag, and more ul descriptions in hf mfu info --- armsrc/appmain.c | 4 +- armsrc/apps.h | 2 +- armsrc/mifarecmd.c | 93 ++++-- client/cmdhf.c | 43 ++- client/cmdhfmfu.c | 730 ++++++++++++++++++++++++++++++++++----------- client/cmdhfmfu.h | 2 +- 6 files changed, 667 insertions(+), 207 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 128f4063..48b8c0dd 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -833,10 +833,8 @@ void UsbPacketReceived(uint8_t *packet, int len) MifareUC_Auth2(c->arg[0],c->d.asBytes); break; case CMD_MIFAREU_READCARD: - MifareUReadCard(c->arg[0], c->arg[1], c->d.asBytes); - break; case CMD_MIFAREUC_READCARD: - MifareUReadCard(c->arg[0], c->arg[1], c->d.asBytes); + MifareUReadCard(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; case CMD_MIFAREUC_SETPWD: MifareUSetPwd(c->arg[0], c->d.asBytes); diff --git a/armsrc/apps.h b/armsrc/apps.h index 7e4aa5e1..d01c6478 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -168,7 +168,7 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *data); void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareUC_Auth1(uint8_t arg0, uint8_t *datain); void MifareUC_Auth2(uint32_t arg0, uint8_t *datain); -void MifareUReadCard(uint8_t arg0, int Pages, uint8_t *datain); +void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain); void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareUWriteBlock(uint8_t arg0,uint8_t *datain); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 3a932409..c51a30dc 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -143,6 +143,9 @@ void MifareUC_Auth2(uint32_t arg0, uint8_t *datain){ LEDsoff(); } +// Arg0 = BlockNo, +// Arg1 = UsePwd bool +// datain = PWD bytes, void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; @@ -151,8 +154,8 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) uint8_t key[16] = {0x00}; bool usePwd = (arg1 == 1); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - + LEDsoff(); + LED_A_ON(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); @@ -193,10 +196,7 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) // decrypt nonce. tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV ); - - rol(random_b,8); - memcpy(rnd_ab ,random_a,8); memcpy(rnd_ab+8,random_b,8); @@ -221,7 +221,6 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) // encrypt out, in, length, key, iv tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); if (len != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); @@ -342,13 +341,14 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } -void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain) +void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { // params - uint8_t sectorNo = arg0; - int Pages = arg1; - int countpages = 0; - byte_t dataout[176] = {0x00};; + uint8_t blockNo = arg0; + uint16_t blocks = arg1; + bool useKey = (arg2 == 1); + int countblocks = 0; + uint8_t dataout[176] = {0x00}; LEDsoff(); LED_A_ON(); @@ -361,32 +361,81 @@ void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain) OnError(1); return; } - - for (int i = 0; i < Pages; i++){ - - len = mifare_ultra_readblock(sectorNo * 4 + i, dataout + 4 * i); - + + // authenticate + if ( useKey ) { + uint8_t key[16] = {0x00}; + memcpy(key, datain, 16); + + uint8_t random_a[8] = {1,1,1,1,1,1,1,1 }; + uint8_t random_b[8] = {0x00}; + uint8_t enc_random_b[8] = {0x00}; + uint8_t rnd_ab[16] = {0x00}; + uint8_t IV[8] = {0x00}; + + uint16_t len; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; + + len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); + if (len != 11) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + OnError(1); + return; + } + + // tag nonce. + memcpy(enc_random_b,receivedAnswer+1,8); + + // decrypt nonce. + tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV ); + rol(random_b,8); + memcpy(rnd_ab ,random_a,8); + memcpy(rnd_ab+8,random_b,8); + + // encrypt out, in, length, key, iv + tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); + + len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); + if (len != 11) { + OnError(1); + return; + } + + uint8_t enc_resp[8] = { 0 }; + uint8_t resp_random_a[8] = { 0 }; + memcpy(enc_resp, receivedAnswer+1, 8); + + // 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 ) + Dbprintf("failed authentication"); + } + + for (int i = 0; i < blocks; i++){ + len = mifare_ultra_readblock(blockNo * 4 + i, dataout + 4 * i); + if (len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block %d error",i); OnError(2); return; } else { - countpages++; + countblocks++; } } - + len = mifare_ultra_halt(); if (len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); OnError(3); return; } - - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Pages read %d", countpages); - len = Pages * 4; + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks); - cmd_send(CMD_ACK, 1, 0, 0, dataout, len); + len = blocks * 4; + + cmd_send(CMD_ACK, 1, len, 0, dataout, len); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } diff --git a/client/cmdhf.c b/client/cmdhf.c index 22063bbb..b2950ed0 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -71,11 +71,52 @@ void annotateIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) case MIFARE_CMD_DEC: snprintf(exp,size,"DEC(%d)",cmd[1]); break; case MIFARE_CMD_RESTORE: snprintf(exp,size,"RESTORE(%d)",cmd[1]); break; case MIFARE_CMD_TRANSFER: snprintf(exp,size,"TRANSFER(%d)",cmd[1]); break; - case MIFARE_AUTH_KEYA: snprintf(exp,size,"AUTH-A(%d)",cmd[1]); break; + case MIFARE_AUTH_KEYA:{ + if ( cmdsize > 3) + snprintf(exp,size,"AUTH-A(%d)",cmd[1]); + else + // case MIFARE_ULEV1_VERSION : both 0x60. + snprintf(exp,size,"EV1 VERSION"); + break; + } case MIFARE_AUTH_KEYB: snprintf(exp,size,"AUTH-B(%d)",cmd[1]); break; case MIFARE_MAGICWUPC1: snprintf(exp,size,"MAGIC WUPC1"); break; case MIFARE_MAGICWUPC2: snprintf(exp,size,"MAGIC WUPC2"); break; 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: snprintf(exp,size,"PWD-AUTH"); break; + case MIFARE_ULEV1_FASTREAD:{ + if ( cmdsize >=3 && cmd[2] < 0x21) + snprintf(exp,size,"READ RANGE (%d-%d)",cmd[1],cmd[2]); + else + snprintf(exp,size,"?"); + break; + } + case MIFARE_ULEV1_WRITE:{ + if ( cmd[1] < 0x21 ) + snprintf(exp,size,"WRITEBLOCK(%d)",cmd[1]); + else + snprintf(exp,size,"?"); + break; + } + case MIFARE_ULEV1_READ_CNT:{ + if ( cmd[1] < 5 ) + snprintf(exp,size,"READ CNT(%d)",cmd[1]); + else + snprintf(exp,size,"?"); + break; + } + case MIFARE_ULEV1_INCR_CNT:{ + if ( cmd[1] < 5 ) + snprintf(exp,size,"INCR(%d)",cmd[1]); + else + snprintf(exp,size,"?"); + break; + } + case MIFARE_ULEV1_READSIG: snprintf(exp,size,"READ_SIG"); break; + case MIFARE_ULEV1_CHECKTEAR: snprintf(exp,size,"CHK_TEARING(%d)",cmd[1]); break; + case MIFARE_ULEV1_VCSL: snprintf(exp,size,"VCSL"); break; default: snprintf(exp,size,"?"); break; } return; diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 620f1b0e..396eb239 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -13,11 +13,31 @@ #include "cmdhf14a.h" #include "mifare.h" #include "util.h" +#include "protocols.h" -#define MAX_UL_BLOCKS 0x0f -#define MAX_ULC_BLOCKS 0x2f -#define MAX_ULEV1a_BLOCKS 0x0b; -#define MAX_ULEV1b_BLOCKS 0x20; +#define MAX_UL_BLOCKS 0x0f +#define MAX_ULC_BLOCKS 0x2f +#define MAX_ULEV1a_BLOCKS 0x0b +#define MAX_ULEV1b_BLOCKS 0x20 +#define MAX_NTAG_213 0x2c +#define MAX_NTAG_215 0x86 +#define MAX_NTAG_216 0xe6 + +typedef enum TAGTYPE_UL { + UNKNOWN = 0x0000, + UL = 0x0001, + UL_C = 0x0002, + UL_EV1_48 = 0x0004, + UL_EV1_128 = 0x0008, + NTAG = 0x0010, + NTAG_213 = 0x0020, + NTAG_215 = 0x0040, + NTAG_216 = 0x0080, + MAGIC = 0x0100, + UL_MAGIC = UL | MAGIC, + UL_C_MAGIC = UL_C | MAGIC, + UL_ERROR = 0xFFFF, +} TagTypeUL_t; uint8_t default_3des_keys[7][16] = { { 0x42,0x52,0x45,0x41,0x4b,0x4d,0x45,0x49,0x46,0x59,0x4f,0x55,0x43,0x41,0x4e,0x21 },// 3des std key @@ -27,185 +47,531 @@ uint8_t default_3des_keys[7][16] = { { 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01 },// all ones { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF },// all FF { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF } // 11 22 33 - }; - +}; + static int CmdHelp(const char *Cmd); -// return 1 if tag responded to 0x1A. -uint8_t requestAuthentication( uint8_t* nonce){ +char* getProductTypeStr( uint8_t id){ - UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC ,2 ,0}}; - c.d.asBytes[0] = 0x1A; - c.d.asBytes[1] = 0x00; + static char buf[20]; + char *retStr = buf; + + switch(id) { + case 3: + sprintf(retStr, "0x%02X %s", id, "(Ultralight)"); + break; + case 4: + sprintf(retStr, "0x%02X %s", id, "(NTAG)"); + break; + default: + sprintf(retStr, "0x%02X %s", id, "(unknown)"); + break; + } + return buf; +} + +/* + 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). +*/ +char* getUlev1CardSizeStr( uint8_t fsize ){ + + static char buf[30]; + char *retStr = buf; + + uint8_t usize = 1 << ((fsize >>1) + 1); + uint8_t lsize = 1 << (fsize >>1); + + // is LSB set? + if ( fsize & 1 ) + sprintf(retStr, "0x%02X (%u - %u bytes)",fsize, usize, lsize); + else + sprintf(retStr, "0x%02X (%u bytes)", fsize, lsize); + return buf; +} + +static void ul_switch_on_field(void) { + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}}; SendCommand(&c); - UsbCommand resp; - WaitForResponse(CMD_ACK, &resp); // skip select answer. +} - if ( !(resp.arg[0] & 0xff) ) - return 0; +static void ul_switch_off_field(void) { + UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; + SendCommand(&c); +} + +static int ul_send_cmd_raw( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uint16_t responseLength ) { + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_APPEND_CRC, cmdlen, 0}}; + memcpy(c.d.asBytes, cmd, cmdlen); + SendCommand(&c); + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + + uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; + if (resp.arg[0] > 0) { + memcpy(response, resp.d.asBytes, resplen); + return resplen; + } else return -1; +} +/* +static int ul_send_cmd_raw_crc( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uint16_t responseLength, bool append_crc ) { + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT , cmdlen, 0}}; + if (append_crc) + c.arg[0] |= ISO14A_APPEND_CRC; + + memcpy(c.d.asBytes, cmd, cmdlen); + SendCommand(&c); + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + + uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; + if (resp.arg[0] > 0) { + memcpy(response, resp.d.asBytes, resplen); + return resplen; + } else return -1; +} +*/ +static int ul_select( iso14a_card_select_t *card ){ + + ul_switch_on_field(); + + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if (resp.arg[0] < 1) return -1; + + memcpy(card, resp.d.asBytes, sizeof(iso14a_card_select_t)); + return resp.arg[0]; +} + +// This read command will at least return 16bytes. +static int ul_read( uint8_t page, uint8_t *response, uint16_t responseLength ){ + + uint8_t cmd[] = {ISO14443A_CMD_READBLOCK, page}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + if ( len == -1 ) + ul_switch_off_field(); + return len; +} + +static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t nonceLength ){ + + uint8_t cmd[] = {MIFARE_ULC_AUTH_1, blockNo}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), nonce, nonceLength); + if ( len == -1 ) + ul_switch_off_field(); + return len; +} + +static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ + + uint8_t cmd[] = {MIFARE_ULEV1_AUTH, pwd[0], pwd[1], pwd[2], pwd[3]}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), pack, packLength); + if ( len == -1) + ul_switch_off_field(); + return len; +} + +static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ + + uint8_t cmd[] = {MIFARE_ULEV1_VERSION}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + if ( len == -1 ) + ul_switch_off_field(); + return len; +} + +// static int ulev1_fastRead( uint8_t startblock, uint8_t endblock, uint8_t *response ){ - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + // uint8_t cmd[] = {MIFARE_ULEV1_FASTREAD, startblock, endblock}; - if ( resp.arg[0] & 0xff ) { - memcpy(nonce, resp.d.asBytes+1, 8); - return 1; - } - } + // if ( !ul_send_cmd_raw(cmd, sizeof(cmd), response)){ + // ul_switch_off_field(); + // return -1; + // } + // return 0; +// } + +static int ulev1_readCounter( uint8_t counter, uint8_t *response, uint16_t responseLength ){ + + uint8_t cmd[] = {MIFARE_ULEV1_READ_CNT, counter}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + if (len == -1) + ul_switch_off_field(); + return len; +} + +static int ul_print_default( uint8_t *data){ + + uint8_t uid[7]; + + uid[0] = data[0]; + uid[1] = data[1]; + uid[2] = data[2]; + uid[3] = data[4]; + uid[4] = data[5]; + uid[5] = data[6]; + uid[6] = data[7]; + + PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); + PrintAndLog(" UID[0] : (Manufacturer Byte) = %02x, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); + + // BBC + // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 + int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; + if ( data[3] == crc0 ) + PrintAndLog(" BCC0 : 0x%02X - Ok", data[3]); + else + PrintAndLog(" BCC0 : 0x%02X - crc should be %02x", data[3], crc0); + + int crc1 = data[4] ^ data[5] ^ data[6] ^data[7]; + if ( data[8] == crc1 ) + PrintAndLog(" BCC1 : 0x%02X - Ok", data[8]); + else + PrintAndLog(" BCC1 : 0x%02X - crc should be 0x%02X", data[8], crc1 ); + + PrintAndLog(" Internal : 0x%02X - %s default", data[9], (data[9]==0x48)?"":"not" ); + PrintAndLog(" Lock : %s - %s", sprint_hex(data+10, 2),printBits( 2, data+10) ); + PrintAndLog("OneTimePad : %s ", sprint_hex(data + 12, 4)); + PrintAndLog(""); return 0; } -typedef enum TAGTYPE_UL { - UNKNOWN = 0x00, - UL = 0x01, - UL_C = 0x02, - UL_EV1_48 = 0x04, - UL_EV1_128 = 0x08, - MAGIC = 0x10, - UL_MAGIC = UL | MAGIC, - UL_C_MAGIC = UL_C | MAGIC, - UL_ERROR = 0xFF, -} TagTypeUL_t; +static int ul_print_CC(uint8_t *data) { + if(data[0] != 0xe1) { + PrintAndLog("no NDEF message"); + return -1; // no NDEF message + } -uint8_t GetHF14AMfU_Type(void){ + PrintAndLog("Capability Container: %s", sprint_hex(data,4) ); + PrintAndLog(" %02X: NDEF Magic Number", data[0]); + PrintAndLog(" %02X: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); + PrintAndLog(" %02X: Physical Memory Size of this tag: %d bytes", data[2], (data[2] + 1) * 8); + PrintAndLog(" %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; +} + +static int ul_print_version(uint8_t *data){ + PrintAndLog("\n--- UL-EV1 / NTAG Version"); + PrintAndLog("Raw version bytes: %s", sprint_hex(data, 8) ); + PrintAndLog(" Vendor ID : 0x%02X, Manufacturer: %s", data[1], getTagInfo(data[1])); + PrintAndLog(" Product type : %s" , getProductTypeStr(data[2])); + PrintAndLog(" Product subtype : 0x%02X %s" , data[3], (data[3]==1) ?"17 pF":"50pF"); + PrintAndLog(" Major version : 0x%02X" , data[4]); + PrintAndLog(" Minor version : 0x%02X" , data[5]); + PrintAndLog(" Size : %s", getUlev1CardSizeStr(data[6])); + PrintAndLog(" Protocol type : 0x%02X" , data[7]); + return 0; +} + +static int ul_print_type(uint16_t tagtype){ + if ( tagtype & UL ) + PrintAndLog(" TYPE : MIFARE Ultralight (MF0ICU1) %s", (tagtype & MAGIC)?"":""); + else if ( tagtype & UL_C) + PrintAndLog(" TYPE : MIFARE Ultralight C (MF0ULC) %s [%x]", (tagtype & MAGIC)?"":"", tagtype ); + else if ( tagtype & UL_EV1_48) + PrintAndLog(" TYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)"); + else if ( tagtype & UL_EV1_128) + PrintAndLog(" TYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)"); + else if ( tagtype & NTAG_213 ) + PrintAndLog(" TYPE : MIFARE NTAG 213 144bytes (NT2H1311G0DU)"); + else if ( tagtype & NTAG_215 ) + PrintAndLog(" TYPE : MIFARE NTAG 215 504bytes (NT2H1511G0DU)"); + else if ( tagtype & NTAG_216 ) + PrintAndLog(" TYPE : MIFARE NTAG 216 888bytes (NT2H1611G0DU)"); + else + PrintAndLog(" TYPE : Unknown %04x",tagtype); + return 0; +} + +static int ulc_print_3deskey( uint8_t *data){ + PrintAndLog(" deskey1 [44/0x2C]: %s", sprint_hex(data ,4)); + PrintAndLog(" deskey1 [45/0x2D]: %s", sprint_hex(data+4 ,4)); + PrintAndLog(" deskey2 [46/0x2E]: %s", sprint_hex(data+8 ,4)); + PrintAndLog(" deskey2 [47/0x2F]: %s", sprint_hex(data+12,4)); + PrintAndLog(" 3des key : %s", sprint_hex(SwapEndian64(data, 16), 16)); + return 0; +} + +static int ulc_print_configuration( uint8_t *data){ + + PrintAndLog("--- UL-C Configuration"); + PrintAndLog(" Higher Lockbits [40/0x28]: %s %s", sprint_hex(data, 4), printBits(2, data)); + PrintAndLog(" Counter [41/0x29]: %s %s", sprint_hex(data+4, 4), printBits(2, data+4)); + + bool validAuth = (data[8] >= 0x03 && data[8] <= 0x30); + if ( validAuth ) + PrintAndLog(" Auth0 [42/0x2A]: %s - Pages above %d needs authentication", sprint_hex(data+8, 4), data[8] ); + else{ + if ( data[8] == 0){ + PrintAndLog(" Auth0 [42/0x2A]: %s - default", sprint_hex(data+8, 4) ); + } else { + PrintAndLog(" Auth0 [42/0x2A]: %s - auth byte is out-of-range", sprint_hex(data+8, 4) ); + } + } + PrintAndLog(" Auth1 [43/0x2B]: %s - %s", + sprint_hex(data+12, 4), + (data[12] & 1) ? "write access restricted": "read and write access restricted" + ); + return 0; +} + +static int ulev1_print_configuration( uint8_t *data){ + + PrintAndLog("\n--- UL-EV1 Configuration"); + + bool strg_mod_en = (data[0] & 2); + uint8_t authlim = (data[4] & 0x07); + bool cfglck = (data[4] & 0x40); + bool prot = (data[4] & 0x80); + uint8_t vctid = data[5]; + + PrintAndLog(" cfg0 [16/0x10]: %s", sprint_hex(data, 4)); + PrintAndLog(" - pages above %d needs authentication",data[3]); + PrintAndLog(" - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); + PrintAndLog(" cfg1 [17/0x11]: %s", sprint_hex(data+4, 4) ); + if ( authlim == 0) + PrintAndLog(" - Max number of password attempts is unlimited"); + else + PrintAndLog(" - Max number of password attempts is %d", authlim); + PrintAndLog(" - user configuration %s", cfglck ? "permanently locked":"writeable"); + PrintAndLog(" - %s access is protected with password", prot ? "read and write":"write"); + PrintAndLog(" 0x%02X - Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); + PrintAndLog(" PWD [18/0x12]: %s", sprint_hex(data+8, 4)); + PrintAndLog(" PACK [19/0x13]: %s", sprint_hex(data+12, 4)); + return 0; +} + +static int ulev1_print_counters(){ + PrintAndLog("--- UL-EV1 Counters"); + uint8_t counter[3] = {0,0,0}; + for ( uint8_t i = 0; i<3; ++i) { + ulev1_readCounter(i,counter, sizeof(counter) ); + PrintAndLog("Counter [%d] : %s", i, sprint_hex(counter,3)); + } + return 0; +} + +uint16_t GetHF14AMfU_Type(void){ TagTypeUL_t tagtype = UNKNOWN; iso14a_card_select_t card; + uint8_t version[10] = {0x00}; + uint8_t nonce1[11] = {0x00}; + uint8_t nonce2[11] = {0x00}; + int status = 0; + int len; - // select and run 0x60 (GET_VERSION - EV1 command) - UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_RAW | ISO14A_APPEND_CRC, 1, 0}}; - c.d.asBytes[0] = 0x60; - SendCommand(&c); - UsbCommand resp; - WaitForResponse(CMD_ACK, &resp); - - if ( resp.arg[0] == 0 ) return UL_ERROR; - - memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("Error: couldn't select"); + ul_switch_off_field(); + return UL_ERROR; + } // Ultralight - ATQA / SAK - if ( card.atqa[1] != 0x00 && card.atqa[0] != 0x44 && card.sak != 0x00 ) return UL_ERROR; - - // EV1 GetVersion - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { - - uint8_t version[10] = {0,0,0,0,0,0,0,0,0,0}; - memcpy(version, resp.d.asBytes, resp.arg[0] < sizeof(version) ? resp.arg[0] : sizeof(version)); - uint8_t len = resp.arg[0] & 0xff; - - if ( len == 0x0A && version[6] == 0x0B ) - tagtype = UL_EV1_48; - else if ( len == 0x0A && version[6] != 0x0B ) - tagtype = UL_EV1_128; - else if ( len == 0x01 ) - tagtype = UL_C; - else if ( len == 0x00 ) - tagtype = UL; + if ( card.atqa[1] != 0x00 && card.atqa[0] != 0x44 && card.sak != 0x00 ) { + ul_switch_off_field(); + return UL_ERROR; } - - // Magic UL-C, mine have a static nonce response to 0x1A command. - uint8_t nonce1[8] = {0,0,0,0,0,0,0,0}; - uint8_t nonce2[8] = {0,0,0,0,0,0,0,0}; - uint8_t status = requestAuthentication(nonce1); - if ( status ) { - requestAuthentication(nonce2); - if ( !memcmp(nonce1, nonce2, 8) ){ - tagtype = UL_C_MAGIC; + + len = ulev1_getVersion(version, sizeof(version)); + ul_switch_off_field(); + + switch (len) { + case -1: + tagtype = (UL | UL_C); + break; + case 0x0A: { + + if ( version[2] == 0x03 && version[6] == 0x0B ) + tagtype = UL_EV1_48; + else if ( version[2] == 0x03 && version[6] != 0x0B ) + tagtype = UL_EV1_128; + else if ( version[2] == 0x04 && version[6] == 0x0F ) + tagtype = NTAG_213; + else if ( version[2] == 0x04 && version[6] != 0x11 ) + tagtype = NTAG_215; + else if ( version[2] == 0x04 && version[6] == 0x13 ) + tagtype = NTAG_216; + else if ( version[2] == 0x04 ) + tagtype = NTAG; + + break; + } + case 0x01:{ + tagtype = UL_C; + break; + } + case 0x00: { + tagtype = UL; + break; + } + default :{ + tagtype = UNKNOWN; + break; } - } else { - // Magic Ultralight test here - TODO } + + if ((tagtype & ( UL_C | UL ))) { + // Magic UL-C, by observation, + // it seems to have a static nonce response to 0x1A command. + status = ul_select(&card); + status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); + if ( status > 0 ) { + + status = ulc_requestAuthentication(0, nonce2, sizeof(nonce2)); + + tagtype =( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; + + } else { + tagtype = UL; + } + ul_switch_off_field(); + } + + //PrintAndLog("ICE %d", tagtype); + //Magic Ultralight test here. It takes present UID, and tries to write it back. + if ( (tagtype & UL) ){ + // read 3des key or PWD, + // if response bytes == all zeros its a NORMAL tag. + //return UL_MAGIC; + } + return tagtype; } int CmdHF14AMfUInfo(const char *Cmd){ - uint8_t datatemp[7] = {0x00}; - uint8_t isOK = 0; + uint8_t data[16] = {0x00}; + iso14a_card_select_t card; uint8_t *key; + int status; + + PrintAndLog("\n--- Tag Information ---------"); + PrintAndLog("-------------------------------------------------------------"); TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; - - PrintAndLog("\n-- Tag Information ---------"); - PrintAndLog("-------------------------------------------------------------"); - if ( tagtype & UL ) - PrintAndLog(" TYPE : MIFARE Ultralight %s", (tagtype & MAGIC)?"(magic)":""); - else if ( tagtype & UL_C) - PrintAndLog(" TYPE : MIFARE Ultralight C %s", (tagtype & MAGIC)?"(magic)":"" ); - else if ( tagtype & UL_EV1_48) - PrintAndLog(" TYPE : MIFARE Ultralight EV1 48 bytes"); - else if ( tagtype & UL_EV1_128) - PrintAndLog(" TYPE : MIFARE Ultralight EV1 128 bytes"); - else - PrintAndLog(" TYPE : Unknown %x",tagtype); + ul_print_type(tagtype); - // read pages 0,1,2,4 - UsbCommand c = {CMD_MIFAREU_READCARD, {0, 4}}; - SendCommand(&c); - UsbCommand resp; - - if (WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { - isOK = resp.arg[0] & 0xff; - memcpy(data, resp.d.asBytes, sizeof(data)); - - if (!isOK) { - PrintAndLog("Error reading from tag"); - return -1; - } - } else { - PrintAndLog("Command execute timed out"); - return -1; + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("Error: couldn't select"); + ul_switch_off_field(); + return status; } - // UID - memcpy( datatemp, data, 3); - memcpy( datatemp+3, data+4, 4); - - PrintAndLog(" UID : %s ", sprint_hex(datatemp, 7)); - PrintAndLog(" UID[0] : (Manufacturer Byte) = %02x, Manufacturer: %s", datatemp[0], getTagInfo(datatemp[0]) ); - - // BBC - // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 - int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; - if ( data[3] == crc0 ) - PrintAndLog(" BCC0 : %02x - Ok", data[3]); - else - PrintAndLog(" BCC0 : %02x - crc should be %02x", data[3], crc0); - - int crc1 = data[4] ^ data[5] ^ data[6] ^data[7]; - if ( data[8] == crc1 ) - PrintAndLog(" BCC1 : %02x - Ok", data[8]); - else - PrintAndLog(" BCC1 : %02x - crc should be %02x", data[8], crc1 ); - - PrintAndLog(" Internal : %s ", sprint_hex(data + 9, 1)); - - memcpy(datatemp, data+10, 2); - PrintAndLog(" Lock : %s - %s", sprint_hex(datatemp, 2),printBits( 2, &datatemp) ); - PrintAndLog("OneTimePad : %s ", sprint_hex(data + 3*4, 4)); - PrintAndLog(""); - - - PrintAndLog("--- "); + // read pages 0,1,2,4 (should read 4pages) + status = ul_read(0, data, sizeof(data)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ A"); + ul_switch_off_field(); + return status; + } + + ul_print_default(data); + if ((tagtype & UL_C)){ - - PrintAndLog("Trying some default 3des keys"); - - for (uint8_t i = 0; i < 5; ++i ){ - key = default_3des_keys[i]; - if (try3DesAuthentication(key)){ - PrintAndLog("Found default 3des key: %s", sprint_hex(key,16)); - return 0; + + // read pages 0x28, 0x29, 0x2A, 0x2B + uint8_t ulc_conf[16] = {0x00}; + status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ - possibly locked"); + //ul_switch_off_field(); + //return status; + + //tag may be locked + } else ulc_print_configuration(ulc_conf); + + if ((tagtype & MAGIC)){ + + uint8_t ulc_deskey[16] = {0x00}; + status = ul_read(0x2C, ulc_deskey, sizeof(ulc_deskey)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ B"); + ul_switch_off_field(); + return status; } - } + + ulc_print_3deskey(ulc_deskey); + + } + else { + PrintAndLog("Trying some default 3des keys"); + ul_switch_off_field(); + for (uint8_t i = 0; i < 7; ++i ){ + key = default_3des_keys[i]; + if (try3DesAuthentication(key) == 1){ + PrintAndLog("Found default 3des key: %s", sprint_hex(key,16)); + return 0; + } + } + } } - else if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { + + if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { + + ulev1_print_counters(); + + uint8_t startconfigblock = (tagtype & UL_EV1_48) ? 0x10 : 0x24; + uint8_t ulev1_conf[16] = {0x00}; + status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ C"); + ul_switch_off_field(); + return status; + } + + ulev1_print_configuration(ulev1_conf); + } + + if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216))) { + + uint8_t version[10] = {0x00}; + status = ulev1_getVersion(version, sizeof(version)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to GETVERSION"); + ul_switch_off_field(); + return status; + } + ul_print_version(version); + //********** TODO ******************************** // --problem, there is a failed pwd tries counter in UL-EV1 - //PrintAndLog("Trying some known EV1 passwords."); + PrintAndLog("\nTrying some known EV1/NTAG passwords."); + + uint8_t password[4] ={0xff,0xff,0xff,0xff}; + uint8_t pack[4] = {0,0,0,0}; + status = ulev1_requestAuthentication(password, pack, sizeof(pack)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to AUTHENTICATE"); + ul_switch_off_field(); + return status; + } + PrintAndLog("Found default password: %s",sprint_hex(password, sizeof(password))); + PrintAndLog("Got PACK : %s", sprint_hex(pack,sizeof(pack))); } + + if ((tagtype & (NTAG_213 | NTAG_215 | NTAG_216))){ + + PrintAndLog("\n--- NTAG NDEF Message"); + uint8_t cc[16] = {0x00}; + status = ul_read(2, cc, sizeof(cc)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ D"); + ul_switch_off_field(); + return status; + } + ul_print_CC(cc); + } + + ul_switch_off_field(); return 0; } @@ -326,6 +692,11 @@ int usage_hf_mfu_dump(void) PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("It autodetects card type.\n"); PrintAndLog("Usage: hf mfu dump k n "); + PrintAndLog(" Options : "); + PrintAndLog(" k : Enter key for authentication"); + PrintAndLog(" n : Enter filename w/o .bin to save the dump as"); + PrintAndLog(" s : Swap entered key's endianness for auth"); + PrintAndLog(""); PrintAndLog(" sample : hf mfu dump"); PrintAndLog(" : hf mfu dump n myfile"); return 0; @@ -354,9 +725,11 @@ int CmdHF14AMfUDump(const char *Cmd){ bool tmplockbit = false; uint8_t dataLen=0; uint8_t cmdp =0; - uint8_t *key= NULL; + uint8_t key[16] = {0x00}; + uint8_t *keyPtr = key; size_t fileNlen = 0; - bool errors = FALSE; + bool errors = false; + bool swapEndian = false; while(param_getchar(Cmd, cmdp) != 0x00) { @@ -371,8 +744,7 @@ int CmdHF14AMfUDump(const char *Cmd){ if (dataLen) { errors = true; } else { - key = SwapEndian64(data, 16); - PrintAndLog("3des key: %s",sprint_hex(key, 16)); + memcpy(key, data, 16); } cmdp += 2; hasPwd = true; @@ -384,6 +756,9 @@ int CmdHF14AMfUDump(const char *Cmd){ if (fileNlen > FILE_PATH_SIZE-5) fileNlen = FILE_PATH_SIZE-5; cmdp += 2; break; + case 's': + swapEndian = true; + cmdp++; default: PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -393,10 +768,10 @@ int CmdHF14AMfUDump(const char *Cmd){ } //Validations - if(errors) - { - return usage_hf_mfu_dump(); - } + if(errors) return usage_hf_mfu_dump(); + + if (swapEndian) + keyPtr = SwapEndian64(data, 16); TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -421,27 +796,24 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLog("Dumping unknown Ultralight, using default values."); } - for (uint8_t i = 0; i "); + PrintAndLog("Usage: hf mfu crdbl "); PrintAndLog(""); PrintAndLog("sample: hf mfu crdbl 0"); PrintAndLog(" hf mfu crdbl 0 00112233445566778899AABBCCDDEEFF"); return 0; - } - + } + blockNo = param_get8(Cmd, 0); if (blockNo < 0) { PrintAndLog("Wrong block number"); return 1; } - + if (blockNo > MAX_ULC_BLOCKS ){ PrintAndLog("Error: Maximum number of blocks is 47 for Ultralight-C"); return 1; @@ -796,13 +1168,13 @@ int CmdHF14AMfUCRdBl(const char *Cmd) hasPwd = TRUE; } } - uint8_t *key2 = SwapEndian64(key, 16); + //uint8_t *key2 = SwapEndian64(key, 16); //Read Block UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; if ( hasPwd ) { c.arg[1] = 1; - memcpy(c.d.asBytes,key2,16); + memcpy(c.d.asBytes,key,16); } SendCommand(&c); diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 64f32a49..8e96775c 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -19,7 +19,7 @@ void rol (uint8_t *data, const size_t len); uint8_t requestAuthentication( uint8_t *nonce); int try3DesAuthentication( uint8_t *key); -uint8_t GetHF14AMfU_Type(void); +uint16_t GetHF14AMfU_Type(void); int usage_hf_mfu_dump(void); From abab60ae216172735f511e116eb3dc87004d168d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 6 May 2015 09:27:03 -0400 Subject: [PATCH 029/132] MFU info adjustments --- client/cmdhfmfu.c | 31 ++++++++++++++++--------------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 396eb239..607cad96 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -107,12 +107,11 @@ static int ul_send_cmd_raw( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uin SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if (resp.arg[0] < 1) return -1; uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; - if (resp.arg[0] > 0) { - memcpy(response, resp.d.asBytes, resplen); - return resplen; - } else return -1; + memcpy(response, resp.d.asBytes, resplen); + return resplen; } /* static int ul_send_cmd_raw_crc( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uint16_t responseLength, bool append_crc ) { @@ -370,9 +369,9 @@ uint16_t GetHF14AMfU_Type(void){ ul_switch_off_field(); return UL_ERROR; } - // Ultralight - ATQA / SAK - if ( card.atqa[1] != 0x00 && card.atqa[0] != 0x44 && card.sak != 0x00 ) { + if ( card.atqa[1] != 0x00 || card.atqa[0] != 0x44 || card.sak != 0x00 ) { + PrintAndLog ("Tag is not UL or NTAG, ATQA1: %x, ATQA0: %x, SAK: %d", card.atqa[1],card.atqa[0],card.sak); ul_switch_off_field(); return UL_ERROR; } @@ -419,13 +418,15 @@ uint16_t GetHF14AMfU_Type(void){ // Magic UL-C, by observation, // it seems to have a static nonce response to 0x1A command. status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("Error: couldn't select B"); + ul_switch_off_field(); + return UL_ERROR; + } status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); if ( status > 0 ) { - status = ulc_requestAuthentication(0, nonce2, sizeof(nonce2)); - tagtype =( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; - } else { tagtype = UL; } @@ -451,12 +452,12 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t *key; int status; - PrintAndLog("\n--- Tag Information ---------"); - PrintAndLog("-------------------------------------------------------------"); TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; + PrintAndLog("\n--- Tag Information ---------"); + PrintAndLog("-------------------------------------------------------------"); ul_print_type(tagtype); status = ul_select(&card); @@ -483,11 +484,11 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ - possibly locked"); - //ul_switch_off_field(); - //return status; + ul_switch_off_field(); + return status; + } - //tag may be locked - } else ulc_print_configuration(ulc_conf); + ulc_print_configuration(ulc_conf); if ((tagtype & MAGIC)){ From 45673b94571cd29b00ef5e76b3bee395c2b9480f Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 6 May 2015 10:16:31 -0400 Subject: [PATCH 030/132] MFU adjustment to allow 0 len returns from raw cmds --- client/cmdhfmfu.c | 1 - 1 file changed, 1 deletion(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 607cad96..a94d8767 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -107,7 +107,6 @@ static int ul_send_cmd_raw( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uin SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; - if (resp.arg[0] < 1) return -1; uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; memcpy(response, resp.d.asBytes, resplen); From 372a82570b3a30ba3714bee9fbafbfe757439dc0 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 6 May 2015 10:17:39 -0400 Subject: [PATCH 031/132] MFU adj to allow 0 len returns on raw cmds --- client/cmdhfmfu.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index a94d8767..e24e3fad 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -107,6 +107,7 @@ static int ul_send_cmd_raw( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uin SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if (!resp.arg[0] && responseLength) return -1; uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; memcpy(response, resp.d.asBytes, resplen); From c585a5cf0b96d30119e1adb45c69e579e475d046 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 6 May 2015 22:15:41 -0400 Subject: [PATCH 032/132] further MFU info updates (mainly icemans) --- client/cmdhf.c | 2 +- client/cmdhfmfu.c | 241 ++++++++++++++++++++++++++++++---------------- client/util.c | 2 + 3 files changed, 160 insertions(+), 85 deletions(-) diff --git a/client/cmdhf.c b/client/cmdhf.c index b2950ed0..020ea94c 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -93,7 +93,7 @@ void annotateIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) snprintf(exp,size,"?"); break; } - case MIFARE_ULEV1_WRITE:{ + case MIFARE_ULC_WRITE:{ if ( cmd[1] < 0x21 ) snprintf(exp,size,"WRITEBLOCK(%d)",cmd[1]); else diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index e24e3fad..f8d38919 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -49,6 +49,12 @@ uint8_t default_3des_keys[7][16] = { { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF } // 11 22 33 }; +uint8_t default_pwd_pack[3][4] = { + {0xFF,0xFF,0xFF,0xFF}, // PACK 0x00,0x00 -- factory default + {0x4A,0xF8,0x4B,0x19}, // PACK 0xE5,0xBE -- italian bus (sniffed) + {0x05,0x22,0xE6,0xB4} // PACK 0x80,0x80 -- Amiiboo (sniffed) +}; + static int CmdHelp(const char *Cmd); char* getProductTypeStr( uint8_t id){ @@ -123,12 +129,11 @@ static int ul_send_cmd_raw_crc( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; + if (!resp.arg[0] && responseLength) return -1; uint16_t resplen = (resp.arg[0] < responseLength) ? resp.arg[0] : responseLength; - if (resp.arg[0] > 0) { - memcpy(response, resp.d.asBytes, resplen); - return resplen; - } else return -1; + memcpy(response, resp.d.asBytes, resplen); + return resplen; } */ static int ul_select( iso14a_card_select_t *card ){ @@ -153,6 +158,26 @@ static int ul_read( uint8_t page, uint8_t *response, uint16_t responseLength ){ return len; } +static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ + + uint8_t cmd[18]; + memset(cmd, 0x00, sizeof(cmd)); + datalen = ( datalen > 16) ? 16 : datalen; + + cmd[0] = ISO14443A_CMD_WRITEBLOCK; + cmd[1] = page; + memcpy(cmd+2, data, datalen); + + uint8_t response[1] = {0xff}; + int len = ul_send_cmd_raw(cmd, 2+datalen, response, sizeof(response)); + if ( len == -1 ) + ul_switch_off_field(); + // ACK + if ( response[0] == 0x0a ) return 0; + // NACK + return -1; +} + static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t nonceLength ){ uint8_t cmd[] = {MIFARE_ULC_AUTH_1, blockNo}; @@ -200,6 +225,15 @@ static int ulev1_readCounter( uint8_t counter, uint8_t *response, uint16_t respo return len; } +static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ + + uint8_t cmd[] = {MIFARE_ULEV1_READSIG, 0x00}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + if (len == -1) + ul_switch_off_field(); + return len; +} + static int ul_print_default( uint8_t *data){ uint8_t uid[7]; @@ -236,7 +270,7 @@ static int ul_print_default( uint8_t *data){ return 0; } -static int ul_print_CC(uint8_t *data) { +static int ntag_print_CC(uint8_t *data) { if(data[0] != 0xe1) { PrintAndLog("no NDEF message"); return -1; // no NDEF message @@ -245,16 +279,23 @@ static int ul_print_CC(uint8_t *data) { PrintAndLog("Capability Container: %s", sprint_hex(data,4) ); PrintAndLog(" %02X: NDEF Magic Number", data[0]); PrintAndLog(" %02X: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); - PrintAndLog(" %02X: Physical Memory Size of this tag: %d bytes", data[2], (data[2] + 1) * 8); + PrintAndLog(" %02X: Physical Memory Size: %d bytes", data[2], (data[2] + 1) * 8); + if ( data[2] == 0x12 ) + PrintAndLog(" %02X: NDEF Memory Size: &d bytes", data[2], 144); + else if ( data[2] == 0x3e ) + PrintAndLog(" %02X: NDEF Memory Size: &d bytes", data[2], 496); + else if ( data[2] == 0x6d ) + PrintAndLog(" %02X: NDEF Memory Size: &d bytes", data[2], 872); + PrintAndLog(" %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; } -static int ul_print_version(uint8_t *data){ +static int ulev1_print_version(uint8_t *data){ PrintAndLog("\n--- UL-EV1 / NTAG Version"); - PrintAndLog("Raw version bytes: %s", sprint_hex(data, 8) ); + PrintAndLog(" Raw bytes : %s", sprint_hex(data, 8) ); PrintAndLog(" Vendor ID : 0x%02X, Manufacturer: %s", data[1], getTagInfo(data[1])); PrintAndLog(" Product type : %s" , getProductTypeStr(data[2])); PrintAndLog(" Product subtype : 0x%02X %s" , data[3], (data[3]==1) ?"17 pF":"50pF"); @@ -286,10 +327,10 @@ static int ul_print_type(uint16_t tagtype){ } static int ulc_print_3deskey( uint8_t *data){ - PrintAndLog(" deskey1 [44/0x2C]: %s", sprint_hex(data ,4)); - PrintAndLog(" deskey1 [45/0x2D]: %s", sprint_hex(data+4 ,4)); - PrintAndLog(" deskey2 [46/0x2E]: %s", sprint_hex(data+8 ,4)); - PrintAndLog(" deskey2 [47/0x2F]: %s", sprint_hex(data+12,4)); + PrintAndLog(" deskey1 [44/0x2C]: %s [%.4s]", sprint_hex(data ,4),data); + PrintAndLog(" deskey1 [45/0x2D]: %s [%.4s]", sprint_hex(data+4 ,4),data+4); + PrintAndLog(" deskey2 [46/0x2E]: %s [%.4s]", sprint_hex(data+8 ,4),data+8); + PrintAndLog(" deskey2 [47/0x2F]: %s [%.4s]", sprint_hex(data+12,4),data+12); PrintAndLog(" 3des key : %s", sprint_hex(SwapEndian64(data, 16), 16)); return 0; } @@ -353,13 +394,69 @@ static int ulev1_print_counters(){ return 0; } +static int ulev1_print_signature( uint8_t *data, uint8_t len){ + PrintAndLog("\n--- UL-EV1 Signature"); + PrintAndLog("IC signature public key name : NXP NTAG21x 2013"); + PrintAndLog("IC signature public key value : 04494e1a386d3d3cfe3dc10e5de68a499b1c202db5b132393e89ed19fe5be8bc61"); + PrintAndLog(" Elliptic curve parameters : secp128r1"); + PrintAndLog(" Tag ECC Signature : %s", sprint_hex(data, len)); + //to do: verify if signature is valid + //PrintAndLog("IC signature status: %s valid", (iseccvalid() )?"":"not"); + return 0; +} + +static int ulc_magic_test(){ + // Magic Ultralight test + // Magic UL-C, by observation, + // 1) it seems to have a static nonce response to 0x1A command. + // 2) the deskey bytes is not-zero:d out on as datasheet states. + // 3) UID - changeable, not only, but pages 0-1-2-3. + // 4) use the ul_magic_test ! magic tags answers specially! + int returnValue = UL_ERROR; + iso14a_card_select_t card; + uint8_t nonce1[11] = {0x00}; + uint8_t nonce2[11] = {0x00}; + int status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("Error: couldn't select ulc_magic_test"); + ul_switch_off_field(); + return UL_ERROR; + } + status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); + if ( status > 0 ) { + status = ulc_requestAuthentication(0, nonce2, sizeof(nonce2)); + returnValue = ( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; + } else { + returnValue = UL; + } + ul_switch_off_field(); + return returnValue; +} + +static int ul_magic_test(){ + + // Magic Ultralight tests + // 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; + int status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("Error: couldn't select ul_magic_test"); + ul_switch_off_field(); + return UL_ERROR; + } + status = ul_comp_write(0, NULL, 0); + ul_switch_off_field(); + if ( status == 0) + return UL_MAGIC; + return UL; +} + uint16_t GetHF14AMfU_Type(void){ TagTypeUL_t tagtype = UNKNOWN; iso14a_card_select_t card; uint8_t version[10] = {0x00}; - uint8_t nonce1[11] = {0x00}; - uint8_t nonce2[11] = {0x00}; int status = 0; int len; @@ -380,9 +477,6 @@ uint16_t GetHF14AMfU_Type(void){ ul_switch_off_field(); switch (len) { - case -1: - tagtype = (UL | UL_C); - break; case 0x0A: { if ( version[2] == 0x03 && version[6] == 0x0B ) @@ -400,59 +494,26 @@ uint16_t GetHF14AMfU_Type(void){ break; } - case 0x01:{ - tagtype = UL_C; - break; - } - case 0x00: { - tagtype = UL; - break; - } - default :{ - tagtype = UNKNOWN; - break; - } + case 0x01: tagtype = UL_C; break; + case 0x00: tagtype = UL; break; + case -1 : tagtype = (UL | UL_C); break; + default : tagtype = UNKNOWN; break; } - if ((tagtype & ( UL_C | UL ))) { - // Magic UL-C, by observation, - // it seems to have a static nonce response to 0x1A command. - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("Error: couldn't select B"); - ul_switch_off_field(); - return UL_ERROR; - } - status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); - if ( status > 0 ) { - status = ulc_requestAuthentication(0, nonce2, sizeof(nonce2)); - tagtype =( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; - } else { - tagtype = UL; - } - ul_switch_off_field(); - } - - //PrintAndLog("ICE %d", tagtype); - //Magic Ultralight test here. It takes present UID, and tries to write it back. - if ( (tagtype & UL) ){ - // read 3des key or PWD, - // if response bytes == all zeros its a NORMAL tag. - //return UL_MAGIC; - } + if ((tagtype & ( UL_C | UL ))) tagtype = ulc_magic_test(); + if ((tagtype & UL)) tagtype = ul_magic_test(); return tagtype; } int CmdHF14AMfUInfo(const char *Cmd){ - + uint8_t authlim = 0xff; uint8_t data[16] = {0x00}; iso14a_card_select_t card; uint8_t *key; int status; - TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -499,17 +560,16 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); return status; } - ulc_print_3deskey(ulc_deskey); - } - else { + } else { PrintAndLog("Trying some default 3des keys"); ul_switch_off_field(); for (uint8_t i = 0; i < 7; ++i ){ key = default_3des_keys[i]; if (try3DesAuthentication(key) == 1){ - PrintAndLog("Found default 3des key: %s", sprint_hex(key,16)); + PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); + ulc_print_3deskey(SwapEndian64(key,16)); return 0; } } @@ -517,10 +577,8 @@ int CmdHF14AMfUInfo(const char *Cmd){ } if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { - - ulev1_print_counters(); - - uint8_t startconfigblock = (tagtype & UL_EV1_48) ? 0x10 : 0x24; + + uint8_t startconfigblock = (tagtype & UL_EV1_48) ? 0x10 : 0x25; uint8_t ulev1_conf[16] = {0x00}; status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); if ( status == -1 ){ @@ -528,8 +586,21 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); return status; } - + // save AUTHENTICATION LIMITS for later: + authlim = (ulev1_conf[4] & 0x07); + ulev1_print_configuration(ulev1_conf); + + uint8_t ulev1_signature[32] = {0x00}; + status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); + ul_switch_off_field(); + return status; + } + ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); + + ulev1_print_counters(); } if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216))) { @@ -541,26 +612,28 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); return status; } - ul_print_version(version); + ulev1_print_version(version); - //********** TODO ******************************** - // --problem, there is a failed pwd tries counter in UL-EV1 - PrintAndLog("\nTrying some known EV1/NTAG passwords."); - - uint8_t password[4] ={0xff,0xff,0xff,0xff}; - uint8_t pack[4] = {0,0,0,0}; - status = ulev1_requestAuthentication(password, pack, sizeof(pack)); - if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to AUTHENTICATE"); + // AUTHLIMIT, (number of failed authentications) + // 0 = limitless. + // 1-7 = ... should we even try then? + if ( authlim == 0 ){ + PrintAndLog("\n--- Known EV1/NTAG passwords."); + + uint8_t pack[4] = {0,0,0,0}; + + for (uint8_t i = 0; i < 3; ++i ){ + key = default_pwd_pack[i]; + if ( ulev1_requestAuthentication(key, pack, sizeof(pack)) > -1 ){ + PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); + } + } ul_switch_off_field(); - return status; } - PrintAndLog("Found default password: %s",sprint_hex(password, sizeof(password))); - PrintAndLog("Got PACK : %s", sprint_hex(pack,sizeof(pack))); } - + if ((tagtype & (NTAG_213 | NTAG_215 | NTAG_216))){ - + PrintAndLog("\n--- NTAG NDEF Message"); uint8_t cc[16] = {0x00}; status = ul_read(2, cc, sizeof(cc)); @@ -569,9 +642,9 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); return status; } - ul_print_CC(cc); + ntag_print_CC(cc); } - + ul_switch_off_field(); return 0; } diff --git a/client/util.c b/client/util.c index 5bb98fd7..54823422 100644 --- a/client/util.c +++ b/client/util.c @@ -112,6 +112,7 @@ char * sprint_hex(const uint8_t * data, const size_t len) { int maxLen = ( len > 1024/3) ? 1024/3 : len; static char buf[1024]; + memset(buf, 0x00, 1024); char * tmp = buf; size_t i; @@ -125,6 +126,7 @@ char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t brea int maxLen = ( len > 1024) ? 1024 : len; static char buf[1024]; + memset(buf, 0x00, 1024); char *tmp = buf; for (size_t i=0; i < maxLen; ++i){ From f805ac7a2b23e0508bd598c0afd438fb2cdb284d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 8 May 2015 13:01:27 -0400 Subject: [PATCH 033/132] minor adjustments to mfu info --- client/cmdhfmfu.c | 33 ++++++++++++++------------------- 1 file changed, 14 insertions(+), 19 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index f8d38919..523f505c 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -432,7 +432,7 @@ static int ulc_magic_test(){ ul_switch_off_field(); return returnValue; } - +/* static int ul_magic_test(){ // Magic Ultralight tests @@ -451,7 +451,7 @@ static int ul_magic_test(){ return UL_MAGIC; return UL; } - +*/ uint16_t GetHF14AMfU_Type(void){ TagTypeUL_t tagtype = UNKNOWN; @@ -474,7 +474,7 @@ uint16_t GetHF14AMfU_Type(void){ } len = ulev1_getVersion(version, sizeof(version)); - ul_switch_off_field(); + if (len > -1) ul_switch_off_field(); //if -1 it is already off switch (len) { case 0x0A: { @@ -496,12 +496,12 @@ uint16_t GetHF14AMfU_Type(void){ } case 0x01: tagtype = UL_C; break; case 0x00: tagtype = UL; break; - case -1 : tagtype = (UL | UL_C); break; + case -1 : tagtype = (UL | UL_C); break; //when does this happen? default : tagtype = UNKNOWN; break; } - if ((tagtype & ( UL_C | UL ))) tagtype = ulc_magic_test(); - if ((tagtype & UL)) tagtype = ul_magic_test(); + tagtype = (ul_magic_test() == UL_MAGIC) ? (tagtype | MAGIC) : tagtype; + //if ((tagtype & UL)) tagtype = ul_magic_test(); return tagtype; } @@ -531,7 +531,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ // read pages 0,1,2,4 (should read 4pages) status = ul_read(0, data, sizeof(data)); if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ A"); + PrintAndLog("Error: tag didn't answer to READ"); ul_switch_off_field(); return status; } @@ -545,7 +545,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ - possibly locked"); - ul_switch_off_field(); return status; } @@ -556,8 +555,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t ulc_deskey[16] = {0x00}; status = ul_read(0x2C, ulc_deskey, sizeof(ulc_deskey)); if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ B"); - ul_switch_off_field(); + PrintAndLog("Error: tag didn't answer to READ magic"); return status; } ulc_print_3deskey(ulc_deskey); @@ -582,8 +580,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t ulev1_conf[16] = {0x00}; status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ C"); - ul_switch_off_field(); + PrintAndLog("Error: tag didn't answer to READ EV1"); return status; } // save AUTHENTICATION LIMITS for later: @@ -595,7 +592,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); - ul_switch_off_field(); return status; } ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); @@ -609,7 +605,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ulev1_getVersion(version, sizeof(version)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to GETVERSION"); - ul_switch_off_field(); return status; } ulev1_print_version(version); @@ -621,14 +616,15 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("\n--- Known EV1/NTAG passwords."); uint8_t pack[4] = {0,0,0,0}; - + int len=0; //if len goes to -1 the connection will be turned off. for (uint8_t i = 0; i < 3; ++i ){ key = default_pwd_pack[i]; - if ( ulev1_requestAuthentication(key, pack, sizeof(pack)) > -1 ){ + if ( len > -1 ){ + len = ulev1_requestAuthentication(key, pack, sizeof(pack)); PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); } } - ul_switch_off_field(); + if (len > -1) ul_switch_off_field(); } } @@ -638,8 +634,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t cc[16] = {0x00}; status = ul_read(2, cc, sizeof(cc)); if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ D"); - ul_switch_off_field(); + PrintAndLog("Error: tag didn't answer to READ ntag"); return status; } ntag_print_CC(cc); From f04ef473110b2b44edd7a69327b324a4966f584d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 11 May 2015 14:49:37 -0400 Subject: [PATCH 034/132] hf mfu info bug fixes --- client/cmdhfmfu.c | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 523f505c..3080cdbb 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -177,7 +177,7 @@ static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ // NACK return -1; } - +/* static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t nonceLength ){ uint8_t cmd[] = {MIFARE_ULC_AUTH_1, blockNo}; @@ -186,7 +186,7 @@ static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t ul_switch_off_field(); return len; } - +*/ static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ uint8_t cmd[] = {MIFARE_ULEV1_AUTH, pwd[0], pwd[1], pwd[2], pwd[3]}; @@ -281,11 +281,11 @@ static int ntag_print_CC(uint8_t *data) { PrintAndLog(" %02X: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); PrintAndLog(" %02X: Physical Memory Size: %d bytes", data[2], (data[2] + 1) * 8); if ( data[2] == 0x12 ) - PrintAndLog(" %02X: NDEF Memory Size: &d bytes", data[2], 144); + PrintAndLog(" %02X: NDEF Memory Size: %d bytes", data[2], 144); else if ( data[2] == 0x3e ) - PrintAndLog(" %02X: NDEF Memory Size: &d bytes", data[2], 496); + PrintAndLog(" %02X: NDEF Memory Size: %d bytes", data[2], 496); else if ( data[2] == 0x6d ) - PrintAndLog(" %02X: NDEF Memory Size: &d bytes", data[2], 872); + PrintAndLog(" %02X: NDEF Memory Size: %d bytes", data[2], 872); PrintAndLog(" %02X: %s / %s", data[3], (data[3] & 0xF0) ? "(RFU)" : "Read access granted without any security", @@ -404,7 +404,7 @@ static int ulev1_print_signature( uint8_t *data, uint8_t len){ //PrintAndLog("IC signature status: %s valid", (iseccvalid() )?"":"not"); return 0; } - +/* static int ulc_magic_test(){ // Magic Ultralight test // Magic UL-C, by observation, @@ -432,7 +432,7 @@ static int ulc_magic_test(){ ul_switch_off_field(); return returnValue; } -/* +*/ static int ul_magic_test(){ // Magic Ultralight tests @@ -451,7 +451,7 @@ static int ul_magic_test(){ return UL_MAGIC; return UL; } -*/ + uint16_t GetHF14AMfU_Type(void){ TagTypeUL_t tagtype = UNKNOWN; @@ -622,6 +622,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( len > -1 ){ len = ulev1_requestAuthentication(key, pack, sizeof(pack)); PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); + break; } } if (len > -1) ul_switch_off_field(); @@ -632,7 +633,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("\n--- NTAG NDEF Message"); uint8_t cc[16] = {0x00}; - status = ul_read(2, cc, sizeof(cc)); + status = ul_read(3, cc, sizeof(cc)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ ntag"); return status; From 345fb24aaa0ba6586c3ac2b4835eefdebcaf3314 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 11 May 2015 15:56:12 -0400 Subject: [PATCH 035/132] hf mfu info - ICEMANS bug fixes. --- client/cmdhfmfu.c | 229 ++++++++++++++++++++++++++++------------------ 1 file changed, 142 insertions(+), 87 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 3080cdbb..ce345789 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -24,22 +24,27 @@ #define MAX_NTAG_216 0xe6 typedef enum TAGTYPE_UL { - UNKNOWN = 0x0000, - UL = 0x0001, - UL_C = 0x0002, - UL_EV1_48 = 0x0004, - UL_EV1_128 = 0x0008, - NTAG = 0x0010, - NTAG_213 = 0x0020, - NTAG_215 = 0x0040, - NTAG_216 = 0x0080, - MAGIC = 0x0100, - UL_MAGIC = UL | MAGIC, - UL_C_MAGIC = UL_C | MAGIC, - UL_ERROR = 0xFFFF, + UNKNOWN = 0x0000, + UL = 0x0001, + UL_C = 0x0002, + UL_EV1_48 = 0x0004, + UL_EV1_128 = 0x0008, + NTAG = 0x0010, + NTAG_213 = 0x0020, + NTAG_215 = 0x0040, + NTAG_216 = 0x0080, + MY_D = 0x0100, + MY_D_NFC = 0x0200, + MY_D_MOVE = 0x0400, + MY_D_MOVE_NFC = 0x0800, + MAGIC = 0x1000, + UL_MAGIC = UL | MAGIC, + UL_C_MAGIC = UL_C | MAGIC, + UL_ERROR = 0xFFFF, } TagTypeUL_t; -uint8_t default_3des_keys[7][16] = { +#define KEYS_3DES_COUNT 7 +uint8_t default_3des_keys[KEYS_3DES_COUNT][16] = { { 0x42,0x52,0x45,0x41,0x4b,0x4d,0x45,0x49,0x46,0x59,0x4f,0x55,0x43,0x41,0x4e,0x21 },// 3des std key { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 },// all zeroes { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f },// 0x00-0x0F @@ -49,10 +54,16 @@ uint8_t default_3des_keys[7][16] = { { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF } // 11 22 33 }; -uint8_t default_pwd_pack[3][4] = { +#define KEYS_PWD_COUNT 8 +uint8_t default_pwd_pack[KEYS_PWD_COUNT][4] = { {0xFF,0xFF,0xFF,0xFF}, // PACK 0x00,0x00 -- factory default {0x4A,0xF8,0x4B,0x19}, // PACK 0xE5,0xBE -- italian bus (sniffed) - {0x05,0x22,0xE6,0xB4} // PACK 0x80,0x80 -- Amiiboo (sniffed) + {0x33,0x6B,0xA1,0x19}, // PACK 0x9c,0x2d -- italian bus (sniffed) + {0xFF,0x90,0x6C,0xB2}, // PACK 0x12,0x9e -- italian bus (sniffed) + {0x05,0x22,0xE6,0xB4}, // PACK 0x80,0x80 -- Amiiboo (sniffed) pikachu-b UID: + {0x7E,0x22,0xE6,0xB4}, // PACK 0x80,0x80 -- AMiiboo (sniffed) + {0x02,0xE1,0xEE,0x36}, // PACK 0x80,0x80 -- AMiiboo (sniffed) sonic UID: 04d257 7ae33e8027 + {0x32,0x0C,0x16,0x17}, // PACK 0x80,0x80 -- AMiiboo (sniffed) }; static int CmdHelp(const char *Cmd); @@ -83,7 +94,7 @@ char* getProductTypeStr( uint8_t id){ */ char* getUlev1CardSizeStr( uint8_t fsize ){ - static char buf[30]; + static char buf[40]; char *retStr = buf; uint8_t usize = 1 << ((fsize >>1) + 1); @@ -91,9 +102,9 @@ char* getUlev1CardSizeStr( uint8_t fsize ){ // is LSB set? if ( fsize & 1 ) - sprintf(retStr, "0x%02X (%u - %u bytes)",fsize, usize, lsize); + sprintf(retStr, "%02X (%u <-> %u bytes)",fsize, usize, lsize); else - sprintf(retStr, "0x%02X (%u bytes)", fsize, lsize); + sprintf(retStr, "%02X (%u bytes)", fsize, lsize); return buf; } @@ -177,7 +188,7 @@ static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ // NACK return -1; } -/* + static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t nonceLength ){ uint8_t cmd[] = {MIFARE_ULC_AUTH_1, blockNo}; @@ -186,7 +197,7 @@ static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t ul_switch_off_field(); return len; } -*/ + static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ uint8_t cmd[] = {MIFARE_ULEV1_AUTH, pwd[0], pwd[1], pwd[2], pwd[3]}; @@ -247,9 +258,15 @@ static int ul_print_default( uint8_t *data){ uid[6] = data[7]; PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); - PrintAndLog(" UID[0] : (Manufacturer Byte) = %02x, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); - - // BBC + PrintAndLog(" UID[0] : %02x, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); + if ( uid[0] == 0x05 ) { + uint8_t chip = (data[8] & 0xC7); // 11000111 mask, bit 3,4,5 RFU + switch (chip){ + case 0xc2: PrintAndLog(" IC type : SLE 66R04P"); break; + case 0xc4: PrintAndLog(" IC type : SLE 66R16P"); break; + case 0xc6: PrintAndLog(" IC type : SLE 66R32P"); break; + } + } // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; if ( data[3] == crc0 ) @@ -266,11 +283,13 @@ static int ul_print_default( uint8_t *data){ PrintAndLog(" Internal : 0x%02X - %s default", data[9], (data[9]==0x48)?"":"not" ); PrintAndLog(" Lock : %s - %s", sprint_hex(data+10, 2),printBits( 2, data+10) ); PrintAndLog("OneTimePad : %s ", sprint_hex(data + 12, 4)); - PrintAndLog(""); return 0; } static int ntag_print_CC(uint8_t *data) { + + PrintAndLog("\n--- NTAG NDEF Message"); + if(data[0] != 0xe1) { PrintAndLog("no NDEF message"); return -1; // no NDEF message @@ -290,30 +309,17 @@ static int ntag_print_CC(uint8_t *data) { PrintAndLog(" %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; -} - -static int ulev1_print_version(uint8_t *data){ - PrintAndLog("\n--- UL-EV1 / NTAG Version"); - PrintAndLog(" Raw bytes : %s", sprint_hex(data, 8) ); - PrintAndLog(" Vendor ID : 0x%02X, Manufacturer: %s", data[1], getTagInfo(data[1])); - PrintAndLog(" Product type : %s" , getProductTypeStr(data[2])); - PrintAndLog(" Product subtype : 0x%02X %s" , data[3], (data[3]==1) ?"17 pF":"50pF"); - PrintAndLog(" Major version : 0x%02X" , data[4]); - PrintAndLog(" Minor version : 0x%02X" , data[5]); - PrintAndLog(" Size : %s", getUlev1CardSizeStr(data[6])); - PrintAndLog(" Protocol type : 0x%02X" , data[7]); return 0; } static int ul_print_type(uint16_t tagtype){ if ( tagtype & UL ) - PrintAndLog(" TYPE : MIFARE Ultralight (MF0ICU1) %s", (tagtype & MAGIC)?"":""); + PrintAndLog(" TYPE : MIFARE Ultralight (MF0ICU1) %s [%x]", (tagtype & MAGIC)?"":"", tagtype); else if ( tagtype & UL_C) PrintAndLog(" TYPE : MIFARE Ultralight C (MF0ULC) %s [%x]", (tagtype & MAGIC)?"":"", tagtype ); else if ( tagtype & UL_EV1_48) PrintAndLog(" TYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)"); - else if ( tagtype & UL_EV1_128) + else if ( tagtype & UL_EV1_128) PrintAndLog(" TYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)"); else if ( tagtype & NTAG_213 ) PrintAndLog(" TYPE : MIFARE NTAG 213 144bytes (NT2H1311G0DU)"); @@ -321,6 +327,14 @@ static int ul_print_type(uint16_t tagtype){ PrintAndLog(" TYPE : MIFARE NTAG 215 504bytes (NT2H1511G0DU)"); else if ( tagtype & NTAG_216 ) PrintAndLog(" TYPE : MIFARE NTAG 216 888bytes (NT2H1611G0DU)"); + else if ( tagtype & MY_D ) + PrintAndLog(" TYPE : INFINEON my-d\x99"); + else if ( tagtype & MY_D_NFC ) + PrintAndLog(" TYPE : INFINEON my-d\x99 NFC"); + else if ( tagtype & MY_D_MOVE ) + PrintAndLog(" TYPE : INFINEON my-d\x99 move"); + else if ( tagtype & MY_D_MOVE_NFC ) + PrintAndLog(" TYPE : INFINEON my-d\x99 move NFC"); else PrintAndLog(" TYPE : Unknown %04x",tagtype); return 0; @@ -338,20 +352,20 @@ static int ulc_print_3deskey( uint8_t *data){ static int ulc_print_configuration( uint8_t *data){ PrintAndLog("--- UL-C Configuration"); - PrintAndLog(" Higher Lockbits [40/0x28]: %s %s", sprint_hex(data, 4), printBits(2, data)); - PrintAndLog(" Counter [41/0x29]: %s %s", sprint_hex(data+4, 4), printBits(2, data+4)); + PrintAndLog(" Higher Lockbits [40/0x28]: %s - %s", sprint_hex(data, 4), printBits(2, data)); + PrintAndLog(" Counter [41/0x29]: %s - %s", sprint_hex(data+4, 4), printBits(2, data+4)); bool validAuth = (data[8] >= 0x03 && data[8] <= 0x30); if ( validAuth ) - PrintAndLog(" Auth0 [42/0x2A]: %s - Pages above %d needs authentication", sprint_hex(data+8, 4), data[8] ); + PrintAndLog(" Auth0 [42/0x2A]: %s Pages above %d needs authentication", sprint_hex(data+8, 4), data[8] ); else{ if ( data[8] == 0){ - PrintAndLog(" Auth0 [42/0x2A]: %s - default", sprint_hex(data+8, 4) ); + PrintAndLog(" Auth0 [42/0x2A]: %s default", sprint_hex(data+8, 4) ); } else { - PrintAndLog(" Auth0 [42/0x2A]: %s - auth byte is out-of-range", sprint_hex(data+8, 4) ); + PrintAndLog(" Auth0 [42/0x2A]: %s auth byte is out-of-range", sprint_hex(data+8, 4) ); } } - PrintAndLog(" Auth1 [43/0x2B]: %s - %s", + PrintAndLog(" Auth1 [43/0x2B]: %s %s", sprint_hex(data+12, 4), (data[12] & 1) ? "write access restricted": "read and write access restricted" ); @@ -369,16 +383,19 @@ static int ulev1_print_configuration( uint8_t *data){ uint8_t vctid = data[5]; PrintAndLog(" cfg0 [16/0x10]: %s", sprint_hex(data, 4)); - PrintAndLog(" - pages above %d needs authentication",data[3]); + if ( data[3] < 0xff ) + PrintAndLog(" - pages above %d needs authentication",data[3]); + else + PrintAndLog(" - pages don't need authentication"); PrintAndLog(" - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); PrintAndLog(" cfg1 [17/0x11]: %s", sprint_hex(data+4, 4) ); if ( authlim == 0) - PrintAndLog(" - Max number of password attempts is unlimited"); + PrintAndLog(" - Unlimited password attempts"); else PrintAndLog(" - Max number of password attempts is %d", authlim); PrintAndLog(" - user configuration %s", cfglck ? "permanently locked":"writeable"); PrintAndLog(" - %s access is protected with password", prot ? "read and write":"write"); - PrintAndLog(" 0x%02X - Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); + PrintAndLog(" %02X - Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); PrintAndLog(" PWD [18/0x12]: %s", sprint_hex(data+8, 4)); PrintAndLog(" PACK [19/0x13]: %s", sprint_hex(data+12, 4)); return 0; @@ -389,7 +406,7 @@ static int ulev1_print_counters(){ uint8_t counter[3] = {0,0,0}; for ( uint8_t i = 0; i<3; ++i) { ulev1_readCounter(i,counter, sizeof(counter) ); - PrintAndLog("Counter [%d] : %s", i, sprint_hex(counter,3)); + PrintAndLog(" [%0d] : %s", i, sprint_hex(counter,3)); } return 0; } @@ -404,6 +421,20 @@ static int ulev1_print_signature( uint8_t *data, uint8_t len){ //PrintAndLog("IC signature status: %s valid", (iseccvalid() )?"":"not"); return 0; } + +static int ulev1_print_version(uint8_t *data){ + PrintAndLog("\n--- UL-EV1 / NTAG Version"); + PrintAndLog(" Raw bytes : %s", sprint_hex(data, 8) ); + PrintAndLog(" Vendor ID : %02X, Manufacturer: %s", data[1], getTagInfo(data[1])); + PrintAndLog(" Product type : %s", getProductTypeStr(data[2])); + PrintAndLog(" Product subtype : %02X %s", data[3], (data[3]==1) ?"17 pF":"50pF"); + PrintAndLog(" Major version : %02X", data[4]); + PrintAndLog(" Minor version : %02X", data[5]); + PrintAndLog(" Size : %s", getUlev1CardSizeStr(data[6])); + PrintAndLog(" Protocol type : %02X", data[7]); + return 0; +} + /* static int ulc_magic_test(){ // Magic Ultralight test @@ -468,36 +499,63 @@ uint16_t GetHF14AMfU_Type(void){ } // Ultralight - ATQA / SAK if ( card.atqa[1] != 0x00 || card.atqa[0] != 0x44 || card.sak != 0x00 ) { - PrintAndLog ("Tag is not UL or NTAG, ATQA1: %x, ATQA0: %x, SAK: %d", card.atqa[1],card.atqa[0],card.sak); + PrintAndLog("Tag is not Ultralight | NTAG | MY-D [ATQA: %02X %02x SAK: %02X]\n", card.atqa[1], card.atqa[0], card.sak); ul_switch_off_field(); return UL_ERROR; } - len = ulev1_getVersion(version, sizeof(version)); - if (len > -1) ul_switch_off_field(); //if -1 it is already off + if ( card.uid[0] != 0x05) { - switch (len) { - case 0x0A: { + len = ulev1_getVersion(version, sizeof(version)); + if (len > -1) ul_switch_off_field(); //if -1 it is already off - if ( version[2] == 0x03 && version[6] == 0x0B ) - tagtype = UL_EV1_48; - else if ( version[2] == 0x03 && version[6] != 0x0B ) - tagtype = UL_EV1_128; - else if ( version[2] == 0x04 && version[6] == 0x0F ) - tagtype = NTAG_213; - else if ( version[2] == 0x04 && version[6] != 0x11 ) - tagtype = NTAG_215; - else if ( version[2] == 0x04 && version[6] == 0x13 ) - tagtype = NTAG_216; - else if ( version[2] == 0x04 ) - tagtype = NTAG; + switch (len) { + case 0x0A: { - break; + if ( version[2] == 0x03 && version[6] == 0x0B ) + tagtype = UL_EV1_48; + else if ( version[2] == 0x03 && version[6] != 0x0B ) + tagtype = UL_EV1_128; + else if ( version[2] == 0x04 && version[6] == 0x0F ) + tagtype = NTAG_213; + else if ( version[2] == 0x04 && version[6] == 0x11 ) + tagtype = NTAG_215; + else if ( version[2] == 0x04 && version[6] == 0x13 ) + tagtype = NTAG_216; + else if ( version[2] == 0x04 ) + tagtype = NTAG; + + break; + } + case 0x01: tagtype = UL_C; break; + case 0x00: tagtype = UL; break; + case -1 : tagtype = (UL | UL_C); break; //when does this happen? + default : tagtype = UNKNOWN; break; + } + if (tagtype == (UL | UL_C)) { + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("Error: couldn't select 2"); + ul_switch_off_field(); + return UL_ERROR; + } + uint8_t nonce1[11] = {0x00}; + status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); + if ( status > 0 ) + tagtype = UL_C; + else + tagtype = UL; + + if (status != -1) ul_switch_off_field(); + } + } else { + // Infinition MY-D tests Exam high nibble + uint8_t nib = (card.uid[1] & 0xf0) >> 4; + switch ( nib ){ + case 1: tagtype = MY_D; break; + case 2: tagtype = (MY_D | MY_D_NFC); break; + case 3: tagtype = (MY_D_MOVE | MY_D_MOVE_NFC); break; } - case 0x01: tagtype = UL_C; break; - case 0x00: tagtype = UL; break; - case -1 : tagtype = (UL | UL_C); break; //when does this happen? - default : tagtype = UNKNOWN; break; } tagtype = (ul_magic_test() == UL_MAGIC) ? (tagtype | MAGIC) : tagtype; @@ -532,7 +590,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_read(0, data, sizeof(data)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ"); - ul_switch_off_field(); return status; } @@ -547,7 +604,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("Error: tag didn't answer to READ - possibly locked"); return status; } - ulc_print_configuration(ulc_conf); if ((tagtype & MAGIC)){ @@ -575,7 +631,17 @@ int CmdHF14AMfUInfo(const char *Cmd){ } if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { - + //do counters and signature first (don't neet auth) + ulev1_print_counters(); + + uint8_t ulev1_signature[32] = {0x00}; + status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); + if ( status == -1 ){ + PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); + return status; + } + ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); + uint8_t startconfigblock = (tagtype & UL_EV1_48) ? 0x10 : 0x25; uint8_t ulev1_conf[16] = {0x00}; status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); @@ -585,18 +651,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } // save AUTHENTICATION LIMITS for later: authlim = (ulev1_conf[4] & 0x07); - ulev1_print_configuration(ulev1_conf); - - uint8_t ulev1_signature[32] = {0x00}; - status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); - if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); - return status; - } - ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); - - ulev1_print_counters(); } if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216))) { @@ -631,7 +686,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ((tagtype & (NTAG_213 | NTAG_215 | NTAG_216))){ - PrintAndLog("\n--- NTAG NDEF Message"); uint8_t cc[16] = {0x00}; status = ul_read(3, cc, sizeof(cc)); if ( status == -1 ){ @@ -642,6 +696,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } ul_switch_off_field(); + PrintAndLog(""); return 0; } From 4693c188ab721316469e5f3ce39865e874d1b122 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 11 May 2015 16:25:11 -0400 Subject: [PATCH 036/132] minor hf mfu output consistancies --- client/cmdhfmfu.c | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index ce345789..8b800874 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -258,7 +258,7 @@ static int ul_print_default( uint8_t *data){ uid[6] = data[7]; PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); - PrintAndLog(" UID[0] : %02x, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); + PrintAndLog(" UID[0] : %02X, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); if ( uid[0] == 0x05 ) { uint8_t chip = (data[8] & 0xC7); // 11000111 mask, bit 3,4,5 RFU switch (chip){ @@ -270,19 +270,20 @@ static int ul_print_default( uint8_t *data){ // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; if ( data[3] == crc0 ) - PrintAndLog(" BCC0 : 0x%02X - Ok", data[3]); + PrintAndLog(" BCC0 : %02X - Ok", data[3]); else - PrintAndLog(" BCC0 : 0x%02X - crc should be %02x", data[3], crc0); + PrintAndLog(" BCC0 : %02X - crc should be %02X", data[3], crc0); int crc1 = data[4] ^ data[5] ^ data[6] ^data[7]; if ( data[8] == crc1 ) - PrintAndLog(" BCC1 : 0x%02X - Ok", data[8]); + PrintAndLog(" BCC1 : %02X - Ok", data[8]); else - PrintAndLog(" BCC1 : 0x%02X - crc should be 0x%02X", data[8], crc1 ); + PrintAndLog(" BCC1 : %02X - crc should be %02X", data[8], crc1 ); - PrintAndLog(" Internal : 0x%02X - %s default", data[9], (data[9]==0x48)?"":"not" ); + PrintAndLog(" Internal : %02X - %s default", data[9], (data[9]==0x48)?"":"not" ); PrintAndLog(" Lock : %s - %s", sprint_hex(data+10, 2),printBits( 2, data+10) ); PrintAndLog("OneTimePad : %s ", sprint_hex(data + 12, 4)); + PrintAndLog(""); return 0; } @@ -499,7 +500,7 @@ uint16_t GetHF14AMfU_Type(void){ } // Ultralight - ATQA / SAK if ( card.atqa[1] != 0x00 || card.atqa[0] != 0x44 || card.sak != 0x00 ) { - PrintAndLog("Tag is not Ultralight | NTAG | MY-D [ATQA: %02X %02x SAK: %02X]\n", card.atqa[1], card.atqa[0], card.sak); + PrintAndLog("Tag is not Ultralight | NTAG | MY-D [ATQA: %02X %02X SAK: %02X]\n", card.atqa[1], card.atqa[0], card.sak); ul_switch_off_field(); return UL_ERROR; } From 2be768af57ffa83d416f7728fbf790fe9e405c54 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 11 May 2015 18:22:50 -0400 Subject: [PATCH 037/132] hf mfu info bugs --- client/cmdhfmfu.c | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 8b800874..fec7a85e 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -96,9 +96,10 @@ char* getUlev1CardSizeStr( uint8_t fsize ){ static char buf[40]; char *retStr = buf; + memset(buf, 0, sizeof(buf)); - uint8_t usize = 1 << ((fsize >>1) + 1); - uint8_t lsize = 1 << (fsize >>1); + uint16_t usize = 1 << ((fsize >>1) + 1); + uint16_t lsize = 1 << (fsize >>1); // is LSB set? if ( fsize & 1 ) @@ -885,6 +886,7 @@ int CmdHF14AMfUDump(const char *Cmd){ case 's': swapEndian = true; cmdp++; + break; default: PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; From 8ceb6b03e5caee0cc7292894bfa25fa4a3f85c4c Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 12 May 2015 00:19:44 -0400 Subject: [PATCH 038/132] hf search - prelim - re-use hf mfu GetTagType... in hf 14a reader to identify UL(+) still a work in progress. --- client/cmdhf.c | 22 +++++++++++++++++--- client/cmdhf14a.c | 39 ++++++++++++++++++++++++++++++++++- client/cmdhfmfu.c | 52 ++++++++++++++++------------------------------- client/cmdhfmfu.h | 22 ++++++++++++++++++++ 4 files changed, 97 insertions(+), 38 deletions(-) diff --git a/client/cmdhf.c b/client/cmdhf.c index 020ea94c..524d9c2e 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -544,6 +544,21 @@ int CmdHFList(const char *Cmd) return 0; } +int CmdHFSearch(const char *Cmd){ + int ans = 0; + ans = CmdHF14AReader(Cmd); + if (ans > 0) return ans; + + ans = CmdHF15Reader(Cmd); + //if (ans > 0) return ans; + + ans = CmdHF14BRead(Cmd); + //if (ans > 0) return ans; + + ans = CmdHFiClassReader(Cmd); + //if (ans > 0) return ans; + return 0; +} static command_t CommandTable[] = { @@ -554,10 +569,11 @@ static command_t CommandTable[] = {"epa", CmdHFEPA, 1, "{ German Identification Card... }"}, {"legic", CmdHFLegic, 0, "{ LEGIC RFIDs... }"}, {"iclass", CmdHFiClass, 1, "{ ICLASS RFIDs... }"}, - {"mf", CmdHFMF, 1, "{ MIFARE RFIDs... }"}, - {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, + {"mf", CmdHFMF, 1, "{ MIFARE RFIDs... }"}, + {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, - {"list", CmdHFList, 1, "List protocol data in trace buffer"}, + {"list", CmdHFList, 1, "List protocol data in trace buffer"}, + {"search", CmdHFSearch, 1, "Search for known HF tags"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index d4285eea..d1f8b363 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -23,6 +23,7 @@ #include "common.h" #include "cmdmain.h" #include "mifare.h" +#include "cmdhfmfu.h" static int CmdHelp(const char *Cmd); static void waitCmd(uint8_t iLen); @@ -169,6 +170,42 @@ int CmdHF14AReader(const char *Cmd) switch (card.sak) { case 0x00: + + //***************************************test**************** + // disconnect + c.arg[0] = 0; + c.arg[1] = 0; + c.arg[2] = 0; + SendCommand(&c); + + uint16_t tagT = GetHF14AMfU_Type(); + ul_print_type(tagT, 0); + + //reconnect for further tests + c.arg[0] = ISO14A_CONNECT | ISO14A_NO_DISCONNECT; + c.arg[1] = 0; + c.arg[2] = 0; + + 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) { + //PrintAndLog("iso14443a card select failed"); + // disconnect + c.arg[0] = 0; + c.arg[1] = 0; + c.arg[2] = 0; + SendCommand(&c); + return 0; + } + + /* orig // check if the tag answers to GETVERSION (0x60) c.arg[0] = ISO14A_RAW | ISO14A_APPEND_CRC | ISO14A_NO_DISCONNECT; c.arg[1] = 1; @@ -187,7 +224,7 @@ int CmdHF14AReader(const char *Cmd) case 0x01:PrintAndLog("TYPE : NXP MIFARE Ultralight C");break; case 0x00:PrintAndLog("TYPE : NXP MIFARE Ultralight");break; } - + */ break; case 0x01: PrintAndLog("TYPE : NXP TNP3xxx Activision Game Appliance"); break; case 0x04: PrintAndLog("TYPE : NXP MIFARE (various !DESFire !DESFire EV1)"); break; diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index fec7a85e..884ed3ff 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -23,26 +23,6 @@ #define MAX_NTAG_215 0x86 #define MAX_NTAG_216 0xe6 -typedef enum TAGTYPE_UL { - UNKNOWN = 0x0000, - UL = 0x0001, - UL_C = 0x0002, - UL_EV1_48 = 0x0004, - UL_EV1_128 = 0x0008, - NTAG = 0x0010, - NTAG_213 = 0x0020, - NTAG_215 = 0x0040, - NTAG_216 = 0x0080, - MY_D = 0x0100, - MY_D_NFC = 0x0200, - MY_D_MOVE = 0x0400, - MY_D_MOVE_NFC = 0x0800, - MAGIC = 0x1000, - UL_MAGIC = UL | MAGIC, - UL_C_MAGIC = UL_C | MAGIC, - UL_ERROR = 0xFFFF, -} TagTypeUL_t; - #define KEYS_3DES_COUNT 7 uint8_t default_3des_keys[KEYS_3DES_COUNT][16] = { { 0x42,0x52,0x45,0x41,0x4b,0x4d,0x45,0x49,0x46,0x59,0x4f,0x55,0x43,0x41,0x4e,0x21 },// 3des std key @@ -314,31 +294,35 @@ static int ntag_print_CC(uint8_t *data) { return 0; } -static int ul_print_type(uint16_t tagtype){ +int ul_print_type(uint16_t tagtype, uint8_t spaces){ + char spc[11] = " "; + spc[10]=0x00; + char *spacer = spc + (10-spaces); + if ( tagtype & UL ) - PrintAndLog(" TYPE : MIFARE Ultralight (MF0ICU1) %s [%x]", (tagtype & MAGIC)?"":"", tagtype); + PrintAndLog("%sTYPE : MIFARE Ultralight (MF0ICU1) %s [%x]", spacer, (tagtype & MAGIC)?"":"", tagtype); else if ( tagtype & UL_C) - PrintAndLog(" TYPE : MIFARE Ultralight C (MF0ULC) %s [%x]", (tagtype & MAGIC)?"":"", tagtype ); + PrintAndLog("%sTYPE : MIFARE Ultralight C (MF0ULC) %s [%x]", spacer, (tagtype & MAGIC)?"":"", tagtype ); else if ( tagtype & UL_EV1_48) - PrintAndLog(" TYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)"); + PrintAndLog("%sTYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)", spacer); else if ( tagtype & UL_EV1_128) - PrintAndLog(" TYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)"); + PrintAndLog("%sTYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)", spacer); else if ( tagtype & NTAG_213 ) - PrintAndLog(" TYPE : MIFARE NTAG 213 144bytes (NT2H1311G0DU)"); + PrintAndLog("%sTYPE : MIFARE NTAG 213 144bytes (NT2H1311G0DU)", spacer); else if ( tagtype & NTAG_215 ) - PrintAndLog(" TYPE : MIFARE NTAG 215 504bytes (NT2H1511G0DU)"); + PrintAndLog("%sTYPE : MIFARE NTAG 215 504bytes (NT2H1511G0DU)", spacer); else if ( tagtype & NTAG_216 ) - PrintAndLog(" TYPE : MIFARE NTAG 216 888bytes (NT2H1611G0DU)"); + PrintAndLog("%sTYPE : MIFARE NTAG 216 888bytes (NT2H1611G0DU)", spacer); else if ( tagtype & MY_D ) - PrintAndLog(" TYPE : INFINEON my-d\x99"); + PrintAndLog("%sTYPE : INFINEON my-d\x99", spacer); else if ( tagtype & MY_D_NFC ) - PrintAndLog(" TYPE : INFINEON my-d\x99 NFC"); + PrintAndLog("%sTYPE : INFINEON my-d\x99 NFC", spacer); else if ( tagtype & MY_D_MOVE ) - PrintAndLog(" TYPE : INFINEON my-d\x99 move"); + PrintAndLog("%sTYPE : INFINEON my-d\x99 move", spacer); else if ( tagtype & MY_D_MOVE_NFC ) - PrintAndLog(" TYPE : INFINEON my-d\x99 move NFC"); + PrintAndLog("%sTYPE : INFINEON my-d\x99 move NFC", spacer); else - PrintAndLog(" TYPE : Unknown %04x",tagtype); + PrintAndLog("%sTYPE : Unknown %04x", spacer, tagtype); return 0; } @@ -579,7 +563,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("\n--- Tag Information ---------"); PrintAndLog("-------------------------------------------------------------"); - ul_print_type(tagtype); + ul_print_type(tagtype, 6); status = ul_select(&card); if ( status < 1 ){ diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 8e96775c..23f97cac 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -20,9 +20,31 @@ void rol (uint8_t *data, const size_t len); uint8_t requestAuthentication( uint8_t *nonce); int try3DesAuthentication( uint8_t *key); uint16_t GetHF14AMfU_Type(void); +int ul_print_type(uint16_t tagtype, uint8_t spacer); int usage_hf_mfu_dump(void); int CmdHFMFUltra(const char *Cmd); int CmdHF14AMfUInfo(const char *Cmd); + +typedef enum TAGTYPE_UL { + UNKNOWN = 0x0000, + UL = 0x0001, + UL_C = 0x0002, + UL_EV1_48 = 0x0004, + UL_EV1_128 = 0x0008, + NTAG = 0x0010, + NTAG_213 = 0x0020, + NTAG_215 = 0x0040, + NTAG_216 = 0x0080, + MY_D = 0x0100, + MY_D_NFC = 0x0200, + MY_D_MOVE = 0x0400, + MY_D_MOVE_NFC = 0x0800, + MAGIC = 0x1000, + UL_MAGIC = UL | MAGIC, + UL_C_MAGIC = UL_C | MAGIC, + UL_ERROR = 0xFFFF, +} TagTypeUL_t; + #endif From 6ce0e5386a5dd4ce8eb171437e2b62ca55a328ea Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 12 May 2015 16:45:48 -0400 Subject: [PATCH 039/132] HF Search - refactoring cmds to work with it --- armsrc/iclass.c | 18 ++++++++++-------- client/cmdhf.c | 29 ++++++++++++++++++++--------- client/cmdhf14a.c | 2 +- client/cmdhf15.c | 18 ++++++++++++++++-- client/cmdhf15.h | 1 + client/cmdhficlass.c | 31 ++++++++++++++++++++++--------- client/cmdhficlass.h | 1 + include/usb_cmd.h | 9 +++++---- 8 files changed, 76 insertions(+), 33 deletions(-) diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 56bc29db..9139d3bd 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1677,7 +1677,7 @@ void ReaderIClass(uint8_t arg0) { uint8_t card_data[6 * 8]={0}; memset(card_data, 0xFF, sizeof(card_data)); - uint8_t last_csn[8]={0}; + uint8_t last_csn[8]={0}; //Read conf block CRC(0x01) => 0xfa 0x22 uint8_t readConf[] = { ICLASS_CMD_READ_OR_IDENTIFY,0x01, 0xfa, 0x22}; @@ -1685,16 +1685,18 @@ void ReaderIClass(uint8_t arg0) { uint8_t readAA[] = { ICLASS_CMD_READ_OR_IDENTIFY,0x05, 0xde, 0x64}; - int read_status= 0; + int read_status= 0; uint8_t result_status = 0; - bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE; - + bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE; + bool try_once = arg0 & FLAG_ICLASS_READER_ONE_TRY; set_tracing(TRUE); - setupIclassReader(); + setupIclassReader(); + uint16_t tryCnt=0; while(!BUTTON_PRESS()) - { - + { + if (try_once && tryCnt > 5) break; + tryCnt++; if(!tracing) { DbpString("Trace full"); break; @@ -1761,7 +1763,7 @@ void ReaderIClass(uint8_t arg0) { } LED_B_OFF(); - } + } cmd_send(CMD_ACK,0,0,0,card_data, 0); LED_A_OFF(); } diff --git a/client/cmdhf.c b/client/cmdhf.c index 524d9c2e..8853a7f3 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -87,7 +87,7 @@ void annotateIso14443a(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) case MIFARE_ULC_AUTH_2: snprintf(exp,size,"AUTH_ANSW"); break; case MIFARE_ULEV1_AUTH: snprintf(exp,size,"PWD-AUTH"); break; case MIFARE_ULEV1_FASTREAD:{ - if ( cmdsize >=3 && cmd[2] < 0x21) + if ( cmdsize >=3 && cmd[2] <= 0xE6) snprintf(exp,size,"READ RANGE (%d-%d)",cmd[1],cmd[2]); else snprintf(exp,size,"?"); @@ -546,17 +546,28 @@ int CmdHFList(const char *Cmd) int CmdHFSearch(const char *Cmd){ int ans = 0; - ans = CmdHF14AReader(Cmd); - if (ans > 0) return ans; + PrintAndLog(""); + ans = CmdHF14AReader("s"); + if (ans > 0) { + PrintAndLog("\nValid ISO14443A Tag Found - Quiting Search\n"); + return ans; + } + ans = HFiClassReader("", false, false); + if (ans) { + PrintAndLog("\nValid iClass Tag (or PicoPass Tag) Found - Quiting Search\n"); + return ans; + } + ans = HF15Reader("", false); + if (ans) { + PrintAndLog("\nValid ISO15693 Tag Found - Quiting Search\n"); + return ans; + } - ans = CmdHF15Reader(Cmd); - //if (ans > 0) return ans; - ans = CmdHF14BRead(Cmd); + //14b has issues currently... + //ans = CmdHF14BRead(Cmd); //if (ans > 0) return ans; - ans = CmdHFiClassReader(Cmd); - //if (ans > 0) return ans; return 0; } @@ -573,7 +584,7 @@ static command_t CommandTable[] = {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, {"list", CmdHFList, 1, "List protocol data in trace buffer"}, - {"search", CmdHFSearch, 1, "Search for known HF tags"}, + {"search", CmdHFSearch, 1, "Search for known HF tags [preliminary]"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index d1f8b363..1973ff22 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -144,7 +144,7 @@ int CmdHF14AReader(const char *Cmd) uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS if(select_status == 0) { - PrintAndLog("iso14443a card select failed"); + if (Cmd[0] != 's') PrintAndLog("iso14443a card select failed"); // disconnect c.arg[0] = 0; c.arg[1] = 0; diff --git a/client/cmdhf15.c b/client/cmdhf15.c index c3ff7dd6..8ddbea89 100644 --- a/client/cmdhf15.c +++ b/client/cmdhf15.c @@ -374,6 +374,20 @@ int CmdHF15Record(const char *Cmd) return 0; } +int HF15Reader(const char *Cmd, bool verbose) +{ + uint8_t uid[8]; + + if (!getUID(uid)) { + if (verbose) PrintAndLog("No Tag found."); + return 0; + } + + PrintAndLog("Tag UID : %s",sprintUID(NULL,uid)); + PrintAndLog("Tag Info: %s",getTagInfo(uid)); + return 1; +} + int CmdHF15Reader(const char *Cmd) { UsbCommand c = {CMD_READER_ISO_15693, {strtol(Cmd, NULL, 0), 0, 0}}; @@ -469,7 +483,7 @@ int CmdHF15DumpMem(const char*Cmd) { // PrintAndLog("bn=%i",blocknum); } else { PrintAndLog("Tag returned Error %i: %s",recv[1],TagErrorStr(recv[1])); - return 0; + return 1; } } // else PrintAndLog("crc"); } // else PrintAndLog("r null"); @@ -481,7 +495,7 @@ int CmdHF15DumpMem(const char*Cmd) { // PrintAndLog("CRC Failed"); // else // PrintAndLog("Tag returned Error %i: %s",recv[1],TagErrorStr(recv[1])); - return 0; + return 1; } diff --git a/client/cmdhf15.h b/client/cmdhf15.h index 8d78e13f..c6264604 100644 --- a/client/cmdhf15.h +++ b/client/cmdhf15.h @@ -15,6 +15,7 @@ int CmdHF15(const char *Cmd); int CmdHF15Demod(const char *Cmd); int CmdHF15Read(const char *Cmd); +int HF15Reader(const char *Cmd, bool verbose); int CmdHF15Reader(const char *Cmd); int CmdHF15Sim(const char *Cmd); int CmdHF15Record(const char *Cmd); diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index b8337196..824aaa36 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -165,34 +165,47 @@ int CmdHFiClassSim(const char *Cmd) return 0; } -int CmdHFiClassReader(const char *Cmd) +int HFiClassReader(const char *Cmd, bool loop, bool verbose) { + bool tagFound = false; UsbCommand c = {CMD_READER_ICLASS, {FLAG_ICLASS_READER_CSN| FLAG_ICLASS_READER_CONF|FLAG_ICLASS_READER_AA}}; + if (!loop) c.arg[0] |= FLAG_ICLASS_READER_ONLY_ONCE | FLAG_ICLASS_READER_ONE_TRY; SendCommand(&c); UsbCommand resp; while(!ukbhit()){ - if (WaitForResponseTimeout(CMD_ACK,&resp,4500)) { - uint8_t readStatus = resp.arg[0] & 0xff; - uint8_t * data = resp.d.asBytes; + if (WaitForResponseTimeout(CMD_ACK,&resp, 4500)) { + uint8_t readStatus = resp.arg[0] & 0xff; + uint8_t *data = resp.d.asBytes; - PrintAndLog("Readstatus:%02x", readStatus); + if (verbose) + PrintAndLog("Readstatus:%02x", readStatus); if( readStatus == 0){ //Aborted - PrintAndLog("Quitting..."); + if (verbose) PrintAndLog("Quitting..."); return 0; } - if( readStatus & FLAG_ICLASS_READER_CSN) PrintAndLog("CSN: %s",sprint_hex(data,8)); + if( readStatus & FLAG_ICLASS_READER_CSN){ + PrintAndLog("CSN: %s",sprint_hex(data,8)); + tagFound = true; + } if( readStatus & FLAG_ICLASS_READER_CC) PrintAndLog("CC: %s",sprint_hex(data+16,8)); if( readStatus & FLAG_ICLASS_READER_CONF){ printIclassDumpInfo(data); } + if (tagFound && !loop) return 1; } else { - PrintAndLog("Command execute timeout"); + if (verbose) PrintAndLog("Command execute timeout"); } + if (!loop) break; } - return 0; + +} + +int CmdHFiClassReader(const char *Cmd) +{ + return HFiClassReader(Cmd, true, true); } int CmdHFiClassReader_Replay(const char *Cmd) diff --git a/client/cmdhficlass.h b/client/cmdhficlass.h index e4048eb1..30c6a8a7 100644 --- a/client/cmdhficlass.h +++ b/client/cmdhficlass.h @@ -17,6 +17,7 @@ int CmdHFiClass(const char *Cmd); int CmdHFiClassSnoop(const char *Cmd); int CmdHFiClassSim(const char *Cmd); int CmdHFiClassList(const char *Cmd); +int HFiClassReader(const char *Cmd, bool loop, bool verbose); int CmdHFiClassReader(const char *Cmd); int CmdHFiClassReader_Replay(const char *Cmd); diff --git a/include/usb_cmd.h b/include/usb_cmd.h index 31498e2a..f67eac58 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -201,10 +201,11 @@ typedef struct{ //Iclass reader flags #define FLAG_ICLASS_READER_ONLY_ONCE 0x01 -#define FLAG_ICLASS_READER_CC 0x02 -#define FLAG_ICLASS_READER_CSN 0x04 -#define FLAG_ICLASS_READER_CONF 0x08 -#define FLAG_ICLASS_READER_AA 0x10 +#define FLAG_ICLASS_READER_CC 0x02 +#define FLAG_ICLASS_READER_CSN 0x04 +#define FLAG_ICLASS_READER_CONF 0x08 +#define FLAG_ICLASS_READER_AA 0x10 +#define FLAG_ICLASS_READER_ONE_TRY 0x20 From a2e2bb8a154fbf786700574e71b6b0a36fdd4ff9 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 12 May 2015 18:16:55 -0400 Subject: [PATCH 040/132] hf mfu info - ICEMANS updates plus slight change to UL_EV1 auth annotation. --- client/cmdhf.c | 7 ++- client/cmdhfmfu.c | 139 +++++++++++++++++++++++++++++++++++++--------- client/cmdhfmfu.h | 13 +++-- 3 files changed, 128 insertions(+), 31 deletions(-) diff --git a/client/cmdhf.c b/client/cmdhf.c index 8853a7f3..16f7bb0f 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -85,7 +85,12 @@ void annotateIso14443a(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: snprintf(exp,size,"PWD-AUTH"); break; + 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 + snprintf(exp,size,"PWD-AUTH"); + break; case MIFARE_ULEV1_FASTREAD:{ if ( cmdsize >=3 && cmd[2] <= 0xE6) snprintf(exp,size,"READ RANGE (%d-%d)",cmd[1],cmd[2]); diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 884ed3ff..7b936792 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -94,7 +94,7 @@ static void ul_switch_on_field(void) { SendCommand(&c); } -static void ul_switch_off_field(void) { +void ul_switch_off_field(void) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; SendCommand(&c); } @@ -170,9 +170,9 @@ static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ return -1; } -static int ulc_requestAuthentication( uint8_t blockNo, uint8_t *nonce, uint16_t nonceLength ){ +static int ulc_requestAuthentication( uint8_t *nonce, uint16_t nonceLength ){ - uint8_t cmd[] = {MIFARE_ULC_AUTH_1, blockNo}; + uint8_t cmd[] = {MIFARE_ULC_AUTH_1, 0x00}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), nonce, nonceLength); if ( len == -1 ) ul_switch_off_field(); @@ -217,6 +217,15 @@ static int ulev1_readCounter( uint8_t counter, uint8_t *response, uint16_t respo return len; } +static int ulev1_readTearing( uint8_t counter, uint8_t *response, uint16_t responseLength ){ + + uint8_t cmd[] = {MIFARE_ULEV1_CHECKTEAR, counter}; + int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); + if (len == -1) + ul_switch_off_field(); + return len; +} + static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_READSIG, 0x00}; @@ -331,7 +340,7 @@ static int ulc_print_3deskey( uint8_t *data){ PrintAndLog(" deskey1 [45/0x2D]: %s [%.4s]", sprint_hex(data+4 ,4),data+4); PrintAndLog(" deskey2 [46/0x2E]: %s [%.4s]", sprint_hex(data+8 ,4),data+8); PrintAndLog(" deskey2 [47/0x2F]: %s [%.4s]", sprint_hex(data+12,4),data+12); - PrintAndLog(" 3des key : %s", sprint_hex(SwapEndian64(data, 16), 16)); + PrintAndLog("\n 3des key : %s", sprint_hex(SwapEndian64(data, 16), 16)); return 0; } @@ -343,7 +352,7 @@ static int ulc_print_configuration( uint8_t *data){ bool validAuth = (data[8] >= 0x03 && data[8] <= 0x30); if ( validAuth ) - PrintAndLog(" Auth0 [42/0x2A]: %s Pages above %d needs authentication", sprint_hex(data+8, 4), data[8] ); + PrintAndLog(" Auth0 [42/0x2A]: %s Page %d and above need authentication", sprint_hex(data+8, 4), data[8] ); else{ if ( data[8] == 0){ PrintAndLog(" Auth0 [42/0x2A]: %s default", sprint_hex(data+8, 4) ); @@ -370,7 +379,7 @@ static int ulev1_print_configuration( uint8_t *data){ PrintAndLog(" cfg0 [16/0x10]: %s", sprint_hex(data, 4)); if ( data[3] < 0xff ) - PrintAndLog(" - pages above %d needs authentication",data[3]); + PrintAndLog(" - page %d and above need authentication",data[3]); else PrintAndLog(" - pages don't need authentication"); PrintAndLog(" - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); @@ -389,10 +398,13 @@ static int ulev1_print_configuration( uint8_t *data){ static int ulev1_print_counters(){ PrintAndLog("--- UL-EV1 Counters"); + uint8_t tear[1] = {0}; uint8_t counter[3] = {0,0,0}; for ( uint8_t i = 0; i<3; ++i) { + ulev1_readTearing(i,tear,sizeof(tear)); ulev1_readCounter(i,counter, sizeof(counter) ); PrintAndLog(" [%0d] : %s", i, sprint_hex(counter,3)); + PrintAndLog(" - %02X tearing %s", tear[0], ( tear[0]==0xBD)?"Ok":"failure"); } return 0; } @@ -439,9 +451,9 @@ static int ulc_magic_test(){ ul_switch_off_field(); return UL_ERROR; } - status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); + status = ulc_requestAuthentication(nonce1, sizeof(nonce1)); if ( status > 0 ) { - status = ulc_requestAuthentication(0, nonce2, sizeof(nonce2)); + status = ulc_requestAuthentication(nonce2, sizeof(nonce2)); returnValue = ( !memcmp(nonce1, nonce2, 11) ) ? UL_C_MAGIC : UL_C; } else { returnValue = UL; @@ -458,13 +470,13 @@ static int ul_magic_test(){ iso14a_card_select_t card; int status = ul_select(&card); if ( status < 1 ){ - PrintAndLog("Error: couldn't select ul_magic_test"); + PrintAndLog("iso14443a card select failed"); ul_switch_off_field(); return UL_ERROR; } status = ul_comp_write(0, NULL, 0); ul_switch_off_field(); - if ( status == 0) + if ( status == 0 ) return UL_MAGIC; return UL; } @@ -518,19 +530,17 @@ uint16_t GetHF14AMfU_Type(void){ case -1 : tagtype = (UL | UL_C); break; //when does this happen? default : tagtype = UNKNOWN; break; } + // UL-C test if (tagtype == (UL | UL_C)) { status = ul_select(&card); if ( status < 1 ){ - PrintAndLog("Error: couldn't select 2"); + PrintAndLog("iso14443a card select failed (UL-C)"); ul_switch_off_field(); return UL_ERROR; } uint8_t nonce1[11] = {0x00}; - status = ulc_requestAuthentication(0, nonce1, sizeof(nonce1)); - if ( status > 0 ) - tagtype = UL_C; - else - tagtype = UL; + status = ulc_requestAuthentication(nonce1, sizeof(nonce1)); + tagtype = ( status > 0 ) ? UL_C : UL; if (status != -1) ul_switch_off_field(); } @@ -557,7 +567,51 @@ int CmdHF14AMfUInfo(const char *Cmd){ iso14a_card_select_t card; uint8_t *key; int status; + bool errors = false; + bool hasAuthKey = false; + uint8_t cmdp = 0; + uint8_t datalen = 0; + uint8_t authenticationkey[16] = {0x00}; + uint8_t pack[4] = {0,0,0,0}; + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_mfu_info(); + case 'k': + case 'K': + // EV1/NTAG size key + datalen = param_gethex(Cmd, cmdp+1, data, 8); + if ( !datalen ) { + memcpy(authenticationkey, data, 4); + cmdp += 2; + hasAuthKey = true; + break; + } + // UL-C size key + datalen = param_gethex(Cmd, cmdp+1, data, 32); + if (!datalen){ + memcpy(authenticationkey, data, 16); + cmdp += 2; + hasAuthKey = true; + break; + } + errors = true; + break; + default: + PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) break; + } + + //Validations + if(errors) return usage_hf_mfu_info(); + TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -567,11 +621,18 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_select(&card); if ( status < 1 ){ - PrintAndLog("Error: couldn't select"); + PrintAndLog("iso14443a card select failed"); ul_switch_off_field(); return status; } + if ( hasAuthKey ) { + if ((tagtype & UL_C)) + try3DesAuthentication(authenticationkey); + else + ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); + } + // read pages 0,1,2,4 (should read 4pages) status = ul_read(0, data, sizeof(data)); if ( status == -1 ){ @@ -587,7 +648,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t ulc_conf[16] = {0x00}; status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ - possibly locked"); + PrintAndLog("Error: tag didn't answer to READ UL-C"); return status; } ulc_print_configuration(ulc_conf); @@ -603,14 +664,17 @@ int CmdHF14AMfUInfo(const char *Cmd){ ulc_print_3deskey(ulc_deskey); } else { + // if we called info with key, just return + if ( hasAuthKey ) return 1; + PrintAndLog("Trying some default 3des keys"); ul_switch_off_field(); - for (uint8_t i = 0; i < 7; ++i ){ + for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ){ key = default_3des_keys[i]; if (try3DesAuthentication(key) == 1){ PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); ulc_print_3deskey(SwapEndian64(key,16)); - return 0; + return 1; } } } @@ -637,6 +701,11 @@ int CmdHF14AMfUInfo(const char *Cmd){ } // save AUTHENTICATION LIMITS for later: authlim = (ulev1_conf[4] & 0x07); + bool allZeros = true; + for (uint8_t idx=0; idx<8; idx++) + if (ulev1_conf[idx]) allZeros = false; + + if (allZeros) authlim=7; ulev1_print_configuration(ulev1_conf); } @@ -650,13 +719,15 @@ int CmdHF14AMfUInfo(const char *Cmd){ } ulev1_print_version(version); + // if we called info with key, just return + if ( hasAuthKey ) return 1; + // AUTHLIMIT, (number of failed authentications) // 0 = limitless. // 1-7 = ... should we even try then? if ( authlim == 0 ){ PrintAndLog("\n--- Known EV1/NTAG passwords."); - uint8_t pack[4] = {0,0,0,0}; int len=0; //if len goes to -1 the connection will be turned off. for (uint8_t i = 0; i < 3; ++i ){ key = default_pwd_pack[i]; @@ -683,7 +754,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); PrintAndLog(""); - return 0; + return 1; } // @@ -797,12 +868,29 @@ int CmdHF14AMfURdBl(const char *Cmd){ return 0; } +int usage_hf_mfu_info(void) +{ + PrintAndLog("It gathers information about the tag and tries to detect what kind it is."); + PrintAndLog("Sometimes the tags are locked down, and you may need a key to be able to read the information"); + PrintAndLog("The following tags can be identified:\n"); + PrintAndLog("Ultralight, Ultralight-C, Ultralight EV1"); + PrintAndLog("NTAG 213, NTAG 215, NTAG 216"); + PrintAndLog("my-d, my-d NFC, my-d move, my-d move NFC\n"); + PrintAndLog("Usage: hf mfu info k "); + PrintAndLog(" Options : "); + PrintAndLog(" k : key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(""); + PrintAndLog(" sample : hf mfu info"); + PrintAndLog(" : hf mfu info k 11223344"); + return 0; +} + int usage_hf_mfu_dump(void) { PrintAndLog("Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("It autodetects card type.\n"); - PrintAndLog("Usage: hf mfu dump k n "); + PrintAndLog("Usage: hf mfu dump s k n "); PrintAndLog(" Options : "); PrintAndLog(" k : Enter key for authentication"); PrintAndLog(" n : Enter filename w/o .bin to save the dump as"); @@ -810,8 +898,10 @@ int usage_hf_mfu_dump(void) PrintAndLog(""); PrintAndLog(" sample : hf mfu dump"); PrintAndLog(" : hf mfu dump n myfile"); + PrintAndLog(" : hf mfu dump k 00112233445566778899AABBCCDDEEFF"); return 0; } + // // Mifare Ultralight / Ultralight-C / Ultralight-EV1 // Read and Dump Card Contents, using auto detection of tag size. @@ -1083,7 +1173,6 @@ int CmdHF14AMfucAuth(const char *Cmd){ int try3DesAuthentication( uint8_t *key){ - uint8_t blockNo = 0; uint32_t cuid = 0; des3_context ctx = { 0 }; @@ -1094,7 +1183,7 @@ int try3DesAuthentication( uint8_t *key){ uint8_t rnd_ab[16] = { 0 }; uint8_t iv[8] = { 0 }; - UsbCommand c = {CMD_MIFAREUC_AUTH1, {blockNo}}; + UsbCommand c = {CMD_MIFAREUC_AUTH1, {0x00}}; SendCommand(&c); UsbCommand resp; if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return -1; diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 23f97cac..0ec82b2d 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -13,19 +13,22 @@ int CmdHF14AMfUCRdBl(const char *Cmd); int CmdHF14AMfUCRdCard(const char *Cmd); int CmdHF14AMfucAuth(const char *Cmd); -//general stuff -int CmdHF14AMfUDump(const char *Cmd); -void rol (uint8_t *data, const size_t len); - uint8_t requestAuthentication( uint8_t *nonce); int try3DesAuthentication( uint8_t *key); + +//general stuff +int CmdHF14AMfUDump(const char *Cmd); +int CmdHF14AMfUInfo(const char *Cmd); uint16_t GetHF14AMfU_Type(void); + +void rol (uint8_t *data, const size_t len); int ul_print_type(uint16_t tagtype, uint8_t spacer); +void ul_switch_off_field(void); int usage_hf_mfu_dump(void); +int usage_hf_mfu_info(void); int CmdHFMFUltra(const char *Cmd); -int CmdHF14AMfUInfo(const char *Cmd); typedef enum TAGTYPE_UL { UNKNOWN = 0x0000, From 2b3af97df2b9368ea02cab49898b931d1c3d0598 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 13 May 2015 11:07:47 -0400 Subject: [PATCH 041/132] various bug fixes --- armsrc/lfops.c | 2 +- client/cmddata.c | 4 ++-- client/cmddata.h | 2 +- client/cmdhfmfu.c | 10 ++++++---- client/util.c | 14 ++++++++------ client/util.h | 2 +- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/armsrc/lfops.c b/armsrc/lfops.c index e45b55fc..c3fa8a0e 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -651,7 +651,7 @@ void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream) int ledcontrol = 1; int n=0, i=0; uint8_t clk = (arg1 >> 8) & 0xFF; - uint8_t encoding = arg1 & 1; + uint8_t encoding = arg1 & 0xFF; uint8_t separator = arg2 & 1; uint8_t invert = (arg2 >> 8) & 1; diff --git a/client/cmddata.c b/client/cmddata.c index 556ede06..3ea75613 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -26,7 +26,7 @@ uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; uint8_t g_debugMode; -int DemodBufferLen; +size_t DemodBufferLen; static int CmdHelp(const char *Cmd); //set the demod buffer with given array of binary (one bit per byte) @@ -1484,7 +1484,7 @@ int CmdIndalaDecode(const char *Cmd) return 0; } uint8_t invert=0; - ans = indala26decode(DemodBuffer,(size_t *) &DemodBufferLen, &invert); + ans = indala26decode(DemodBuffer, &DemodBufferLen, &invert); if (ans < 1) { if (g_debugMode==1) PrintAndLog("Error2: %d",ans); diff --git a/client/cmddata.h b/client/cmddata.h index 57f04001..c6230736 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -70,7 +70,7 @@ int getSamples(const char *Cmd, bool silent); #define MAX_DEMOD_BUF_LEN (1024*128) extern uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; -extern int DemodBufferLen; +extern size_t DemodBufferLen; extern uint8_t g_debugMode; #define BIGBUF_SIZE 40000 diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 7b936792..e7b90b4c 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -340,7 +340,7 @@ static int ulc_print_3deskey( uint8_t *data){ PrintAndLog(" deskey1 [45/0x2D]: %s [%.4s]", sprint_hex(data+4 ,4),data+4); PrintAndLog(" deskey2 [46/0x2E]: %s [%.4s]", sprint_hex(data+8 ,4),data+8); PrintAndLog(" deskey2 [47/0x2F]: %s [%.4s]", sprint_hex(data+12,4),data+12); - PrintAndLog("\n 3des key : %s", sprint_hex(SwapEndian64(data, 16), 16)); + PrintAndLog("\n 3des key : %s", sprint_hex(SwapEndian64(data, 16, 8), 16)); return 0; } @@ -673,7 +673,9 @@ int CmdHF14AMfUInfo(const char *Cmd){ key = default_3des_keys[i]; if (try3DesAuthentication(key) == 1){ PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); - ulc_print_3deskey(SwapEndian64(key,16)); + uint8_t keySwap[16]; + memcpy(keySwap, SwapEndian64(key,16,8), 16); + ulc_print_3deskey(keySwap); return 1; } } @@ -973,7 +975,7 @@ int CmdHF14AMfUDump(const char *Cmd){ if(errors) return usage_hf_mfu_dump(); if (swapEndian) - keyPtr = SwapEndian64(data, 16); + keyPtr = SwapEndian64(data, 16, 8); TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -1369,7 +1371,7 @@ int CmdHF14AMfUCRdBl(const char *Cmd) hasPwd = TRUE; } } - //uint8_t *key2 = SwapEndian64(key, 16); + //uint8_t *key2 = SwapEndian64(key, 16, 8); //Read Block UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; diff --git a/client/util.c b/client/util.c index 54823422..0dd6905e 100644 --- a/client/util.c +++ b/client/util.c @@ -164,14 +164,16 @@ uint64_t bytes_to_num(uint8_t* src, size_t len) // to // hh,gg,ff,ee,dd,cc,bb,aa, pp,oo,nn,mm,ll,kk,jj,ii // up to 64 bytes or 512 bits -uint8_t *SwapEndian64(uint8_t *src, size_t len){ - static uint8_t temp[64]={0}; - for (uint8_t block=0; block < (uint8_t)len/8; block++){ - for (size_t i = 0; i < 8; i++){ - temp[i+(8*block)] = src[(7-i)+(8*block)]; +uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize){ + static uint8_t buf[64]; + memset(buf, 0x00, 64); + uint8_t *tmp = buf; + for (uint8_t block=0; block < (uint8_t)(len/blockSize); block++){ + for (size_t i = 0; i < blockSize; i++){ + tmp[i+(blockSize*block)] = src[(blockSize-1-i)+(blockSize*block)]; } } - return temp; + return tmp; } //assumes little endian diff --git a/client/util.h b/client/util.h index fb587da0..f58f64cb 100644 --- a/client/util.h +++ b/client/util.h @@ -44,7 +44,7 @@ char * sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t bre void num_to_bytes(uint64_t n, size_t len, uint8_t* dest); uint64_t bytes_to_num(uint8_t* src, size_t len); char * printBits(size_t const size, void const * const ptr); -uint8_t *SwapEndian64(uint8_t *src, size_t len); +uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize); char param_getchar(const char *line, int paramnum); uint8_t param_get8(const char *line, int paramnum); From e6432f05795ba0eaf1e34bb47b2a7f87a762de29 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 13 May 2015 11:14:17 -0400 Subject: [PATCH 042/132] @iceman1001 s coverity scan fixes --- client/cmddata.c | 2 +- client/cmdhfmf.c | 10 ++++++---- client/cmdhfmfu.c | 2 +- client/cmdscript.c | 2 +- client/mifarehost.c | 10 ++-------- client/scripting.c | 1 + client/util.c | 2 +- 7 files changed, 13 insertions(+), 16 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 3ea75613..b9069bc1 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1892,7 +1892,7 @@ int getSamples(const char *Cmd, bool silent) PrintAndLog("Unpacking..."); BitstreamOut bout = { got, bits_per_sample * n, 0}; int j =0; - for (j = 0; j * bits_per_sample < n * 8 && j < sizeof(GraphBuffer); j++) { + for (j = 0; j * bits_per_sample < n * 8 && j < n; j++) { uint8_t sample = getByte(bits_per_sample, &bout); GraphBuffer[j] = ((int) sample )- 128; } diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index b96c9c1a..aa3b66dc 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -547,7 +547,7 @@ int CmdHF14AMfNested(const char *Cmd) uint8_t trgKeyType = 0; uint8_t SectorsCnt = 0; uint8_t key[6] = {0, 0, 0, 0, 0, 0}; - uint8_t keyBlock[13*6]; + uint8_t keyBlock[14*6]; uint64_t key64 = 0; bool transferToEml = false; @@ -1202,7 +1202,7 @@ int CmdHF14AMfELoad(const char *Cmd) if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; - fnameptr += len; + fnameptr += len-4; sprintf(fnameptr, ".eml"); @@ -1311,7 +1311,7 @@ int CmdHF14AMfESave(const char *Cmd) for (j = 0; j < 7; j++, fnameptr += 2) sprintf(fnameptr, "%02X", buf[j]); } else { - fnameptr += len; + fnameptr += len-4; } // add file extension @@ -1575,7 +1575,7 @@ int CmdHF14AMfCLoad(const char *Cmd) if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; memcpy(filename, Cmd, len); - fnameptr += len; + fnameptr += len-4; sprintf(fnameptr, ".eml"); @@ -1592,6 +1592,7 @@ int CmdHF14AMfCLoad(const char *Cmd) memset(buf, 0, sizeof(buf)); if (fgets(buf, sizeof(buf), f) == NULL) { + fclose(f); PrintAndLog("File reading error."); return 2; } @@ -1600,6 +1601,7 @@ int CmdHF14AMfCLoad(const char *Cmd) if(strlen(buf) && feof(f)) break; PrintAndLog("File content error. Block data must include 32 HEX symbols"); + fclose(f); return 2; } for (i = 0; i < 32; i += 2) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index e7b90b4c..11282857 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -1103,7 +1103,7 @@ int CmdHF14AMfUDump(const char *Cmd){ sprintf(fnameptr,"%02X%02X%02X%02X%02X%02X%02X.bin", data[0],data[1], data[2], data[4],data[5],data[6], data[7]); } else { - sprintf(fnameptr + fileNlen," .bin"); + sprintf(fnameptr + fileNlen,".bin"); } if ((fout = fopen(filename,"wb")) == NULL) { diff --git a/client/cmdscript.c b/client/cmdscript.c index 928a216d..730f4e96 100644 --- a/client/cmdscript.c +++ b/client/cmdscript.c @@ -83,7 +83,7 @@ int CmdList(const char *Cmd) { while ((ep = readdir (dp)) != NULL) { - if(ep->d_name != NULL && str_ends_with(ep->d_name, ".lua")) + if(str_ends_with(ep->d_name, ".lua")) PrintAndLog("%-16s %s", ep->d_name, "A script file"); } (void) closedir (dp); diff --git a/client/mifarehost.c b/client/mifarehost.c index 35499b83..237979c1 100644 --- a/client/mifarehost.c +++ b/client/mifarehost.c @@ -354,10 +354,7 @@ int loadTraceCard(uint8_t *tuid) { FillFileNameByUID(traceFileName, tuid, ".eml", 7); f = fopen(traceFileName, "r"); - if (!f) { - fclose(f); - return 1; - } + if (!f) return 1; blockNum = 0; @@ -394,10 +391,7 @@ int saveTraceCard(void) { if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0; f = fopen(traceFileName, "w+"); - if ( !f ) { - fclose(f); - return 1; - } + if ( !f ) return 1; for (int i = 0; i < 64; i++) { // blocks for (int j = 0; j < 16; j++) // bytes diff --git a/client/scripting.c b/client/scripting.c index d7f51c23..a7cf27d7 100644 --- a/client/scripting.c +++ b/client/scripting.c @@ -298,6 +298,7 @@ int setLuaPath( lua_State* L, const char* path ) lua_pushstring( L, buf ); // push the new one lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack lua_pop( L, 1 ); // get rid of package table from top of stack + free(buf); return 0; // all done! } diff --git a/client/util.c b/client/util.c index 0dd6905e..cea9f7d7 100644 --- a/client/util.c +++ b/client/util.c @@ -124,7 +124,7 @@ char * sprint_hex(const uint8_t * data, const size_t len) { char *sprint_bin_break(const uint8_t *data, const size_t len, const uint8_t breaks) { - int maxLen = ( len > 1024) ? 1024 : len; + int maxLen = ( len > 1020) ? 1020 : len; static char buf[1024]; memset(buf, 0x00, 1024); char *tmp = buf; From 6fdf42c61cd4c1a71c2b1de2887e28ed33b4cd70 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 13 May 2015 11:22:27 -0400 Subject: [PATCH 043/132] minor hf mfu info adjustment from @iceman1001 --- client/cmdhfmfu.c | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 11282857..d8060894 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -271,9 +271,14 @@ static int ul_print_default( uint8_t *data){ PrintAndLog(" BCC1 : %02X - crc should be %02X", data[8], crc1 ); PrintAndLog(" Internal : %02X - %s default", data[9], (data[9]==0x48)?"":"not" ); - PrintAndLog(" Lock : %s - %s", sprint_hex(data+10, 2),printBits( 2, data+10) ); - PrintAndLog("OneTimePad : %s ", sprint_hex(data + 12, 4)); - PrintAndLog(""); + PrintAndLog(" Lock : %s - %s", + sprint_hex(data+10, 2), + printBits(2, data+10) + ); + PrintAndLog("OneTimePad : %s - %s\n", + sprint_hex(data + 12, 4), + printBits(4, data+12) + ); return 0; } From d730878d8c932cdbdd1c386e8491af27f3764dae Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 13 May 2015 21:14:35 -0400 Subject: [PATCH 044/132] scripting updates from @iceman1001 it compiles but i'm not sure how to fully test it... :) --- client/Makefile | 1 + client/scripting.c | 419 +++++++++++++++++++++++++-------------------- common/crc64.c | 85 +++++++++ common/crc64.h | 14 ++ 4 files changed, 332 insertions(+), 187 deletions(-) create mode 100644 common/crc64.c create mode 100644 common/crc64.h diff --git a/client/Makefile b/client/Makefile index 81af0149..7954d1ea 100644 --- a/client/Makefile +++ b/client/Makefile @@ -68,6 +68,7 @@ CMDSRCS = nonce2key/crapto1.c\ mifarehost.c\ crc.c \ crc16.c \ + crc64.c \ iso14443crc.c \ iso15693tools.c \ data.c \ diff --git a/client/scripting.c b/client/scripting.c index a7cf27d7..152fd9d4 100644 --- a/client/scripting.c +++ b/client/scripting.c @@ -19,6 +19,7 @@ #include "nonce2key/nonce2key.h" #include "../common/iso15693tools.h" #include "../common/crc16.h" +#include "../common/crc64.h" #include "aes.h" /** * The following params expected: @@ -29,34 +30,34 @@ */ static int l_SendCommand(lua_State *L){ - /* - * - The SendCommand (native) expects the following structure: + /* + * + The SendCommand (native) expects the following structure: - typedef struct { - uint64_t cmd; //8 bytes - uint64_t arg[3]; // 8*3 bytes = 24 bytes - union { - uint8_t asBytes[USB_CMD_DATA_SIZE]; // 1 byte * 512 = 512 bytes (OR) - uint32_t asDwords[USB_CMD_DATA_SIZE/4]; // 4 byte * 128 = 512 bytes - } d; - } PACKED UsbCommand; + typedef struct { + uint64_t cmd; //8 bytes + uint64_t arg[3]; // 8*3 bytes = 24 bytes + union { + uint8_t asBytes[USB_CMD_DATA_SIZE]; // 1 byte * 512 = 512 bytes (OR) + uint32_t asDwords[USB_CMD_DATA_SIZE/4]; // 4 byte * 128 = 512 bytes + } d; + } PACKED UsbCommand; - ==> A 544 byte buffer will do. - **/ - //Pop cmd - size_t size; - const char *data = luaL_checklstring(L, 1, &size); - if(size != sizeof(UsbCommand)) - { - printf("Got data size %d, expected %d" , (int) size,(int) sizeof(UsbCommand)); - lua_pushstring(L,"Wrong data size"); - return 1; - } + ==> A 544 byte buffer will do. + **/ + //Pop cmd + size_t size; + const char *data = luaL_checklstring(L, 1, &size); + if(size != sizeof(UsbCommand)) + { + printf("Got data size %d, expected %d" , (int) size,(int) sizeof(UsbCommand)); + lua_pushstring(L,"Wrong data size"); + return 1; + } // UsbCommand c = (*data); - SendCommand((UsbCommand* )data); - return 0; // no return values + SendCommand((UsbCommand* )data); + return 0; // no return values } /** * @brief The following params expected: @@ -67,105 +68,105 @@ static int l_SendCommand(lua_State *L){ */ static int l_WaitForResponseTimeout(lua_State *L){ - uint32_t cmd = 0; - size_t ms_timeout = -1; + uint32_t cmd = 0; + size_t ms_timeout = -1; - //Check number of arguments - int n = lua_gettop(L); - if(n == 0) - { - //signal error by returning Nil, errorstring - lua_pushnil(L); - lua_pushstring(L,"You need to supply at least command to wait for"); - return 2; // two return values - } - if(n >= 1) - { - //pop cmd - cmd = luaL_checkunsigned(L,1); - } - if(n >= 2) - { - //Did the user send a timeout ? - //Check if the current top of stack is an integer - ms_timeout = luaL_checkunsigned(L,2); - //printf("Timeout set to %dms\n" , (int) ms_timeout); - } + //Check number of arguments + int n = lua_gettop(L); + if(n == 0) + { + //signal error by returning Nil, errorstring + lua_pushnil(L); + lua_pushstring(L,"You need to supply at least command to wait for"); + return 2; // two return values + } + if(n >= 1) + { + //pop cmd + cmd = luaL_checkunsigned(L,1); + } + if(n >= 2) + { + //Did the user send a timeout ? + //Check if the current top of stack is an integer + ms_timeout = luaL_checkunsigned(L,2); + //printf("Timeout set to %dms\n" , (int) ms_timeout); + } - UsbCommand response; + UsbCommand response; - if(WaitForResponseTimeout(cmd, &response, ms_timeout)) - { - //Push it as a string - lua_pushlstring(L,(const char *)&response,sizeof(UsbCommand)); + if(WaitForResponseTimeout(cmd, &response, ms_timeout)) + { + //Push it as a string + lua_pushlstring(L,(const char *)&response,sizeof(UsbCommand)); - return 1;// return 1 to signal one return value - }else{ - //Push a Nil instead - lua_pushnil(L); - return 1;// one return value - } + return 1;// return 1 to signal one return value + }else{ + //Push a Nil instead + lua_pushnil(L); + return 1;// one return value + } } static int returnToLuaWithError(lua_State *L, const char* fmt, ...) { - char buffer[200]; - va_list args; - va_start(args,fmt); - vsnprintf(buffer, sizeof(buffer), fmt,args); - va_end(args); + char buffer[200]; + va_list args; + va_start(args,fmt); + vsnprintf(buffer, sizeof(buffer), fmt,args); + va_end(args); - lua_pushnil(L); - lua_pushstring(L,buffer); - return 2; + lua_pushnil(L); + lua_pushstring(L,buffer); + return 2; } static int l_nonce2key(lua_State *L){ - size_t size; - const char *p_uid = luaL_checklstring(L, 1, &size); - if(size != 4) return returnToLuaWithError(L,"Wrong size of uid, got %d bytes, expected 4", (int) size); + size_t size; + const char *p_uid = luaL_checklstring(L, 1, &size); + if(size != 4) return returnToLuaWithError(L,"Wrong size of uid, got %d bytes, expected 4", (int) size); - const char *p_nt = luaL_checklstring(L, 2, &size); - if(size != 4) return returnToLuaWithError(L,"Wrong size of nt, got %d bytes, expected 4", (int) size); + const char *p_nt = luaL_checklstring(L, 2, &size); + if(size != 4) return returnToLuaWithError(L,"Wrong size of nt, got %d bytes, expected 4", (int) size); - const char *p_nr = luaL_checklstring(L, 3, &size); - if(size != 4) return returnToLuaWithError(L,"Wrong size of nr, got %d bytes, expected 4", (int) size); + const char *p_nr = luaL_checklstring(L, 3, &size); + if(size != 4) return returnToLuaWithError(L,"Wrong size of nr, got %d bytes, expected 4", (int) size); - const char *p_par_info = luaL_checklstring(L, 4, &size); - if(size != 8) return returnToLuaWithError(L,"Wrong size of par_info, got %d bytes, expected 8", (int) size); + const char *p_par_info = luaL_checklstring(L, 4, &size); + if(size != 8) return returnToLuaWithError(L,"Wrong size of par_info, got %d bytes, expected 8", (int) size); - const char *p_pks_info = luaL_checklstring(L, 5, &size); - if(size != 8) return returnToLuaWithError(L,"Wrong size of ks_info, got %d bytes, expected 8", (int) size); + const char *p_pks_info = luaL_checklstring(L, 5, &size); + if(size != 8) return returnToLuaWithError(L,"Wrong size of ks_info, got %d bytes, expected 8", (int) size); - uint32_t uid = bytes_to_num(( uint8_t *)p_uid,4); - uint32_t nt = bytes_to_num(( uint8_t *)p_nt,4); + uint32_t uid = bytes_to_num(( uint8_t *)p_uid,4); + uint32_t nt = bytes_to_num(( uint8_t *)p_nt,4); - uint32_t nr = bytes_to_num(( uint8_t*)p_nr,4); - uint64_t par_info = bytes_to_num(( uint8_t *)p_par_info,8); - uint64_t ks_info = bytes_to_num(( uint8_t *)p_pks_info,8); + uint32_t nr = bytes_to_num(( uint8_t*)p_nr,4); + uint64_t par_info = bytes_to_num(( uint8_t *)p_par_info,8); + uint64_t ks_info = bytes_to_num(( uint8_t *)p_pks_info,8); - uint64_t key = 0; + uint64_t key = 0; - int retval = nonce2key(uid,nt, nr, par_info,ks_info, &key); + int retval = nonce2key(uid,nt, nr, par_info,ks_info, &key); - //Push the retval on the stack - lua_pushinteger(L,retval); - - //Push the key onto the stack - uint8_t dest_key[8]; - num_to_bytes(key,sizeof(dest_key),dest_key); + //Push the retval on the stack + lua_pushinteger(L,retval); - //printf("Pushing to lua stack: %012"llx"\n",key); - lua_pushlstring(L,(const char *) dest_key,sizeof(dest_key)); + //Push the key onto the stack + uint8_t dest_key[8]; + num_to_bytes(key,sizeof(dest_key),dest_key); - return 2; //Two return values + //printf("Pushing to lua stack: %012"llx"\n",key); + lua_pushlstring(L,(const char *) dest_key,sizeof(dest_key)); + + return 2; //Two return values } //static int l_PrintAndLog(lua_State *L){ return CmdHF14AMfDump(luaL_checkstring(L, 1));} static int l_clearCommandBuffer(lua_State *L){ - clearCommandBuffer(); - return 0; + clearCommandBuffer(); + return 0; } /** * @brief l_foobar is a dummy function to test lua-integration with @@ -174,23 +175,23 @@ static int l_clearCommandBuffer(lua_State *L){ */ static int l_foobar(lua_State *L) { - //Check number of arguments - int n = lua_gettop(L); - printf("foobar called with %d arguments" , n); - lua_settop(L, 0); - printf("Arguments discarded, stack now contains %d elements", lua_gettop(L)); - - // todo: this is not used, where was it intended for? - // UsbCommand response = {CMD_MIFARE_READBL, {1337, 1338, 1339}}; - - printf("Now returning a uint64_t as a string"); - uint64_t x = 0xDEADBEEF; - uint8_t destination[8]; - num_to_bytes(x,sizeof(x),destination); - lua_pushlstring(L,(const char *)&x,sizeof(x)); - lua_pushlstring(L,(const char *)destination,sizeof(destination)); + //Check number of arguments + int n = lua_gettop(L); + printf("foobar called with %d arguments" , n); + lua_settop(L, 0); + printf("Arguments discarded, stack now contains %d elements", lua_gettop(L)); - return 2; + // todo: this is not used, where was it intended for? + // UsbCommand response = {CMD_MIFARE_READBL, {1337, 1338, 1339}}; + + printf("Now returning a uint64_t as a string"); + uint64_t x = 0xDEADBEEF; + uint8_t destination[8]; + num_to_bytes(x,sizeof(x),destination); + lua_pushlstring(L,(const char *)&x,sizeof(x)); + lua_pushlstring(L,(const char *)destination,sizeof(destination)); + + return 2; } @@ -201,8 +202,8 @@ static int l_foobar(lua_State *L) */ static int l_ukbhit(lua_State *L) { - lua_pushboolean(L,ukbhit() ? true : false); - return 1; + lua_pushboolean(L,ukbhit() ? true : false); + return 1; } /** * @brief Calls the command line parser to deal with the command. This enables @@ -212,58 +213,78 @@ static int l_ukbhit(lua_State *L) */ static int l_CmdConsole(lua_State *L) { - CommandReceived((char *)luaL_checkstring(L, 1)); - return 0; + CommandReceived((char *)luaL_checkstring(L, 1)); + return 0; } static int l_iso15693_crc(lua_State *L) { - // uint16_t Iso15693Crc(uint8_t *v, int n); - size_t size; - const char *v = luaL_checklstring(L, 1, &size); - uint16_t retval = Iso15693Crc((uint8_t *) v, size); - lua_pushinteger(L, (int) retval); - return 1; + // uint16_t Iso15693Crc(uint8_t *v, int n); + size_t size; + const char *v = luaL_checklstring(L, 1, &size); + uint16_t retval = Iso15693Crc((uint8_t *) v, size); + lua_pushinteger(L, (int) retval); + return 1; } /* Simple AES 128 cbc hook up to OpenSSL. params: key, input */ -static int l_aes(lua_State *L) +static int l_aes128decrypt(lua_State *L) { //Check number of arguments int i; - size_t size; - const char *p_key = luaL_checklstring(L, 1, &size); - if(size != 32) return returnToLuaWithError(L,"Wrong size of key, got %d bytes, expected 32", (int) size); + size_t size; + const char *p_key = luaL_checklstring(L, 1, &size); + if(size != 32) return returnToLuaWithError(L,"Wrong size of key, got %d bytes, expected 32", (int) size); + + const char *p_encTxt = luaL_checklstring(L, 2, &size); - const char *p_encTxt = luaL_checklstring(L, 2, &size); - unsigned char indata[16] = {0x00}; unsigned char outdata[16] = {0x00}; - unsigned char aes_key[16] = {0x00}; + unsigned char aes_key[16] = {0x00}; unsigned char iv[16] = {0x00}; - - // convert key to bytearray + + // convert key to bytearray and convert input to bytearray for (i = 0; i < 32; i += 2) { sscanf(&p_encTxt[i], "%02x", (unsigned int *)&indata[i / 2]); - } - - // convert input to bytearray - for (i = 0; i < 32; i += 2) { sscanf(&p_key[i], "%02x", (unsigned int *)&aes_key[i / 2]); } - - //AES_KEY key; - //AES_set_decrypt_key(aes_key, 128, &key); - //AES_cbc_encrypt(indata, outdata, sizeof(indata), &key, iv, AES_DECRYPT); - aes_context ctx; - aes_init(&ctx); - aes_setkey_dec(&ctx, aes_key, 128); + aes_context ctx; + aes_init(&ctx); + aes_setkey_dec(&ctx, aes_key, 128); aes_crypt_cbc(&ctx,AES_DECRYPT,sizeof(indata), iv, indata,outdata ); - //Push decrypted array as a string + //Push decrypted array as a string + lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); + return 1;// return 1 to signal one return value +} +static int l_aes128encrypt(lua_State *L) +{ + //Check number of arguments + int i; + size_t size; + const char *p_key = luaL_checklstring(L, 1, &size); + 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", (unsigned int *)&indata[i / 2]); + sscanf(&p_key[i], "%02x", (unsigned int *)&aes_key[i / 2]); + } + + aes_context ctx; + aes_init(&ctx); + aes_setkey_enc(&ctx, aes_key, 128); + aes_crypt_cbc(&ctx, AES_ENCRYPT, sizeof(indata), iv, indata, outdata ); + //Push encrypted array as a string lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); return 1;// return 1 to signal one return value } @@ -272,10 +293,32 @@ static int l_crc16(lua_State *L) { size_t size; const char *p_str = luaL_checklstring(L, 1, &size); - + uint16_t retval = crc16_ccitt( (uint8_t*) p_str, size); - lua_pushinteger(L, (int) retval); - return 1; + lua_pushinteger(L, (int) retval); + return 1; +} + +static int l_crc64(lua_State *L) +{ + size_t size; + uint64_t crc = 0; + unsigned char outdata[8] = {0x00}; + + const char *p_str = luaL_checklstring(L, 1, &size); + + crc64( (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; + outdata[3] = (uint8_t)(crc >> 32) & 0xff; + outdata[4] = (uint8_t)(crc >> 24) & 0xff; + outdata[5] = (uint8_t)(crc >> 16) & 0xff; + outdata[6] = (uint8_t)(crc >> 8) & 0xff; + outdata[7] = crc & 0xff; + lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); + return 1; } /** @@ -288,58 +331,60 @@ static int l_crc16(lua_State *L) */ int setLuaPath( lua_State* L, const char* path ) { - lua_getglobal( L, "package" ); - lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1) - const char* cur_path = lua_tostring( L, -1 ); // grab path string from top of stack - int requiredLength = strlen(cur_path)+ strlen(path)+10; //A few bytes too many, whatever we can afford it - char * buf = malloc(requiredLength); - snprintf(buf, requiredLength, "%s;%s", cur_path, path); - lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5 - lua_pushstring( L, buf ); // push the new one - lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack - lua_pop( L, 1 ); // get rid of package table from top of stack - free(buf); - return 0; // all done! + lua_getglobal( L, "package" ); + lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1) + const char* cur_path = lua_tostring( L, -1 ); // grab path string from top of stack + int requiredLength = strlen(cur_path)+ strlen(path)+10; //A few bytes too many, whatever we can afford it + char * buf = malloc(requiredLength); + snprintf(buf, requiredLength, "%s;%s", cur_path, path); + lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5 + lua_pushstring( L, buf ); // push the new one + lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack + lua_pop( L, 1 ); // get rid of package table from top of stack + free(buf); + return 0; // all done! } int set_pm3_libraries(lua_State *L) { - static const luaL_Reg libs[] = { - {"SendCommand", l_SendCommand}, - {"WaitForResponseTimeout", l_WaitForResponseTimeout}, - {"nonce2key", l_nonce2key}, - //{"PrintAndLog", l_PrintAndLog}, - {"foobar", l_foobar}, - {"ukbhit", l_ukbhit}, - {"clearCommandBuffer", l_clearCommandBuffer}, - {"console", l_CmdConsole}, - {"iso15693_crc", l_iso15693_crc}, - {"aes", l_aes}, + static const luaL_Reg libs[] = { + {"SendCommand", l_SendCommand}, + {"WaitForResponseTimeout", l_WaitForResponseTimeout}, + {"nonce2key", l_nonce2key}, + //{"PrintAndLog", l_PrintAndLog}, + {"foobar", l_foobar}, + {"ukbhit", l_ukbhit}, + {"clearCommandBuffer", l_clearCommandBuffer}, + {"console", l_CmdConsole}, + {"iso15693_crc", l_iso15693_crc}, + {"aes128_decrypt", l_aes128decrypt}, + {"aes128_encrypt", l_aes128encrypt}, {"crc16", l_crc16}, - {NULL, NULL} - }; + {"crc64", l_crc64}, + {NULL, NULL} + }; - lua_pushglobaltable(L); - // Core library is in this table. Contains ' - //this is 'pm3' table - lua_newtable(L); + lua_pushglobaltable(L); + // Core library is in this table. Contains ' + //this is 'pm3' table + lua_newtable(L); - //Put the function into the hash table. - for (int i = 0; libs[i].name; i++) { - lua_pushcfunction(L, libs[i].func); - lua_setfield(L, -2, libs[i].name);//set the name, pop stack - } - //Name of 'core' - lua_setfield(L, -2, "core"); + //Put the function into the hash table. + for (int i = 0; libs[i].name; i++) { + lua_pushcfunction(L, libs[i].func); + lua_setfield(L, -2, libs[i].name);//set the name, pop stack + } + //Name of 'core' + lua_setfield(L, -2, "core"); - //-- remove the global environment table from the stack - lua_pop(L, 1); + //-- remove the global environment table from the stack + lua_pop(L, 1); - //-- Last but not least, add to the LUA_PATH (package.path in lua) - // so we can load libraries from the ./lualib/ - directory - setLuaPath(L,"./lualibs/?.lua"); + //-- Last but not least, add to the LUA_PATH (package.path in lua) + // so we can load libraries from the ./lualib/ - directory + setLuaPath(L,"./lualibs/?.lua"); - return 1; + return 1; } diff --git a/common/crc64.c b/common/crc64.c new file mode 100644 index 00000000..709c64d6 --- /dev/null +++ b/common/crc64.c @@ -0,0 +1,85 @@ +#include +#include +#include "crc64.h" + +#define CRC64_ISO_PRESET 0xFFFFFFFFFFFFFFFF +#define CRC64_ECMA_PRESET 0x0000000000000000 + +const uint64_t crc64_table[] = { + 0x0000000000000000, 0x42F0E1EBA9EA3693, 0x85E1C3D753D46D26, 0xC711223CFA3E5BB5, + 0x493366450E42ECDF, 0x0BC387AEA7A8DA4C, 0xCCD2A5925D9681F9, 0x8E224479F47CB76A, + 0x9266CC8A1C85D9BE, 0xD0962D61B56FEF2D, 0x17870F5D4F51B498, 0x5577EEB6E6BB820B, + 0xDB55AACF12C73561, 0x99A54B24BB2D03F2, 0x5EB4691841135847, 0x1C4488F3E8F96ED4, + 0x663D78FF90E185EF, 0x24CD9914390BB37C, 0xE3DCBB28C335E8C9, 0xA12C5AC36ADFDE5A, + 0x2F0E1EBA9EA36930, 0x6DFEFF5137495FA3, 0xAAEFDD6DCD770416, 0xE81F3C86649D3285, + 0xF45BB4758C645C51, 0xB6AB559E258E6AC2, 0x71BA77A2DFB03177, 0x334A9649765A07E4, + 0xBD68D2308226B08E, 0xFF9833DB2BCC861D, 0x388911E7D1F2DDA8, 0x7A79F00C7818EB3B, + 0xCC7AF1FF21C30BDE, 0x8E8A101488293D4D, 0x499B3228721766F8, 0x0B6BD3C3DBFD506B, + 0x854997BA2F81E701, 0xC7B97651866BD192, 0x00A8546D7C558A27, 0x4258B586D5BFBCB4, + 0x5E1C3D753D46D260, 0x1CECDC9E94ACE4F3, 0xDBFDFEA26E92BF46, 0x990D1F49C77889D5, + 0x172F5B3033043EBF, 0x55DFBADB9AEE082C, 0x92CE98E760D05399, 0xD03E790CC93A650A, + 0xAA478900B1228E31, 0xE8B768EB18C8B8A2, 0x2FA64AD7E2F6E317, 0x6D56AB3C4B1CD584, + 0xE374EF45BF6062EE, 0xA1840EAE168A547D, 0x66952C92ECB40FC8, 0x2465CD79455E395B, + 0x3821458AADA7578F, 0x7AD1A461044D611C, 0xBDC0865DFE733AA9, 0xFF3067B657990C3A, + 0x711223CFA3E5BB50, 0x33E2C2240A0F8DC3, 0xF4F3E018F031D676, 0xB60301F359DBE0E5, + 0xDA050215EA6C212F, 0x98F5E3FE438617BC, 0x5FE4C1C2B9B84C09, 0x1D14202910527A9A, + 0x93366450E42ECDF0, 0xD1C685BB4DC4FB63, 0x16D7A787B7FAA0D6, 0x5427466C1E109645, + 0x4863CE9FF6E9F891, 0x0A932F745F03CE02, 0xCD820D48A53D95B7, 0x8F72ECA30CD7A324, + 0x0150A8DAF8AB144E, 0x43A04931514122DD, 0x84B16B0DAB7F7968, 0xC6418AE602954FFB, + 0xBC387AEA7A8DA4C0, 0xFEC89B01D3679253, 0x39D9B93D2959C9E6, 0x7B2958D680B3FF75, + 0xF50B1CAF74CF481F, 0xB7FBFD44DD257E8C, 0x70EADF78271B2539, 0x321A3E938EF113AA, + 0x2E5EB66066087D7E, 0x6CAE578BCFE24BED, 0xABBF75B735DC1058, 0xE94F945C9C3626CB, + 0x676DD025684A91A1, 0x259D31CEC1A0A732, 0xE28C13F23B9EFC87, 0xA07CF2199274CA14, + 0x167FF3EACBAF2AF1, 0x548F120162451C62, 0x939E303D987B47D7, 0xD16ED1D631917144, + 0x5F4C95AFC5EDC62E, 0x1DBC74446C07F0BD, 0xDAAD56789639AB08, 0x985DB7933FD39D9B, + 0x84193F60D72AF34F, 0xC6E9DE8B7EC0C5DC, 0x01F8FCB784FE9E69, 0x43081D5C2D14A8FA, + 0xCD2A5925D9681F90, 0x8FDAB8CE70822903, 0x48CB9AF28ABC72B6, 0x0A3B7B1923564425, + 0x70428B155B4EAF1E, 0x32B26AFEF2A4998D, 0xF5A348C2089AC238, 0xB753A929A170F4AB, + 0x3971ED50550C43C1, 0x7B810CBBFCE67552, 0xBC902E8706D82EE7, 0xFE60CF6CAF321874, + 0xE224479F47CB76A0, 0xA0D4A674EE214033, 0x67C58448141F1B86, 0x253565A3BDF52D15, + 0xAB1721DA49899A7F, 0xE9E7C031E063ACEC, 0x2EF6E20D1A5DF759, 0x6C0603E6B3B7C1CA, + 0xF6FAE5C07D3274CD, 0xB40A042BD4D8425E, 0x731B26172EE619EB, 0x31EBC7FC870C2F78, + 0xBFC9838573709812, 0xFD39626EDA9AAE81, 0x3A28405220A4F534, 0x78D8A1B9894EC3A7, + 0x649C294A61B7AD73, 0x266CC8A1C85D9BE0, 0xE17DEA9D3263C055, 0xA38D0B769B89F6C6, + 0x2DAF4F0F6FF541AC, 0x6F5FAEE4C61F773F, 0xA84E8CD83C212C8A, 0xEABE6D3395CB1A19, + 0x90C79D3FEDD3F122, 0xD2377CD44439C7B1, 0x15265EE8BE079C04, 0x57D6BF0317EDAA97, + 0xD9F4FB7AE3911DFD, 0x9B041A914A7B2B6E, 0x5C1538ADB04570DB, 0x1EE5D94619AF4648, + 0x02A151B5F156289C, 0x4051B05E58BC1E0F, 0x87409262A28245BA, 0xC5B073890B687329, + 0x4B9237F0FF14C443, 0x0962D61B56FEF2D0, 0xCE73F427ACC0A965, 0x8C8315CC052A9FF6, + 0x3A80143F5CF17F13, 0x7870F5D4F51B4980, 0xBF61D7E80F251235, 0xFD913603A6CF24A6, + 0x73B3727A52B393CC, 0x31439391FB59A55F, 0xF652B1AD0167FEEA, 0xB4A25046A88DC879, + 0xA8E6D8B54074A6AD, 0xEA16395EE99E903E, 0x2D071B6213A0CB8B, 0x6FF7FA89BA4AFD18, + 0xE1D5BEF04E364A72, 0xA3255F1BE7DC7CE1, 0x64347D271DE22754, 0x26C49CCCB40811C7, + 0x5CBD6CC0CC10FAFC, 0x1E4D8D2B65FACC6F, 0xD95CAF179FC497DA, 0x9BAC4EFC362EA149, + 0x158E0A85C2521623, 0x577EEB6E6BB820B0, 0x906FC95291867B05, 0xD29F28B9386C4D96, + 0xCEDBA04AD0952342, 0x8C2B41A1797F15D1, 0x4B3A639D83414E64, 0x09CA82762AAB78F7, + 0x87E8C60FDED7CF9D, 0xC51827E4773DF90E, 0x020905D88D03A2BB, 0x40F9E43324E99428, + 0x2CFFE7D5975E55E2, 0x6E0F063E3EB46371, 0xA91E2402C48A38C4, 0xEBEEC5E96D600E57, + 0x65CC8190991CB93D, 0x273C607B30F68FAE, 0xE02D4247CAC8D41B, 0xA2DDA3AC6322E288, + 0xBE992B5F8BDB8C5C, 0xFC69CAB42231BACF, 0x3B78E888D80FE17A, 0x7988096371E5D7E9, + 0xF7AA4D1A85996083, 0xB55AACF12C735610, 0x724B8ECDD64D0DA5, 0x30BB6F267FA73B36, + 0x4AC29F2A07BFD00D, 0x08327EC1AE55E69E, 0xCF235CFD546BBD2B, 0x8DD3BD16FD818BB8, + 0x03F1F96F09FD3CD2, 0x41011884A0170A41, 0x86103AB85A2951F4, 0xC4E0DB53F3C36767, + 0xD8A453A01B3A09B3, 0x9A54B24BB2D03F20, 0x5D45907748EE6495, 0x1FB5719CE1045206, + 0x919735E51578E56C, 0xD367D40EBC92D3FF, 0x1476F63246AC884A, 0x568617D9EF46BED9, + 0xE085162AB69D5E3C, 0xA275F7C11F7768AF, 0x6564D5FDE549331A, 0x279434164CA30589, + 0xA9B6706FB8DFB2E3, 0xEB46918411358470, 0x2C57B3B8EB0BDFC5, 0x6EA7525342E1E956, + 0x72E3DAA0AA188782, 0x30133B4B03F2B111, 0xF7021977F9CCEAA4, 0xB5F2F89C5026DC37, + 0x3BD0BCE5A45A6B5D, 0x79205D0E0DB05DCE, 0xBE317F32F78E067B, 0xFCC19ED95E6430E8, + 0x86B86ED5267CDBD3, 0xC4488F3E8F96ED40, 0x0359AD0275A8B6F5, 0x41A94CE9DC428066, + 0xCF8B0890283E370C, 0x8D7BE97B81D4019F, 0x4A6ACB477BEA5A2A, 0x089A2AACD2006CB9, + 0x14DEA25F3AF9026D, 0x562E43B4931334FE, 0x913F6188692D6F4B, 0xD3CF8063C0C759D8, + 0x5DEDC41A34BBEEB2, 0x1F1D25F19D51D821, 0xD80C07CD676F8394, 0x9AFCE626CE85B507 +}; + +void crc64 (const uint8_t *data, const size_t len, uint64_t *crc) { + + for (size_t i = 0; i < len; i++) + { + //uint8_t tableIndex = (((uint8_t)(*crc >> 56)) ^ data[i]) & 0xff; + uint8_t tableIndex = (((uint8_t)(*crc >> 56)) ^ data[i]) & 0xff; + *crc = crc64_table[tableIndex] ^ (*crc << 8); + } +} + +//suint8_t x = (c & 0xFF00000000000000 ) >> 56; \ No newline at end of file diff --git a/common/crc64.h b/common/crc64.h new file mode 100644 index 00000000..e28fba14 --- /dev/null +++ b/common/crc64.h @@ -0,0 +1,14 @@ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- +// CRC64 ECMA +//----------------------------------------------------------------------------- + +#ifndef __CRC64_H +#define __CRC64_H + +void crc64 (const uint8_t *data, const size_t len, uint64_t *crc) ; + +#endif From ab7fdfcbed90cb96f281b13c079741df099ce6d2 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 13 May 2015 21:20:23 -0400 Subject: [PATCH 045/132] @iceman1001 updated scripts --- client/scripts/formatMifare.lua | 6 +-- client/scripts/tnp3clone.lua | 16 +++++--- client/scripts/tnp3dump.lua | 11 ++++-- client/scripts/tnp3sim.lua | 65 ++++++++++++++++++++------------- 4 files changed, 59 insertions(+), 39 deletions(-) diff --git a/client/scripts/formatMifare.lua b/client/scripts/formatMifare.lua index 0d735e98..66a61fba 100644 --- a/client/scripts/formatMifare.lua +++ b/client/scripts/formatMifare.lua @@ -80,14 +80,14 @@ function GetCardInfo() core.clearCommandBuffer() - if 0x18 == result.sak then --NXP MIFARE Classic 4k | Plus 4k + if 0x18 == result.sak then -- NXP MIFARE Classic 4k | Plus 4k -- IFARE Classic 4K offers 4096 bytes split into forty sectors, -- of which 32 are same size as in the 1K with eight more that are quadruple size sectors. numSectors = 40 - elseif 0x08 == result.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k + elseif 0x08 == result.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k -- 1K offers 1024 bytes of data storage, split into 16 sector numSectors = 16 - elseif 0x09 == result.sak then -- NXP MIFARE Mini 0.3k + elseif 0x09 == result.sak then -- NXP MIFARE Mini 0.3k -- MIFARE Classic mini offers 320 bytes split into five sectors. numSectors = 5 elseif 0x10 == result.sak then -- NXP MIFARE Plus 2k diff --git a/client/scripts/tnp3clone.lua b/client/scripts/tnp3clone.lua index 6c4a148c..e87c338e 100644 --- a/client/scripts/tnp3clone.lua +++ b/client/scripts/tnp3clone.lua @@ -13,6 +13,7 @@ local band = bit32.band example =[[ script run tnp3clone script run tnp3clone -h + script run tnp3clone -l script run tnp3clone -t aa00 -s 0030 ]] @@ -23,7 +24,8 @@ This script will try making a barebone clone of a tnp3 tag on to a magic generat Arguments: -h : this help - -t : toytype id, 4hex symbols. + -l : list all known toy tokens + -t : toytype id, 4hex symbols -s : subtype id, 4hex symbols For fun, try the following subtype id: @@ -32,7 +34,7 @@ Arguments: 0138 - Series 2 0234 - Special 023c - Special - + 0020 - Swapforce ]] @@ -74,7 +76,7 @@ local function readmagicblock( blocknum ) -- Read block 0 local CSETBLOCK_SINGLE_OPERATION = 0x1F cmd = Command:new{cmd = cmds.CMD_MIFARE_CGETBLOCK, arg1 = CSETBLOCK_SINGLE_OPERATION, arg2 = 0, arg3 = blocknum} - err = core.SendCommand(cmd:getBytes()) + err = core.SendCommand(cmd:getBytes()) if err then return nil, err end local block0, err = waitCmd() if err then return nil, err end @@ -98,12 +100,13 @@ local function main(args) local DEBUG = true -- Arguments for the script - for o, a in getopt.getopt(args, 'ht:s:') do + for o, a in getopt.getopt(args, 'ht:s:l') do if o == "h" then return help() end if o == "t" then toytype = a end if o == "s" then subtype = a end + if o == "l" then return toys.List() end end - + if #toytype ~= 4 then return oops('Wrong size - toytype. (4hex symbols)') end if #subtype ~= 4 then return oops('Wrong size - subtype. (4hex symbols)') end @@ -139,8 +142,9 @@ local function main(args) -- wipe card. local cmd = (csetuid..'%s 0004 08 w'):format(result.uid) core.console(cmd) + + local b1 = toytype..string.rep('00',10)..subtype - local b1 = toytype..'00000000000000000000'..subtype local calc = utils.Crc16(b0..b1) local calcEndian = bor(rsh(calc,8), lsh(band(calc, 0xff), 8)) diff --git a/client/scripts/tnp3dump.lua b/client/scripts/tnp3dump.lua index cd547e8a..211d146f 100644 --- a/client/scripts/tnp3dump.lua +++ b/client/scripts/tnp3dump.lua @@ -205,18 +205,19 @@ local function main(args) if blockNo < 8 then -- Block 0-7 not encrypted - blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) + blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) else -- blocks with zero not encrypted. if string.find(blockdata, '^0+$') then - blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) + blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata) else local baseStr = utils.ConvertHexToAscii(tmpHash:format(blockNo)) local key = md5.sumhexa(baseStr) local aestest = core.aes128_decrypt(key, blockdata) - local hex = utils.ConvertAsciiToBytes(aestest) + local hex = utils.ConvertAsciiToBytes(aestest) hex = utils.ConvertBytesToHex(hex) - blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,hex) + blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,hex) + io.write(blockNo..',') end end else @@ -273,5 +274,7 @@ local function main(args) print( (' UID : 0x%s'):format(uid) ) print( (' CARDID : 0x%s'):format(cardid ) ) print( string.rep('--',20) ) + + core.clearCommandBuffer() end main(args) \ No newline at end of file diff --git a/client/scripts/tnp3sim.lua b/client/scripts/tnp3sim.lua index af3d2d4c..4e10eb75 100644 --- a/client/scripts/tnp3sim.lua +++ b/client/scripts/tnp3sim.lua @@ -23,10 +23,22 @@ Arguments: -h : this help -m : Maxed out items (experimental) -i : filename for the datadump to read (bin) -]] + + ]] local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds -local DEBUG = true -- the debug flag +local DEBUG = false -- the debug flag +local RANDOM = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20' + +local band = bit32.band +local bor = bit32.bor +local lshift = bit32.lshift +local rshift = bit32.rshift +local byte = string.byte +local char = string.char +local sub = string.sub +local format = string.format + local band = bit32.band @@ -197,8 +209,6 @@ local function ValidateCheckSums(blocks) io.write( ('TYPE 3 area 2: %04x = %04x -- %s\n'):format(crc,calc,isOk)) end -local function LoadEmulator(blocks) - local HASHCONSTANT = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20' local cmd local blockdata for _,b in pairs(blocks) do @@ -207,10 +217,10 @@ local function LoadEmulator(blocks) if _%4 ~= 3 then if (_ >= 8 and _<=21) or (_ >= 36 and _<=49) then - local base = ('%s%s%02x%s'):format(blocks[0], blocks[1], _ , HASHCONSTANT) + local base = ('%s%s%02x%s'):format(blocks[0], blocks[1], _ , RANDOM) local baseStr = utils.ConvertHexToAscii(base) local key = md5.sumhexa(baseStr) - local enc = core.aes(key, blockdata) + local enc = core.aes128_encrypt(key, blockdata) local hex = utils.ConvertAsciiToBytes(enc) hex = utils.ConvertBytesToHex(hex) @@ -346,21 +356,6 @@ local function main(args) local cmdSetDbgOff = "hf mf dbg 0" core.console( cmdSetDbgOff) - -- if not loadFromDump then - -- -- Look for tag present on reader, - -- result, err = lib14a.read1443a(false) - -- if not result then return oops(err) end - - -- core.clearCommandBuffer() - - -- if 0x01 ~= result.sak then -- NXP MIFARE TNP3xxx - -- return oops('This is not a TNP3xxx tag. aborting.') - -- end - - -- -- Show tag info - -- print((' Found tag : %s'):format(result.name)) - -- end - -- Load dump.bin file print( (' Load data from %s'):format(inputTemplate)) hex, err = utils.ReadDumpFile(inputTemplate) @@ -374,7 +369,7 @@ local function main(args) end if DEBUG then - print('Validating checksums in the loaded datadump') + print(' Validating checksums') ValidateCheckSums(blocks) end @@ -393,7 +388,7 @@ local function main(args) local item = toys.Find( toytype, subtype) if item then local itemStr = ('%s - %s (%s)'):format(item[6],item[5], item[4]) - print(' ITEM TYPE :'..itemStr ) + print(' ITEM TYPE : '..itemStr ) else print( (' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype) ) end @@ -407,12 +402,19 @@ local function main(args) print( string.rep('--',20) ) - -- lets do something. - -- + -- Experience should be: local experience = blocks[8]:sub(1,6) - print(('Experience : %d'):format(utils.SwapEndianness(experience,24))) + print(('Experience : %d'):format(utils.SwapEndianness(experience,16))) + local money = blocks[8]:sub(7,10) print(('Money : %d'):format(utils.SwapEndianness(money,16))) + + -- + + -- Sequence number + local seqnum = blocks[8]:sub(18,19) + print(('Sequence number : %d'):format( tonumber(seqnum,16))) + local fairy = blocks[9]:sub(1,8) --FD0F = Left, FF0F = Right local path = 'not choosen' @@ -425,6 +427,12 @@ local function main(args) local hat = blocks[9]:sub(8,11) print(('Hat : %d'):format(utils.SwapEndianness(hat,16))) + + local level = blocks[13]:sub(27,28) + print(('LEVEL : %d'):format( tonumber(level,16))) + --hälsa: 667 029b + --local health = blocks[]:sub(); + --print(('Health : %d'):format( tonumber(health,16)) --0x0D 0x29 0x0A 0x02 16-bit hero points value. Maximum 100. local heropoints = blocks[13]:sub(20,23) @@ -434,6 +442,11 @@ local function main(args) local challenges = blocks[16]:sub(25,32) print(('Finished hero challenges : %d'):format(utils.SwapEndianness(challenges,32))) + -- Character Name + local name1 = blocks[10]:sub(1,32) + local name2 = blocks[12]:sub(1,32) + print('Custom name : '..utils.ConvertHexToAscii(name1..name2)) + if maxed then print('Lets try to max out some values') -- max out money, experience From 9ccfb3a8bcadeba557c285783f8ebbe2cde5fd3b Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 13 May 2015 21:36:20 -0400 Subject: [PATCH 046/132] @iceman1001 's updated lualibs --- client/lualibs/commands.lua | 20 +- client/lualibs/default_toys.lua | 60 ++++- client/lualibs/html_dumplib.lua | 4 +- client/lualibs/md5.lua | 384 +++++++++++++++++++++++++++++ client/lualibs/mf_default_keys.lua | 26 +- client/lualibs/precalc.lua | 94 +++++++ client/lualibs/read14a.lua | 4 +- client/lualibs/utils.lua | 65 ++++- 8 files changed, 627 insertions(+), 30 deletions(-) create mode 100644 client/lualibs/md5.lua create mode 100644 client/lualibs/precalc.lua diff --git a/client/lualibs/commands.lua b/client/lualibs/commands.lua index 0a0d98cc..b0257ef0 100644 --- a/client/lualibs/commands.lua +++ b/client/lualibs/commands.lua @@ -135,10 +135,11 @@ local _commands = { CMD_MIFARE_SNIFFER = 0x0630, --//ultralightC - CMD_MIFAREUC_AUTH1 = 0x0724, - CMD_MIFAREUC_AUTH2 = 0x0725, - CMD_MIFAREUC_READCARD = 0x0726, - CMD_MIFAREUC_SETPWD = 0x0727, + CMD_MIFAREUC_AUTH1 = 0x0724, + CMD_MIFAREUC_AUTH2 = 0x0725, + CMD_MIFAREUC_READCARD = 0x0726, + CMD_MIFAREUC_SETPWD = 0x0727, + CMD_MIFAREU_SETUID = 0x0728, --// mifare desfire CMD_MIFARE_DESFIRE_READBL = 0x0728, @@ -154,10 +155,10 @@ local _commands = { local _reverse_lookup,k,v = {} -for k, v in pairs(_commands) do - _reverse_lookup[v] = k -end -_commands.tostring = function(command) + for k, v in pairs(_commands) do + _reverse_lookup[v] = k + end + _commands.tostring = function(command) if(type(command) == 'number') then return ("%s (%d)"):format(_reverse_lookup[command]or "ERROR UNDEFINED!", command) end @@ -218,7 +219,6 @@ function Command:getBytes() local data = self.data local cmd = self.cmd local arg1, arg2, arg3 = self.arg1, self.arg2, self.arg3 - - return bin.pack("LLLLH",cmd, arg1, arg2, arg3,data); + return bin.pack("LLLLH",cmd, arg1, arg2, arg3, data); end return _commands diff --git a/client/lualibs/default_toys.lua b/client/lualibs/default_toys.lua index f34d510d..cb603ec0 100644 --- a/client/lualibs/default_toys.lua +++ b/client/lualibs/default_toys.lua @@ -24,6 +24,7 @@ local _names = { {"13", "0d00", "0030", "water", "regular", "Wham Shell"}, {"14", "0e00", "0030", "water", "regular", "Gill Grunt"}, --{"14", "0e00", "0030", "water", "regular", "Elite Gill Grunt"}, +--{"14", "0e00", "0030", "water", "regular", "Tidal Wave Gill Grunt"}, {"15", "0f00", "0030", "water", "regular", "Slam Bam"}, --{"15", "0f00", "0030", "water", "regular", "Surfer Slam Bam"}, {"16", "1000", "0030", "magic", "regular", "Spyro"}, @@ -43,7 +44,8 @@ local _names = { {"25", "1900", "0030", "life", "regular", "Zook"}, {"26", "1a00", "0030", "life", "regular", "Stealth Elf"}, --{"26", "1a00", "0030", "life", "regular", "Elite Stealth Elf"}, ---{"26", "1a00", "0030", "life", "regular", "Dark Stealth Elf"}, +--{"26", "1a00", "0528", "life", "regular", "Dark Stealth Elf"}, +{"26", "1a00", "0528", "life", "swapforce", "Ninja Stealth Elf"}, {"27", "1b00", "0030", "life", "regular", "Stump Smash"}, {"27", "1b00", "0118", "life", "regular", "Stump Smash"}, --{"27", "1b00", "0030", "life", "regular", "Autumn Stump Smash"}, @@ -59,6 +61,7 @@ local _names = { --{"32", "2000", "0030", "undead", "regular", "Skeletal Cynder"}, {"100", "6400", "0030", "air", "giant", "Jet Vac"}, +--{"100", "6400", "0030", "air", "giant", "Full blast Jet Vac"}, {"101", "6500", "0030", "air", "giant", "Swarm"}, {"102", "6600", "0030", "earth", "giant", "Crusher"}, {"103", "6700", "0030", "earth", "giant", "Flashwing"}, @@ -73,12 +76,14 @@ local _names = { --{"108", "6c00", "0030", "magic", "giant", "Hoppity Pop Fizz"}, {"108", "6c00", "023c", "magic", "giant", "Love Potion Pop Fizz"}, --{"108", "6c00", "0030", "magic", "giant", "Punch Pop Fizz"}, +--{"108", "6c00", "0030", "magic", "giant", "Fizzy Frenzy Pop Fizz"}, {"109", "6d00", "0030", "magic", "giant", "Nin Jini"}, {"110", "6e00", "0030", "tech", "giant", "Bouncer"}, {"111", "6f00", "0030", "tech", "giant", "Sprocket"}, {"112", "7000", "0030", "life", "giant", "Tree Rex"}, --{"112", "7000", "0030", "life", "giant", "Gnarly Tree Rex"}, -{"113", "7100", "0030", "life", "giant", "Shroomboom"}, --lightcore +{"113", "7100", "0030", "life", "giant", "Shroomboom"}, +--{"113", "7100", "0030", "life", "giant", "Sure shot Shroomboom"}, {"114", "7200", "0030", "undead", "giant", "Eye Broawl"}, {"115", "7300", "0030", "undead", "giant", "Fright Rider"}, @@ -268,27 +273,35 @@ local _names = { {"485", "e501", "0030", "dark", "regular", "Blackout"}, --{"485", "e501", "0234", "dark", "regular", "Special Blackout"}, +-- MINI's {"502", "f601", "0030", "earth", "mini", "Bop"}, -{"503", "f701", "0030", "magic", "mini", "Spry"}, -{"504", "f801", "0030", "undead", "mini", "Hijinx"}, {"505", "f901", "0030", "earth", "mini", "Terrabite"}, + {"506", "fa01", "0030", "air", "mini", "Breeze"}, -{"507", "fb01", "0030", "fire", "mini", "Weeruptor"}, ---{"507", "fb01", "0030", "fire", "mini", "Eggsellent Weeruptor"}, {"508", "fc01", "0030", "air", "mini", "Pet Vac"}, --{"508", "fc01", "0030", "air", "mini", "Power Punch Pet Vac"}, + +{"507", "fb01", "0030", "fire", "mini", "Weeruptor"}, +--{"507", "fb01", "0030", "fire", "mini", "Eggsellent Weeruptor"}, {"509", "fd01", "0030", "fire", "mini", "Small Fry"}, + {"510", "fe01", "0030", "tech", "mini", "Drobit"}, -{"514", "0202", "0030", "water", "mini", "Gill Runt"}, {"519", "0702", "0030", "tech", "mini", "Trigger Snappy"}, + {"526", "0e02", "0030", "life", "mini", "Whisper Elf"}, {"540", "1c02", "0030", "life", "mini", "Barkley"}, --{"540", "1c02", "0030", "life", "mini", "Gnarly Barkley"}, + {"541", "1d02", "0030", "water", "mini", "Thumpling"}, +{"514", "0202", "0030", "water", "mini", "Gill Runt"}, + {"542", "1e02", "0030", "magic", "mini", "mini Jini"}, +{"503", "f701", "0030", "magic", "mini", "Spry"}, + +{"504", "f801", "0030", "undead", "mini", "Hijinx"}, {"543", "1f02", "0030", "undead", "mini", "Eye Small"}, -{"3000", "b80b", "0030", "air", "SWAPFORCE", "Scratch"}, +{"3000", "b80b", "0030", "air", "mini", "Scratch", "SWAPFORCE"}, {"3001", "b90b", "0030", "air", "SWAPFORCE", "Pop Thorn"}, --{"3001", "b90b", "0030", "air", "SWAPFORCE", "Buttered Pop Thorn"}, {"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Slobber Tooth"}, @@ -315,6 +328,29 @@ local _names = { {"3013", "c50b", "0030", "undead", "SWAPFORCE", "Grim Creeper"}, {"3014", "c60b", "0030", "water", "SWAPFORCE", "Rip Tide"}, {"3015", "c70b", "0030", "water", "SWAPFORCE", "Punk Shock"}, + +--{"", "", "0030", "water", "SWAPFORCE", "Hoot Loop"}, +--{"", "", "0030", "water", "SWAPFORCE", "Trap Shadow"}, +--{"", "", "0030", "water", "SWAPFORCE", "Wash Buckler"}, +--{"", "", "0030", "water", "SWAPFORCE", "Freeze Blade"}, +--{"", "", "0030", "fire", "SWAPFORCE", "Magna Charge"}, +--{"", "", "0030", "fire", "SWAPFORCE", "Spy Rise"}, + +--{"", "", "0030", "fire", "SWAPFORCE", "Doom Stone"}, +--{"", "", "0030", "fire", "SWAPFORCE", "Rubble Rouser"}, + +--{"", "", "0030", "fire", "SWAPFORCE", "Blast Zone"} +--{"", "", "0030", "fire", "SWAPFORCE", "Fire Kraken"}, + +--{"", "", "0030", "fire", "SWAPFORCE", "Rattle Shake"}, +--{"", "", "0030", "fire", "SWAPFORCE", "Night Shift"}, + +--{"", "", "0030", "life", "SWAPFORCE", "Stink Bomb"}, +--{"", "", "0030", "life", "SWAPFORCE", "Grilla Drilla"}, + +--{"", "", "0030", "air", "SWAPFORCE", "Free Ranger"}, +--{"", "", "0030", "air", "SWAPFORCE", "Boom Jet"}, + } local function find( main, sub) @@ -327,7 +363,15 @@ local function find( main, sub) end return nil end +local function list() + print ("Type\tSub\tElement\tGame Name") + print (string.rep('=', 54)) + for k, v in pairs(_names) do + print(("%s\t%s\t%s\t%-9s\t%s"):format(v[2],v[3],v[4], v[5], v[6] )) + end +end return { Find = find, + List = list, } diff --git a/client/lualibs/html_dumplib.lua b/client/lualibs/html_dumplib.lua index 3a28d5ae..566128f7 100644 --- a/client/lualibs/html_dumplib.lua +++ b/client/lualibs/html_dumplib.lua @@ -192,7 +192,7 @@ end return { convert_bin_to_html = convert_bin_to_html, convert_eml_to_html = convert_eml_to_html, - convert_eml_to_bin = convert_eml_to_bin, - SaveAsBinary = save_BIN, + convert_eml_to_bin = convert_eml_to_bin, + SaveAsBinary = save_BIN, SaveAsText = save_TEXT, } diff --git a/client/lualibs/md5.lua b/client/lualibs/md5.lua new file mode 100644 index 00000000..2390f957 --- /dev/null +++ b/client/lualibs/md5.lua @@ -0,0 +1,384 @@ +local md5 = { + _VERSION = "md5.lua 0.5.0", + _DESCRIPTION = "MD5 computation in Lua (5.1)", + _URL = "https://github.com/kikito/md5.lua", + _LICENSE = [[ + MIT LICENSE + + Copyright (c) 2013 Enrique García Cota + Adam Baldwin + hanzao + Equi 4 Software + + Permission is hereby granted, free of charge, to any person obtaining a + copy of this software and associated documentation files (the + "Software"), to deal in the Software without restriction, including + without limitation the rights to use, copy, modify, merge, publish, + distribute, sublicense, and/or sell copies of the Software, and to + permit persons to whom the Software is furnished to do so, subject to + the following conditions: + + The above copyright notice and this permission notice shall be included + in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + ]] +} + +-- bit lib implementions + +local floor, abs, max = math.floor, math.abs, math.max +local char, byte, format, rep, sub = + string.char, string.byte, string.format, string.rep, string.sub + +local function check_int(n) + -- checking not float + if(n - floor(n) > 0) then + error("trying to use bitwise operation on non-integer!") + end +end + +local function tbl2number(tbl) + local n = #tbl + + local rslt = 0 + local power = 1 + for i = 1, n do + rslt = rslt + tbl[i]*power + power = power*2 + end + + return rslt +end + +local function expand(tbl_m, tbl_n) + local big = {} + local small = {} + if(#tbl_m > #tbl_n) then + big = tbl_m + small = tbl_n + else + big = tbl_n + small = tbl_m + end + -- expand small + for i = #small + 1, #big do + small[i] = 0 + end + +end + +local to_bits -- needs to be declared before bit_not + +local function bit_not(n) + local tbl = to_bits(n) + local size = max(#tbl, 32) + for i = 1, size do + if(tbl[i] == 1) then + tbl[i] = 0 + else + tbl[i] = 1 + end + end + return tbl2number(tbl) +end + +-- defined as local above +to_bits = function (n) + check_int(n) + if(n < 0) then + -- negative + return to_bits(bit_not(abs(n)) + 1) + end + -- to bits table + local tbl = {} + local cnt = 1 + while (n > 0) do + local last = math.fmod(n,2) + if(last == 1) then + tbl[cnt] = 1 + else + tbl[cnt] = 0 + end + n = (n-last)/2 + cnt = cnt + 1 + end + + return tbl +end + +local function bit_or(m, n) + local tbl_m = to_bits(m) + local tbl_n = to_bits(n) + expand(tbl_m, tbl_n) + + local tbl = {} + local rslt = max(#tbl_m, #tbl_n) + for i = 1, rslt do + if(tbl_m[i]== 0 and tbl_n[i] == 0) then + tbl[i] = 0 + else + tbl[i] = 1 + end + end + + return tbl2number(tbl) +end + +local function bit_and(m, n) + local tbl_m = to_bits(m) + local tbl_n = to_bits(n) + expand(tbl_m, tbl_n) + + local tbl = {} + local rslt = max(#tbl_m, #tbl_n) + for i = 1, rslt do + if(tbl_m[i]== 0 or tbl_n[i] == 0) then + tbl[i] = 0 + else + tbl[i] = 1 + end + end + + return tbl2number(tbl) +end + +local function bit_xor(m, n) + local tbl_m = to_bits(m) + local tbl_n = to_bits(n) + expand(tbl_m, tbl_n) + + local tbl = {} + local rslt = max(#tbl_m, #tbl_n) + for i = 1, rslt do + if(tbl_m[i] ~= tbl_n[i]) then + tbl[i] = 1 + else + tbl[i] = 0 + end + end + + return tbl2number(tbl) +end + +local function bit_rshift(n, bits) + check_int(n) + + local high_bit = 0 + if(n < 0) then + -- negative + n = bit_not(abs(n)) + 1 + high_bit = 2147483648 -- 0x80000000 + end + + for i=1, bits do + n = n/2 + n = bit_or(floor(n), high_bit) + end + return floor(n) +end + +local function bit_lshift(n, bits) + check_int(n) + + if(n < 0) then + -- negative + n = bit_not(abs(n)) + 1 + end + + for i=1, bits do + n = n*2 + end + return bit_and(n, 4294967295) -- 0xFFFFFFFF +end + +-- convert little-endian 32-bit int to a 4-char string +local function lei2str(i) + local f=function (s) return char( bit_and( bit_rshift(i, s), 255)) end + return f(0)..f(8)..f(16)..f(24) +end + +-- convert raw string to big-endian int +local function str2bei(s) + local v=0 + for i=1, #s do + v = v * 256 + byte(s, i) + end + return v +end + +-- convert raw string to little-endian int +local function str2lei(s) + local v=0 + for i = #s,1,-1 do + v = v*256 + byte(s, i) + end + return v +end + +-- cut up a string in little-endian ints of given size +local function cut_le_str(s,...) + local o, r = 1, {} + local args = {...} + for i=1, #args do + table.insert(r, str2lei(sub(s, o, o + args[i] - 1))) + o = o + args[i] + end + return r +end + +local swap = function (w) return str2bei(lei2str(w)) end + +local function hex2binaryaux(hexval) + return char(tonumber(hexval, 16)) +end + +local function hex2binary(hex) + local result, _ = hex:gsub('..', hex2binaryaux) + return result +end + +-- An MD5 mplementation in Lua, requires bitlib (hacked to use LuaBit from above, ugh) +-- 10/02/2001 jcw@equi4.com + +local FF = 0xffffffff +local CONSTS = { + 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, + 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, + 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be, + 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, + 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, + 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8, + 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, + 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, + 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c, + 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, + 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, + 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665, + 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, + 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, + 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1, + 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391, + 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 +} + +local f=function (x,y,z) return bit_or(bit_and(x,y),bit_and(-x-1,z)) end +local g=function (x,y,z) return bit_or(bit_and(x,z),bit_and(y,-z-1)) end +local h=function (x,y,z) return bit_xor(x,bit_xor(y,z)) end +local i=function (x,y,z) return bit_xor(y,bit_or(x,-z-1)) end +local z=function (f,a,b,c,d,x,s,ac) + a=bit_and(a+f(b,c,d)+x+ac,FF) + -- be *very* careful that left shift does not cause rounding! + return bit_or(bit_lshift(bit_and(a,bit_rshift(FF,s)),s),bit_rshift(a,32-s))+b +end + +local function transform(A,B,C,D,X) + local a,b,c,d=A,B,C,D + local t=CONSTS + + a=z(f,a,b,c,d,X[ 0], 7,t[ 1]) + d=z(f,d,a,b,c,X[ 1],12,t[ 2]) + c=z(f,c,d,a,b,X[ 2],17,t[ 3]) + b=z(f,b,c,d,a,X[ 3],22,t[ 4]) + a=z(f,a,b,c,d,X[ 4], 7,t[ 5]) + d=z(f,d,a,b,c,X[ 5],12,t[ 6]) + c=z(f,c,d,a,b,X[ 6],17,t[ 7]) + b=z(f,b,c,d,a,X[ 7],22,t[ 8]) + a=z(f,a,b,c,d,X[ 8], 7,t[ 9]) + d=z(f,d,a,b,c,X[ 9],12,t[10]) + c=z(f,c,d,a,b,X[10],17,t[11]) + b=z(f,b,c,d,a,X[11],22,t[12]) + a=z(f,a,b,c,d,X[12], 7,t[13]) + d=z(f,d,a,b,c,X[13],12,t[14]) + c=z(f,c,d,a,b,X[14],17,t[15]) + b=z(f,b,c,d,a,X[15],22,t[16]) + + a=z(g,a,b,c,d,X[ 1], 5,t[17]) + d=z(g,d,a,b,c,X[ 6], 9,t[18]) + c=z(g,c,d,a,b,X[11],14,t[19]) + b=z(g,b,c,d,a,X[ 0],20,t[20]) + a=z(g,a,b,c,d,X[ 5], 5,t[21]) + d=z(g,d,a,b,c,X[10], 9,t[22]) + c=z(g,c,d,a,b,X[15],14,t[23]) + b=z(g,b,c,d,a,X[ 4],20,t[24]) + a=z(g,a,b,c,d,X[ 9], 5,t[25]) + d=z(g,d,a,b,c,X[14], 9,t[26]) + c=z(g,c,d,a,b,X[ 3],14,t[27]) + b=z(g,b,c,d,a,X[ 8],20,t[28]) + a=z(g,a,b,c,d,X[13], 5,t[29]) + d=z(g,d,a,b,c,X[ 2], 9,t[30]) + c=z(g,c,d,a,b,X[ 7],14,t[31]) + b=z(g,b,c,d,a,X[12],20,t[32]) + + a=z(h,a,b,c,d,X[ 5], 4,t[33]) + d=z(h,d,a,b,c,X[ 8],11,t[34]) + c=z(h,c,d,a,b,X[11],16,t[35]) + b=z(h,b,c,d,a,X[14],23,t[36]) + a=z(h,a,b,c,d,X[ 1], 4,t[37]) + d=z(h,d,a,b,c,X[ 4],11,t[38]) + c=z(h,c,d,a,b,X[ 7],16,t[39]) + b=z(h,b,c,d,a,X[10],23,t[40]) + a=z(h,a,b,c,d,X[13], 4,t[41]) + d=z(h,d,a,b,c,X[ 0],11,t[42]) + c=z(h,c,d,a,b,X[ 3],16,t[43]) + b=z(h,b,c,d,a,X[ 6],23,t[44]) + a=z(h,a,b,c,d,X[ 9], 4,t[45]) + d=z(h,d,a,b,c,X[12],11,t[46]) + c=z(h,c,d,a,b,X[15],16,t[47]) + b=z(h,b,c,d,a,X[ 2],23,t[48]) + + a=z(i,a,b,c,d,X[ 0], 6,t[49]) + d=z(i,d,a,b,c,X[ 7],10,t[50]) + c=z(i,c,d,a,b,X[14],15,t[51]) + b=z(i,b,c,d,a,X[ 5],21,t[52]) + a=z(i,a,b,c,d,X[12], 6,t[53]) + d=z(i,d,a,b,c,X[ 3],10,t[54]) + c=z(i,c,d,a,b,X[10],15,t[55]) + b=z(i,b,c,d,a,X[ 1],21,t[56]) + a=z(i,a,b,c,d,X[ 8], 6,t[57]) + d=z(i,d,a,b,c,X[15],10,t[58]) + c=z(i,c,d,a,b,X[ 6],15,t[59]) + b=z(i,b,c,d,a,X[13],21,t[60]) + a=z(i,a,b,c,d,X[ 4], 6,t[61]) + d=z(i,d,a,b,c,X[11],10,t[62]) + c=z(i,c,d,a,b,X[ 2],15,t[63]) + b=z(i,b,c,d,a,X[ 9],21,t[64]) + + return A+a,B+b,C+c,D+d +end + +---------------------------------------------------------------- + +function md5.sumhexa(s) + local msgLen = #s + local padLen = 56 - msgLen % 64 + + if msgLen % 64 > 56 then padLen = padLen + 64 end + + if padLen == 0 then padLen = 64 end + + s = s .. char(128) .. rep(char(0),padLen-1) .. lei2str(8*msgLen) .. lei2str(0) + + assert(#s % 64 == 0) + + local t = CONSTS + local a,b,c,d = t[65],t[66],t[67],t[68] + + for i=1,#s,64 do + local X = cut_le_str(sub(s,i,i+63),4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4) + assert(#X == 16) + X[0] = table.remove(X,1) -- zero based! + a,b,c,d = transform(a,b,c,d,X) + end + + return format("%08x%08x%08x%08x",swap(a),swap(b),swap(c),swap(d)) +end + +function md5.sum(s) + return hex2binary(md5.sumhexa(s)) +end + +return md5 diff --git a/client/lualibs/mf_default_keys.lua b/client/lualibs/mf_default_keys.lua index 757112c6..804d4a84 100644 --- a/client/lualibs/mf_default_keys.lua +++ b/client/lualibs/mf_default_keys.lua @@ -2,6 +2,7 @@ local _keys = { + --[[ These keys are from the pm3 c-codebase. @@ -157,9 +158,30 @@ local _keys = { '9de89e070277', 'eff603e1efe9', '644672bd4afe', - 'b5ff67cba951', - } + + --[[ + hotel system cards, + http://www.proxmark.org/forum/viewtopic.php?id=2430 + --]] + '44ab09010845', + '85fed980ea5a', + + --[[ + VIGIK1 + --]] + '314B49474956', + '564c505f4d41', + + --[[ + BCARD keyB + --]] + 'f4a9ef2afc6d', + + --[[ + --]] + 'a9f953def0a3', +} --- -- The keys above have just been pasted in, for completeness sake. They contain duplicates. diff --git a/client/lualibs/precalc.lua b/client/lualibs/precalc.lua new file mode 100644 index 00000000..ce58998a --- /dev/null +++ b/client/lualibs/precalc.lua @@ -0,0 +1,94 @@ +--[[ + This is an experimental lib. +--]] +local utils = require('utils') + +-- LOOKUP Tables +local perm = {} +perm [1]= { 0x0, 0x1, 0x3, 0x2, 0x7, 0x6, 0x4, 0x5, 0xF, 0xE, 0xC, 0xD, 0x8, 0x9, 0xB, 0xA } +perm [2]= { 0x1, 0x0, 0x2, 0x3, 0x6, 0x7, 0x5, 0x4, 0xE, 0xF, 0xD, 0xC, 0x9, 0x8, 0xA, 0xB } +perm [3]= { 0x2, 0x3, 0x1, 0x0, 0x5, 0x4, 0x6, 0x7, 0xD, 0xC, 0xE, 0xF, 0xA, 0xB, 0x9, 0x8 } +perm [4]= { 0x3, 0x2, 0x0, 0x1, 0x4, 0x5, 0x7, 0x6, 0xC, 0xD, 0xF, 0xE, 0xB, 0xA, 0x8, 0x9 } +perm [5]= { 0x4, 0x5, 0x7, 0x6, 0x3, 0x2, 0x0, 0x1, 0xB, 0xA, 0x8, 0x9,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 0x7, 0x6, 0x3, 0x2, 0x0, 0x1, 0xB, 0xA, 0x8, 0x9, 0xC, 0xD, 0xF, 0xE } +shifts[2]= { 0x4, 0xB, 0xB, 0x4, 0xB, 0x4, 0x4, 0xB, 0xA, 0x5, 0x5, 0xA, 0x5, 0xA, 0xA, 0x5 } +shifts[3]= { 0xB, 0x6, 0x0, 0xD, 0xD, 0x0, 0x6, 0xB, 0x6, 0xB, 0xD, 0x0, 0x0, 0xD, 0xB, 0x6 } +shifts[4]= { 0xE, 0x5, 0x9, 0x2, 0x0, 0xB, 0x7, 0xC, 0x3, 0x8, 0x4, 0xF, 0xD, 0x6, 0xA, 0x1 } +shifts[5]= { 0x4, 0xE, 0x1, 0xB, 0xF, 0x5, 0xA, 0x0, 0x3, 0x9, 0x6, 0xC, 0x8, 0x2, 0xD, 0x7 } +shifts[6]= { 0xA, 0x4, 0x7, 0x9, 0x0, 0xE, 0xD, 0x3, 0xE, 0x0, 0x3, 0xD, 0x4, 0xA, 0x9, 0x7 } +shifts[7]= { 0xE, 0x6, 0xE, 0x6, 0xF, 0x7, 0xF, 0x7, 0xD, 0x5, 0xD, 0x5, 0xC, 0x4, 0xC, 0x4 } +shifts[8]= { 0x7, 0x1, 0xB, 0xD, 0xE, 0x8, 0x2, 0x4, 0x4, 0x2, 0x8, 0xE, 0xD, 0xB, 0x1, 0x7 } +shifts[9]= { 0xD, 0xB, 0x0, 0x6, 0x6, 0x0, 0xB, 0xD, 0xA, 0xC, 0x7, 0x1, 0x1, 0x7, 0xC, 0xA } +shifts[10]= { 0xe, 0x1, 0x1, 0xe, 0x1, 0xe, 0xe, 0x1, 0x1, 0xe, 0xe, 0x1, 0xe, 0x1, 0x1, 0xe } + +local function ApplyPermutationAndShifts( pos, value, nibble) + local shiftbytes = shifts[pos] + local shiftElem = shiftbytes[nibble+1] --one indexed + local shiftOne = shiftbytes[1] + local rs = bit32.bxor(value, bit32.bxor(shiftOne, shiftElem)) + return rs +end + +local function GetOne( uid, block ) + + if uid == nil then return nil, 'empty uid string' end + if #uid == 0 then return nil, 'empty uid string' end + if #uid ~= 8 then return nil, 'uid wrong length. Should be 4 hex bytes' end + if type(block) ~= 'number' then return nil, 'block is not number' end + if block > 16 or block < 0 then return nil, 'block is out-of-range' end + + local s = ('%s%02X'):format(uid,block) + local nibble1 = tonumber(s:sub(1,1),16) + 1 + + local permuted = '' + for i = 1, #s do + local el_row = shifts[i] + local el_value = el_row[nibble1] + j = 1 + while j <= i do + if i-j > 0 then + local nibble = tonumber(s:sub(j+1,j+1),16) + el_value = ApplyPermutationAndShifts(i-j, el_value, nibble) + end + j = j+1 + end + permuted =('%s%X'):format(permuted,el_value) + end + + permuted = 'C2'..permuted + local crc64numStr = utils.Crc64(permuted) + local keybytes = utils.ConvertAsciiToBytes(crc64numStr, true) + local key = utils.ConvertBytesToHex(keybytes) + return key:sub(1,12) +end + +local PreCalc = +{ + GetAll = function(id) + if id == nil then return nil, 'empty string' end + if #id == 0 then return nil, 'empty string' end + if #id ~= 8 then return nil, 'wrong length. Should be 4 hex bytes' end + + local list = '4b0b20107ccb' + for i = 1,15 do + local key, err = GetOne(id,i) + if not key then return oops(err) end + list = list..key + end + return list + end, +} +return PreCalc \ No newline at end of file diff --git a/client/lualibs/read14a.lua b/client/lualibs/read14a.lua index 10e7c2d4..943a1722 100644 --- a/client/lualibs/read14a.lua +++ b/client/lualibs/read14a.lua @@ -20,7 +20,9 @@ local ISO14A_COMMAND = { ISO14A_RAW = 8, ISO14A_REQUEST_TRIGGER = 0x10, ISO14A_APPEND_CRC = 0x20, - ISO14A_SET_TIMEOUT = 0x40 + ISO14A_SET_TIMEOUT = 0x40, + ISO14A_NO_SELECT = 0x80, + ISO14A_TOPAZMODE = 0x100 } local ISO14443a_TYPES = {} diff --git a/client/lualibs/utils.lua b/client/lualibs/utils.lua index c5baa406..a968fde2 100644 --- a/client/lualibs/utils.lua +++ b/client/lualibs/utils.lua @@ -71,8 +71,8 @@ local Utils = return outResults end, - ------------ CRC-16 ccitt checksums + ------------ CRC-16 ccitt checksums -- Takes a hex string and calculates a crc16 Crc16 = function(s) if s == nil then return nil end @@ -85,7 +85,22 @@ local Utils = end return nil end, - + + ------------ CRC-64 ecma checksums + -- Takes a hex string and calculates a crc64 ecma + Crc64 = function(s) + if s == nil then return nil end + if #s == 0 then return nil end + if type(s) == 'string' then + local utils = require('utils') + local asc = utils.ConvertHexToAscii(s) + local hash = core.crc64(asc) + return hash + end + return nil + end, + + -- input parameter is a string -- Swaps the endianess and returns a number, -- IE: 'cd7a' -> '7acd' -> 0x7acd @@ -135,7 +150,7 @@ local Utils = while IN>0 do I=I+1 IN , D = math.floor(IN/B), math.modf(IN,B)+1 - OUT=string.sub(K,D,D)..OUT + OUT = string.sub(K,D,D)..OUT end return OUT end, @@ -147,7 +162,7 @@ local Utils = end local s={} for i = 1, #(bytes) do - s[i] = string.format("%02X",bytes[i]) + s[i] = string.format("%02X",bytes[i]) end return table.concat(s) end, @@ -171,16 +186,28 @@ local Utils = end return t end, - ConvertAsciiToBytes = function(s) - local t={} + ConvertAsciiToBytes = function(s, reverse) + local t = {} if s == nil then return t end if #s == 0 then return t end for k in s:gmatch"(.)" do table.insert(t, string.byte(k)) end - return t + + if not reverse then + return t + end + + local rev = {} + if reverse then + for i = #t, 1,-1 do + table.insert(rev, t[i] ) + end + end + return rev end, + ConvertHexToAscii = function(s) local t={} if s == nil then return t end @@ -191,6 +218,30 @@ local Utils = return table.concat(t) end, + Chars2num = function(s) + return (s:byte(1)*16777216)+(s:byte(2)*65536)+(s:byte(3)*256)+(s:byte(4)) + end, + + -- use length of string to determine 8,16,32,64 bits + bytes_to_int = function(str,endian,signed) + local t={str:byte(1,-1)} + if endian=="big" then --reverse bytes + local tt={} + for k=1,#t do + tt[#t-k+1]=t[k] + end + t=tt + end + local n=0 + for k=1,#t do + n=n+t[k]*2^((k-1)*8) + end + if signed then + n = (n > 2^(#t*8-1) -1) and (n - 2^(#t*8)) or n -- if last bit set, negative. + end + return n + end, + -- function convertStringToBytes(str) -- local bytes = {} -- local strLength = string.len(str) From 93737008ee29d7748ccc9fcffa1ff4c5c706ea7f Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 14 May 2015 22:55:18 -0400 Subject: [PATCH 047/132] @iceman1001 s default keys --- client/default_keys.dic | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/client/default_keys.dic b/client/default_keys.dic index 5c277300..520317bf 100644 --- a/client/default_keys.dic +++ b/client/default_keys.dic @@ -11,7 +11,7 @@ d3f7d3f7d3f7, 587ee5f9350f, a0478cc39091, 533cb6c723f6, -8fd0a4f256e9 +8fd0a4f256e9, # more Keys from mf_default_keys.lua 000000000001, 000000000002, @@ -42,6 +42,7 @@ a0478cc39091, 47524f555041,--RKFJOJOGROUPKeyA 47524f555042,--RKFJOJOGROUPKeyB 4AF9D7ADEBE4,--DirectoryandeventlogKeyA +4b0b20107ccb,--TNP3xxx 505249564141,--RKFJOJOPRIVAKeyA 505249564142,--RKFJOJOPRIVAKeyB 505249565441, @@ -49,14 +50,19 @@ a0478cc39091, 54726176656c,--VästtrafikenKeyA 555555555555, 55f5a5dd38c9, +569369c5a0e5,--kiev 5c598c9c58b5,--RKFSLKeyB +632193be1c3c,--kiev +644672bd4afe,--kiev 666666666666, 722bfcc5375f,--RKFRejskortDanmarkKeyA 776974687573,--VästtrafikenKeyB 777777777777, 888888888888, +8fe644038790,--kiev 999999999999, 99c636334433, +9de89e070277,--kiev a00000000000, a053a292a4af, a64598a77478,--RKFSLKeyA @@ -65,6 +71,7 @@ aaaaaaaaaaaa, abcdef123456,--Keyfromladyada.net b00000000000, b127c6f41436, +b5ff67cba951,--kiev bbbbbbbbbbbb, bd493a3962b6, c934fe34d934, @@ -73,7 +80,15 @@ dddddddddddd, e4d2770a89be,--RKFSLKeyB ee0042f88840,--VästtrafikenKeyB eeeeeeeeeeee, +eff603e1efe9,--kiev +f14ee7cae863,--kiev f1a97341a9fc, f1d83f964314,--RKFRejskortDanmarkKeyB fc00018778f7,--VästtrafikenKeyA fc0001877bf7,--RKFÖstgötaTrafikenKeyA +44ab09010845,-- hotel system +85fed980ea5a,-- hotel system +314B49474956,--VIGIK1KeyA +564c505f4d41,--VIGIK1KeyB +f4a9ef2afc6d,--BCARD KeyB +a9f953def0a3,-- \ No newline at end of file From 5b99376a8f30ab4946b10176ea5fe7e6596d5281 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 15 May 2015 00:57:51 -0400 Subject: [PATCH 048/132] hf mfu dump testing --- client/cmdhfmfu.c | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index d8060894..37f7f0c0 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -17,7 +17,7 @@ #define MAX_UL_BLOCKS 0x0f #define MAX_ULC_BLOCKS 0x2f -#define MAX_ULEV1a_BLOCKS 0x0b +#define MAX_ULEV1a_BLOCKS 0x12 #define MAX_ULEV1b_BLOCKS 0x20 #define MAX_NTAG_213 0x2c #define MAX_NTAG_215 0x86 @@ -46,6 +46,14 @@ uint8_t default_pwd_pack[KEYS_PWD_COUNT][4] = { {0x32,0x0C,0x16,0x17}, // PACK 0x80,0x80 -- AMiiboo (sniffed) }; +#define MAX_UL_TYPES 13 +uint16_t UL_TYPES_ARRAY[MAX_UL_TYPES] = {UNKNOWN, UL, UL_C, UL_EV1_48, UL_EV1_128, + NTAG, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC}; +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_213, MAX_NTAG_213, MAX_NTAG_215, + MAX_NTAG_216, MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS}; + + static int CmdHelp(const char *Cmd); char* getProductTypeStr( uint8_t id){ @@ -919,7 +927,7 @@ int CmdHF14AMfUDump(const char *Cmd){ FILE *fout; char filename[FILE_PATH_SIZE] = {0x00}; char *fnameptr = filename; - char *str = "Dumping Ultralight%s%s Card Data..."; + //char *str = "Dumping Ultralight%s%s Card Data..."; uint8_t *lockbytes_t = NULL; uint8_t lockbytes[2] = {0x00}; uint8_t *lockbytes_t2 = NULL; @@ -985,6 +993,13 @@ int CmdHF14AMfUDump(const char *Cmd){ TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++) + if (tagtype & UL_TYPES_ARRAY[idx]) + Pages = UL_MEMORY_ARRAY[idx]+1; + + ul_print_type(tagtype, 0); + PrintAndLog("Dumping tag memory..."); + /* if ( tagtype & UL ) { Pages = 16; PrintAndLog(str,"", (tagtype & MAGIC)?" (magic)":"" ); @@ -1004,7 +1019,7 @@ int CmdHF14AMfUDump(const char *Cmd){ Pages = 16; PrintAndLog("Dumping unknown Ultralight, using default values."); } - + */ UsbCommand c = {CMD_MIFAREUC_READCARD, {0,Pages}}; if ( hasPwd ) { c.arg[2] = 1; From ae8303c13ca731ef70a35ae2ff5e79c4b1d6559d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 15 May 2015 01:19:58 -0400 Subject: [PATCH 049/132] mfu dump - beginning of additions --- client/cmdhfmfu.c | 72 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 49 insertions(+), 23 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 37f7f0c0..e1169659 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -946,7 +946,8 @@ int CmdHF14AMfUDump(const char *Cmd){ size_t fileNlen = 0; bool errors = false; bool swapEndian = false; - + bool manualPages = false; + uint8_t startPage = 0; while(param_getchar(Cmd, cmdp) != 0x00) { switch(param_getchar(Cmd, cmdp)) @@ -972,10 +973,29 @@ int CmdHF14AMfUDump(const char *Cmd){ if (fileNlen > FILE_PATH_SIZE-5) fileNlen = FILE_PATH_SIZE-5; cmdp += 2; break; + case 'p': + case 'P': + startPage = param_get8(Cmd, cmdp+1); + manualPages = true; + cmdp += 2; + break; + case 'q': + case 'Q': + Pages = param_get8(Cmd, cmdp+1); + cmdp += 2; + manualPages = true; + break; case 's': + case 'S': swapEndian = true; cmdp++; break; + case 't': + case 'T': + //key type - ul-c or ev1/ntag + //TODO + cmdp += 2; + break; default: PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -993,12 +1013,13 @@ int CmdHF14AMfUDump(const char *Cmd){ TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; - for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++) - if (tagtype & UL_TYPES_ARRAY[idx]) - Pages = UL_MEMORY_ARRAY[idx]+1; - + if (!manualPages) + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++) + if (tagtype & UL_TYPES_ARRAY[idx]) + Pages = UL_MEMORY_ARRAY[idx]+1; + ul_print_type(tagtype, 0); - PrintAndLog("Dumping tag memory..."); + PrintAndLog("Reading tag memory..."); /* if ( tagtype & UL ) { Pages = 16; @@ -1020,24 +1041,29 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLog("Dumping unknown Ultralight, using default values."); } */ - UsbCommand c = {CMD_MIFAREUC_READCARD, {0,Pages}}; - if ( hasPwd ) { - c.arg[2] = 1; - memcpy(c.d.asBytes, key, 16); - } - SendCommand(&c); - UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp,1500)) { - PrintAndLog("Command execute time-out"); - return 1; - } - PrintAndLog ("%u,%u",resp.arg[0],resp.arg[1]); - uint8_t isOK = resp.arg[0] & 0xff; - if (isOK) { - memcpy(data, resp.d.asBytes, resp.arg[1]); + if (!hasPwd || (tagtype & UL_C)){ + UsbCommand c = {CMD_MIFAREUC_READCARD, {startPage,Pages}}; + if ( hasPwd ) { + c.arg[2] = 1; + memcpy(c.d.asBytes, key, 16); + } + SendCommand(&c); + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp,1500)) { + PrintAndLog("Command execute time-out"); + return 1; + } + PrintAndLog ("%u,%u",resp.arg[0],resp.arg[1]); + uint8_t isOK = resp.arg[0] & 0xff; + if (isOK) { + memcpy(data, resp.d.asBytes, resp.arg[1]); + } else { + PrintAndLog("Failed reading block: (%02x)", i); + return 1; + } } else { - PrintAndLog("Failed reading block: (%02x)", i); - return 1; + PrintAndLog("EV1 and NTAG pwd mode not ready yet"); + return 0; } // Load lock bytes. From cceabb79e6f1bc8e9c2cab766f6edb3a4200bb74 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 16 May 2015 01:00:31 -0400 Subject: [PATCH 050/132] mfu info / dump attempt at missing auths NOT TESTED. will test soon. probably has bugs! --- armsrc/apps.h | 2 +- armsrc/mifarecmd.c | 33 ++++++--- armsrc/mifareutil.c | 20 ++++++ armsrc/mifareutil.h | 3 +- client/cmdhfmfu.c | 160 ++++++++++++++++++++++---------------------- client/cmdhfmfu.h | 2 +- 6 files changed, 129 insertions(+), 91 deletions(-) diff --git a/armsrc/apps.h b/armsrc/apps.h index d01c6478..d325dbe8 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -167,7 +167,7 @@ int32_t dist_nt(uint32_t nt1, uint32_t nt2); void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *data); void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareUC_Auth1(uint8_t arg0, uint8_t *datain); -void MifareUC_Auth2(uint32_t arg0, uint8_t *datain); +void MifareUC_Auth2(uint8_t arg0, uint8_t *datain); void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain); void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index c51a30dc..cf36b95a 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -121,7 +121,7 @@ void MifareUC_Auth1(uint8_t arg0, uint8_t *datain){ cmd_send(CMD_ACK,1,cuid,0,dataoutbuf,11); LEDsoff(); } -void MifareUC_Auth2(uint32_t arg0, uint8_t *datain){ +void MifareUC_Auth2(uint8_t arg0, uint8_t *datain){ uint8_t key[16] = {0x00}; byte_t dataoutbuf[16] = {0x00}; @@ -139,8 +139,10 @@ void MifareUC_Auth2(uint32_t arg0, uint8_t *datain){ if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 2 FINISHED"); cmd_send(CMD_ACK,1,0,0,dataoutbuf,11); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - LEDsoff(); + if (arg0) { + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); + } } // Arg0 = BlockNo, @@ -346,7 +348,8 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) // params uint8_t blockNo = arg0; uint16_t blocks = arg1; - bool useKey = (arg2 == 1); + bool useKey = (arg2 == 1); //UL_C + bool usePwd = (arg2 == 2); //UL_EV1/NTAG int countblocks = 0; uint8_t dataout[176] = {0x00}; @@ -373,12 +376,12 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) uint8_t rnd_ab[16] = {0x00}; uint8_t IV[8] = {0x00}; - uint16_t len; + uint16_t len2; uint8_t receivedAnswer[MAX_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); - if (len != 11) { + len2 = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); + if (len2 != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); OnError(1); return; @@ -396,8 +399,8 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) // encrypt out, in, length, key, iv tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); - if (len != 11) { + len2 = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); + if (len2 != 11) { OnError(1); return; } @@ -412,6 +415,18 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) Dbprintf("failed authentication"); } + if (usePwd) { //ev1 or ntag auth + uint8_t Pwd[4] = {0x00}; + memcpy(Pwd, datain, 4); + uint8_t pack[4] = {0,0,0,0}; + + if (mifare_ul_ev1_auth(Pwd, pack)){ + OnError(1); + Dbprintf("failed authentication"); + return; + } + } + for (int i = 0; i < blocks; i++){ len = mifare_ultra_readblock(blockNo * 4 + i, dataout + 4 * i); diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index b7408cf1..cc54b740 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -288,6 +288,26 @@ int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blo } // mifare ultralight commands +int mifare_ul_ev1_auth(uint8_t *key, uint8_t *pack){ + + uint16_t len; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; + + len = mifare_sendcmd_short_mfucauth(NULL, 0, 0x1B, key, receivedAnswer, receivedAnswerPar, NULL); + if (len != 4) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", receivedAnswer[0], len); + return 1; + } + + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { + Dbprintf("Auth Resp: %02x%02x%02x%02x", + receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3]); + } + memcpy(pack, receivedAnswer, 4); + return 0; +} + int mifare_ultra_auth1(uint8_t *blockData){ uint16_t len; diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index ee3ae7c6..03a545b4 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -61,7 +61,8 @@ int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cm 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_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); +int mifare_ul_ev1_auth(uint8_t *key, uint8_t *pack); int mifare_ultra_auth1(uint8_t *blockData); int mifare_ultra_auth2(uint8_t *key, uint8_t *blockData); int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData); diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index e1169659..a502a23d 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -586,6 +586,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t datalen = 0; uint8_t authenticationkey[16] = {0x00}; uint8_t pack[4] = {0,0,0,0}; + int len=0; while(param_getchar(Cmd, cmdp) != 0x00) { @@ -640,12 +641,25 @@ int CmdHF14AMfUInfo(const char *Cmd){ } if ( hasAuthKey ) { - if ((tagtype & UL_C)) - try3DesAuthentication(authenticationkey); - else - ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); + if ((tagtype & UL_C)) { + ul_switch_off_field(); + //will select card automatically + if (try3DesAuthentication(authenticationkey, false) != 1) { + ul_switch_off_field(); + PrintAndLog("Error: Authentication Failed UL-C"); + return 0; + } + } else { + len = ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); + if (len < 1) { + if (!len) ul_switch_off_field(); + PrintAndLog("Error: Authentication Failed UL-EV1/NTAG"); + return 0; + } + } } + // read pages 0,1,2,4 (should read 4pages) status = ul_read(0, data, sizeof(data)); if ( status == -1 ){ @@ -681,17 +695,18 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( hasAuthKey ) return 1; PrintAndLog("Trying some default 3des keys"); - ul_switch_off_field(); + ul_switch_off_field(); //will select again in try3DesAuth... for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ){ key = default_3des_keys[i]; - if (try3DesAuthentication(key) == 1){ + if (try3DesAuthentication(key, true) == 1){ PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); return 1; - } + } } + return 1; //return even if key not found (UL_C is done) } } @@ -743,13 +758,14 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( authlim == 0 ){ PrintAndLog("\n--- Known EV1/NTAG passwords."); - int len=0; //if len goes to -1 the connection will be turned off. for (uint8_t i = 0; i < 3; ++i ){ key = default_pwd_pack[i]; if ( len > -1 ){ len = ulev1_requestAuthentication(key, pack, sizeof(pack)); - PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); - break; + if (len == 1) { + PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); + break; + } } } if (len > -1) ul_switch_off_field(); @@ -907,9 +923,12 @@ int usage_hf_mfu_dump(void) PrintAndLog("It autodetects card type.\n"); PrintAndLog("Usage: hf mfu dump s k n "); PrintAndLog(" Options : "); - PrintAndLog(" k : Enter key for authentication"); - PrintAndLog(" n : Enter filename w/o .bin to save the dump as"); - PrintAndLog(" s : Swap entered key's endianness for auth"); + PrintAndLog(" k : key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(" l : swap entered key's endianness for auth"); + PrintAndLog(" n : filename w/o .bin to save the dump as"); + PrintAndLog(" p : starting Page number to manually set a page to start the dump at"); + PrintAndLog(" q : number of Pages to manually set how many pages to dump"); + PrintAndLog(""); PrintAndLog(" sample : hf mfu dump"); PrintAndLog(" : hf mfu dump n myfile"); @@ -948,6 +967,8 @@ int CmdHF14AMfUDump(const char *Cmd){ bool swapEndian = false; bool manualPages = false; uint8_t startPage = 0; + char tempStr[50]; + while(param_getchar(Cmd, cmdp) != 0x00) { switch(param_getchar(Cmd, cmdp)) @@ -957,15 +978,25 @@ int CmdHF14AMfUDump(const char *Cmd){ return usage_hf_mfu_dump(); case 'k': case 'K': - dataLen = param_gethex(Cmd, cmdp+1, data, 32); - if (dataLen) { - errors = true; - } else { - memcpy(key, data, 16); - } + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 32) //ul-c + errors = param_gethex(tempStr, 0, key, dataLen); + else if (dataLen == 8) //ev1/ntag + errors = param_gethex(tempStr, 0, key, dataLen); + else + errors = true; + + if (!errors) + memcpy(key, data, dataLen/2); + cmdp += 2; hasPwd = true; break; + case 'l': + case 'L': + swapEndian = true; + cmdp++; + break; case 'n': case 'N': fileNlen = param_getstr(Cmd, cmdp+1, filename); @@ -985,17 +1016,6 @@ int CmdHF14AMfUDump(const char *Cmd){ cmdp += 2; manualPages = true; break; - case 's': - case 'S': - swapEndian = true; - cmdp++; - break; - case 't': - case 'T': - //key type - ul-c or ev1/ntag - //TODO - cmdp += 2; - break; default: PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); errors = true; @@ -1007,7 +1027,7 @@ int CmdHF14AMfUDump(const char *Cmd){ //Validations if(errors) return usage_hf_mfu_dump(); - if (swapEndian) + if (swapEndian && dataLen == 32) keyPtr = SwapEndian64(data, 16, 8); TagTypeUL_t tagtype = GetHF14AMfU_Type(); @@ -1020,50 +1040,29 @@ int CmdHF14AMfUDump(const char *Cmd){ ul_print_type(tagtype, 0); PrintAndLog("Reading tag memory..."); - /* - if ( tagtype & UL ) { - Pages = 16; - PrintAndLog(str,"", (tagtype & MAGIC)?" (magic)":"" ); + + UsbCommand c = {CMD_MIFAREUC_READCARD, {startPage,Pages}}; + if ( hasPwd ) { + if (tagtype & UL_C) + c.arg[2] = 1; //UL_C auth + else + c.arg[2] = 2; //UL_EV1/NTAG auth + + memcpy(c.d.asBytes, key, dataLen/2); } - else if ( tagtype & UL_C ) { - Pages = 44; - PrintAndLog(str,"-C", (tagtype & MAGIC)?" (magic)":"" ); + SendCommand(&c); + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp,1500)) { + PrintAndLog("Command execute time-out"); + return 1; } - else if ( tagtype & UL_EV1_48 ) { - Pages = 18; - PrintAndLog(str," EV1_48",""); - } - else if ( tagtype & UL_EV1_128 ) { - Pages = 32; - PrintAndLog(str," EV1_128",""); + PrintAndLog ("%u,%u",resp.arg[0],resp.arg[1]); + uint8_t isOK = resp.arg[0] & 0xff; + if (isOK) { + memcpy(data, resp.d.asBytes, resp.arg[1]); } else { - Pages = 16; - PrintAndLog("Dumping unknown Ultralight, using default values."); - } - */ - if (!hasPwd || (tagtype & UL_C)){ - UsbCommand c = {CMD_MIFAREUC_READCARD, {startPage,Pages}}; - if ( hasPwd ) { - c.arg[2] = 1; - memcpy(c.d.asBytes, key, 16); - } - SendCommand(&c); - UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp,1500)) { - PrintAndLog("Command execute time-out"); - return 1; - } - PrintAndLog ("%u,%u",resp.arg[0],resp.arg[1]); - uint8_t isOK = resp.arg[0] & 0xff; - if (isOK) { - memcpy(data, resp.d.asBytes, resp.arg[1]); - } else { - PrintAndLog("Failed reading block: (%02x)", i); - return 1; - } - } else { - PrintAndLog("EV1 and NTAG pwd mode not ready yet"); - return 0; + PrintAndLog("Failed reading block: (%02x)", i); + return 1; } // Load lock bytes. @@ -1077,6 +1076,7 @@ int CmdHF14AMfUDump(const char *Cmd){ } // Load bottom lockbytes if available + // HOW DOES THIS APPLY TO EV1 and/or NTAG??? if ( Pages == 44 ) { lockbytes_t2 = data + (40*4); lockbytes2[0] = lockbytes_t2[2]; @@ -1087,10 +1087,12 @@ int CmdHF14AMfUDump(const char *Cmd){ } // add keys - if (hasPwd){ + if (hasPwd && dataLen == 32){ //UL_C memcpy(data + Pages*4, key, 16); Pages += 4; - } + } + //TODO add key MEM location for other tags + for (i = 0; i < Pages; ++i) { if ( i < 3 ) { PrintAndLog("Block %02x:%s ", i,sprint_hex(data + i * 4, 4)); @@ -1211,7 +1213,7 @@ int CmdHF14AMfucAuth(const char *Cmd){ } uint8_t *key = default_3des_keys[keyNo]; - if (try3DesAuthentication(key)>0) + if (try3DesAuthentication(key, true) > 0) PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 16)); else PrintAndLog("Authentication failed"); @@ -1219,9 +1221,9 @@ int CmdHF14AMfucAuth(const char *Cmd){ return 0; } -int try3DesAuthentication( uint8_t *key){ +int try3DesAuthentication( uint8_t *key, bool switch_off_field ){ - uint32_t cuid = 0; + //uint32_t cuid = 0; des3_context ctx = { 0 }; @@ -1237,7 +1239,7 @@ int try3DesAuthentication( uint8_t *key){ if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return -1; if ( !(resp.arg[0] & 0xff) ) return -2; - cuid = resp.arg[1]; + //cuid = resp.arg[1]; memcpy(enc_random_b,resp.d.asBytes+1,8); des3_set2key_dec(&ctx, key); @@ -1254,7 +1256,7 @@ int try3DesAuthentication( uint8_t *key){ //Auth2 c.cmd = CMD_MIFAREUC_AUTH2; - c.arg[0] = cuid; + c.arg[0] = switch_off_field; memcpy(c.d.asBytes, rnd_ab, 16); SendCommand(&c); diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 0ec82b2d..806c27d3 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -14,7 +14,7 @@ int CmdHF14AMfUCRdCard(const char *Cmd); int CmdHF14AMfucAuth(const char *Cmd); uint8_t requestAuthentication( uint8_t *nonce); -int try3DesAuthentication( uint8_t *key); +int try3DesAuthentication( uint8_t *key, bool switch_off_field); //general stuff int CmdHF14AMfUDump(const char *Cmd); From 8258f409697ab41a6858ef9bdcdf406989223bbb Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 17 May 2015 20:49:25 -0400 Subject: [PATCH 051/132] Iceman1001 s MFU clean up cleaned up MF UL_C auth code device side. --- armsrc/appmain.c | 7 +- armsrc/apps.h | 3 +- armsrc/mifarecmd.c | 230 +++++++++----------------------------------- armsrc/mifareutil.c | 157 +++++++++++++++++++++--------- armsrc/mifareutil.h | 4 +- client/cmdhfmfu.c | 156 +++++++++--------------------- 6 files changed, 211 insertions(+), 346 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 48b8c0dd..7b94f8a3 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -826,11 +826,8 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_MIFAREU_READBL: MifareUReadBlock(c->arg[0],c->arg[1], c->d.asBytes); break; - case CMD_MIFAREUC_AUTH1: - MifareUC_Auth1(c->arg[0],c->d.asBytes); - break; - case CMD_MIFAREUC_AUTH2: - MifareUC_Auth2(c->arg[0],c->d.asBytes); + case CMD_MIFAREUC_AUTH: + MifareUC_Auth(c->arg[0],c->d.asBytes); break; case CMD_MIFAREU_READCARD: case CMD_MIFAREUC_READCARD: diff --git a/armsrc/apps.h b/armsrc/apps.h index d325dbe8..57fb55fd 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -166,8 +166,7 @@ void ReaderMifare(bool first_try); int32_t dist_nt(uint32_t nt1, uint32_t nt2); void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *data); void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); -void MifareUC_Auth1(uint8_t arg0, uint8_t *datain); -void MifareUC_Auth2(uint8_t arg0, uint8_t *datain); +void MifareUC_Auth(uint8_t arg0, uint8_t *datain); void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain); void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index cf36b95a..1f8f4ee8 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -17,7 +17,6 @@ #include "apps.h" #include "util.h" -#include "des.h" #include "crc.h" // the block number for the ISO14443-4 PCB @@ -93,53 +92,28 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } -void MifareUC_Auth1(uint8_t arg0, uint8_t *datain){ +void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes){ - byte_t dataoutbuf[16] = {0x00}; - uint8_t uid[10] = {0x00}; - uint32_t cuid = 0x00; + bool turnOffField = (arg0 == 1); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - if(!iso14443a_select_card(uid, NULL, &cuid)) { + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); OnError(0); return; }; - if(mifare_ultra_auth1(dataoutbuf)){ - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part1: Fail."); + if(mifare_ultra_auth(keybytes) == 1){ + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed"); OnError(1); return; } + cmd_send(CMD_ACK,1,0,0,0,0); - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 1 FINISHED"); - - cmd_send(CMD_ACK,1,cuid,0,dataoutbuf,11); - LEDsoff(); -} -void MifareUC_Auth2(uint8_t arg0, uint8_t *datain){ - - uint8_t key[16] = {0x00}; - byte_t dataoutbuf[16] = {0x00}; - - memcpy(key, datain, 16); - - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - - if(mifare_ultra_auth2(key, dataoutbuf)){ - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part2: Fail..."); - OnError(1); - return; - } - - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 2 FINISHED"); - - cmd_send(CMD_ACK,1,0,0,dataoutbuf,11); - if (arg0) { + if (turnOffField) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } @@ -152,125 +126,56 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; byte_t dataout[16] = {0x00}; - uint8_t uid[10] = {0x00}; - uint8_t key[16] = {0x00}; - bool usePwd = (arg1 == 1); + bool useKey = (arg1 == 1); //UL_C + bool usePwd = (arg1 == 2); //UL_EV1/NTAG LEDsoff(); LED_A_ON(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - int len = iso14443a_select_card(uid, NULL, NULL); + int len = iso14443a_select_card(NULL, NULL, NULL); if(!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%02X)",len); OnError(1); return; } - // authenticate here. - if ( usePwd ) { + // UL-C authentication + if ( useKey ) { + uint8_t key[16] = {0x00}; + memcpy(key, datain, sizeof(key) ); - memcpy(key, datain, 16); - - // Dbprintf("KEY: %02x %02x %02x %02x %02x %02x %02x %02x", key[0],key[1],key[2],key[3],key[4],key[5],key[6],key[7] ); - // Dbprintf("KEY: %02x %02x %02x %02x %02x %02x %02x %02x", key[8],key[9],key[10],key[11],key[12],key[13],key[14],key[15] ); - - uint8_t random_a[8] = {1,1,1,1,1,1,1,1 }; - uint8_t random_b[8] = {0x00}; - uint8_t enc_random_b[8] = {0x00}; - uint8_t rnd_ab[16] = {0x00}; - uint8_t IV[8] = {0x00}; - - uint16_t len; - uint8_t receivedAnswer[MAX_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - - len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); - if (len != 11) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if ( mifare_ultra_auth(key) == 1 ) { OnError(1); return; } - - // tag nonce. - memcpy(enc_random_b,receivedAnswer+1,8); - - // decrypt nonce. - tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV ); - rol(random_b,8); - memcpy(rnd_ab ,random_a,8); - memcpy(rnd_ab+8,random_b,8); - - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { - Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x", - enc_random_b[0],enc_random_b[1],enc_random_b[2],enc_random_b[3], - enc_random_b[4],enc_random_b[5],enc_random_b[6],enc_random_b[7]); - - Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x", - random_b[0],random_b[1],random_b[2],random_b[3], - random_b[4],random_b[5],random_b[6],random_b[7]); - - Dbprintf("rnd_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]); - - Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x", - rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11], - rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15] ); - } - - // encrypt out, in, length, key, iv - tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); - if (len != 11) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); - OnError(1); - return; - } - - uint8_t enc_resp[8] = { 0 }; - uint8_t resp_random_a[8] = { 0 }; - memcpy(enc_resp, receivedAnswer+1, 8); - - // 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 ) - Dbprintf("failed authentication"); - - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { - 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]); - - Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", - rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11], - rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15]); - - Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x", - random_a[0],random_a[1],random_a[2],random_a[3], - random_a[4],random_a[5],random_a[6],random_a[7]); - - Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x", - resp_random_a[0],resp_random_a[1],resp_random_a[2],resp_random_a[3], - resp_random_a[4],resp_random_a[5],resp_random_a[6],resp_random_a[7]); - } } - + + // UL-EV1 / NTAG authentication + if ( usePwd ) { + uint8_t pwd[4] = {0x00}; + memcpy(pwd, datain, 4); + uint8_t pack[4] = {0,0,0,0}; + if (mifare_ul_ev1_auth(pwd, pack) == 1) { + OnError(1); + return; + } + } + if( mifare_ultra_readblock(blockNo, dataout) ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block error"); OnError(2); return; } - + if( mifare_ultra_halt() ) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Halt error"); OnError(3); return; } - - cmd_send(CMD_ACK,1,0,0,dataout,16); + + cmd_send(CMD_ACK,1,0,0,dataout,16); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } @@ -365,64 +270,25 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) return; } - // authenticate + // UL-C authentication if ( useKey ) { uint8_t key[16] = {0x00}; - memcpy(key, datain, 16); + memcpy(key, datain, sizeof(key) ); - uint8_t random_a[8] = {1,1,1,1,1,1,1,1 }; - uint8_t random_b[8] = {0x00}; - uint8_t enc_random_b[8] = {0x00}; - uint8_t rnd_ab[16] = {0x00}; - uint8_t IV[8] = {0x00}; - - uint16_t len2; - uint8_t receivedAnswer[MAX_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - - len2 = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); - if (len2 != 11) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if ( mifare_ultra_auth(key) == 1 ) { OnError(1); return; } - - // tag nonce. - memcpy(enc_random_b,receivedAnswer+1,8); - - // decrypt nonce. - tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV ); - rol(random_b,8); - memcpy(rnd_ab ,random_a,8); - memcpy(rnd_ab+8,random_b,8); - - // encrypt out, in, length, key, iv - tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - - len2 = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, receivedAnswer, receivedAnswerPar, NULL); - if (len2 != 11) { - OnError(1); - return; - } - - uint8_t enc_resp[8] = { 0 }; - uint8_t resp_random_a[8] = { 0 }; - memcpy(enc_resp, receivedAnswer+1, 8); - - // 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 ) - Dbprintf("failed authentication"); } - if (usePwd) { //ev1 or ntag auth - uint8_t Pwd[4] = {0x00}; - memcpy(Pwd, datain, 4); + // UL-EV1 / NTAG authentication + if (usePwd) { + uint8_t pwd[4] = {0x00}; + memcpy(pwd, datain, sizeof(pwd)); uint8_t pack[4] = {0,0,0,0}; - if (mifare_ul_ev1_auth(Pwd, pack)){ + if (mifare_ul_ev1_auth(pwd, pack) == 1){ OnError(1); - Dbprintf("failed authentication"); return; } } @@ -569,16 +435,15 @@ void MifareUWriteBlock_Special(uint8_t arg0, uint8_t *datain) { uint8_t blockNo = arg0; byte_t blockdata[4] = {0x00}; - - memcpy(blockdata, datain,4); - uint8_t uid[10] = {0x00}; + memcpy(blockdata, datain,4); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + LEDsoff(); + LED_A_ON(); clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - if(!iso14443a_select_card(uid, NULL, NULL)) { + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); return; @@ -1320,21 +1185,18 @@ void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain){ int len = iso14443a_select_card(uid, NULL, &cuid); if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Can't select card"); - //OnError(1); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); + OnError(1); return; }; if(mifare_desfire_des_auth1(cuid, dataout)){ - if (MF_DBGLEVEL >= MF_DBG_ERROR) - Dbprintf("Authentication part1: Fail."); - //OnError(4); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication part1: Fail."); + OnError(4); return; } if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 1 FINISHED"); - cmd_send(CMD_ACK,1,cuid,0,dataout, sizeof(dataout)); } diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index cc54b740..0469364c 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -18,6 +18,7 @@ #include "iso14443a.h" #include "crapto1.h" #include "mifareutil.h" +#include "des.h" int MF_DBGLEVEL = MF_DBG_ALL; @@ -110,6 +111,27 @@ int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uin return len; } +int mifare_sendcmd_short_mfuev1auth(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[7]; + int len; + dcmd[0] = cmd; + memcpy(dcmd+1,data,4); + AppendCrc14443a(dcmd, 5); + + ReaderTransmit(dcmd, sizeof(dcmd), timing); + len = ReaderReceive(answer, answer_parity); + if(!len) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); + len = ReaderReceive(answer,answer_parity); + } + if(len==1) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); + return 1; + } + return len; +} + int mifare_sendcmd_shortex(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[4], ecmd[4]; @@ -288,67 +310,114 @@ int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blo } // mifare ultralight commands -int mifare_ul_ev1_auth(uint8_t *key, uint8_t *pack){ +int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){ uint16_t len; - uint8_t receivedAnswer[MAX_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - - len = mifare_sendcmd_short_mfucauth(NULL, 0, 0x1B, key, receivedAnswer, receivedAnswerPar, NULL); + uint8_t resp[4]; + uint8_t respPar[1]; + uint8_t key[4] = {0x00}; + memcpy(key, keybytes, 4); + + Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); + len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); if (len != 4) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", receivedAnswer[0], len); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len); + OnError(1); return 1; } - - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { - Dbprintf("Auth Resp: %02x%02x%02x%02x", - receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3]); - } - memcpy(pack, receivedAnswer, 4); + + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) + Dbprintf("Auth Resp: %02x%02x%02x%02x", resp[0],resp[1],resp[2],resp[3]); + + memcpy(pack, resp, 4); return 0; } -int mifare_ultra_auth1(uint8_t *blockData){ +int mifare_ultra_auth(uint8_t *keybytes){ + + /// 3des2k + + uint8_t random_a[8] = {1,1,1,1,1,1,1,1}; + uint8_t random_b[8] = {0x00}; + uint8_t enc_random_b[8] = {0x00}; + uint8_t rnd_ab[16] = {0x00}; + uint8_t IV[8] = {0x00}; + uint8_t key[16] = {0x00}; + memcpy(key, keybytes, 16); uint16_t len; - uint8_t receivedAnswer[MAX_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - - len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL); + uint8_t resp[19] = {0x00}; + uint8_t respPar[3] = {0,0,0}; + + // REQUEST AUTHENTICATION + len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, resp, respPar ,NULL); if (len != 11) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]); + OnError(1); + return 1; + } + + // tag nonce. + memcpy(enc_random_b,resp+1,8); + + // decrypt nonce. + tdes_2key_dec(random_b, enc_random_b, sizeof(random_b), key, IV ); + rol(random_b,8); + memcpy(rnd_ab ,random_a,8); + memcpy(rnd_ab+8,random_b,8); + + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { + Dbprintf("enc_B: %02x %02x %02x %02x %02x %02x %02x %02x", + enc_random_b[0],enc_random_b[1],enc_random_b[2],enc_random_b[3],enc_random_b[4],enc_random_b[5],enc_random_b[6],enc_random_b[7]); + + Dbprintf(" B: %02x %02x %02x %02x %02x %02x %02x %02x", + random_b[0],random_b[1],random_b[2],random_b[3],random_b[4],random_b[5],random_b[6],random_b[7]); + + Dbprintf("rnd_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]); + + Dbprintf("rnd_ab: %02x %02x %02x %02x %02x %02x %02x %02x", + rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11],rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15] ); + } + + // encrypt out, in, length, key, iv + tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); + + len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL); + if (len != 11) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]); + OnError(1); + return 1; + } + + uint8_t enc_resp[8] = { 0,0,0,0,0,0,0,0 }; + 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 + 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"); return 1; } if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { - Dbprintf("Auth1 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3],receivedAnswer[4], - receivedAnswer[5],receivedAnswer[6],receivedAnswer[7],receivedAnswer[8],receivedAnswer[9], - receivedAnswer[10]); - } - memcpy(blockData, receivedAnswer, 11); - return 0; -} + 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]); -int mifare_ultra_auth2(uint8_t *key, uint8_t *blockData){ + Dbprintf("e_AB: %02x %02x %02x %02x %02x %02x %02x %02x", + rnd_ab[8],rnd_ab[9],rnd_ab[10],rnd_ab[11], + rnd_ab[12],rnd_ab[13],rnd_ab[14],rnd_ab[15]); - uint16_t len; - uint8_t receivedAnswer[MAX_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, key, receivedAnswer, receivedAnswerPar, NULL); - if (len != 11) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); - return 1; + Dbprintf("a: %02x %02x %02x %02x %02x %02x %02x %02x", + random_a[0],random_a[1],random_a[2],random_a[3], + random_a[4],random_a[5],random_a[6],random_a[7]); + + Dbprintf("b: %02x %02x %02x %02x %02x %02x %02x %02x", + resp_random_a[0],resp_random_a[1],resp_random_a[2],resp_random_a[3], + resp_random_a[4],resp_random_a[5],resp_random_a[6],resp_random_a[7]); } - - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { - Dbprintf("Auth2 Resp: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x", - receivedAnswer[0],receivedAnswer[1],receivedAnswer[2],receivedAnswer[3],receivedAnswer[4], - receivedAnswer[5],receivedAnswer[6],receivedAnswer[7],receivedAnswer[8],receivedAnswer[9], - receivedAnswer[10]); - } - memcpy(blockData, receivedAnswer, 11); return 0; } @@ -380,8 +449,6 @@ int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) return 0; } - - int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) { // variables diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index 03a545b4..d4fcd818 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -57,14 +57,14 @@ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); +int mifare_sendcmd_short_mfuev1auth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); 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_ul_ev1_auth(uint8_t *key, uint8_t *pack); -int mifare_ultra_auth1(uint8_t *blockData); -int mifare_ultra_auth2(uint8_t *key, uint8_t *blockData); +int mifare_ultra_auth(uint8_t *key); int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData); int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData); diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index a502a23d..a22ff859 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -34,12 +34,16 @@ uint8_t default_3des_keys[KEYS_3DES_COUNT][16] = { { 0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xAA,0xBB,0xCC,0xDD,0xEE,0xFF } // 11 22 33 }; -#define KEYS_PWD_COUNT 8 +#define KEYS_PWD_COUNT 10 uint8_t default_pwd_pack[KEYS_PWD_COUNT][4] = { {0xFF,0xFF,0xFF,0xFF}, // PACK 0x00,0x00 -- factory default + {0x4A,0xF8,0x4B,0x19}, // PACK 0xE5,0xBE -- italian bus (sniffed) {0x33,0x6B,0xA1,0x19}, // PACK 0x9c,0x2d -- italian bus (sniffed) {0xFF,0x90,0x6C,0xB2}, // PACK 0x12,0x9e -- italian bus (sniffed) + {0x46,0x1c,0xA3,0x19}, // PACK 0xE9,0x5A -- italian bus (sniffed) + {0x35,0x1C,0xD0,0x19}, // PACK 0x9A,0x5a -- italian bus (sniffed) + {0x05,0x22,0xE6,0xB4}, // PACK 0x80,0x80 -- Amiiboo (sniffed) pikachu-b UID: {0x7E,0x22,0xE6,0xB4}, // PACK 0x80,0x80 -- AMiiboo (sniffed) {0x02,0xE1,0xEE,0x36}, // PACK 0x80,0x80 -- AMiiboo (sniffed) sonic UID: 04d257 7ae33e8027 @@ -56,20 +60,20 @@ uint8_t UL_MEMORY_ARRAY[MAX_UL_TYPES] = {MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_ULC_B static int CmdHelp(const char *Cmd); -char* getProductTypeStr( uint8_t id){ +char *getProductTypeStr( uint8_t id){ static char buf[20]; char *retStr = buf; switch(id) { case 3: - sprintf(retStr, "0x%02X %s", id, "(Ultralight)"); + sprintf(retStr, "%02X %s", id, "(Ultralight)"); break; case 4: - sprintf(retStr, "0x%02X %s", id, "(NTAG)"); + sprintf(retStr, "%02X %s", id, "(NTAG)"); break; default: - sprintf(retStr, "0x%02X %s", id, "(unknown)"); + sprintf(retStr, "%02X %s", id, "(unknown)"); break; } return buf; @@ -80,7 +84,7 @@ char* getProductTypeStr( uint8_t id){ 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). */ -char* getUlev1CardSizeStr( uint8_t fsize ){ +char *getUlev1CardSizeStr( uint8_t fsize ){ static char buf[40]; char *retStr = buf; @@ -153,8 +157,6 @@ static int ul_read( uint8_t page, uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {ISO14443A_CMD_READBLOCK, page}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); - if ( len == -1 ) - ul_switch_off_field(); return len; } @@ -169,9 +171,7 @@ static int ul_comp_write( uint8_t page, uint8_t *data, uint8_t datalen ){ memcpy(cmd+2, data, datalen); uint8_t response[1] = {0xff}; - int len = ul_send_cmd_raw(cmd, 2+datalen, response, sizeof(response)); - if ( len == -1 ) - ul_switch_off_field(); + ul_send_cmd_raw(cmd, 2+datalen, response, sizeof(response)); // ACK if ( response[0] == 0x0a ) return 0; // NACK @@ -182,17 +182,25 @@ static int ulc_requestAuthentication( uint8_t *nonce, uint16_t nonceLength ){ uint8_t cmd[] = {MIFARE_ULC_AUTH_1, 0x00}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), nonce, nonceLength); - if ( len == -1 ) - ul_switch_off_field(); return len; } +static int ulc_authentication( uint8_t *key, bool switch_off_field ){ + + UsbCommand c = {CMD_MIFAREUC_AUTH, {switch_off_field}}; + memcpy(c.d.asBytes, key, 16); + SendCommand(&c); + UsbCommand resp; + if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return -1; + if ( resp.arg[0] == 1 ) return 0; + + return -2; +} + static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ uint8_t cmd[] = {MIFARE_ULEV1_AUTH, pwd[0], pwd[1], pwd[2], pwd[3]}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), pack, packLength); - if ( len == -1) - ul_switch_off_field(); return len; } @@ -200,8 +208,6 @@ static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_VERSION}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); - if ( len == -1 ) - ul_switch_off_field(); return len; } @@ -210,7 +216,6 @@ static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ // uint8_t cmd[] = {MIFARE_ULEV1_FASTREAD, startblock, endblock}; // if ( !ul_send_cmd_raw(cmd, sizeof(cmd), response)){ - // ul_switch_off_field(); // return -1; // } // return 0; @@ -220,8 +225,6 @@ static int ulev1_readCounter( uint8_t counter, uint8_t *response, uint16_t respo uint8_t cmd[] = {MIFARE_ULEV1_READ_CNT, counter}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); - if (len == -1) - ul_switch_off_field(); return len; } @@ -229,8 +232,6 @@ static int ulev1_readTearing( uint8_t counter, uint8_t *response, uint16_t respo uint8_t cmd[] = {MIFARE_ULEV1_CHECKTEAR, counter}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); - if (len == -1) - ul_switch_off_field(); return len; } @@ -238,15 +239,12 @@ static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_READSIG, 0x00}; int len = ul_send_cmd_raw(cmd, sizeof(cmd), response, responseLength); - if (len == -1) - ul_switch_off_field(); return len; } static int ul_print_default( uint8_t *data){ uint8_t uid[7]; - uid[0] = data[0]; uid[1] = data[1]; uid[2] = data[2]; @@ -504,7 +502,7 @@ uint16_t GetHF14AMfU_Type(void){ status = ul_select(&card); if ( status < 1 ){ - PrintAndLog("Error: couldn't select"); + PrintAndLog("iso14443a card select failed"); ul_switch_off_field(); return UL_ERROR; } @@ -518,7 +516,7 @@ uint16_t GetHF14AMfU_Type(void){ if ( card.uid[0] != 0x05) { len = ulev1_getVersion(version, sizeof(version)); - if (len > -1) ul_switch_off_field(); //if -1 it is already off + ul_switch_off_field(); switch (len) { case 0x0A: { @@ -551,11 +549,11 @@ uint16_t GetHF14AMfU_Type(void){ ul_switch_off_field(); return UL_ERROR; } - uint8_t nonce1[11] = {0x00}; - status = ulc_requestAuthentication(nonce1, sizeof(nonce1)); + uint8_t nonce[11] = {0x00}; + status = ulc_requestAuthentication(nonce, sizeof(nonce)); tagtype = ( status > 0 ) ? UL_C : UL; - if (status != -1) ul_switch_off_field(); + ul_switch_off_field(); } } else { // Infinition MY-D tests Exam high nibble @@ -642,9 +640,8 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( hasAuthKey ) { if ((tagtype & UL_C)) { - ul_switch_off_field(); //will select card automatically - if (try3DesAuthentication(authenticationkey, false) != 1) { + if (ulc_authentication(authenticationkey, false) != 0) { ul_switch_off_field(); PrintAndLog("Error: Authentication Failed UL-C"); return 0; @@ -652,7 +649,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } else { len = ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); if (len < 1) { - if (!len) ul_switch_off_field(); + ul_switch_off_field(); PrintAndLog("Error: Authentication Failed UL-EV1/NTAG"); return 0; } @@ -663,6 +660,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ // read pages 0,1,2,4 (should read 4pages) status = ul_read(0, data, sizeof(data)); if ( status == -1 ){ + ul_switch_off_field(); PrintAndLog("Error: tag didn't answer to READ"); return status; } @@ -685,6 +683,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t ulc_deskey[16] = {0x00}; status = ul_read(0x2C, ulc_deskey, sizeof(ulc_deskey)); if ( status == -1 ){ + ul_switch_off_field(); PrintAndLog("Error: tag didn't answer to READ magic"); return status; } @@ -695,17 +694,18 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( hasAuthKey ) return 1; PrintAndLog("Trying some default 3des keys"); - ul_switch_off_field(); //will select again in try3DesAuth... for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ){ key = default_3des_keys[i]; - if (try3DesAuthentication(key, true) == 1){ + if (ulc_authentication(key, true) == 0){ PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); + ul_switch_off_field(); return 1; } } + ul_switch_off_field(); return 1; //return even if key not found (UL_C is done) } } @@ -718,6 +718,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); + ul_switch_off_field(); return status; } ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); @@ -727,6 +728,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ EV1"); + ul_switch_off_field(); return status; } // save AUTHENTICATION LIMITS for later: @@ -745,12 +747,16 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ulev1_getVersion(version, sizeof(version)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to GETVERSION"); + ul_switch_off_field(); return status; } ulev1_print_version(version); // if we called info with key, just return - if ( hasAuthKey ) return 1; + if ( hasAuthKey ) { + ul_switch_off_field(); + return 1; + } // AUTHLIMIT, (number of failed authentications) // 0 = limitless. @@ -768,7 +774,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ } } } - if (len > -1) ul_switch_off_field(); } } @@ -985,9 +990,6 @@ int CmdHF14AMfUDump(const char *Cmd){ errors = param_gethex(tempStr, 0, key, dataLen); else errors = true; - - if (!errors) - memcpy(key, data, dataLen/2); cmdp += 2; hasPwd = true; @@ -1087,11 +1089,10 @@ int CmdHF14AMfUDump(const char *Cmd){ } // add keys - if (hasPwd && dataLen == 32){ //UL_C - memcpy(data + Pages*4, key, 16); + if (hasPwd){ //UL_C + memcpy(data + Pages*4, key, dataLen/2); Pages += 4; } - //TODO add key MEM location for other tags for (i = 0; i < Pages; ++i) { if ( i < 3 ) { @@ -1165,6 +1166,7 @@ int CmdHF14AMfUDump(const char *Cmd){ return 0; } +/* // Needed to Authenticate to Ultralight C tags void rol (uint8_t *data, const size_t len){ uint8_t first = data[0]; @@ -1173,6 +1175,7 @@ void rol (uint8_t *data, const size_t len){ } data[len-1] = first; } +*/ //------------------------------------------------------------------------------- // Ultralight C Methods @@ -1191,7 +1194,7 @@ int CmdHF14AMfucAuth(const char *Cmd){ //Change key to user defined one if (cmdp == 'k' || cmdp == 'K'){ keyNo = param_get8(Cmd, 1); - if(keyNo > 6) + if(keyNo > KEYS_3DES_COUNT) errors = true; } @@ -1213,7 +1216,7 @@ int CmdHF14AMfucAuth(const char *Cmd){ } uint8_t *key = default_3des_keys[keyNo]; - if (try3DesAuthentication(key, true) > 0) + if (ulc_authentication(key, true) == 0) PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 16)); else PrintAndLog("Authentication failed"); @@ -1221,68 +1224,6 @@ int CmdHF14AMfucAuth(const char *Cmd){ return 0; } -int try3DesAuthentication( uint8_t *key, bool switch_off_field ){ - - //uint32_t cuid = 0; - - des3_context ctx = { 0 }; - - uint8_t random_a[8] = { 1,1,1,1,1,1,1,1 }; - uint8_t random_b[8] = { 0 }; - uint8_t enc_random_b[8] = { 0 }; - uint8_t rnd_ab[16] = { 0 }; - uint8_t iv[8] = { 0 }; - - UsbCommand c = {CMD_MIFAREUC_AUTH1, {0x00}}; - SendCommand(&c); - UsbCommand resp; - if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return -1; - if ( !(resp.arg[0] & 0xff) ) return -2; - - //cuid = resp.arg[1]; - memcpy(enc_random_b,resp.d.asBytes+1,8); - - des3_set2key_dec(&ctx, key); - // context, mode, length, IV, input, output - des3_crypt_cbc( &ctx, DES_DECRYPT, sizeof(random_b), iv , enc_random_b , random_b); - - rol(random_b,8); - memcpy(rnd_ab ,random_a,8); - memcpy(rnd_ab+8,random_b,8); - - des3_set2key_enc(&ctx, key); - // context, mode, length, IV, input, output - des3_crypt_cbc(&ctx, DES_ENCRYPT, sizeof(rnd_ab), enc_random_b, rnd_ab, rnd_ab); - - //Auth2 - c.cmd = CMD_MIFAREUC_AUTH2; - c.arg[0] = switch_off_field; - memcpy(c.d.asBytes, rnd_ab, 16); - SendCommand(&c); - - if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; - if ( !(resp.arg[0] & 0xff)) return -2; - - uint8_t enc_resp[8] = { 0 }; - uint8_t resp_random_a[8] = { 0 }; - memcpy(enc_resp, resp.d.asBytes+1, 8); - - des3_set2key_dec(&ctx, key); - // context, mode, length, IV, input, output - des3_crypt_cbc( &ctx, DES_DECRYPT, 8, enc_random_b, enc_resp, resp_random_a); - - if ( !memcmp(resp_random_a, random_a, 8)) - return 1; - return 0; - - //PrintAndLog(" RndA :%s", sprint_hex(random_a, 8)); - //PrintAndLog(" enc(RndB) :%s", sprint_hex(enc_random_b, 8)); - //PrintAndLog(" RndB :%s", sprint_hex(random_b, 8)); - //PrintAndLog(" A+B :%s", sprint_hex(random_a_and_b, 16)); - //PrintAndLog(" enc(A+B) :%s", sprint_hex(random_a_and_b, 16)); - //PrintAndLog(" enc(RndA') :%s", sprint_hex(data2+1, 8)); -} - /** A test function to validate that the polarssl-function works the same was as the openssl-implementation. @@ -1419,7 +1360,6 @@ int CmdHF14AMfUCRdBl(const char *Cmd) hasPwd = TRUE; } } - //uint8_t *key2 = SwapEndian64(key, 16, 8); //Read Block UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; From 9d87eb66500080f76d81b8d453f3f5340717c001 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 18 May 2015 13:11:00 -0400 Subject: [PATCH 052/132] MF ultralight code cleanup --- armsrc/appmain.c | 1 - armsrc/mifarecmd.c | 38 +++++++++----- armsrc/mifareutil.c | 15 +++--- client/cmdhfmfu.c | 102 ++++++++++++++++++++---------------- client/lualibs/commands.lua | 8 ++- include/usb_cmd.h | 5 +- 6 files changed, 93 insertions(+), 76 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 7b94f8a3..96644b9a 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -830,7 +830,6 @@ void UsbPacketReceived(uint8_t *packet, int len) MifareUC_Auth(c->arg[0],c->d.asBytes); break; case CMD_MIFAREU_READCARD: - case CMD_MIFAREUC_READCARD: MifareUReadCard(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; case CMD_MIFAREUC_SETPWD: diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 1f8f4ee8..23652070 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -106,17 +106,17 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes){ return; }; - if(mifare_ultra_auth(keybytes) == 1){ + if(!mifare_ultra_auth(keybytes)){ if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed"); OnError(1); return; } - cmd_send(CMD_ACK,1,0,0,0,0); if (turnOffField) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } + cmd_send(CMD_ACK,1,0,0,0,0); } // Arg0 = BlockNo, @@ -146,7 +146,7 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) uint8_t key[16] = {0x00}; memcpy(key, datain, sizeof(key) ); - if ( mifare_ultra_auth(key) == 1 ) { + if ( !mifare_ultra_auth(key) ) { OnError(1); return; } @@ -157,7 +157,7 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) uint8_t pwd[4] = {0x00}; memcpy(pwd, datain, 4); uint8_t pack[4] = {0,0,0,0}; - if (mifare_ul_ev1_auth(pwd, pack) == 1) { + if (!mifare_ul_ev1_auth(pwd, pack)) { OnError(1); return; } @@ -255,8 +255,8 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) uint16_t blocks = arg1; bool useKey = (arg2 == 1); //UL_C bool usePwd = (arg2 == 2); //UL_EV1/NTAG - int countblocks = 0; - uint8_t dataout[176] = {0x00}; + uint32_t countblocks = 0; + uint8_t *dataout = BigBuf_get_addr(); LEDsoff(); LED_A_ON(); @@ -275,7 +275,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) uint8_t key[16] = {0x00}; memcpy(key, datain, sizeof(key) ); - if ( mifare_ultra_auth(key) == 1 ) { + if ( !mifare_ultra_auth(key) ) { OnError(1); return; } @@ -287,19 +287,30 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) memcpy(pwd, datain, sizeof(pwd)); uint8_t pack[4] = {0,0,0,0}; - if (mifare_ul_ev1_auth(pwd, pack) == 1){ + if (!mifare_ul_ev1_auth(pwd, pack)){ OnError(1); return; } } for (int i = 0; i < blocks; i++){ - len = mifare_ultra_readblock(blockNo * 4 + i, dataout + 4 * i); + if ((i*4) + 4 > BigBuf_get_traceLen()) { + Dbprintf("Data exceeds buffer!!"); + break; + } + + len = mifare_ultra_readblock(blockNo + i, dataout + 4 * i); if (len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Read block %d error",i); - OnError(2); - return; + // if no blocks read - error out + if (i==0){ + OnError(2); + return; + } else { + //stop at last successful read block and return what we got + break; + } } else { countblocks++; } @@ -314,9 +325,8 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks); - len = blocks * 4; - - cmd_send(CMD_ACK, 1, len, 0, dataout, len); + countblocks *= 4; + cmd_send(CMD_ACK, 1, countblocks, countblocks, 0, 0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index 0469364c..77169a36 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -322,15 +322,14 @@ int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){ len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); if (len != 4) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len); - OnError(1); - return 1; + return 0; } if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Auth Resp: %02x%02x%02x%02x", resp[0],resp[1],resp[2],resp[3]); memcpy(pack, resp, 4); - return 0; + return 1; } int mifare_ultra_auth(uint8_t *keybytes){ @@ -353,8 +352,7 @@ int mifare_ultra_auth(uint8_t *keybytes){ len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, resp, respPar ,NULL); if (len != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]); - OnError(1); - return 1; + return 0; } // tag nonce. @@ -386,8 +384,7 @@ int mifare_ultra_auth(uint8_t *keybytes){ len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL); if (len != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]); - OnError(1); - return 1; + return 0; } uint8_t enc_resp[8] = { 0,0,0,0,0,0,0,0 }; @@ -398,7 +395,7 @@ int mifare_ultra_auth(uint8_t *keybytes){ 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"); - return 1; + return 0; } if (MF_DBGLEVEL >= MF_DBG_EXTENDED) { @@ -418,7 +415,7 @@ int mifare_ultra_auth(uint8_t *keybytes){ resp_random_a[0],resp_random_a[1],resp_random_a[2],resp_random_a[3], resp_random_a[4],resp_random_a[5],resp_random_a[6],resp_random_a[7]); } - return 0; + return 1; } int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index a22ff859..15fa8e42 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -14,9 +14,10 @@ #include "mifare.h" #include "util.h" #include "protocols.h" +#include "data.h" #define MAX_UL_BLOCKS 0x0f -#define MAX_ULC_BLOCKS 0x2f +#define MAX_ULC_BLOCKS 0x2b #define MAX_ULEV1a_BLOCKS 0x12 #define MAX_ULEV1b_BLOCKS 0x20 #define MAX_NTAG_213 0x2c @@ -191,10 +192,10 @@ static int ulc_authentication( uint8_t *key, bool switch_off_field ){ memcpy(c.d.asBytes, key, 16); SendCommand(&c); UsbCommand resp; - if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return -1; - if ( resp.arg[0] == 1 ) return 0; + if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return 0; + if ( resp.arg[0] == 1 ) return 1; - return -2; + return 0; } static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t packLength ){ @@ -631,22 +632,20 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("-------------------------------------------------------------"); ul_print_type(tagtype, 6); - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed"); - ul_switch_off_field(); - return status; - } - - if ( hasAuthKey ) { - if ((tagtype & UL_C)) { - //will select card automatically - if (ulc_authentication(authenticationkey, false) != 0) { - ul_switch_off_field(); - PrintAndLog("Error: Authentication Failed UL-C"); - return 0; - } - } else { + if ( hasAuthKey && (tagtype & UL_C)) { + //will select card automatically and close connection on error + if (!ulc_authentication(authenticationkey, false)) { + PrintAndLog("Error: Authentication Failed UL-C"); + return 0; + } + } else { + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("iso14443a card select failed"); + ul_switch_off_field(); + return status; + } + if (hasAuthKey) { len = ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); if (len < 1) { ul_switch_off_field(); @@ -674,6 +673,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_read(0x28, ulc_conf, sizeof(ulc_conf)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ UL-C"); + ul_switch_off_field(); return status; } ulc_print_configuration(ulc_conf); @@ -690,22 +690,21 @@ int CmdHF14AMfUInfo(const char *Cmd){ ulc_print_3deskey(ulc_deskey); } else { + ul_switch_off_field(); // if we called info with key, just return if ( hasAuthKey ) return 1; PrintAndLog("Trying some default 3des keys"); for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ){ key = default_3des_keys[i]; - if (ulc_authentication(key, true) == 0){ + if (ulc_authentication(key, true)){ PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); - ul_switch_off_field(); return 1; } } - ul_switch_off_field(); return 1; //return even if key not found (UL_C is done) } } @@ -763,14 +762,19 @@ int CmdHF14AMfUInfo(const char *Cmd){ // 1-7 = ... should we even try then? if ( authlim == 0 ){ PrintAndLog("\n--- Known EV1/NTAG passwords."); - - for (uint8_t i = 0; i < 3; ++i ){ + len = 0; + for (uint8_t i = 0; i < KEYS_PWD_COUNT; ++i ){ key = default_pwd_pack[i]; - if ( len > -1 ){ - len = ulev1_requestAuthentication(key, pack, sizeof(pack)); - if (len == 1) { - PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); - break; + len = ulev1_requestAuthentication(key, pack, sizeof(pack)); + if (len >= 1) { + PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); + break; + } else { + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("iso14443a card select failed - ev1 auth"); + ul_switch_off_field(); + return status; } } } @@ -783,6 +787,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ status = ul_read(3, cc, sizeof(cc)); if ( status == -1 ){ PrintAndLog("Error: tag didn't answer to READ ntag"); + ul_switch_off_field(); return status; } ntag_print_CC(cc); @@ -988,8 +993,10 @@ int CmdHF14AMfUDump(const char *Cmd){ errors = param_gethex(tempStr, 0, key, dataLen); else if (dataLen == 8) //ev1/ntag errors = param_gethex(tempStr, 0, key, dataLen); - else + else{ + PrintAndLog("\nERROR: Key is incorrect length\n"); errors = true; + } cmdp += 2; hasPwd = true; @@ -1042,8 +1049,7 @@ int CmdHF14AMfUDump(const char *Cmd){ ul_print_type(tagtype, 0); PrintAndLog("Reading tag memory..."); - - UsbCommand c = {CMD_MIFAREUC_READCARD, {startPage,Pages}}; + UsbCommand c = {CMD_MIFAREU_READCARD, {startPage,Pages}}; if ( hasPwd ) { if (tagtype & UL_C) c.arg[2] = 1; //UL_C auth @@ -1058,15 +1064,20 @@ int CmdHF14AMfUDump(const char *Cmd){ PrintAndLog("Command execute time-out"); return 1; } - PrintAndLog ("%u,%u",resp.arg[0],resp.arg[1]); - uint8_t isOK = resp.arg[0] & 0xff; - if (isOK) { - memcpy(data, resp.d.asBytes, resp.arg[1]); - } else { + if (resp.arg[0] != 1) { PrintAndLog("Failed reading block: (%02x)", i); return 1; } + uint32_t bufferSize = resp.arg[1]; + if (bufferSize > sizeof(data)) { + PrintAndLog("Data exceeded Buffer size!"); + bufferSize = sizeof(data); + } + GetFromBigBuf(data, bufferSize, 0); + WaitForResponse(CMD_ACK,NULL); + + Pages = bufferSize/4; // Load lock bytes. int j = 0; @@ -1088,11 +1099,14 @@ int CmdHF14AMfUDump(const char *Cmd){ } } - // add keys - if (hasPwd){ //UL_C + // add keys to block dump + if (hasPwd && (tagtype & UL_C)){ //UL_C memcpy(data + Pages*4, key, dataLen/2); Pages += 4; - } + } else if (hasPwd) { //not sure output is in correct location. + memcpy(data + Pages*4, key, dataLen/2); + Pages += 1; + } for (i = 0; i < Pages; ++i) { if ( i < 3 ) { @@ -1186,7 +1200,7 @@ void rol (uint8_t *data, const size_t len){ // int CmdHF14AMfucAuth(const char *Cmd){ - uint8_t keyNo = 0; + uint8_t keyNo = 3; bool errors = false; char cmdp = param_getchar(Cmd, 0); @@ -1216,11 +1230,11 @@ int CmdHF14AMfucAuth(const char *Cmd){ } uint8_t *key = default_3des_keys[keyNo]; - if (ulc_authentication(key, true) == 0) + if (ulc_authentication(key, true)) PrintAndLog("Authentication successful. 3des key: %s",sprint_hex(key, 16)); else PrintAndLog("Authentication failed"); - + return 0; } diff --git a/client/lualibs/commands.lua b/client/lualibs/commands.lua index b0257ef0..678c745e 100644 --- a/client/lualibs/commands.lua +++ b/client/lualibs/commands.lua @@ -135,11 +135,9 @@ local _commands = { CMD_MIFARE_SNIFFER = 0x0630, --//ultralightC - CMD_MIFAREUC_AUTH1 = 0x0724, - CMD_MIFAREUC_AUTH2 = 0x0725, - CMD_MIFAREUC_READCARD = 0x0726, - CMD_MIFAREUC_SETPWD = 0x0727, - CMD_MIFAREU_SETUID = 0x0728, + CMD_MIFAREUC_AUTH = 0x0724, + CMD_MIFAREUC_SETPWD = 0x0727, + CMD_MIFAREU_SETUID = 0x0728, --// mifare desfire CMD_MIFARE_DESFIRE_READBL = 0x0728, diff --git a/include/usb_cmd.h b/include/usb_cmd.h index f67eac58..357395d4 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -174,9 +174,8 @@ typedef struct{ #define CMD_MIFARE_SNIFFER 0x0630 //ultralightC -#define CMD_MIFAREUC_AUTH1 0x0724 -#define CMD_MIFAREUC_AUTH2 0x0725 -#define CMD_MIFAREUC_READCARD 0x0726 +#define CMD_MIFAREUC_AUTH 0x0724 +//0x0725 and 0x0726 no longer used #define CMD_MIFAREUC_SETPWD 0x0727 From 29250969b0e2762fca3cbfa24e0648f29b21407d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 18 May 2015 22:07:11 -0400 Subject: [PATCH 053/132] @iceman1001 s comments/updates mfu cmds --- armsrc/mifareutil.c | 4 ++-- client/cmdhfmfu.c | 27 ++++++++------------------- client/cmdhfmfu.h | 4 ---- 3 files changed, 10 insertions(+), 25 deletions(-) diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index 77169a36..2f84797b 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -728,8 +728,8 @@ int mifare_desfire_des_auth1(uint32_t uid, uint8_t *blockData){ int len; // load key, keynumber uint8_t data[2]={0x0a, 0x00}; - uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; - uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; + uint8_t receivedAnswer[MAX_FRAME_SIZE]; + uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; len = mifare_sendcmd_special(NULL, 1, 0x02, data, receivedAnswer,receivedAnswerPar,NULL); if (len == 1) { diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 15fa8e42..d087ff6d 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -278,14 +278,17 @@ static int ul_print_default( uint8_t *data){ PrintAndLog(" BCC1 : %02X - crc should be %02X", data[8], crc1 ); PrintAndLog(" Internal : %02X - %s default", data[9], (data[9]==0x48)?"":"not" ); + PrintAndLog(" Lock : %s - %s", sprint_hex(data+10, 2), printBits(2, data+10) ); + PrintAndLog("OneTimePad : %s - %s\n", sprint_hex(data + 12, 4), printBits(4, data+12) ); + return 0; } @@ -364,7 +367,7 @@ static int ulc_print_configuration( uint8_t *data){ bool validAuth = (data[8] >= 0x03 && data[8] <= 0x30); if ( validAuth ) - PrintAndLog(" Auth0 [42/0x2A]: %s Page %d and above need authentication", sprint_hex(data+8, 4), data[8] ); + PrintAndLog(" Auth0 [42/0x2A]: %s page %d/0x%02X and above need authentication", sprint_hex(data+8, 4), data[8], data[8]); else{ if ( data[8] == 0){ PrintAndLog(" Auth0 [42/0x2A]: %s default", sprint_hex(data+8, 4) ); @@ -539,7 +542,7 @@ uint16_t GetHF14AMfU_Type(void){ } case 0x01: tagtype = UL_C; break; case 0x00: tagtype = UL; break; - case -1 : tagtype = (UL | UL_C); break; //when does this happen? + case -1 : tagtype = (UL | UL_C); break; //when does this happen? -- if getversion fails, it assumes it is either UL/ULC -- but why? magic tags? default : tagtype = UNKNOWN; break; } // UL-C test @@ -698,7 +701,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ){ key = default_3des_keys[i]; if (ulc_authentication(key, true)){ - PrintAndLog("Found default 3des key: "); //%s", sprint_hex(key,16)); + PrintAndLog("Found default 3des key: "); uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); @@ -931,7 +934,7 @@ int usage_hf_mfu_dump(void) PrintAndLog("Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("It autodetects card type.\n"); - PrintAndLog("Usage: hf mfu dump s k n "); + PrintAndLog("Usage: hf mfu dump l k n "); PrintAndLog(" Options : "); PrintAndLog(" k : key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); PrintAndLog(" l : swap entered key's endianness for auth"); @@ -949,14 +952,11 @@ int usage_hf_mfu_dump(void) // // Mifare Ultralight / Ultralight-C / Ultralight-EV1 // Read and Dump Card Contents, using auto detection of tag size. -// -// TODO: take a password to read UL-C / UL-EV1 tags. int CmdHF14AMfUDump(const char *Cmd){ FILE *fout; char filename[FILE_PATH_SIZE] = {0x00}; char *fnameptr = filename; - //char *str = "Dumping Ultralight%s%s Card Data..."; uint8_t *lockbytes_t = NULL; uint8_t lockbytes[2] = {0x00}; uint8_t *lockbytes_t2 = NULL; @@ -1089,7 +1089,7 @@ int CmdHF14AMfUDump(const char *Cmd){ } // Load bottom lockbytes if available - // HOW DOES THIS APPLY TO EV1 and/or NTAG??? + // TODO -- FIGURE OUT LOCK BYTES FOR TO EV1 and/or NTAG if ( Pages == 44 ) { lockbytes_t2 = data + (40*4); lockbytes2[0] = lockbytes_t2[2]; @@ -1180,17 +1180,6 @@ int CmdHF14AMfUDump(const char *Cmd){ return 0; } -/* -// Needed to Authenticate to Ultralight C tags -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]; - } - data[len-1] = first; -} -*/ - //------------------------------------------------------------------------------- // Ultralight C Methods //------------------------------------------------------------------------------- diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 806c27d3..53342219 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -13,15 +13,11 @@ int CmdHF14AMfUCRdBl(const char *Cmd); int CmdHF14AMfUCRdCard(const char *Cmd); int CmdHF14AMfucAuth(const char *Cmd); -uint8_t requestAuthentication( uint8_t *nonce); -int try3DesAuthentication( uint8_t *key, bool switch_off_field); - //general stuff int CmdHF14AMfUDump(const char *Cmd); int CmdHF14AMfUInfo(const char *Cmd); uint16_t GetHF14AMfU_Type(void); -void rol (uint8_t *data, const size_t len); int ul_print_type(uint16_t tagtype, uint8_t spacer); void ul_switch_off_field(void); From d7acc6403ed1e1a138c8d8fb662ee995442f209b Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 19 May 2015 11:30:50 -0400 Subject: [PATCH 054/132] hf mfu dump - bigbuf allocation fix some larger nfc tags can get large so set the allocation to the 4k CARD_MEMORY_SIZE buffersize. --- armsrc/mifarecmd.c | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 23652070..0586a25d 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -250,17 +250,26 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { + // free eventually allocated BigBuf memory + BigBuf_free(); + // clear trace + clear_trace(); + // params uint8_t blockNo = arg0; uint16_t blocks = arg1; bool useKey = (arg2 == 1); //UL_C bool usePwd = (arg2 == 2); //UL_EV1/NTAG uint32_t countblocks = 0; - uint8_t *dataout = BigBuf_get_addr(); + uint8_t *dataout = BigBuf_malloc(CARD_MEMORY_SIZE); + if (dataout == NULL){ + Dbprintf("out of memory"); + OnError(1); + return; + } LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); int len = iso14443a_select_card(NULL, NULL, NULL); @@ -294,7 +303,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) } for (int i = 0; i < blocks; i++){ - if ((i*4) + 4 > BigBuf_get_traceLen()) { + if ((i*4) + 4 > CARD_MEMORY_SIZE) { Dbprintf("Data exceeds buffer!!"); break; } From a98b05b71df1acf84aab0e70e721fe9901301494 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 19 May 2015 15:03:35 -0400 Subject: [PATCH 055/132] missed file in previous commit... duh... --- common/protocols.h | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/common/protocols.h b/common/protocols.h index 01b738c2..58034272 100644 --- a/common/protocols.h +++ b/common/protocols.h @@ -123,9 +123,21 @@ NXP/Philips CUSTOM COMMANDS #define MIFARE_CMD_RESTORE 0xC2 #define MIFARE_CMD_TRANSFER 0xB0 -#define MIFARE_ULC_WRITE 0xA0 +#define MIFARE_ULC_WRITE 0xA2 +//#define MIFARE_ULC__COMP_WRITE 0xA0 #define MIFARE_ULC_AUTH_1 0x1A -#define MIFARE_ULC_AUTH_2 0xAF +#define MIFARE_ULC_AUTH_2 0xAF + +#define MIFARE_ULEV1_AUTH 0x1B +#define MIFARE_ULEV1_VERSION 0x60 +#define MIFARE_ULEV1_FASTREAD 0x3A +//#define MIFARE_ULEV1_WRITE 0xA2 +//#define MIFARE_ULEV1_COMP_WRITE 0xA0 +#define MIFARE_ULEV1_READ_CNT 0x39 +#define MIFARE_ULEV1_INCR_CNT 0xA5 +#define MIFARE_ULEV1_READSIG 0x3C +#define MIFARE_ULEV1_CHECKTEAR 0x3E +#define MIFARE_ULEV1_VCSL 0x4B /** 06 00 = INITIATE From a383f4b708f818894a67636857e28d62efd22cdd Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 11:27:44 -0400 Subject: [PATCH 056/132] Add ntag 210, 212, 203 and bug fix --- client/cmdhfmfu.c | 219 +++++++++++++++++++++++++++------------------- client/cmdhfmfu.h | 19 ++-- 2 files changed, 141 insertions(+), 97 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index d087ff6d..88d502b8 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -19,7 +19,10 @@ #define MAX_UL_BLOCKS 0x0f #define MAX_ULC_BLOCKS 0x2b #define MAX_ULEV1a_BLOCKS 0x12 -#define MAX_ULEV1b_BLOCKS 0x20 +#define MAX_ULEV1b_BLOCKS 0x28 +#define MAX_NTAG_203 0x29 +#define MAX_NTAG_210 0x13 +#define MAX_NTAG_212 0x28 #define MAX_NTAG_213 0x2c #define MAX_NTAG_215 0x86 #define MAX_NTAG_216 0xe6 @@ -51,12 +54,13 @@ uint8_t default_pwd_pack[KEYS_PWD_COUNT][4] = { {0x32,0x0C,0x16,0x17}, // PACK 0x80,0x80 -- AMiiboo (sniffed) }; -#define MAX_UL_TYPES 13 -uint16_t UL_TYPES_ARRAY[MAX_UL_TYPES] = {UNKNOWN, UL, UL_C, UL_EV1_48, UL_EV1_128, - NTAG, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC}; -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_213, MAX_NTAG_213, MAX_NTAG_215, - MAX_NTAG_216, MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS}; +#define MAX_UL_TYPES 16 +uint16_t UL_TYPES_ARRAY[MAX_UL_TYPES] = {UNKNOWN, UL, UL_C, UL_EV1_48, UL_EV1_128, NTAG, NTAG_203, + NTAG_210, NTAG_212, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC}; + +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_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS}; static int CmdHelp(const char *Cmd); @@ -292,15 +296,14 @@ static int ul_print_default( uint8_t *data){ return 0; } -static int ntag_print_CC(uint8_t *data) { - - PrintAndLog("\n--- NTAG NDEF Message"); +static int ndef_print_CC(uint8_t *data) { if(data[0] != 0xe1) { - PrintAndLog("no NDEF message"); + //PrintAndLog("no NDEF message"); return -1; // no NDEF message } + PrintAndLog("--- NDEF Message"); PrintAndLog("Capability Container: %s", sprint_hex(data,4) ); PrintAndLog(" %02X: NDEF Magic Number", data[0]); PrintAndLog(" %02X: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); @@ -331,12 +334,20 @@ int ul_print_type(uint16_t tagtype, uint8_t spaces){ PrintAndLog("%sTYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)", spacer); else if ( tagtype & UL_EV1_128) PrintAndLog("%sTYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)", spacer); + else if ( tagtype & NTAG ) + PrintAndLog("%sTYPE : NTAG UNKNOWN", spacer); + else if ( tagtype & NTAG_203 ) + PrintAndLog("%sTYPE : NTAG 203 144bytes (NT2H0301F0DT)", spacer); else if ( tagtype & NTAG_213 ) - PrintAndLog("%sTYPE : MIFARE NTAG 213 144bytes (NT2H1311G0DU)", spacer); + PrintAndLog("%sTYPE : NTAG 210 48bytes (NT2L1011G0DU)", spacer); + else if ( tagtype & NTAG_213 ) + PrintAndLog("%sTYPE : NTAG 212 128bytes (NT2L1211G0DU)", spacer); + else if ( tagtype & NTAG_213 ) + PrintAndLog("%sTYPE : NTAG 213 144bytes (NT2H1311G0DU)", spacer); else if ( tagtype & NTAG_215 ) - PrintAndLog("%sTYPE : MIFARE NTAG 215 504bytes (NT2H1511G0DU)", spacer); + PrintAndLog("%sTYPE : NTAG 215 504bytes (NT2H1511G0DU)", spacer); else if ( tagtype & NTAG_216 ) - PrintAndLog("%sTYPE : MIFARE NTAG 216 888bytes (NT2H1611G0DU)", spacer); + PrintAndLog("%sTYPE : NTAG 216 888bytes (NT2H1611G0DU)", spacer); else if ( tagtype & MY_D ) PrintAndLog("%sTYPE : INFINEON my-d\x99", spacer); else if ( tagtype & MY_D_NFC ) @@ -384,7 +395,7 @@ static int ulc_print_configuration( uint8_t *data){ static int ulev1_print_configuration( uint8_t *data){ - PrintAndLog("\n--- UL-EV1 Configuration"); + PrintAndLog("\n--- Tag Configuration"); bool strg_mod_en = (data[0] & 2); uint8_t authlim = (data[4] & 0x07); @@ -412,7 +423,7 @@ static int ulev1_print_configuration( uint8_t *data){ } static int ulev1_print_counters(){ - PrintAndLog("--- UL-EV1 Counters"); + PrintAndLog("--- Tag Counters"); uint8_t tear[1] = {0}; uint8_t counter[3] = {0,0,0}; for ( uint8_t i = 0; i<3; ++i) { @@ -425,7 +436,7 @@ static int ulev1_print_counters(){ } static int ulev1_print_signature( uint8_t *data, uint8_t len){ - PrintAndLog("\n--- UL-EV1 Signature"); + PrintAndLog("\n--- Tag Signature"); PrintAndLog("IC signature public key name : NXP NTAG21x 2013"); PrintAndLog("IC signature public key value : 04494e1a386d3d3cfe3dc10e5de68a499b1c202db5b132393e89ed19fe5be8bc61"); PrintAndLog(" Elliptic curve parameters : secp128r1"); @@ -436,7 +447,7 @@ static int ulev1_print_signature( uint8_t *data, uint8_t len){ } static int ulev1_print_version(uint8_t *data){ - PrintAndLog("\n--- UL-EV1 / NTAG Version"); + PrintAndLog("\n--- Tag Version"); PrintAndLog(" Raw bytes : %s", sprint_hex(data, 8) ); PrintAndLog(" Vendor ID : %02X, Manufacturer: %s", data[1], getTagInfo(data[1])); PrintAndLog(" Product type : %s", getProductTypeStr(data[2])); @@ -529,11 +540,15 @@ uint16_t GetHF14AMfU_Type(void){ tagtype = UL_EV1_48; else if ( version[2] == 0x03 && version[6] != 0x0B ) tagtype = UL_EV1_128; - else if ( version[2] == 0x04 && version[6] == 0x0F ) + else if ( version[2] == 0x04 && version[3] == 0x01 && version[6] == 0x0B ) + tagtype = NTAG_210; + else if ( version[2] == 0x04 && version[3] == 0x01 && version[6] == 0x0E ) + tagtype = NTAG_212; + else if ( version[2] == 0x04 && version[3] == 0x02 && version[6] == 0x0F ) tagtype = NTAG_213; - else if ( version[2] == 0x04 && version[6] == 0x11 ) + else if ( version[2] == 0x04 && version[3] == 0x02 && version[6] == 0x11 ) tagtype = NTAG_215; - else if ( version[2] == 0x04 && version[6] == 0x13 ) + else if ( version[2] == 0x04 && version[3] == 0x02 && version[6] == 0x13 ) tagtype = NTAG_216; else if ( version[2] == 0x04 ) tagtype = NTAG; @@ -542,35 +557,60 @@ uint16_t GetHF14AMfU_Type(void){ } case 0x01: tagtype = UL_C; break; case 0x00: tagtype = UL; break; - case -1 : tagtype = (UL | UL_C); break; //when does this happen? -- if getversion fails, it assumes it is either UL/ULC -- but why? magic tags? + case -1 : tagtype = (UL | UL_C | NTAG_203); break; //when does this happen? -- if getversion fails, it assumes it is either UL/ULC -- but why? magic tags? default : tagtype = UNKNOWN; break; } - // UL-C test - if (tagtype == (UL | UL_C)) { + // UL vs UL-C vs ntag203 test + if (tagtype & (UL | UL_C | NTAG_203)) { status = ul_select(&card); if ( status < 1 ){ PrintAndLog("iso14443a card select failed (UL-C)"); ul_switch_off_field(); return UL_ERROR; } + + // do UL_C check first... uint8_t nonce[11] = {0x00}; status = ulc_requestAuthentication(nonce, sizeof(nonce)); - tagtype = ( status > 0 ) ? UL_C : UL; - ul_switch_off_field(); + if (status > 1) { + tagtype = UL_C; + } else { + // need to re-select after authentication error + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("iso14443a card select failed (UL-C)"); + ul_switch_off_field(); + return UL_ERROR; + } + uint8_t data[16] = {0x00}; + // read page 0x26-0x29 (last valid ntag203 page) + status = ul_read(0x26, data, sizeof(data)); + if ( status <= 1 ) { + tagtype = UL; + } else { + // read page 0x30 (should error if it is a ntag203) + status = ul_read(30, data, sizeof(data)); + if ( status <= 1 ){ + tagtype = NTAG_203; + } else { + tagtype = UNKNOWN; + } + } + ul_switch_off_field(); + } } } else { // Infinition MY-D tests Exam high nibble uint8_t nib = (card.uid[1] & 0xf0) >> 4; switch ( nib ){ case 1: tagtype = MY_D; break; - case 2: tagtype = (MY_D | MY_D_NFC); break; - case 3: tagtype = (MY_D_MOVE | MY_D_MOVE_NFC); break; + case 2: tagtype = (MY_D | MY_D_NFC); break; //notice: we can not currently distinguish between these two + case 3: tagtype = (MY_D_MOVE | MY_D_MOVE_NFC); break; //notice: we can not currently distinguish between these two } } tagtype = (ul_magic_test() == UL_MAGIC) ? (tagtype | MAGIC) : tagtype; - //if ((tagtype & UL)) tagtype = ul_magic_test(); return tagtype; } @@ -584,6 +624,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ int status; bool errors = false; bool hasAuthKey = false; + bool locked = false; uint8_t cmdp = 0; uint8_t datalen = 0; uint8_t authenticationkey[16] = {0x00}; @@ -658,18 +699,21 @@ int CmdHF14AMfUInfo(const char *Cmd){ } } - - // read pages 0,1,2,4 (should read 4pages) + // read pages 0,1,2,3 (should read 4pages) status = ul_read(0, data, sizeof(data)); - if ( status == -1 ){ + if ( status == -1 ) { ul_switch_off_field(); PrintAndLog("Error: tag didn't answer to READ"); return status; } + if (status == 16) { + ul_print_default(data); + ndef_print_CC(data+12); - ul_print_default(data); + } else locked = true; - if ((tagtype & UL_C)){ + // UL_C Specific + if ((tagtype & UL_C)) { // read pages 0x28, 0x29, 0x2A, 0x2B uint8_t ulc_conf[16] = {0x00}; @@ -679,18 +723,19 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); return status; } - ulc_print_configuration(ulc_conf); - - if ((tagtype & MAGIC)){ + if (status == 16) ulc_print_configuration(ulc_conf); + else locked = true; + if ((tagtype & MAGIC)) { + //just read key uint8_t ulc_deskey[16] = {0x00}; status = ul_read(0x2C, ulc_deskey, sizeof(ulc_deskey)); - if ( status == -1 ){ + if ( status == -1 ) { ul_switch_off_field(); PrintAndLog("Error: tag didn't answer to READ magic"); return status; } - ulc_print_3deskey(ulc_deskey); + if (status == 16) ulc_print_3deskey(ulc_deskey); } else { ul_switch_off_field(); @@ -698,75 +743,81 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ( hasAuthKey ) return 1; PrintAndLog("Trying some default 3des keys"); - for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ){ + for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ) { key = default_3des_keys[i]; - if (ulc_authentication(key, true)){ + if (ulc_authentication(key, true)) { PrintAndLog("Found default 3des key: "); uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); - return 1; + break; } } - return 1; //return even if key not found (UL_C is done) + // reselect for future tests (ntag test) + status = ul_select(&card); + if ( status < 1 ){ + PrintAndLog("iso14443a card select failed"); + ul_switch_off_field(); + return status; + } } } - if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { - //do counters and signature first (don't neet auth) - ulev1_print_counters(); + // do counters and signature first (don't neet auth) + // ul counters are different than ntag counters + if ((tagtype & (UL_EV1_48 | UL_EV1_128))) ulev1_print_counters(); + + if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216 ))) { uint8_t ulev1_signature[32] = {0x00}; status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); - if ( status == -1 ){ + if ( status == -1 ) { PrintAndLog("Error: tag didn't answer to READ SIGNATURE"); ul_switch_off_field(); return status; - } - ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); - - uint8_t startconfigblock = (tagtype & UL_EV1_48) ? 0x10 : 0x25; - uint8_t ulev1_conf[16] = {0x00}; - status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); - if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ EV1"); - ul_switch_off_field(); - return status; } - // save AUTHENTICATION LIMITS for later: - authlim = (ulev1_conf[4] & 0x07); - bool allZeros = true; - for (uint8_t idx=0; idx<8; idx++) - if (ulev1_conf[idx]) allZeros = false; - - if (allZeros) authlim=7; - ulev1_print_configuration(ulev1_conf); + if (status == 32) ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); } - if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216))) { - + if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_210 | NTAG_212 | NTAG_213 | NTAG_215 | NTAG_216))) { uint8_t version[10] = {0x00}; status = ulev1_getVersion(version, sizeof(version)); - if ( status == -1 ){ + if ( status == -1 ) { PrintAndLog("Error: tag didn't answer to GETVERSION"); ul_switch_off_field(); return status; } - ulev1_print_version(version); + if (status == 10) ulev1_print_version(version); + else locked = true; - // if we called info with key, just return - if ( hasAuthKey ) { + uint8_t startconfigblock = 0; + uint8_t ulev1_conf[16] = {0x00}; + // config blocks always are last 4 pages + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++) + if (tagtype & UL_TYPES_ARRAY[idx]) + startconfigblock = UL_MEMORY_ARRAY[idx]-3; + + status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); + if ( status == -1 ) { + PrintAndLog("Error: tag didn't answer to READ EV1"); ul_switch_off_field(); - return 1; + return status; + } else if (status == 16) { + // save AUTHENTICATION LIMITS for later: + authlim = (ulev1_conf[4] & 0x07); + ulev1_print_configuration(ulev1_conf); + } else { + authlim=7; } // AUTHLIMIT, (number of failed authentications) // 0 = limitless. - // 1-7 = ... should we even try then? - if ( authlim == 0 ){ + // 1-7 = limit. No automatic tries then. + // hasAuthKey, if we was called with key, skip test. + if ( !authlim && !hasAuthKey ) { PrintAndLog("\n--- Known EV1/NTAG passwords."); len = 0; - for (uint8_t i = 0; i < KEYS_PWD_COUNT; ++i ){ + for (uint8_t i = 0; i < KEYS_PWD_COUNT; ++i ) { key = default_pwd_pack[i]; len = ulev1_requestAuthentication(key, pack, sizeof(pack)); if (len >= 1) { @@ -774,29 +825,19 @@ int CmdHF14AMfUInfo(const char *Cmd){ break; } else { status = ul_select(&card); - if ( status < 1 ){ + if ( status < 1 ) { PrintAndLog("iso14443a card select failed - ev1 auth"); ul_switch_off_field(); return status; } } } + if (len < 1) PrintAndLog("password not known"); } } - if ((tagtype & (NTAG_213 | NTAG_215 | NTAG_216))){ - - uint8_t cc[16] = {0x00}; - status = ul_read(3, cc, sizeof(cc)); - if ( status == -1 ){ - PrintAndLog("Error: tag didn't answer to READ ntag"); - ul_switch_off_field(); - return status; - } - ntag_print_CC(cc); - } - ul_switch_off_field(); + if (locked) PrintAndLog("\nTag appears to be locked, try using the key to get more info"); PrintAndLog(""); return 1; } @@ -1100,7 +1141,7 @@ int CmdHF14AMfUDump(const char *Cmd){ } // add keys to block dump - if (hasPwd && (tagtype & UL_C)){ //UL_C + if (hasPwd && (tagtype & UL_C)) { //UL_C memcpy(data + Pages*4, key, dataLen/2); Pages += 4; } else if (hasPwd) { //not sure output is in correct location. diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 53342219..4087b311 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -33,14 +33,17 @@ typedef enum TAGTYPE_UL { UL_EV1_48 = 0x0004, UL_EV1_128 = 0x0008, NTAG = 0x0010, - NTAG_213 = 0x0020, - NTAG_215 = 0x0040, - NTAG_216 = 0x0080, - MY_D = 0x0100, - MY_D_NFC = 0x0200, - MY_D_MOVE = 0x0400, - MY_D_MOVE_NFC = 0x0800, - MAGIC = 0x1000, + NTAG_203 = 0x0020, + NTAG_210 = 0x0040, + NTAG_212 = 0x0080, + NTAG_213 = 0x0100, + NTAG_215 = 0x0200, + NTAG_216 = 0x0400, + MY_D = 0x0800, + MY_D_NFC = 0x1000, + MY_D_MOVE = 0x2000, + MY_D_MOVE_NFC = 0x4000, + MAGIC = 0x8000, UL_MAGIC = UL | MAGIC, UL_C_MAGIC = UL_C | MAGIC, UL_ERROR = 0xFFFF, From c7442b76732e1dbc31fdd8a996142e34534ef5fb Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 14:06:46 -0400 Subject: [PATCH 057/132] Add NTAG i2c and bug fix also streamlined select tag code --- client/cmdhf14a.c | 2 +- client/cmdhfmfu.c | 106 +++++++++++++++++++++------------------------- client/cmdhfmfu.h | 42 +++++++++--------- 3 files changed, 71 insertions(+), 79 deletions(-) diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index 1973ff22..9a761864 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -178,7 +178,7 @@ int CmdHF14AReader(const char *Cmd) c.arg[2] = 0; SendCommand(&c); - uint16_t tagT = GetHF14AMfU_Type(); + uint32_t tagT = GetHF14AMfU_Type(); ul_print_type(tagT, 0); //reconnect for further tests diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 88d502b8..e3ea9378 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -150,11 +150,16 @@ static int ul_select( iso14a_card_select_t *card ){ ul_switch_on_field(); UsbCommand resp; - if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; - if (resp.arg[0] < 1) return -1; + bool ans = false; + ans = WaitForResponseTimeout(CMD_ACK, &resp, 1500); + if (resp.arg[0] < 1 || !ans) { + PrintAndLog("iso14443a card select failed"); + ul_switch_off_field(); + return 0; + } memcpy(card, resp.d.asBytes, sizeof(iso14a_card_select_t)); - return resp.arg[0]; + return 1; } // This read command will at least return 16bytes. @@ -321,7 +326,7 @@ static int ndef_print_CC(uint8_t *data) { return 0; } -int ul_print_type(uint16_t tagtype, uint8_t spaces){ +int ul_print_type(uint32_t tagtype, uint8_t spaces){ char spc[11] = " "; spc[10]=0x00; char *spacer = spc + (10-spaces); @@ -338,9 +343,9 @@ int ul_print_type(uint16_t tagtype, uint8_t spaces){ PrintAndLog("%sTYPE : NTAG UNKNOWN", spacer); else if ( tagtype & NTAG_203 ) PrintAndLog("%sTYPE : NTAG 203 144bytes (NT2H0301F0DT)", spacer); - else if ( tagtype & NTAG_213 ) + else if ( tagtype & NTAG_210 ) PrintAndLog("%sTYPE : NTAG 210 48bytes (NT2L1011G0DU)", spacer); - else if ( tagtype & NTAG_213 ) + else if ( tagtype & NTAG_212 ) PrintAndLog("%sTYPE : NTAG 212 128bytes (NT2L1211G0DU)", spacer); else if ( tagtype & NTAG_213 ) PrintAndLog("%sTYPE : NTAG 213 144bytes (NT2H1311G0DU)", spacer); @@ -357,7 +362,7 @@ int ul_print_type(uint16_t tagtype, uint8_t spaces){ else if ( tagtype & MY_D_MOVE_NFC ) PrintAndLog("%sTYPE : INFINEON my-d\x99 move NFC", spacer); else - PrintAndLog("%sTYPE : Unknown %04x", spacer, tagtype); + PrintAndLog("%sTYPE : Unknown %06x", spacer, tagtype); return 0; } @@ -426,13 +431,16 @@ static int ulev1_print_counters(){ PrintAndLog("--- Tag Counters"); uint8_t tear[1] = {0}; uint8_t counter[3] = {0,0,0}; + uint16_t len = 0; for ( uint8_t i = 0; i<3; ++i) { ulev1_readTearing(i,tear,sizeof(tear)); - ulev1_readCounter(i,counter, sizeof(counter) ); - PrintAndLog(" [%0d] : %s", i, sprint_hex(counter,3)); - PrintAndLog(" - %02X tearing %s", tear[0], ( tear[0]==0xBD)?"Ok":"failure"); + len = ulev1_readCounter(i,counter, sizeof(counter) ); + if (len == 3) { + PrintAndLog(" [%0d] : %s", i, sprint_hex(counter,3)); + PrintAndLog(" - %02X tearing %s", tear[0], ( tear[0]==0xBD)?"Ok":"failure"); + } } - return 0; + return len; } static int ulev1_print_signature( uint8_t *data, uint8_t len){ @@ -472,9 +480,7 @@ static int ulc_magic_test(){ uint8_t nonce1[11] = {0x00}; uint8_t nonce2[11] = {0x00}; int status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("Error: couldn't select ulc_magic_test"); - ul_switch_off_field(); + if ( !status ){ return UL_ERROR; } status = ulc_requestAuthentication(nonce1, sizeof(nonce1)); @@ -494,12 +500,9 @@ static int ul_magic_test(){ // 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; - int status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed"); - ul_switch_off_field(); + int status; + if ( !ul_select(&card) ) return UL_ERROR; - } status = ul_comp_write(0, NULL, 0); ul_switch_off_field(); if ( status == 0 ) @@ -507,7 +510,7 @@ static int ul_magic_test(){ return UL; } -uint16_t GetHF14AMfU_Type(void){ +uint32_t GetHF14AMfU_Type(void){ TagTypeUL_t tagtype = UNKNOWN; iso14a_card_select_t card; @@ -515,12 +518,8 @@ uint16_t GetHF14AMfU_Type(void){ int status = 0; int len; - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed"); - ul_switch_off_field(); - return UL_ERROR; - } + if (!ul_select(&card)) return UL_ERROR; + // Ultralight - ATQA / SAK if ( card.atqa[1] != 0x00 || card.atqa[0] != 0x44 || card.sak != 0x00 ) { PrintAndLog("Tag is not Ultralight | NTAG | MY-D [ATQA: %02X %02X SAK: %02X]\n", card.atqa[1], card.atqa[0], card.sak); @@ -550,6 +549,11 @@ uint16_t GetHF14AMfU_Type(void){ tagtype = NTAG_215; else if ( version[2] == 0x04 && version[3] == 0x02 && version[6] == 0x13 ) tagtype = NTAG_216; + else if ( version[2] == 0x04 && version[3] == 0x05 && version[6] == 0x13 ) + tagtype = NTAG_I2C_1K; + else if ( version[2] == 0x04 && version[3] == 0x05 && version[6] == 0x15 ) + tagtype = NTAG_I2C_2K; + else if ( version[2] == 0x04 ) tagtype = NTAG; @@ -562,12 +566,7 @@ uint16_t GetHF14AMfU_Type(void){ } // UL vs UL-C vs ntag203 test if (tagtype & (UL | UL_C | NTAG_203)) { - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed (UL-C)"); - ul_switch_off_field(); - return UL_ERROR; - } + if ( !ul_select(&card) ) return UL_ERROR; // do UL_C check first... uint8_t nonce[11] = {0x00}; @@ -577,12 +576,8 @@ uint16_t GetHF14AMfU_Type(void){ tagtype = UL_C; } else { // need to re-select after authentication error - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed (UL-C)"); - ul_switch_off_field(); - return UL_ERROR; - } + if ( !ul_select(&card) ) return UL_ERROR; + uint8_t data[16] = {0x00}; // read page 0x26-0x29 (last valid ntag203 page) status = ul_read(0x26, data, sizeof(data)); @@ -611,7 +606,7 @@ uint16_t GetHF14AMfU_Type(void){ } tagtype = (ul_magic_test() == UL_MAGIC) ? (tagtype | MAGIC) : tagtype; - + if (tagtype == (UNKNOWN | MAGIC)) tagtype = (UL | MAGIC); return tagtype; } @@ -683,12 +678,8 @@ int CmdHF14AMfUInfo(const char *Cmd){ return 0; } } else { - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed"); - ul_switch_off_field(); - return status; - } + if ( !ul_select(&card) ) return 0; + if (hasAuthKey) { len = ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); if (len < 1) { @@ -754,19 +745,19 @@ int CmdHF14AMfUInfo(const char *Cmd){ } } // reselect for future tests (ntag test) - status = ul_select(&card); - if ( status < 1 ){ - PrintAndLog("iso14443a card select failed"); - ul_switch_off_field(); - return status; - } + if ( !ul_select(&card) ) return 0; } } // do counters and signature first (don't neet auth) // ul counters are different than ntag counters - if ((tagtype & (UL_EV1_48 | UL_EV1_128))) ulev1_print_counters(); + if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { + if (ulev1_print_counters() != 3) { + // failed - re-select + if ( !ul_select(&card) ) return 0; + } + } if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216 ))) { uint8_t ulev1_signature[32] = {0x00}; @@ -777,6 +768,10 @@ int CmdHF14AMfUInfo(const char *Cmd){ return status; } if (status == 32) ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); + else { + // re-select + if ( !ul_select(&card) ) return 0; + } } if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_210 | NTAG_212 | NTAG_213 | NTAG_215 | NTAG_216))) { @@ -824,12 +819,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); break; } else { - status = ul_select(&card); - if ( status < 1 ) { - PrintAndLog("iso14443a card select failed - ev1 auth"); - ul_switch_off_field(); - return status; - } + if ( !ul_select(&card) ) return 0; } } if (len < 1) PrintAndLog("password not known"); diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 4087b311..83f28403 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -16,9 +16,9 @@ int CmdHF14AMfucAuth(const char *Cmd); //general stuff int CmdHF14AMfUDump(const char *Cmd); int CmdHF14AMfUInfo(const char *Cmd); -uint16_t GetHF14AMfU_Type(void); +uint32_t GetHF14AMfU_Type(void); -int ul_print_type(uint16_t tagtype, uint8_t spacer); +int ul_print_type(uint32_t tagtype, uint8_t spacer); void ul_switch_off_field(void); int usage_hf_mfu_dump(void); @@ -27,26 +27,28 @@ int usage_hf_mfu_info(void); int CmdHFMFUltra(const char *Cmd); typedef enum TAGTYPE_UL { - UNKNOWN = 0x0000, - UL = 0x0001, - UL_C = 0x0002, - UL_EV1_48 = 0x0004, - UL_EV1_128 = 0x0008, - NTAG = 0x0010, - NTAG_203 = 0x0020, - NTAG_210 = 0x0040, - NTAG_212 = 0x0080, - NTAG_213 = 0x0100, - NTAG_215 = 0x0200, - NTAG_216 = 0x0400, - MY_D = 0x0800, - MY_D_NFC = 0x1000, - MY_D_MOVE = 0x2000, - MY_D_MOVE_NFC = 0x4000, - MAGIC = 0x8000, + UNKNOWN = 0x000000, + UL = 0x000001, + UL_C = 0x000002, + UL_EV1_48 = 0x000004, + UL_EV1_128 = 0x000008, + NTAG = 0x000010, + NTAG_203 = 0x000020, + NTAG_210 = 0x000040, + NTAG_212 = 0x000080, + NTAG_213 = 0x000100, + NTAG_215 = 0x000200, + NTAG_216 = 0x000400, + MY_D = 0x000800, + MY_D_NFC = 0x001000, + MY_D_MOVE = 0x002000, + MY_D_MOVE_NFC = 0x004000, + NTAG_I2C_1K = 0x008000, + NTAG_I2C_2K = 0x010000, + MAGIC = 0x020000, UL_MAGIC = UL | MAGIC, UL_C_MAGIC = UL_C | MAGIC, - UL_ERROR = 0xFFFF, + UL_ERROR = 0xFFFFFF, } TagTypeUL_t; #endif From ea11861793628ce153926ffe9b60068d83e9aa9f Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 14:17:43 -0400 Subject: [PATCH 058/132] minor adjustments to hf mfu --- client/cmdhfmfu.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index e3ea9378..9826a592 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -152,7 +152,7 @@ static int ul_select( iso14a_card_select_t *card ){ UsbCommand resp; bool ans = false; ans = WaitForResponseTimeout(CMD_ACK, &resp, 1500); - if (resp.arg[0] < 1 || !ans) { + if (!ans || resp.arg[0] < 1) { PrintAndLog("iso14443a card select failed"); ul_switch_off_field(); return 0; @@ -408,22 +408,22 @@ static int ulev1_print_configuration( uint8_t *data){ bool prot = (data[4] & 0x80); uint8_t vctid = data[5]; - PrintAndLog(" cfg0 [16/0x10]: %s", sprint_hex(data, 4)); + PrintAndLog(" cfg0 [16/0x10]: %s", sprint_hex(data, 4)); if ( data[3] < 0xff ) PrintAndLog(" - page %d and above need authentication",data[3]); else PrintAndLog(" - pages don't need authentication"); PrintAndLog(" - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); - PrintAndLog(" cfg1 [17/0x11]: %s", sprint_hex(data+4, 4) ); + PrintAndLog(" cfg1 [17/0x11]: %s", sprint_hex(data+4, 4) ); if ( authlim == 0) PrintAndLog(" - Unlimited password attempts"); else PrintAndLog(" - Max number of password attempts is %d", authlim); PrintAndLog(" - user configuration %s", cfglck ? "permanently locked":"writeable"); PrintAndLog(" - %s access is protected with password", prot ? "read and write":"write"); - PrintAndLog(" %02X - Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); - PrintAndLog(" PWD [18/0x12]: %s", sprint_hex(data+8, 4)); - PrintAndLog(" PACK [19/0x13]: %s", sprint_hex(data+12, 4)); + PrintAndLog(" %02X - Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); + PrintAndLog(" PWD [18/0x12]: %s", sprint_hex(data+8, 4)); + PrintAndLog(" PACK [19/0x13]: %s", sprint_hex(data+12, 4)); return 0; } From 8241872c4702766159594eae0ef7ab4292d37d40 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 14:22:26 -0400 Subject: [PATCH 059/132] ULEV1_48 had the wrong max block --- client/cmdhfmfu.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 9826a592..c0fd136a 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -18,7 +18,7 @@ #define MAX_UL_BLOCKS 0x0f #define MAX_ULC_BLOCKS 0x2b -#define MAX_ULEV1a_BLOCKS 0x12 +#define MAX_ULEV1a_BLOCKS 0x13 #define MAX_ULEV1b_BLOCKS 0x28 #define MAX_NTAG_203 0x29 #define MAX_NTAG_210 0x13 From 46fcd738e02bb4e3c5159e6848121666160de7a5 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 15:41:48 -0400 Subject: [PATCH 060/132] finish NTAG i2c +... thanks @iceman1001 --- client/cmdhfmfu.c | 55 ++++++++++++++++++++++++----------------------- 1 file changed, 28 insertions(+), 27 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index c0fd136a..68ed11d5 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -72,13 +72,13 @@ char *getProductTypeStr( uint8_t id){ switch(id) { case 3: - sprintf(retStr, "%02X %s", id, "(Ultralight)"); + sprintf(retStr, "%02X %s", id, "Ultralight"); break; case 4: - sprintf(retStr, "%02X %s", id, "(NTAG)"); + sprintf(retStr, "%02X %s", id, "NTAG"); break; default: - sprintf(retStr, "%02X %s", id, "(unknown)"); + sprintf(retStr, "%02X %s", id, "unknown"); break; } return buf; @@ -264,7 +264,7 @@ static int ul_print_default( uint8_t *data){ uid[6] = data[7]; PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); - PrintAndLog(" UID[0] : %02X, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); + PrintAndLog(" UID[0] : %02X Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); if ( uid[0] == 0x05 ) { uint8_t chip = (data[8] & 0xC7); // 11000111 mask, bit 3,4,5 RFU switch (chip){ @@ -353,6 +353,8 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ PrintAndLog("%sTYPE : NTAG 215 504bytes (NT2H1511G0DU)", spacer); else if ( tagtype & NTAG_216 ) PrintAndLog("%sTYPE : NTAG 216 888bytes (NT2H1611G0DU)", spacer); + else if ( tagtype & NTAG_I2C_1K ) + else if ( tagtype & NTAG_I2C_2K ) else if ( tagtype & MY_D ) PrintAndLog("%sTYPE : INFINEON my-d\x99", spacer); else if ( tagtype & MY_D_NFC ) @@ -445,7 +447,7 @@ static int ulev1_print_counters(){ static int ulev1_print_signature( uint8_t *data, uint8_t len){ PrintAndLog("\n--- Tag Signature"); - PrintAndLog("IC signature public key name : NXP NTAG21x 2013"); + PrintAndLog("IC signature public key name : NXP NTAG21x 2013"); // don't know if there is other NXP public keys.. :( PrintAndLog("IC signature public key value : 04494e1a386d3d3cfe3dc10e5de68a499b1c202db5b132393e89ed19fe5be8bc61"); PrintAndLog(" Elliptic curve parameters : secp128r1"); PrintAndLog(" Tag ECC Signature : %s", sprint_hex(data, len)); @@ -457,7 +459,7 @@ static int ulev1_print_signature( uint8_t *data, uint8_t len){ static int ulev1_print_version(uint8_t *data){ PrintAndLog("\n--- Tag Version"); PrintAndLog(" Raw bytes : %s", sprint_hex(data, 8) ); - PrintAndLog(" Vendor ID : %02X, Manufacturer: %s", data[1], getTagInfo(data[1])); + PrintAndLog(" Vendor ID : %02X %s", data[1], getTagInfo(data[1])); PrintAndLog(" Product type : %s", getProductTypeStr(data[2])); PrintAndLog(" Product subtype : %02X %s", data[3], (data[3]==1) ?"17 pF":"50pF"); PrintAndLog(" Major version : %02X", data[4]); @@ -500,14 +502,13 @@ static int ul_magic_test(){ // 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; - int status; if ( !ul_select(&card) ) return UL_ERROR; - status = ul_comp_write(0, NULL, 0); + int status = ul_comp_write(0, NULL, 0); ul_switch_off_field(); if ( status == 0 ) - return UL_MAGIC; - return UL; + return MAGIC; + return 0; } uint32_t GetHF14AMfU_Type(void){ @@ -561,7 +562,7 @@ uint32_t GetHF14AMfU_Type(void){ } case 0x01: tagtype = UL_C; break; case 0x00: tagtype = UL; break; - case -1 : tagtype = (UL | UL_C | NTAG_203); break; //when does this happen? -- if getversion fails, it assumes it is either UL/ULC -- but why? magic tags? + case -1 : tagtype = (UL | UL_C | NTAG_203); break; // could be UL | UL_C magic tags default : tagtype = UNKNOWN; break; } // UL vs UL-C vs ntag203 test @@ -605,8 +606,9 @@ uint32_t GetHF14AMfU_Type(void){ } } - tagtype = (ul_magic_test() == UL_MAGIC) ? (tagtype | MAGIC) : tagtype; - if (tagtype == (UNKNOWN | MAGIC)) tagtype = (UL | MAGIC); + + tagtype |= ul_magic_test(); + if (tagtype == (UNKNOWN | MAGIC)) tagtype = (UL_MAGIC); return tagtype; } @@ -700,7 +702,6 @@ int CmdHF14AMfUInfo(const char *Cmd){ if (status == 16) { ul_print_default(data); ndef_print_CC(data+12); - } else locked = true; // UL_C Specific @@ -759,7 +760,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } } - if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216 ))) { + if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_213 | NTAG_215 | NTAG_216 | NTAG_I2C_1K | NTAG_I2C_2K ))) { uint8_t ulev1_signature[32] = {0x00}; status = ulev1_readSignature( ulev1_signature, sizeof(ulev1_signature)); if ( status == -1 ) { @@ -774,7 +775,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } } - if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_210 | NTAG_212 | NTAG_213 | NTAG_215 | NTAG_216))) { + if ((tagtype & (UL_EV1_48 | UL_EV1_128 | NTAG_210 | NTAG_212 | NTAG_213 | NTAG_215 | NTAG_216 | NTAG_I2C_1K | NTAG_I2C_2K))) { uint8_t version[10] = {0x00}; status = ulev1_getVersion(version, sizeof(version)); if ( status == -1 ) { @@ -792,17 +793,17 @@ int CmdHF14AMfUInfo(const char *Cmd){ if (tagtype & UL_TYPES_ARRAY[idx]) startconfigblock = UL_MEMORY_ARRAY[idx]-3; - status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); - if ( status == -1 ) { - PrintAndLog("Error: tag didn't answer to READ EV1"); - ul_switch_off_field(); - return status; - } else if (status == 16) { - // save AUTHENTICATION LIMITS for later: - authlim = (ulev1_conf[4] & 0x07); - ulev1_print_configuration(ulev1_conf); - } else { - authlim=7; + if (startconfigblock){ // if we know where the config block is... + status = ul_read(startconfigblock, ulev1_conf, sizeof(ulev1_conf)); + if ( status == -1 ) { + PrintAndLog("Error: tag didn't answer to READ EV1"); + ul_switch_off_field(); + return status; + } else if (status == 16) { + // save AUTHENTICATION LIMITS for later: + authlim = (ulev1_conf[4] & 0x07); + ulev1_print_configuration(ulev1_conf); + } } // AUTHLIMIT, (number of failed authentications) From cd87ee9133bf4b12e7b8a250e44e2924f515a617 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 15:42:58 -0400 Subject: [PATCH 061/132] finish NTAG i2c +... thanks iceman --- client/cmdhfmfu.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 68ed11d5..aebde833 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -354,7 +354,9 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ else if ( tagtype & NTAG_216 ) PrintAndLog("%sTYPE : NTAG 216 888bytes (NT2H1611G0DU)", spacer); else if ( tagtype & NTAG_I2C_1K ) + PrintAndLog("%sTYPE : NTAG I%sC 888bytes (NT3H1101FHK)", spacer, "\xFD"); else if ( tagtype & NTAG_I2C_2K ) + PrintAndLog("%sTYPE : NTAG I%sC 1904bytes (NT3H1201FHK)", spacer, "\xFD"); else if ( tagtype & MY_D ) PrintAndLog("%sTYPE : INFINEON my-d\x99", spacer); else if ( tagtype & MY_D_NFC ) From 1c429594a13155b464c9ccf618067c29339d7fff Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 20 May 2015 16:47:40 -0400 Subject: [PATCH 062/132] further mfu info updates needed to auth select when a command failed for locked tags. some output cleanups from @iceman1001 --- client/cmdhfmfu.c | 155 +++++++++++++++++++++++----------------------- 1 file changed, 77 insertions(+), 78 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index aebde833..7f0e8fc5 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -71,15 +71,9 @@ char *getProductTypeStr( uint8_t id){ char *retStr = buf; switch(id) { - case 3: - sprintf(retStr, "%02X %s", id, "Ultralight"); - break; - case 4: - sprintf(retStr, "%02X %s", id, "NTAG"); - break; - default: - sprintf(retStr, "%02X %s", id, "unknown"); - break; + case 3: sprintf(retStr, "%02X, Ultralight", id); break; + case 4: sprintf(retStr, "%02X, NTAG", id); break; + default: sprintf(retStr, "%02X, unknown", id); break; } return buf; } @@ -214,6 +208,27 @@ static int ulev1_requestAuthentication( uint8_t *pwd, uint8_t *pack, uint16_t pa return len; } +static int ul_auth_select( iso14a_card_select_t *card, TagTypeUL_t tagtype, bool hasAuthKey, uint8_t *authenticationkey, uint8_t *pack, uint8_t packSize){ + if ( hasAuthKey && (tagtype & UL_C)) { + //will select card automatically and close connection on error + if (!ulc_authentication(authenticationkey, false)) { + PrintAndLog("Error: Authentication Failed UL-C"); + return 0; + } + } else { + if ( !ul_select(card) ) return 0; + + if (hasAuthKey) { + if (ulev1_requestAuthentication(authenticationkey, pack, packSize) < 1) { + ul_switch_off_field(); + PrintAndLog("Error: Authentication Failed UL-EV1/NTAG"); + return 0; + } + } + } + return 1; +} + static int ulev1_getVersion( uint8_t *response, uint16_t responseLength ){ uint8_t cmd[] = {MIFARE_ULEV1_VERSION}; @@ -264,7 +279,7 @@ static int ul_print_default( uint8_t *data){ uid[6] = data[7]; PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); - PrintAndLog(" UID[0] : %02X Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); + PrintAndLog(" UID[0] : %02X, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); if ( uid[0] == 0x05 ) { uint8_t chip = (data[8] & 0xC7); // 11000111 mask, bit 3,4,5 RFU switch (chip){ @@ -276,17 +291,17 @@ static int ul_print_default( uint8_t *data){ // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 int crc0 = 0x88 ^ data[0] ^ data[1] ^data[2]; if ( data[3] == crc0 ) - PrintAndLog(" BCC0 : %02X - Ok", data[3]); + PrintAndLog(" BCC0 : %02X, Ok", data[3]); else - PrintAndLog(" BCC0 : %02X - crc should be %02X", data[3], crc0); + PrintAndLog(" BCC0 : %02X, crc should be %02X", data[3], crc0); int crc1 = data[4] ^ data[5] ^ data[6] ^data[7]; if ( data[8] == crc1 ) - PrintAndLog(" BCC1 : %02X - Ok", data[8]); + PrintAndLog(" BCC1 : %02X, Ok", data[8]); else - PrintAndLog(" BCC1 : %02X - crc should be %02X", data[8], crc1 ); + PrintAndLog(" BCC1 : %02X, crc should be %02X", data[8], crc1 ); - PrintAndLog(" Internal : %02X - %s default", data[9], (data[9]==0x48)?"":"not" ); + PrintAndLog(" Internal : %02X, %sdefault", data[9], (data[9]==0x48)?"":"not " ); PrintAndLog(" Lock : %s - %s", sprint_hex(data+10, 2), @@ -302,25 +317,23 @@ static int ul_print_default( uint8_t *data){ } static int ndef_print_CC(uint8_t *data) { - - if(data[0] != 0xe1) { - //PrintAndLog("no NDEF message"); - return -1; // no NDEF message - } + // no NDEF message + if(data[0] != 0xe1) + return -1; PrintAndLog("--- NDEF Message"); PrintAndLog("Capability Container: %s", sprint_hex(data,4) ); - PrintAndLog(" %02X: NDEF Magic Number", data[0]); - PrintAndLog(" %02X: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); - PrintAndLog(" %02X: Physical Memory Size: %d bytes", data[2], (data[2] + 1) * 8); + PrintAndLog(" %02X : NDEF Magic Number", data[0]); + PrintAndLog(" %02X : version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); + PrintAndLog(" %02X : Physical Memory Size: %d bytes", data[2], (data[2] + 1) * 8); if ( data[2] == 0x12 ) - PrintAndLog(" %02X: NDEF Memory Size: %d bytes", data[2], 144); + PrintAndLog(" %02X : NDEF Memory Size: %d bytes", data[2], 144); else if ( data[2] == 0x3e ) - PrintAndLog(" %02X: NDEF Memory Size: %d bytes", data[2], 496); + PrintAndLog(" %02X : NDEF Memory Size: %d bytes", data[2], 496); else if ( data[2] == 0x6d ) - PrintAndLog(" %02X: NDEF Memory Size: %d bytes", data[2], 872); - - PrintAndLog(" %02X: %s / %s", data[3], + PrintAndLog(" %02X : NDEF Memory Size: %d bytes", data[2], 872); + + PrintAndLog(" %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; @@ -332,19 +345,19 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ char *spacer = spc + (10-spaces); if ( tagtype & UL ) - PrintAndLog("%sTYPE : MIFARE Ultralight (MF0ICU1) %s [%x]", spacer, (tagtype & MAGIC)?"":"", tagtype); + PrintAndLog("%sTYPE : MIFARE Ultralight (MF0ICU1) %s", spacer, (tagtype & MAGIC) ? "" : "" ); else if ( tagtype & UL_C) - PrintAndLog("%sTYPE : MIFARE Ultralight C (MF0ULC) %s [%x]", spacer, (tagtype & MAGIC)?"":"", tagtype ); + PrintAndLog("%sTYPE : MIFARE Ultralight C (MF0ULC) %s", spacer, (tagtype & MAGIC) ? "" : "" ); else if ( tagtype & UL_EV1_48) PrintAndLog("%sTYPE : MIFARE Ultralight EV1 48bytes (MF0UL1101)", spacer); - else if ( tagtype & UL_EV1_128) + else if ( tagtype & UL_EV1_128) PrintAndLog("%sTYPE : MIFARE Ultralight EV1 128bytes (MF0UL2101)", spacer); else if ( tagtype & NTAG ) PrintAndLog("%sTYPE : NTAG UNKNOWN", spacer); else if ( tagtype & NTAG_203 ) PrintAndLog("%sTYPE : NTAG 203 144bytes (NT2H0301F0DT)", spacer); else if ( tagtype & NTAG_210 ) - PrintAndLog("%sTYPE : NTAG 210 48bytes (NT2L1011G0DU)", spacer); + PrintAndLog("%sTYPE : NTAG 210 48bytes (NT2L1011G0DU)", spacer); else if ( tagtype & NTAG_212 ) PrintAndLog("%sTYPE : NTAG 212 128bytes (NT2L1211G0DU)", spacer); else if ( tagtype & NTAG_213 ) @@ -371,10 +384,10 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ } static int ulc_print_3deskey( uint8_t *data){ - PrintAndLog(" deskey1 [44/0x2C]: %s [%.4s]", sprint_hex(data ,4),data); - PrintAndLog(" deskey1 [45/0x2D]: %s [%.4s]", sprint_hex(data+4 ,4),data+4); - PrintAndLog(" deskey2 [46/0x2E]: %s [%.4s]", sprint_hex(data+8 ,4),data+8); - PrintAndLog(" deskey2 [47/0x2F]: %s [%.4s]", sprint_hex(data+12,4),data+12); + PrintAndLog(" deskey1 [44/0x2C] : %s [%.4s]", sprint_hex(data ,4),data); + PrintAndLog(" deskey1 [45/0x2D] : %s [%.4s]", sprint_hex(data+4 ,4),data+4); + PrintAndLog(" deskey2 [46/0x2E] : %s [%.4s]", sprint_hex(data+8 ,4),data+8); + PrintAndLog(" deskey2 [47/0x2F] : %s [%.4s]", sprint_hex(data+12,4),data+12); PrintAndLog("\n 3des key : %s", sprint_hex(SwapEndian64(data, 16, 8), 16)); return 0; } @@ -382,20 +395,20 @@ static int ulc_print_3deskey( uint8_t *data){ static int ulc_print_configuration( uint8_t *data){ PrintAndLog("--- UL-C Configuration"); - PrintAndLog(" Higher Lockbits [40/0x28]: %s - %s", sprint_hex(data, 4), printBits(2, data)); - PrintAndLog(" Counter [41/0x29]: %s - %s", sprint_hex(data+4, 4), printBits(2, data+4)); + PrintAndLog(" Higher Lockbits [40/0x28] : %s - %s", sprint_hex(data, 4), printBits(2, data)); + PrintAndLog(" Counter [41/0x29] : %s - %s", sprint_hex(data+4, 4), printBits(2, data+4)); bool validAuth = (data[8] >= 0x03 && data[8] <= 0x30); if ( validAuth ) - PrintAndLog(" Auth0 [42/0x2A]: %s page %d/0x%02X and above need authentication", sprint_hex(data+8, 4), data[8], data[8]); + PrintAndLog(" Auth0 [42/0x2A] : %s page %d/0x%02X and above need authentication", sprint_hex(data+8, 4), data[8],data[8] ); else{ if ( data[8] == 0){ - PrintAndLog(" Auth0 [42/0x2A]: %s default", sprint_hex(data+8, 4) ); + PrintAndLog(" Auth0 [42/0x2A] : %s default", sprint_hex(data+8, 4) ); } else { - PrintAndLog(" Auth0 [42/0x2A]: %s auth byte is out-of-range", sprint_hex(data+8, 4) ); + PrintAndLog(" Auth0 [42/0x2A] : %s auth byte is out-of-range", sprint_hex(data+8, 4) ); } } - PrintAndLog(" Auth1 [43/0x2B]: %s %s", + PrintAndLog(" Auth1 [43/0x2B] : %s %s", sprint_hex(data+12, 4), (data[12] & 1) ? "write access restricted": "read and write access restricted" ); @@ -412,22 +425,22 @@ static int ulev1_print_configuration( uint8_t *data){ bool prot = (data[4] & 0x80); uint8_t vctid = data[5]; - PrintAndLog(" cfg0 [16/0x10]: %s", sprint_hex(data, 4)); + PrintAndLog(" cfg0 [16/0x10] : %s", sprint_hex(data, 4)); if ( data[3] < 0xff ) PrintAndLog(" - page %d and above need authentication",data[3]); else PrintAndLog(" - pages don't need authentication"); PrintAndLog(" - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); - PrintAndLog(" cfg1 [17/0x11]: %s", sprint_hex(data+4, 4) ); + PrintAndLog(" cfg1 [17/0x11] : %s", sprint_hex(data+4, 4) ); if ( authlim == 0) PrintAndLog(" - Unlimited password attempts"); else PrintAndLog(" - Max number of password attempts is %d", authlim); PrintAndLog(" - user configuration %s", cfglck ? "permanently locked":"writeable"); PrintAndLog(" - %s access is protected with password", prot ? "read and write":"write"); - PrintAndLog(" %02X - Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); - PrintAndLog(" PWD [18/0x12]: %s", sprint_hex(data+8, 4)); - PrintAndLog(" PACK [19/0x13]: %s", sprint_hex(data+12, 4)); + PrintAndLog(" - %02X, Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); + PrintAndLog(" PWD [18/0x12] : %s", sprint_hex(data+8, 4)); + PrintAndLog(" PACK [19/0x13] : %s", sprint_hex(data+12, 4)); return 0; } @@ -460,10 +473,10 @@ static int ulev1_print_signature( uint8_t *data, uint8_t len){ static int ulev1_print_version(uint8_t *data){ PrintAndLog("\n--- Tag Version"); - PrintAndLog(" Raw bytes : %s", sprint_hex(data, 8) ); - PrintAndLog(" Vendor ID : %02X %s", data[1], getTagInfo(data[1])); + PrintAndLog(" Raw bytes : %s",sprint_hex(data, 8) ); + PrintAndLog(" Vendor ID : %02X, %s", data[1], getTagInfo(data[1])); PrintAndLog(" Product type : %s", getProductTypeStr(data[2])); - PrintAndLog(" Product subtype : %02X %s", data[3], (data[3]==1) ?"17 pF":"50pF"); + PrintAndLog(" Product subtype : %02X, %s", data[3], (data[3]==1) ?"17 pF":"50pF"); PrintAndLog(" Major version : %02X", data[4]); PrintAndLog(" Minor version : %02X", data[5]); PrintAndLog(" Size : %s", getUlev1CardSizeStr(data[6])); @@ -556,7 +569,6 @@ uint32_t GetHF14AMfU_Type(void){ tagtype = NTAG_I2C_1K; else if ( version[2] == 0x04 && version[3] == 0x05 && version[6] == 0x15 ) tagtype = NTAG_I2C_2K; - else if ( version[2] == 0x04 ) tagtype = NTAG; @@ -675,24 +687,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("-------------------------------------------------------------"); ul_print_type(tagtype, 6); - if ( hasAuthKey && (tagtype & UL_C)) { - //will select card automatically and close connection on error - if (!ulc_authentication(authenticationkey, false)) { - PrintAndLog("Error: Authentication Failed UL-C"); - return 0; - } - } else { - if ( !ul_select(&card) ) return 0; - - if (hasAuthKey) { - len = ulev1_requestAuthentication(authenticationkey, pack, sizeof(pack)); - if (len < 1) { - ul_switch_off_field(); - PrintAndLog("Error: Authentication Failed UL-EV1/NTAG"); - return 0; - } - } - } + if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; // read pages 0,1,2,3 (should read 4pages) status = ul_read(0, data, sizeof(data)); @@ -700,11 +695,12 @@ int CmdHF14AMfUInfo(const char *Cmd){ ul_switch_off_field(); PrintAndLog("Error: tag didn't answer to READ"); return status; - } - if (status == 16) { + } else if (status == 16) { ul_print_default(data); ndef_print_CC(data+12); - } else locked = true; + } else { + locked = true; + } // UL_C Specific if ((tagtype & UL_C)) { @@ -748,7 +744,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } } // reselect for future tests (ntag test) - if ( !ul_select(&card) ) return 0; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; } } @@ -758,7 +754,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { if (ulev1_print_counters() != 3) { // failed - re-select - if ( !ul_select(&card) ) return 0; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; } } @@ -773,7 +769,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ if (status == 32) ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); else { // re-select - if ( !ul_select(&card) ) return 0; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; } } @@ -784,9 +780,12 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("Error: tag didn't answer to GETVERSION"); ul_switch_off_field(); return status; + } else if (status == 10) { + ulev1_print_version(version); + } else { + locked = true; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; } - if (status == 10) ulev1_print_version(version); - else locked = true; uint8_t startconfigblock = 0; uint8_t ulev1_conf[16] = {0x00}; @@ -822,7 +821,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); break; } else { - if ( !ul_select(&card) ) return 0; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; } } if (len < 1) PrintAndLog("password not known"); From efd193519c5e4613a16b7a13dd69a9962df0b218 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 21 May 2015 11:17:01 -0400 Subject: [PATCH 063/132] hf mfu bug fixes, and help text fixes --- client/cmdhfmfu.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 7f0e8fc5..b3304f16 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -600,7 +600,7 @@ uint32_t GetHF14AMfU_Type(void){ tagtype = UL; } else { // read page 0x30 (should error if it is a ntag203) - status = ul_read(30, data, sizeof(data)); + status = ul_read(0x30, data, sizeof(data)); if ( status <= 1 ){ tagtype = NTAG_203; } else { @@ -679,7 +679,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ //Validations if(errors) return usage_hf_mfu_info(); - + TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -698,7 +698,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } else if (status == 16) { ul_print_default(data); ndef_print_CC(data+12); - } else { + } else { locked = true; } @@ -740,11 +740,10 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t keySwap[16]; memcpy(keySwap, SwapEndian64(key,16,8), 16); ulc_print_3deskey(keySwap); - break; + return 1; } } - // reselect for future tests (ntag test) - if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; + return 1; } } @@ -950,8 +949,8 @@ int usage_hf_mfu_info(void) PrintAndLog("It gathers information about the tag and tries to detect what kind it is."); PrintAndLog("Sometimes the tags are locked down, and you may need a key to be able to read the information"); PrintAndLog("The following tags can be identified:\n"); - PrintAndLog("Ultralight, Ultralight-C, Ultralight EV1"); - PrintAndLog("NTAG 213, NTAG 215, NTAG 216"); + PrintAndLog("Ultralight, Ultralight-C, Ultralight EV1, NTAG 203, NTAG 210,"); + PrintAndLog("NTAG 212, NTAG 213, NTAG 215, NTAG 216, NTAG I2C 1K & 2K"); PrintAndLog("my-d, my-d NFC, my-d move, my-d move NFC\n"); PrintAndLog("Usage: hf mfu info k "); PrintAndLog(" Options : "); @@ -965,6 +964,7 @@ int usage_hf_mfu_info(void) int usage_hf_mfu_dump(void) { PrintAndLog("Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); + PrintAndLog("NTAG 203, NTAG 210, NTAG 212, NTAG 213, NTAG 215, NTAG 216"); PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("It autodetects card type.\n"); PrintAndLog("Usage: hf mfu dump l k n "); From 06561c34efdb6c0aaaf1008cca3ac8cb82065df9 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 22 May 2015 00:15:57 -0400 Subject: [PATCH 064/132] fix to dump cmd print keys. add l option to info cmd. add ascii print to dump (screen only) other minor clean up --- client/cmdhfmfu.c | 135 ++++++++++++++++++++++++---------------------- 1 file changed, 70 insertions(+), 65 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index b3304f16..c5f061b1 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -94,9 +94,9 @@ char *getUlev1CardSizeStr( uint8_t fsize ){ // is LSB set? if ( fsize & 1 ) - sprintf(retStr, "%02X (%u <-> %u bytes)",fsize, usize, lsize); + sprintf(retStr, "%02X, (%u <-> %u bytes)",fsize, usize, lsize); else - sprintf(retStr, "%02X (%u bytes)", fsize, lsize); + sprintf(retStr, "%02X, (%u bytes)", fsize, lsize); return buf; } @@ -462,7 +462,7 @@ static int ulev1_print_counters(){ static int ulev1_print_signature( uint8_t *data, uint8_t len){ PrintAndLog("\n--- Tag Signature"); - PrintAndLog("IC signature public key name : NXP NTAG21x 2013"); // don't know if there is other NXP public keys.. :( + //PrintAndLog("IC signature public key name : NXP NTAG21x 2013"); // don't know if there is other NXP public keys.. :( PrintAndLog("IC signature public key value : 04494e1a386d3d3cfe3dc10e5de68a499b1c202db5b132393e89ed19fe5be8bc61"); PrintAndLog(" Elliptic curve parameters : secp128r1"); PrintAndLog(" Tag ECC Signature : %s", sprint_hex(data, len)); @@ -620,7 +620,6 @@ uint32_t GetHF14AMfU_Type(void){ } } - tagtype |= ul_magic_test(); if (tagtype == (UNKNOWN | MAGIC)) tagtype = (UL_MAGIC); return tagtype; @@ -631,16 +630,19 @@ int CmdHF14AMfUInfo(const char *Cmd){ uint8_t authlim = 0xff; uint8_t data[16] = {0x00}; iso14a_card_select_t card; - uint8_t *key; int status; bool errors = false; bool hasAuthKey = false; bool locked = false; + bool swapEndian = false; uint8_t cmdp = 0; - uint8_t datalen = 0; + uint8_t dataLen = 0; uint8_t authenticationkey[16] = {0x00}; + uint8_t *authkeyptr = authenticationkey; + uint8_t *key; uint8_t pack[4] = {0,0,0,0}; - int len=0; + int len = 0; + char tempStr[50]; while(param_getchar(Cmd, cmdp) != 0x00) { @@ -651,23 +653,21 @@ int CmdHF14AMfUInfo(const char *Cmd){ return usage_hf_mfu_info(); case 'k': case 'K': - // EV1/NTAG size key - datalen = param_gethex(Cmd, cmdp+1, data, 8); - if ( !datalen ) { - memcpy(authenticationkey, data, 4); - cmdp += 2; - hasAuthKey = true; - break; + dataLen = param_getstr(Cmd, cmdp+1, tempStr); + if (dataLen == 32 || dataLen == 8) { //ul-c or ev1/ntag key length + errors = param_gethex(tempStr, 0, authenticationkey, dataLen); + dataLen /= 2; // handled as bytes from now on + } else { + PrintAndLog("\nERROR: Key is incorrect length\n"); + errors = true; } - // UL-C size key - datalen = param_gethex(Cmd, cmdp+1, data, 32); - if (!datalen){ - memcpy(authenticationkey, data, 16); - cmdp += 2; - hasAuthKey = true; - break; - } - errors = true; + cmdp += 2; + hasAuthKey = true; + break; + case 'l': + case 'L': + swapEndian = true; + cmdp++; break; default: PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); @@ -687,7 +687,10 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("-------------------------------------------------------------"); ul_print_type(tagtype, 6); - if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; + // 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; // read pages 0,1,2,3 (should read 4pages) status = ul_read(0, data, sizeof(data)); @@ -732,6 +735,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ // if we called info with key, just return if ( hasAuthKey ) return 1; + // also try to diversify default keys.. look into CmdHF14AMfuGenDiverseKeys PrintAndLog("Trying some default 3des keys"); for (uint8_t i = 0; i < KEYS_3DES_COUNT; ++i ) { key = default_3des_keys[i]; @@ -944,33 +948,33 @@ int CmdHF14AMfURdBl(const char *Cmd){ return 0; } -int usage_hf_mfu_info(void) -{ +int usage_hf_mfu_info(void) { PrintAndLog("It gathers information about the tag and tries to detect what kind it is."); PrintAndLog("Sometimes the tags are locked down, and you may need a key to be able to read the information"); PrintAndLog("The following tags can be identified:\n"); PrintAndLog("Ultralight, Ultralight-C, Ultralight EV1, NTAG 203, NTAG 210,"); PrintAndLog("NTAG 212, NTAG 213, NTAG 215, NTAG 216, NTAG I2C 1K & 2K"); PrintAndLog("my-d, my-d NFC, my-d move, my-d move NFC\n"); - PrintAndLog("Usage: hf mfu info k "); + PrintAndLog("Usage: hf mfu info k l"); PrintAndLog(" Options : "); - PrintAndLog(" k : key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(" k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(" l : (optional) swap entered key's endianness"); PrintAndLog(""); PrintAndLog(" sample : hf mfu info"); - PrintAndLog(" : hf mfu info k 11223344"); + PrintAndLog(" : hf mfu info k 00112233445566778899AABBCCDDEEFF"); + PrintAndLog(" : hf mfu info k AABBCCDDD"); return 0; } -int usage_hf_mfu_dump(void) -{ +int usage_hf_mfu_dump(void) { PrintAndLog("Reads all pages from Ultralight, Ultralight-C, Ultralight EV1"); PrintAndLog("NTAG 203, NTAG 210, NTAG 212, NTAG 213, NTAG 215, NTAG 216"); PrintAndLog("and saves binary dump into the file `filename.bin` or `cardUID.bin`"); PrintAndLog("It autodetects card type.\n"); - PrintAndLog("Usage: hf mfu dump l k n "); + PrintAndLog("Usage: hf mfu dump k l n "); PrintAndLog(" Options : "); - PrintAndLog(" k : key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); - PrintAndLog(" l : swap entered key's endianness for auth"); + PrintAndLog(" k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(" l : (optional) swap entered key's endianness"); PrintAndLog(" n : filename w/o .bin to save the dump as"); PrintAndLog(" p : starting Page number to manually set a page to start the dump at"); PrintAndLog(" q : number of Pages to manually set how many pages to dump"); @@ -979,6 +983,7 @@ int usage_hf_mfu_dump(void) PrintAndLog(" sample : hf mfu dump"); PrintAndLog(" : hf mfu dump n myfile"); PrintAndLog(" : hf mfu dump k 00112233445566778899AABBCCDDEEFF"); + PrintAndLog(" : hf mfu dump k AABBCCDDD\n"); return 0; } @@ -997,14 +1002,14 @@ int CmdHF14AMfUDump(const char *Cmd){ bool bit[16] = {0x00}; bool bit2[16] = {0x00}; uint8_t data[1024] = {0x00}; - bool hasPwd = false; + bool hasAuthKey = false; int i = 0; int Pages = 16; bool tmplockbit = false; - uint8_t dataLen=0; - uint8_t cmdp =0; - uint8_t key[16] = {0x00}; - uint8_t *keyPtr = key; + uint8_t dataLen = 0; + uint8_t cmdp = 0; + uint8_t authenticationkey[16] = {0x00}; + uint8_t *authKeyPtr = authenticationkey; size_t fileNlen = 0; bool errors = false; bool swapEndian = false; @@ -1022,17 +1027,15 @@ int CmdHF14AMfUDump(const char *Cmd){ case 'k': case 'K': dataLen = param_getstr(Cmd, cmdp+1, tempStr); - if (dataLen == 32) //ul-c - errors = param_gethex(tempStr, 0, key, dataLen); - else if (dataLen == 8) //ev1/ntag - errors = param_gethex(tempStr, 0, key, dataLen); - else{ + if (dataLen == 32 || dataLen == 8) { //ul-c or ev1/ntag key length + errors = param_gethex(tempStr, 0, authenticationkey, dataLen); + dataLen /= 2; + } else { PrintAndLog("\nERROR: Key is incorrect length\n"); errors = true; } - cmdp += 2; - hasPwd = true; + hasAuthKey = true; break; case 'l': case 'L': @@ -1069,8 +1072,8 @@ int CmdHF14AMfUDump(const char *Cmd){ //Validations if(errors) return usage_hf_mfu_dump(); - if (swapEndian && dataLen == 32) - keyPtr = SwapEndian64(data, 16, 8); + if (swapEndian && hasAuthKey) + authKeyPtr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4); TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; @@ -1083,13 +1086,13 @@ int CmdHF14AMfUDump(const char *Cmd){ ul_print_type(tagtype, 0); PrintAndLog("Reading tag memory..."); UsbCommand c = {CMD_MIFAREU_READCARD, {startPage,Pages}}; - if ( hasPwd ) { + if ( hasAuthKey ) { if (tagtype & UL_C) c.arg[2] = 1; //UL_C auth else c.arg[2] = 2; //UL_EV1/NTAG auth - memcpy(c.d.asBytes, key, dataLen/2); + memcpy(c.d.asBytes, authKeyPtr, dataLen); } SendCommand(&c); UsbCommand resp; @@ -1133,12 +1136,14 @@ int CmdHF14AMfUDump(const char *Cmd){ } // add keys to block dump - if (hasPwd && (tagtype & UL_C)) { //UL_C - memcpy(data + Pages*4, key, dataLen/2); - Pages += 4; - } else if (hasPwd) { //not sure output is in correct location. - memcpy(data + Pages*4, key, dataLen/2); - Pages += 1; + if (hasAuthKey) { + if (!swapEndian) { + authKeyPtr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4); + memcpy(data + Pages*4, authKeyPtr, dataLen); + } else { + memcpy(data + Pages*4, authenticationkey, dataLen); + } + Pages += dataLen/4; //not sure output is in correct location for all tag types. } for (i = 0; i < Pages; ++i) { @@ -1148,11 +1153,11 @@ int CmdHF14AMfUDump(const char *Cmd){ } switch(i){ case 3: tmplockbit = bit[4]; break; - case 4: tmplockbit = bit[3]; break; - case 5: tmplockbit = bit[2]; break; - case 6: tmplockbit = bit[1]; break; - case 7: tmplockbit = bit[0]; break; - case 8: tmplockbit = bit[15]; break; + case 4: tmplockbit = bit[3]; break; + case 5: tmplockbit = bit[2]; break; + case 6: tmplockbit = bit[1]; break; + case 7: tmplockbit = bit[0]; break; + case 8: tmplockbit = bit[15]; break; case 9: tmplockbit = bit[14]; break; case 10: tmplockbit = bit[13]; break; case 11: tmplockbit = bit[12]; break; @@ -1171,7 +1176,7 @@ int CmdHF14AMfUDump(const char *Cmd){ case 24: case 25: case 26: - case 27: tmplockbit = bit2[4]; break; + case 27: tmplockbit = bit2[4]; break; case 28: case 29: case 30: @@ -1190,8 +1195,8 @@ int CmdHF14AMfUDump(const char *Cmd){ case 43: tmplockbit = bit2[9]; break; //auth1 default: break; } - PrintAndLog("Block %02x:%s [%d]", i,sprint_hex(data + i * 4, 4),tmplockbit); - } + PrintAndLog("Block %02x:%s [%d] {%.4s}", i, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); + } // user supplied filename? if (fileNlen < 1) { @@ -1204,7 +1209,7 @@ int CmdHF14AMfUDump(const char *Cmd){ if ((fout = fopen(filename,"wb")) == NULL) { PrintAndLog("Could not create file name %s", filename); - return 1; + return 1; } fwrite( data, 1, Pages*4, fout ); fclose(fout); From 8f2e50b4c5aad09db70f82bbf6b865e283ad5e5e Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 22 May 2015 07:29:18 -0400 Subject: [PATCH 065/132] mfu info authkeyptr fix didn't follow @iceman1001 s l parameter changes fully... fixed now.. :) --- client/cmdhfmfu.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index c5f061b1..dbe4a754 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -757,7 +757,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ if ((tagtype & (UL_EV1_48 | UL_EV1_128))) { if (ulev1_print_counters() != 3) { // failed - re-select - if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } } @@ -772,7 +772,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ if (status == 32) ulev1_print_signature( ulev1_signature, sizeof(ulev1_signature)); else { // re-select - if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } } @@ -787,7 +787,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ ulev1_print_version(version); } else { locked = true; - if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } uint8_t startconfigblock = 0; @@ -824,7 +824,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ PrintAndLog("Found a default password: %s || Pack: %02X %02X",sprint_hex(key, 4), pack[0], pack[1]); break; } else { - if (!ul_auth_select( &card, tagtype, hasAuthKey, authenticationkey, pack, sizeof(pack))) return -1; + if (!ul_auth_select( &card, tagtype, hasAuthKey, authkeyptr, pack, sizeof(pack))) return -1; } } if (len < 1) PrintAndLog("password not known"); From 012c0761bd69ac3bba5e89ae4347c5e16aa81701 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 22 May 2015 13:17:51 -0400 Subject: [PATCH 066/132] hf mfu minor output adjustments dump key placed properly for EV1 and NTAGs config pages for ntags corrected in printout note on config that PWD and PACK cannot actually be read from memory (probably could just delete them (other than it shows what memory block they are stored in for changing...) --- client/cmdhfmfu.c | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index dbe4a754..07c379bc 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -415,7 +415,7 @@ static int ulc_print_configuration( uint8_t *data){ return 0; } -static int ulev1_print_configuration( uint8_t *data){ +static int ulev1_print_configuration( uint8_t *data, uint8_t startPage){ PrintAndLog("\n--- Tag Configuration"); @@ -425,13 +425,13 @@ static int ulev1_print_configuration( uint8_t *data){ bool prot = (data[4] & 0x80); uint8_t vctid = data[5]; - PrintAndLog(" cfg0 [16/0x10] : %s", sprint_hex(data, 4)); + PrintAndLog(" cfg0 [%u/0x%02X] : %s", startPage, startPage, sprint_hex(data, 4)); if ( data[3] < 0xff ) PrintAndLog(" - page %d and above need authentication",data[3]); else PrintAndLog(" - pages don't need authentication"); PrintAndLog(" - strong modulation mode %s", (strg_mod_en) ? "enabled":"disabled"); - PrintAndLog(" cfg1 [17/0x11] : %s", sprint_hex(data+4, 4) ); + PrintAndLog(" cfg1 [%u/0x%02X] : %s", startPage + 1, startPage + 1, sprint_hex(data+4, 4) ); if ( authlim == 0) PrintAndLog(" - Unlimited password attempts"); else @@ -439,8 +439,9 @@ static int ulev1_print_configuration( uint8_t *data){ PrintAndLog(" - user configuration %s", cfglck ? "permanently locked":"writeable"); PrintAndLog(" - %s access is protected with password", prot ? "read and write":"write"); PrintAndLog(" - %02X, Virtual Card Type Identifier is %s default", vctid, (vctid==0x05)? "":"not"); - PrintAndLog(" PWD [18/0x12] : %s", sprint_hex(data+8, 4)); - PrintAndLog(" PACK [19/0x13] : %s", sprint_hex(data+12, 4)); + PrintAndLog(" PWD [%u/0x%02X] : %s- (cannot be read)", startPage + 2, startPage + 2, sprint_hex(data+8, 4)); + PrintAndLog(" PACK [%u/0x%02X] : %s - (cannot be read)", startPage + 3, startPage + 3, sprint_hex(data+12, 2)); + PrintAndLog(" RFU [%u/0x%02X] : %s- (cannot be read)", startPage + 3, startPage + 3, sprint_hex(data+12, 2)); return 0; } @@ -806,7 +807,7 @@ int CmdHF14AMfUInfo(const char *Cmd){ } else if (status == 16) { // save AUTHENTICATION LIMITS for later: authlim = (ulev1_conf[4] & 0x07); - ulev1_print_configuration(ulev1_conf); + ulev1_print_configuration(ulev1_conf, startconfigblock); } } @@ -1137,13 +1138,18 @@ int CmdHF14AMfUDump(const char *Cmd){ // add keys to block dump if (hasAuthKey) { - if (!swapEndian) { + if (!swapEndian){ authKeyPtr = SwapEndian64(authenticationkey, dataLen, (dataLen == 16) ? 8 : 4); - memcpy(data + Pages*4, authKeyPtr, dataLen); } else { - memcpy(data + Pages*4, authenticationkey, dataLen); + authKeyPtr = authenticationkey; + } + + if (tagtype & UL_C){ //add 4 pages + memcpy(data + Pages*4, authKeyPtr, dataLen); + Pages += dataLen/4; + } else { // 2nd page from end + memcpy(data + (Pages*4) - 8, authenticationkey, dataLen); } - Pages += dataLen/4; //not sure output is in correct location for all tag types. } for (i = 0; i < Pages; ++i) { @@ -1195,7 +1201,7 @@ int CmdHF14AMfUDump(const char *Cmd){ case 43: tmplockbit = bit2[9]; break; //auth1 default: break; } - PrintAndLog("Block %02x:%s [%d] {%.4s}", i, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); + PrintAndLog("Block %02X:%s [%d] {%.4s}", i, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); } // user supplied filename? From 0ce03d9ab0084cd34f483b24e97ef0a92b11284b Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 23 May 2015 22:35:50 -0400 Subject: [PATCH 067/132] fix mfu dump getbigbuffer bug Thanks @iceman1001 for catching my oops, and fixing it :) --- armsrc/mifarecmd.c | 2 +- client/cmdhfmfu.c | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 0586a25d..8355cd19 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -335,7 +335,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks); countblocks *= 4; - cmd_send(CMD_ACK, 1, countblocks, countblocks, 0, 0); + cmd_send(CMD_ACK, 1, countblocks, BigBuf_max_traceLen(), 0, 0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 07c379bc..19103298 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -1106,12 +1106,13 @@ int CmdHF14AMfUDump(const char *Cmd){ return 1; } + uint32_t startindex = resp.arg[2]; uint32_t bufferSize = resp.arg[1]; if (bufferSize > sizeof(data)) { PrintAndLog("Data exceeded Buffer size!"); bufferSize = sizeof(data); } - GetFromBigBuf(data, bufferSize, 0); + GetFromBigBuf(data, bufferSize, startindex); WaitForResponse(CMD_ACK,NULL); Pages = bufferSize/4; From 0b14440dce5d879fed70afb455b1f7c56ee85b1e Mon Sep 17 00:00:00 2001 From: Pierre LALET Date: Sun, 24 May 2015 20:14:22 +0200 Subject: [PATCH 068/132] Fix filenames for hf mf esave / eload --- client/cmdhfmf.c | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index aa3b66dc..407f34a0 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -1200,9 +1200,9 @@ int CmdHF14AMfELoad(const char *Cmd) len = param_getstr(Cmd,nameParamNo,filename); - if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; + if (len > FILE_PATH_SIZE - 4) len = FILE_PATH_SIZE - 4; - fnameptr += len-4; + fnameptr += len; sprintf(fnameptr, ".eml"); @@ -1299,19 +1299,22 @@ int CmdHF14AMfESave(const char *Cmd) len = param_getstr(Cmd,nameParamNo,filename); - if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; + if (len > FILE_PATH_SIZE - 4) len = FILE_PATH_SIZE - 4; // user supplied filename? if (len < 1) { // get filename (UID from memory) if (mfEmlGetMem(buf, 0, 1)) { PrintAndLog("Can\'t get UID from block: %d", 0); - sprintf(filename, "dump.eml"); + len = sprintf(fnameptr, "dump"); + fnameptr += len; + } + else { + for (j = 0; j < 7; j++, fnameptr += 2) + sprintf(fnameptr, "%02X", buf[j]); } - for (j = 0; j < 7; j++, fnameptr += 2) - sprintf(fnameptr, "%02X", buf[j]); } else { - fnameptr += len-4; + fnameptr += len; } // add file extension From 292fe7253596b98901fd8162bab82dd1ba394237 Mon Sep 17 00:00:00 2001 From: Pierre LALET Date: Sun, 24 May 2015 22:43:08 +0200 Subject: [PATCH 069/132] Fix filenames for hf mf cload / csave --- client/cmdhfmf.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 407f34a0..2b5a5b87 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -1575,10 +1575,10 @@ int CmdHF14AMfCLoad(const char *Cmd) return 0; } else { len = strlen(Cmd); - if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; + if (len > FILE_PATH_SIZE - 4) len = FILE_PATH_SIZE - 4; memcpy(filename, Cmd, len); - fnameptr += len-4; + fnameptr += len; sprintf(fnameptr, ".eml"); @@ -1744,7 +1744,7 @@ int CmdHF14AMfCSave(const char *Cmd) { return 0; } else { len = strlen(Cmd); - if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE; + if (len > FILE_PATH_SIZE - 4) len = FILE_PATH_SIZE - 4; if (len < 1) { // get filename From 79d7bcbb51db25dab899b3b250f48a0ab40e30e9 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 24 May 2015 22:28:21 -0400 Subject: [PATCH 070/132] updated mfu rdbl and wrbl commands @iceman1001 s rdbl and wrbl cmd updates. dump screen output adjusted --- armsrc/appmain.c | 2 +- armsrc/apps.h | 2 +- armsrc/mifarecmd.c | 45 ++++- client/cmdhfmfu.c | 494 ++++++++++++++++++++++++--------------------- client/cmdhfmfu.h | 7 +- 5 files changed, 307 insertions(+), 243 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 96644b9a..f8594fcc 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -845,7 +845,7 @@ void UsbPacketReceived(uint8_t *packet, int len) MifareUWriteBlock(c->arg[0], c->d.asBytes); break; case CMD_MIFAREU_WRITEBL: - MifareUWriteBlock_Special(c->arg[0], c->d.asBytes); + MifareUWriteBlock_Special(c->arg[0], c->arg[1], c->d.asBytes); break; case CMD_MIFARE_NESTED: MifareNested(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); diff --git a/armsrc/apps.h b/armsrc/apps.h index 57fb55fd..dfd1fe52 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -171,7 +171,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareUWriteBlock(uint8_t arg0,uint8_t *datain); -void MifareUWriteBlock_Special(uint8_t arg0,uint8_t *datain); +void MifareUWriteBlock_Special(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 8355cd19..2a21ac48 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -16,7 +16,6 @@ #include "mifarecmd.h" #include "apps.h" #include "util.h" - #include "crc.h" // the block number for the ISO14443-4 PCB @@ -24,7 +23,6 @@ uint8_t pcb_blocknum = 0; // Deselect card by sending a s-block. the crc is precalced for speed static uint8_t deselect_cmd[] = {0xc2,0xe0,0xb4}; - //----------------------------------------------------------------------------- // Select, Authenticate, Read a MIFARE tag. // read block @@ -248,6 +246,10 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } +// arg0 = blockNo (start) +// arg1 = Pages (number of blocks) +// arg2 = useKey +// datain = KEY bytes void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { // free eventually allocated BigBuf memory @@ -335,6 +337,13 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks); countblocks *= 4; +/* + LED_B_ON(); + for(size_t i=0; i < countblocks; i += USB_CMD_DATA_SIZE) { + size_t len = MIN((countblocks - i),USB_CMD_DATA_SIZE); + cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K,i,len,countblocks,dataout+i,len); + } +*/ cmd_send(CMD_ACK, 1, countblocks, BigBuf_max_traceLen(), 0, 0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); @@ -450,9 +459,17 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) LEDsoff(); } -void MifareUWriteBlock_Special(uint8_t arg0, uint8_t *datain) +// Arg0 : Block to write to. +// Arg1 : 0 = use no authentication. +// 1 = use 0x1A authentication. +// 2 = use 0x1B authentication. +// datain : 4 first bytes is data to be written. +// : 4/16 next bytes is authentication key. +void MifareUWriteBlock_Special(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; + bool useKey = (arg1 == 1); //UL_C + bool usePwd = (arg1 == 2); //UL_EV1/NTAG byte_t blockdata[4] = {0x00}; memcpy(blockdata, datain,4); @@ -468,6 +485,28 @@ void MifareUWriteBlock_Special(uint8_t arg0, uint8_t *datain) return; }; + // UL-C authentication + if ( useKey ) { + uint8_t key[16] = {0x00}; + memcpy(key, datain+4, sizeof(key) ); + + if ( !mifare_ultra_auth(key) ) { + OnError(1); + return; + } + } + + // UL-EV1 / NTAG authentication + 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; + } + } + if(mifare_ultra_special_writeblock(blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(0); diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 19103298..057708ca 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -279,7 +279,7 @@ static int ul_print_default( uint8_t *data){ uid[6] = data[7]; PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); - PrintAndLog(" UID[0] : %02X, Manufacturer: %s", uid[0], getTagInfo(uid[0]) ); + PrintAndLog(" UID[0] : %02X, %s", uid[0], getTagInfo(uid[0]) ); if ( uid[0] == 0x05 ) { uint8_t chip = (data[8] & 0xC7); // 11000111 mask, bit 3,4,5 RFU switch (chip){ @@ -839,105 +839,239 @@ int CmdHF14AMfUInfo(const char *Cmd){ } // -// Mifare Ultralight Write Single Block +// Write Single Block // int CmdHF14AMfUWrBl(const char *Cmd){ - uint8_t blockNo = -1; - bool chinese_card = FALSE; - uint8_t bldata[16] = {0x00}; + + int blockNo = -1; + bool errors = false; + bool hasAuthKey = false; + bool hasPwdKey = false; + bool swapEndian = false; + + uint8_t cmdp = 0; + uint8_t keylen = 0; + uint8_t blockdata[20] = {0x00}; + uint8_t data[16] = {0x00}; + uint8_t authenticationkey[16] = {0x00}; + uint8_t *authKeyPtr = authenticationkey; + + // starting with getting tagtype + TagTypeUL_t tagtype = GetHF14AMfU_Type(); + if (tagtype == UL_ERROR) return -1; + + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_mfu_wrbl(); + case 'k': + case 'K': + // EV1/NTAG size key + keylen = param_gethex(Cmd, cmdp+1, data, 8); + if ( !keylen ) { + memcpy(authenticationkey, data, 4); + cmdp += 2; + hasPwdKey = true; + break; + } + // UL-C size key + keylen = param_gethex(Cmd, cmdp+1, data, 32); + if (!keylen){ + memcpy(authenticationkey, data, 16); + cmdp += 2; + hasAuthKey = true; + break; + } + PrintAndLog("\nERROR: Key is incorrect length\n"); + errors = true; + break; + case 'b': + case 'B': + blockNo = param_get8(Cmd, cmdp+1); + + uint8_t maxblockno = 0; + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++){ + if (tagtype & UL_TYPES_ARRAY[idx]) + maxblockno = UL_MEMORY_ARRAY[idx]; + } + + if (blockNo < 0) { + PrintAndLog("Wrong block number"); + errors = true; + } + if (blockNo > maxblockno){ + PrintAndLog("block number too large. Max block is %u/0x%02X \n", maxblockno,maxblockno); + errors = true; + } + cmdp += 2; + break; + case 'l': + case 'L': + swapEndian = true; + cmdp++; + break; + case 'd': + case 'D': + if ( param_gethex(Cmd, cmdp+1, blockdata, 8) ) { + PrintAndLog("Block data must include 8 HEX symbols"); + errors = true; + break; + } + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + //Validations + if(errors) return usage_hf_mfu_wrbl(); + } + + if ( blockNo == -1 ) return usage_hf_mfu_wrbl(); + + // Swap endianness + if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, 16, 8); + if (swapEndian && hasPwdKey) authKeyPtr = SwapEndian64(authenticationkey, 4, 4); + + if ( blockNo <= 3) + PrintAndLog("Special Block: %0d (0x%02X) [ %s]", blockNo, blockNo, sprint_hex(blockdata, 4)); + else + PrintAndLog("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); + + if ( hasAuthKey ) { + c.arg[1] = 1; + memcpy(c.d.asBytes+4,authKeyPtr,16); + } + else if ( hasPwdKey ) { + c.arg[1] = 2; + memcpy(c.d.asBytes+4,authKeyPtr,4); + } + + SendCommand(&c); UsbCommand resp; - - char cmdp = param_getchar(Cmd, 0); - if (strlen(Cmd) < 3 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: hf mfu wrbl [w]"); - PrintAndLog(" [block number]"); - PrintAndLog(" [block data] - (8 hex symbols)"); - PrintAndLog(" [w] - Chinese magic ultralight tag"); - PrintAndLog(""); - PrintAndLog(" sample: hf mfu wrbl 0 01020304"); - PrintAndLog(""); - return 0; - } - - blockNo = param_get8(Cmd, 0); - - if (blockNo > MAX_UL_BLOCKS){ - PrintAndLog("Error: Maximum number of blocks is 15 for Ultralight Cards!"); - return 1; - } - - if (param_gethex(Cmd, 1, bldata, 8)) { - PrintAndLog("Block data must include 8 HEX symbols"); - return 1; - } - - if (strchr(Cmd,'w') != 0 || strchr(Cmd,'W') != 0 ) { - chinese_card = TRUE; - } - - if ( blockNo <= 3) { - if (!chinese_card){ - PrintAndLog("Access Denied"); - } else { - PrintAndLog("--specialblock no:%02x", blockNo); - PrintAndLog("--data: %s", sprint_hex(bldata, 4)); - UsbCommand d = {CMD_MIFAREU_WRITEBL, {blockNo}}; - memcpy(d.d.asBytes,bldata, 4); - SendCommand(&d); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - PrintAndLog("isOk:%02x", isOK); - } else { - PrintAndLog("Command execute timeout"); - } - } + if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { + uint8_t isOK = resp.arg[0] & 0xff; + PrintAndLog("isOk:%02x", isOK); } else { - PrintAndLog("--block no:%02x", blockNo); - PrintAndLog("--data: %s", sprint_hex(bldata, 4)); - UsbCommand e = {CMD_MIFAREU_WRITEBL, {blockNo}}; - memcpy(e.d.asBytes,bldata, 4); - SendCommand(&e); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - PrintAndLog("isOk:%02x", isOK); - } else { - PrintAndLog("Command execute timeout"); - } + PrintAndLog("Command execute timeout"); } + return 0; } - // -// Mifare Ultralight Read Single Block +// Read Single Block // int CmdHF14AMfURdBl(const char *Cmd){ - UsbCommand resp; - uint8_t blockNo = -1; - char cmdp = param_getchar(Cmd, 0); - - if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: hf mfu rdbl "); - PrintAndLog(" sample: hfu mfu rdbl 0"); - return 0; + int blockNo = -1; + bool errors = false; + bool hasAuthKey = false; + bool hasPwdKey = false; + bool swapEndian = false; + uint8_t cmdp = 0; + uint8_t keylen = 0; + uint8_t data[16] = {0x00}; + uint8_t authenticationkey[16] = {0x00}; + uint8_t *authKeyPtr = authenticationkey; + + // starting with getting tagtype + TagTypeUL_t tagtype = GetHF14AMfU_Type(); + if (tagtype == UL_ERROR) return -1; + + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_hf_mfu_rdbl(); + case 'k': + case 'K': + // EV1/NTAG size key + keylen = param_gethex(Cmd, cmdp+1, data, 8); + if ( !keylen ) { + memcpy(authenticationkey, data, 4); + cmdp += 2; + hasPwdKey = true; + break; + } + // UL-C size key + keylen = param_gethex(Cmd, cmdp+1, data, 32); + if (!keylen){ + memcpy(authenticationkey, data, 16); + cmdp += 2; + hasAuthKey = true; + break; + } + PrintAndLog("\nERROR: Key is incorrect length\n"); + errors = true; + break; + case 'b': + case 'B': + blockNo = param_get8(Cmd, cmdp+1); + + uint8_t maxblockno = 0; + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++){ + if (tagtype & UL_TYPES_ARRAY[idx]) + maxblockno = UL_MEMORY_ARRAY[idx]; + } + + if (blockNo < 0) { + PrintAndLog("Wrong block number"); + errors = true; + } + if (blockNo > maxblockno){ + PrintAndLog("block number to large. Max block is %u/0x%02X \n", maxblockno,maxblockno); + errors = true; + } + cmdp += 2; + break; + case 'l': + case 'L': + swapEndian = true; + cmdp++; + break; + default: + PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + //Validations + if(errors) return usage_hf_mfu_rdbl(); } - blockNo = param_get8(Cmd, 0); + if ( blockNo == -1 ) return usage_hf_mfu_rdbl(); - if (blockNo > MAX_UL_BLOCKS){ - PrintAndLog("Error: Maximum number of blocks is 15 for Ultralight"); - return 1; - } + // 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 ){ + c.arg[1] = 1; + memcpy(c.d.asBytes,authKeyPtr,16); + } + else if ( hasPwdKey ) { + c.arg[1] = 2; + memcpy(c.d.asBytes,authKeyPtr,4); + } + SendCommand(&c); - - + UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; if (isOK) { uint8_t *data = resp.d.asBytes; - PrintAndLog("Block: %0d (0x%02X) [ %s]", (int)blockNo, blockNo, sprint_hex(data, 4)); + PrintAndLog("Block: %0d (0x%02X) [ %s]", blockNo, blockNo, sprint_hex(data, 4)); } else { PrintAndLog("Failed reading block: (%02x)", isOK); @@ -945,7 +1079,6 @@ int CmdHF14AMfURdBl(const char *Cmd){ } else { PrintAndLog("Command execute time-out"); } - return 0; } @@ -988,6 +1121,34 @@ int usage_hf_mfu_dump(void) { return 0; } +int usage_hf_mfu_rdbl(void) { + PrintAndLog("Read a block and print. It autodetects card type.\n"); + PrintAndLog("Usage: hf mfu rdbl b k l\n"); + PrintAndLog(" Options:"); + PrintAndLog(" b : block to read"); + PrintAndLog(" k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(" l : (optional) swap entered key's endianness"); + PrintAndLog(""); + PrintAndLog(" sample : hf mfu rdbl b 0"); + PrintAndLog(" : hf mfu rdbl b 0 k 00112233445566778899AABBCCDDEEFF"); + PrintAndLog(" : hf mfu rdbl b 0 k AABBCCDDD\n"); + return 0; +} + +int usage_hf_mfu_wrbl(void) { + PrintAndLog("Write a block. It autodetects card type.\n"); + PrintAndLog("Usage: hf mfu wrbl b d k l\n"); + PrintAndLog(" Options:"); + PrintAndLog(" b : block to write"); + PrintAndLog(" d : block data - (8 hex symbols)"); + PrintAndLog(" k : (optional) key for authentication [UL-C 16bytes, EV1/NTAG 4bytes]"); + PrintAndLog(" l : (optional) swap entered key's endianness"); + PrintAndLog(""); + PrintAndLog(" sample : hf mfu wrbl b 0 d 01234567"); + PrintAndLog(" : hf mfu wrbl b 0 d 01234567 k AABBCCDDD\n"); + return 0; +} + // // Mifare Ultralight / Ultralight-C / Ultralight-EV1 // Read and Dump Card Contents, using auto detection of tag size. @@ -1079,10 +1240,10 @@ int CmdHF14AMfUDump(const char *Cmd){ TagTypeUL_t tagtype = GetHF14AMfU_Type(); if (tagtype == UL_ERROR) return -1; - if (!manualPages) + if (!manualPages) //get number of pages to read for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++) if (tagtype & UL_TYPES_ARRAY[idx]) - Pages = UL_MEMORY_ARRAY[idx]+1; + Pages = UL_MEMORY_ARRAY[idx]+1; //add one as maxblks starts at 0 ul_print_type(tagtype, 0); PrintAndLog("Reading tag memory..."); @@ -1153,9 +1314,11 @@ int CmdHF14AMfUDump(const char *Cmd){ } } + PrintAndLog("Block# | Data |lck| Ascii"); + PrintAndLog("---------------------------------"); for (i = 0; i < Pages; ++i) { if ( i < 3 ) { - PrintAndLog("Block %02x:%s ", i,sprint_hex(data + i * 4, 4)); + PrintAndLog("%02d/0x%02X | %s | | ", i, i, sprint_hex(data + i * 4, 4)); continue; } switch(i){ @@ -1202,9 +1365,10 @@ int CmdHF14AMfUDump(const char *Cmd){ case 43: tmplockbit = bit2[9]; break; //auth1 default: break; } - PrintAndLog("Block %02X:%s [%d] {%.4s}", i, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); + PrintAndLog("%02d/0x%02X | %s | %d | %.4s", i, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); } - + PrintAndLog("---------------------------------"); + // user supplied filename? if (fileNlen < 1) { // UID = data 0-1-2 4-5-6-7 (skips a beat) @@ -1369,142 +1533,6 @@ int CmdTestDES(const char * cmd) } **/ -// -// Ultralight C Read Single Block -// -int CmdHF14AMfUCRdBl(const char *Cmd) -{ - UsbCommand resp; - bool hasPwd = FALSE; - uint8_t blockNo = -1; - uint8_t key[16]; - char cmdp = param_getchar(Cmd, 0); - - if (strlen(Cmd) < 1 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: hf mfu crdbl "); - PrintAndLog(""); - PrintAndLog("sample: hf mfu crdbl 0"); - PrintAndLog(" hf mfu crdbl 0 00112233445566778899AABBCCDDEEFF"); - return 0; - } - - blockNo = param_get8(Cmd, 0); - if (blockNo < 0) { - PrintAndLog("Wrong block number"); - return 1; - } - - if (blockNo > MAX_ULC_BLOCKS ){ - PrintAndLog("Error: Maximum number of blocks is 47 for Ultralight-C"); - return 1; - } - - // key - if ( strlen(Cmd) > 3){ - if (param_gethex(Cmd, 1, key, 32)) { - PrintAndLog("Key must include %d HEX symbols", 32); - return 1; - } else { - hasPwd = TRUE; - } - } - - //Read Block - UsbCommand c = {CMD_MIFAREU_READBL, {blockNo}}; - if ( hasPwd ) { - c.arg[1] = 1; - memcpy(c.d.asBytes,key,16); - } - SendCommand(&c); - - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - if (isOK) { - uint8_t *data = resp.d.asBytes; - PrintAndLog("Block: %0d (0x%02X) [ %s]", (int)blockNo, blockNo, sprint_hex(data, 4)); - } - else { - PrintAndLog("Failed reading block: (%02x)", isOK); - } - } else { - PrintAndLog("Command execute time-out"); - } - return 0; -} - -// -// Mifare Ultralight C Write Single Block -// -int CmdHF14AMfUCWrBl(const char *Cmd){ - - uint8_t blockNo = -1; - bool chinese_card = FALSE; - uint8_t bldata[16] = {0x00}; - UsbCommand resp; - - char cmdp = param_getchar(Cmd, 0); - - if (strlen(Cmd) < 3 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: hf mfu cwrbl [w]"); - PrintAndLog(" [block number]"); - PrintAndLog(" [block data] - (8 hex symbols)"); - PrintAndLog(" [w] - Chinese magic ultralight tag"); - PrintAndLog(""); - PrintAndLog(" sample: hf mfu cwrbl 0 01020304"); - PrintAndLog(""); - return 0; - } - - blockNo = param_get8(Cmd, 0); - if (blockNo > MAX_ULC_BLOCKS ){ - PrintAndLog("Error: Maximum number of blocks is 47 for Ultralight-C Cards!"); - return 1; - } - - if (param_gethex(Cmd, 1, bldata, 8)) { - PrintAndLog("Block data must include 8 HEX symbols"); - return 1; - } - - if (strchr(Cmd,'w') != 0 || strchr(Cmd,'W') != 0 ) { - chinese_card = TRUE; - } - - if ( blockNo <= 3 ) { - if (!chinese_card){ - PrintAndLog("Access Denied"); - return 1; - } else { - PrintAndLog("--Special block no: 0x%02x", blockNo); - PrintAndLog("--Data: %s", sprint_hex(bldata, 4)); - UsbCommand d = {CMD_MIFAREU_WRITEBL, {blockNo}}; - memcpy(d.d.asBytes,bldata, 4); - SendCommand(&d); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - PrintAndLog("isOk:%02x", isOK); - } else { - PrintAndLog("Command execute timeout"); - return 1; - } - } - } else { - PrintAndLog("--Block no : 0x%02x", blockNo); - PrintAndLog("--Data: %s", sprint_hex(bldata, 4)); - UsbCommand e = {CMD_MIFAREU_WRITEBL, {blockNo}}; - memcpy(e.d.asBytes,bldata, 4); - SendCommand(&e); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - uint8_t isOK = resp.arg[0] & 0xff; - PrintAndLog("isOk : %02x", isOK); - } else { - PrintAndLog("Command execute timeout"); - return 1; - } - } - return 0; -} - // // Mifare Ultralight C - Set password // @@ -1629,10 +1657,10 @@ int CmdHF14AMfucSetUid(const char *Cmd){ } int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ - + uint8_t iv[8] = { 0x00 }; uint8_t block = 0x07; - + // UL-EV1 //04 57 b6 e2 05 3f 80 UID //4a f8 4b 19 PWD @@ -1646,14 +1674,14 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ 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]; - + des3_context ctx = { 0x00 }; des3_set2key_enc(&ctx, masterkey); @@ -1672,9 +1700,9 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ PrintAndLog("Mifare key :\t %s", sprint_hex(mifarekeyA, sizeof(mifarekeyA))); PrintAndLog("Message :\t %s", sprint_hex(mix, sizeof(mix))); PrintAndLog("Diversified key: %s", sprint_hex(divkey+1, 6)); - + PrintAndLog("\n DES version"); - + for (int i=0; i < sizeof(mifarekeyA); ++i){ dkeyA[i] = (mifarekeyA[i] << 1) & 0xff; dkeyA[6] |= ((mifarekeyA[i] >> 7) & 1) << (i+1); @@ -1692,7 +1720,7 @@ int CmdHF14AMfuGenDiverseKeys(const char *Cmd){ memcpy(dmkey+8, dkeyB, 8); memcpy(dmkey+16, dkeyA, 8); memset(iv, 0x00, 8); - + des3_set3key_enc(&ctx, dmkey); des3_crypt_cbc(&ctx // des3_context @@ -1735,11 +1763,9 @@ static command_t CommandTable[] = {"help", CmdHelp, 1, "This help"}, {"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"}, {"info", CmdHF14AMfUInfo, 0, "Tag information"}, - {"dump", CmdHF14AMfUDump, 0, "Dump Ultralight / Ultralight-C tag to binary file"}, - {"rdbl", CmdHF14AMfURdBl, 0, "Read block - Ultralight"}, - {"wrbl", CmdHF14AMfUWrBl, 0, "Write block - Ultralight"}, - {"crdbl", CmdHF14AMfUCRdBl, 0, "Read block - Ultralight C"}, - {"cwrbl", CmdHF14AMfUCWrBl, 0, "Write block - Ultralight C"}, + {"dump", CmdHF14AMfUDump, 0, "Dump Ultralight / Ultralight-C / NTAG tag to binary file"}, + {"rdbl", CmdHF14AMfURdBl, 0, "Read block"}, + {"wrbl", CmdHF14AMfUWrBl, 0, "Write block"}, {"cauth", CmdHF14AMfucAuth, 0, "Authentication - Ultralight C"}, {"setpwd", CmdHF14AMfucSetPwd, 1, "Set 3des password - Ultralight-C"}, {"setuid", CmdHF14AMfucSetUid, 1, "Set UID - MAGIC tags only"}, diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 83f28403..4ec48ff9 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -4,25 +4,24 @@ #ifndef CMDHFMFU_H__ #define CMDHFMFU_H__ -//standard ultralight int CmdHF14AMfUWrBl(const char *Cmd); int CmdHF14AMfURdBl(const char *Cmd); //Crypto Cards -int CmdHF14AMfUCRdBl(const char *Cmd); -int CmdHF14AMfUCRdCard(const char *Cmd); int CmdHF14AMfucAuth(const char *Cmd); //general stuff int CmdHF14AMfUDump(const char *Cmd); int CmdHF14AMfUInfo(const char *Cmd); -uint32_t GetHF14AMfU_Type(void); +uint32_t GetHF14AMfU_Type(void); int ul_print_type(uint32_t tagtype, uint8_t spacer); void ul_switch_off_field(void); int usage_hf_mfu_dump(void); int usage_hf_mfu_info(void); +int usage_hf_mfu_rdbl(void); +int usage_hf_mfu_wrbl(void); int CmdHFMFUltra(const char *Cmd); From 1d537ad65c54d8821cf228a36fc15ac6e9764f50 Mon Sep 17 00:00:00 2001 From: Pierre LALET Date: Mon, 25 May 2015 11:47:27 +0200 Subject: [PATCH 071/132] Ported hf mf esave trick for unreadable UIDs to hf mf csave Thanks: iceman1001 --- client/cmdhfmf.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 2b5a5b87..5abda060 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -1750,10 +1750,13 @@ int CmdHF14AMfCSave(const char *Cmd) { // get filename if (mfCGetBlock(0, buf, CSETBLOCK_SINGLE_OPER)) { PrintAndLog("Cant get block: %d", 0); - return 1; + len = sprintf(fnameptr, "dump"); + fnameptr += len; + } + else { + for (j = 0; j < 7; j++, fnameptr += 2) + sprintf(fnameptr, "%02x", buf[j]); } - for (j = 0; j < 7; j++, fnameptr += 2) - sprintf(fnameptr, "%02x", buf[j]); } else { memcpy(filename, Cmd, len); fnameptr += len; From e61530408c4b3605390748fc544b5afcfda996a3 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Sun, 5 Apr 2015 19:15:02 +0200 Subject: [PATCH 072/132] add: hw ver: show FPGA versions for both HF and LF FPGA configs add: hw ver: show used and free flash memory chg: prepare fpgaloader for compressed FPGA configs --- armsrc/Makefile | 3 +- armsrc/appmain.c | 11 +- armsrc/apps.h | 2 +- armsrc/fpga_hf.bit.gz | Bin 0 -> 19160 bytes armsrc/fpga_lf.bit.gz | Bin 0 -> 18299 bytes armsrc/fpgaloader.c | 246 +++--- armsrc/inffast.h | 11 + armsrc/inffixed.h | 94 +++ armsrc/inflate.c | 1512 ++++++++++++++++++++++++++++++++++ armsrc/inflate.h | 122 +++ armsrc/inftrees.h | 62 ++ armsrc/ldscript | 1 + armsrc/zconf.h | 511 ++++++++++++ armsrc/zlib.h | 1768 ++++++++++++++++++++++++++++++++++++++++ armsrc/zutil.h | 253 ++++++ client/Makefile | 12 +- client/cmdhftopaz.c | 408 ++++++++++ client/cmdhw.c | 34 +- client/fpga_compress.c | 221 +++++ 19 files changed, 5137 insertions(+), 134 deletions(-) create mode 100644 armsrc/fpga_hf.bit.gz create mode 100644 armsrc/fpga_lf.bit.gz create mode 100644 armsrc/inffast.h create mode 100644 armsrc/inffixed.h create mode 100644 armsrc/inflate.c create mode 100644 armsrc/inflate.h create mode 100644 armsrc/inftrees.h create mode 100644 armsrc/zconf.h create mode 100644 armsrc/zlib.h create mode 100644 armsrc/zutil.h create mode 100644 client/cmdhftopaz.c create mode 100644 client/fpga_compress.c diff --git a/armsrc/Makefile b/armsrc/Makefile index 899b0307..3fd93ac3 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -30,7 +30,8 @@ THUMBSRC = start.c \ util.c \ string.c \ usb_cdc.c \ - cmd.c + cmd.c \ + inflate.c # These are to be compiled in ARM mode ARMSRC = fpgaloader.c \ diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 96644b9a..80ae4bc2 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -310,7 +310,7 @@ void ReadMem(int addr) /* osimage version information is linked in */ extern struct version_information version_information; /* bootrom version information is pointed to from _bootphase1_version_pointer */ -extern char *_bootphase1_version_pointer, _flash_start, _flash_end; +extern char *_bootphase1_version_pointer, _flash_start, _flash_end, _bootrom_start, _bootrom_end, __os_size__; void SendVersion(void) { char temp[512]; /* Limited data payload in USB packets */ @@ -331,10 +331,13 @@ void SendVersion(void) FormatVersionInformation(temp, sizeof(temp), "os: ", &version_information); DbpString(temp); - FpgaGatherVersion(temp, sizeof(temp)); + FpgaGatherVersion(FPGA_BITSTREAM_LF, temp, sizeof(temp)); DbpString(temp); - // Send Chip ID - cmd_send(CMD_ACK,*(AT91C_DBGU_CIDR),0,0,NULL,0); + FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp)); + DbpString(temp); + + // Send Chip ID and used flash memory + cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), (uint32_t)&_bootrom_end - (uint32_t)&_bootrom_start + (uint32_t)&__os_size__, 0, NULL, 0); } #ifdef WITH_LF diff --git a/armsrc/apps.h b/armsrc/apps.h index 57fb55fd..fa081d21 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -55,7 +55,7 @@ void FpgaSendCommand(uint16_t cmd, uint16_t v); void FpgaWriteConfWord(uint8_t v); void FpgaDownloadAndGo(int bitstream_version); int FpgaGatherBitstreamVersion(); -void FpgaGatherVersion(char *dst, int len); +void FpgaGatherVersion(int bitstream_version, char *dst, int len); void FpgaSetupSsc(void); void SetupSpi(int mode); bool FpgaSetupSscDma(uint8_t *buf, int len); diff --git a/armsrc/fpga_hf.bit.gz b/armsrc/fpga_hf.bit.gz new file mode 100644 index 0000000000000000000000000000000000000000..0cbb214d2cd73816870d583a0890aa3f64142f8d GIT binary patch literal 19160 zcmV*AKySYviwFpM^BYwH17>h%VP9xwE@EkP0PVdGbX3=MH@fe+SMt@|E6qiSRPn!D zjbvv`M$#Y=Ot3t<2<%R68YYR;(r%H|nSu5VY zKDu+xJ@=g7{_Xucd!Wic?fwryS_|{P)cq%G|F`vDYVLk;?HB)eUCW<+aUDDWzP7Km zhyUWCMd2`f5wy1OqEEJl+grn*f^|?8Ub<}YqGgNQ;Ew@zbzj5J5B~P^UkU@40N}c? z6sLcxVab$$cQ%K?p?`<$f3FII>HT*p3>L(o>5EWnz_0%(T>Rs=XrsvRn?CM+*l*FM z7JiHV{KhsZw~h6i+KB(ZY(O09p%NtS8g|7&>CfN>UTedS&JpolPQ_KY%G)jfjNAqn zc)RUCFGu*l^Ujmim*i>a79BU2>uCL9ABDED{;~3 z1ygVdmc{)kxdo=3HttVrA^2A%;#8;QaYfuGBOQiW=c$Z;T)t$^LTAFCmao8NxYI#n z2E=_VV-L(g#0m|`6EGQD#`Uzkhh2uD5k0LLib-uoD?%^?Eta~Ny~~raKw6z)A=n0u zPW3cv1Mz?}6|1mKDC1kqUI5!M)9O;T$9MuvM-8*3_=@4jlx~Loyg8$OgM9#x^gLk) zH*C2XHm4dgRU4S<-Y2T+Fby5YYQpj;w;`O+!}3=64c(K7WyZCotV`{2nz%2_rhvv?6~_CBd7oUc8~fb0+rL|0mN*RuxE_}u;4dpf zT(`Al?sr8YW6Z!2@b}5D!;HGj@N?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8GDP%UMGexa{sx7I<*E z+;H!M9V9fDRT%afQ8Jvuca`I5*5KLilIFtYtdX6InDm?Ollv}9iAi;E7tAX+y4>%I zT9vSz8*!yxDmSuo8ig`kE*Oyet`c1K8di3nm+n>`>bWugyY=&qml?U|Bi+p&;*ZBa zUSD;*%*eKhxwu@6?>S>QH(&qx`m*r-U(4&`xSBSV8F^feD;uPn;dlAGOqt;n=Bo&o zy+-c4aJ~w-Tw?ITyJ7Vh=1O%QD>EQBE*WA@UARJ*R+Jf5Zd}E<>>A89^7B=U%SA@+ zyQDeRSB051a^sp~eIa9Zjof#|m8DV*tl&nb%*Z~&7;XV!I+ID_s=Q&kMt*%&z#>bJ z$#w8tnK7LEt`$oBXnpu@eO_;wkzZfduh~}$xNJ#Lg5$m%E*BYv^|dlKuTHs3nm31$ zo3CFp=LwIGREo=9BR^liFMrN@Y5bFmtILhtcS+IT0t*O^Yje0(W&*@yFa)0HkFc)(@!R!sQAA|pz z_p=>zM=^ifx4EO^H~dGxAO6>WIaYdL59-(AaP#{bBDe#094ZPqgT zpRtzVf8JVV{|nag=5Wz{=3L84@m@FQTJG~c!C$kM<#28)KU~ZIuWR$4f5Ko&O#HL! z_u#|Nho28WAAUakeE9kB^Wo>i&)ohJ6aJF*;nVo=^Wo>i&xfB6KOcTR{QUpV7ou40 nJ5CscxJeF!RrTBbooHVX23soJ=jeYeeWL#tJ0n*RzoY;Fa!6#A literal 0 HcmV?d00001 diff --git a/armsrc/fpga_lf.bit.gz b/armsrc/fpga_lf.bit.gz new file mode 100644 index 0000000000000000000000000000000000000000..d736beed49b3f8d06886758910df578f539042f7 GIT binary patch literal 18299 zcmWh!1w)iw6IGG!Zg@dO5$Tp#X(c3-j+O52+Li9^2BoByMsjHoq`{@TyIGcvkM9TE z`^+@)PDq$KQaWjix_e0}|v1ap$cR7}Of9SyyJ|-Nkc7GK0#2T4j%XuNK z7*xGJZvGJhJB*49zG7Q?X7N)@73X#Aj927OF)?zwA&TMJz2!p$j3R46)c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K|1Qi88H=BUb` zV;m`KvV>vPIe)7x-L=v9j5;?{G-h{~rL81g;ZDEWOZqL0E@AlEobIYM)~K^Hp0TW} z!dR1>?cS3v+bDeoKF#Mk#_Y7TQEI0vrqi!-X%$bUm0F1mJzY~U4P8}i zgEGjH!aq@`Cl%+O=hw*pj-O25SX=2gx`g5Ut>@R2-PLtl`m?ojUvQ0CMZ;M;A6p~e z#ZRYis;zv%H6$|rtoFm!Z0DZR=Y0AFWhq~u{v;a788I@tdg+Suw?0Pe zYol0A!vByl%egXp=JiDeh6lsK@IG*#kixJUbjvf+*h(_oduUmu{p)KK8t@)*rT9}O zEj8Dt=F}+9JI2S#W<%1Pqbu$`^<|p|{-EHT2`8-^6P4?QQI}BBkcQ}r_qR&1 zVD9j&qT#)t+T;uR(w^^HbKH_R^G=ul^~X$Cm`k|AZ)B+A0l>S>1Q^ec$VXv}u6xZ@SXWrI#gcdj^pOZrXg z%jwr|SYK|x(#i^{3RZKyFwH2w!xXxJgrlY{H7u#vuQFI_hEsA4JU`7CbpFB?*pu99#|<-ugl~#@GPic)HSLI zN%Q3Bjms*h8_wU7lK%oMAULjea5-SC`hNwNgK+E^e-Xsx=9zH${h4t&Xt?*V9@s@E z8tP=IF|$I?I9I#|c}Sy53K^z*#l^uM64aYfUF|XI)Lyer@9klA(2G}QdQQ9)!`vT! z^-1PL&w*c>hFG`7EABnM(~ASgI#Scv#YLU{}TRn|8*_@^FIkNBqsjb{t5Wt=YyXQem?m5 z;OB#%4}L!Q`QT^fc!`O4$@E{B!Lq`tuaxuu><1qsLl_d_f8}$SWM+7c{@Z8|J?CHD zo_}laN35w8In0) - DownloadFPGA_byte(FpgaImage[(i++)^0x3]); - /* Explanation of the magic in the above line: - * i^0x3 inverts the lower two bits of the integer i, counting backwards - * for each 4 byte increment. The generated sequence of (i++)^3 is - * 3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 etc. pp. - */ - } - } else { - while(FpgaImageLen-->0) - DownloadFPGA_byte(*FpgaImage++); + while(FpgaImageLen-->0) { + DownloadFPGA_byte(get_from_fpga_stream()); } // continue to clock FPGA until ready signal goes high @@ -250,39 +262,21 @@ static void DownloadFPGA(const char *FpgaImage, int FpgaImageLen, int byterevers LED_D_OFF(); } -static char *bitparse_headers_start; -static char *bitparse_bitstream_end; -static int bitparse_initialized = 0; + /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01 * After that the format is 1 byte section type (ASCII character), 2 byte length * (big endian), bytes content. Except for section 'e' which has 4 bytes * length. */ -static const char _bitparse_fixed_header[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x00, 0x00, 0x01}; -static int bitparse_init(void * start_address, void *end_address) +int bitparse_find_section(char section_name, unsigned int *section_length) { - bitparse_initialized = 0; - - if(memcmp(_bitparse_fixed_header, start_address, sizeof(_bitparse_fixed_header)) != 0) { - return 0; /* Not matched */ - } else { - bitparse_headers_start= ((char*)start_address) + sizeof(_bitparse_fixed_header); - bitparse_bitstream_end= (char*)end_address; - bitparse_initialized = 1; - return 1; - } -} - -int bitparse_find_section(char section_name, char **section_start, unsigned int *section_length) -{ - char *pos = bitparse_headers_start; int result = 0; - - if(!bitparse_initialized) return 0; - - while(pos < bitparse_bitstream_end) { - char current_name = *pos++; + #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section + uint16_t numbytes = 0; + while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) { + char current_name = get_from_fpga_stream(); + numbytes++; unsigned int current_length = 0; if(current_name < 'a' || current_name > 'e') { /* Strange section name, abort */ @@ -292,11 +286,13 @@ int bitparse_find_section(char section_name, char **section_start, unsigned int switch(current_name) { case 'e': /* Four byte length field */ - current_length += (*pos++) << 24; - current_length += (*pos++) << 16; + current_length += get_from_fpga_stream() << 24; + current_length += get_from_fpga_stream() << 16; + numbytes += 2; default: /* Fall through, two byte length field */ - current_length += (*pos++) << 8; - current_length += (*pos++) << 0; + current_length += get_from_fpga_stream() << 8; + current_length += get_from_fpga_stream() << 0; + numbytes += 2; } if(current_name != 'e' && current_length > 255) { @@ -306,108 +302,136 @@ int bitparse_find_section(char section_name, char **section_start, unsigned int if(current_name == section_name) { /* Found it */ - *section_start = pos; *section_length = current_length; result = 1; break; } - pos += current_length; /* Skip section */ + for (uint16_t i = 0; i < current_length && numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH; i++) { + get_from_fpga_stream(); + numbytes++; + } } return result; } +void init_fpga_inflate(void) +{ + // initialize zlib for inflate +} + + //----------------------------------------------------------------------------- // Find out which FPGA image format is stored in flash, then call DownloadFPGA // with the right parameters to download the image //----------------------------------------------------------------------------- -extern char _binary_fpga_lf_bit_start, _binary_fpga_lf_bit_end; -extern char _binary_fpga_hf_bit_start, _binary_fpga_hf_bit_end; void FpgaDownloadAndGo(int bitstream_version) { - void *bit_start; - void *bit_end; - + uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; + // check whether or not the bitstream is already loaded - if (FpgaGatherBitstreamVersion() == bitstream_version) + if (downloaded_bitstream == bitstream_version) return; if (bitstream_version == FPGA_BITSTREAM_LF) { - bit_start = &_binary_fpga_lf_bit_start; - bit_end = &_binary_fpga_lf_bit_end; + reset_fpga_stream(&_binary_fpga_lf_bit_start); } else if (bitstream_version == FPGA_BITSTREAM_HF) { - bit_start = &_binary_fpga_hf_bit_start; - bit_end = &_binary_fpga_hf_bit_end; + reset_fpga_stream(&_binary_fpga_hf_bit_start); } else return; - /* Check for the new flash image format: Should have the .bit file at &_binary_fpga_bit_start - */ - if(bitparse_init(bit_start, bit_end)) { - /* Successfully initialized the .bit parser. Find the 'e' section and - * send its contents to the FPGA. - */ - char *bitstream_start; - unsigned int bitstream_length; - if(bitparse_find_section('e', &bitstream_start, &bitstream_length)) { - DownloadFPGA(bitstream_start, bitstream_length, 0); + uint16_t i = 0; + for (; i < GZIP_HEADER_SIZE; i++) { + header[i] = get_from_fpga_stream(); + } + + // Check for compressed new flash image format (starts with gzip header) + if(memcmp(_gzip_header, header, GZIP_HEADER_SIZE) == 0) { + init_fpga_inflate(); + } + + for (; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { + header[i] = get_from_fpga_stream(); + } + + // Check for the new flash image format: Should have the .bit file at &_binary_fpga_bit_start + if(memcmp(_bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) { + unsigned int bitstream_length; + if(bitparse_find_section('e', &bitstream_length)) { + DownloadFPGA(bitstream_length); + downloaded_bitstream = bitstream_version; return; /* All done */ } } - - /* Fallback for the old flash image format: Check for the magic marker 0xFFFFFFFF - * 0xAA995566 at address 0x102000. This is raw bitstream with a size of 336,768 bits - * = 10,524 uint32_t, stored as uint32_t e.g. little-endian in memory, but each DWORD - * is still to be transmitted in MSBit first order. Set the invert flag to indicate - * that the DownloadFPGA function should invert every 4 byte sequence when doing - * the bytewise download. - */ - if( *(uint32_t*)0x102000 == 0xFFFFFFFF && *(uint32_t*)0x102004 == 0xAA995566 ) - DownloadFPGA((char*)0x102000, 10524*4, 1); -} +} int FpgaGatherBitstreamVersion() { - char temp[256]; - FpgaGatherVersion(temp, sizeof (temp)); - if (!memcmp("LF", temp, 2)) - return FPGA_BITSTREAM_LF; - else if (!memcmp("HF", temp, 2)) - return FPGA_BITSTREAM_HF; - return FPGA_BITSTREAM_ERR; + return downloaded_bitstream; } -void FpgaGatherVersion(char *dst, int len) +void FpgaGatherVersion(int bitstream_version, char *dst, int len) { - char *fpga_info; unsigned int fpga_info_len; - dst[0] = 0; - if(!bitparse_find_section('e', &fpga_info, &fpga_info_len)) { - strncat(dst, "FPGA image: legacy image without version information", len-1); - } else { - /* USB packets only have 48 bytes data payload, so be terse */ - if(bitparse_find_section('a', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - if (!memcmp("fpga_lf", fpga_info, 7)) - strncat(dst, "LF ", len-1); - else if (!memcmp("fpga_hf", fpga_info, 7)) - strncat(dst, "HF ", len-1); + char tempstr[40]; + + dst[0] = '\0'; + + if (bitstream_version == FPGA_BITSTREAM_LF) { + reset_fpga_stream(&_binary_fpga_lf_bit_start); + } else if (bitstream_version == FPGA_BITSTREAM_HF) { + reset_fpga_stream(&_binary_fpga_hf_bit_start); + } else + return; + + + for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { + get_from_fpga_stream(); + } + + if(bitparse_find_section('a', &fpga_info_len)) { + for (uint16_t i = 0; i < fpga_info_len; i++) { + char c = (char)get_from_fpga_stream(); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } - strncat(dst, "FPGA image built", len-1); -#if 0 - if(bitparse_find_section('b', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - strncat(dst, " for ", len-1); - strncat(dst, fpga_info, len-1); + if (!memcmp("fpga_lf", tempstr, 7)) + strncat(dst, "LF ", len-1); + else if (!memcmp("fpga_hf", tempstr, 7)) + strncat(dst, "HF ", len-1); + } + strncat(dst, "FPGA image built", len-1); + if(bitparse_find_section('b', &fpga_info_len)) { + strncat(dst, " for ", len-1); + for (uint16_t i = 0; i < fpga_info_len; i++) { + char c = (char)get_from_fpga_stream(); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } -#endif - if(bitparse_find_section('c', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - strncat(dst, " on ", len-1); - strncat(dst, fpga_info, len-1); + strncat(dst, tempstr, len-1); + } + if(bitparse_find_section('c', &fpga_info_len)) { + strncat(dst, " on ", len-1); + for (uint16_t i = 0; i < fpga_info_len; i++) { + char c = (char)get_from_fpga_stream(); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } - if(bitparse_find_section('d', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - strncat(dst, " at ", len-1); - strncat(dst, fpga_info, len-1); + strncat(dst, tempstr, len-1); + } + if(bitparse_find_section('d', &fpga_info_len)) { + strncat(dst, " at ", len-1); + for (uint16_t i = 0; i < fpga_info_len; i++) { + char c = (char)get_from_fpga_stream(); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } + strncat(dst, tempstr, len-1); } } diff --git a/armsrc/inffast.h b/armsrc/inffast.h new file mode 100644 index 00000000..e5c1aa4c --- /dev/null +++ b/armsrc/inffast.h @@ -0,0 +1,11 @@ +/* inffast.h -- header to use inffast.c + * Copyright (C) 1995-2003, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start)); diff --git a/armsrc/inffixed.h b/armsrc/inffixed.h new file mode 100644 index 00000000..d6283277 --- /dev/null +++ b/armsrc/inffixed.h @@ -0,0 +1,94 @@ + /* inffixed.h -- table for decoding fixed codes + * Generated automatically by makefixed(). + */ + + /* WARNING: this file should *not* be used by applications. + It is part of the implementation of this library and is + subject to change. Applications should only use zlib.h. + */ + + static const code lenfix[512] = { + {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48}, + {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128}, + {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59}, + {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176}, + {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20}, + {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100}, + {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8}, + {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216}, + {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76}, + {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114}, + {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2}, + {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148}, + {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42}, + {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86}, + {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15}, + {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236}, + {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62}, + {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142}, + {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31}, + {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162}, + {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25}, + {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105}, + {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4}, + {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202}, + {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69}, + {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125}, + {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13}, + {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195}, + {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35}, + {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91}, + {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19}, + {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246}, + {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55}, + {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135}, + {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99}, + {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190}, + {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16}, + {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96}, + {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6}, + {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209}, + {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72}, + {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116}, + {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4}, + {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153}, + {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44}, + {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82}, + {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11}, + {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229}, + {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58}, + {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138}, + {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51}, + {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173}, + {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30}, + {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110}, + {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0}, + {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195}, + {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65}, + {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121}, + {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9}, + {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258}, + {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37}, + {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93}, + {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23}, + {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251}, + {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51}, + {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131}, + {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67}, + {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183}, + {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23}, + {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103}, + {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9}, + {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223}, + {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79}, + {0,9,255} + }; + + static const code distfix[32] = { + {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025}, + {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193}, + {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385}, + {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577}, + {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073}, + {22,5,193},{64,5,0} + }; diff --git a/armsrc/inflate.c b/armsrc/inflate.c new file mode 100644 index 00000000..870f89bb --- /dev/null +++ b/armsrc/inflate.c @@ -0,0 +1,1512 @@ +/* inflate.c -- zlib decompression + * Copyright (C) 1995-2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * Change history: + * + * 1.2.beta0 24 Nov 2002 + * - First version -- complete rewrite of inflate to simplify code, avoid + * creation of window when not needed, minimize use of window when it is + * needed, make inffast.c even faster, implement gzip decoding, and to + * improve code readability and style over the previous zlib inflate code + * + * 1.2.beta1 25 Nov 2002 + * - Use pointers for available input and output checking in inffast.c + * - Remove input and output counters in inffast.c + * - Change inffast.c entry and loop from avail_in >= 7 to >= 6 + * - Remove unnecessary second byte pull from length extra in inffast.c + * - Unroll direct copy to three copies per loop in inffast.c + * + * 1.2.beta2 4 Dec 2002 + * - Change external routine names to reduce potential conflicts + * - Correct filename to inffixed.h for fixed tables in inflate.c + * - Make hbuf[] unsigned char to match parameter type in inflate.c + * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset) + * to avoid negation problem on Alphas (64 bit) in inflate.c + * + * 1.2.beta3 22 Dec 2002 + * - Add comments on state->bits assertion in inffast.c + * - Add comments on op field in inftrees.h + * - Fix bug in reuse of allocated window after inflateReset() + * - Remove bit fields--back to byte structure for speed + * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths + * - Change post-increments to pre-increments in inflate_fast(), PPC biased? + * - Add compile time option, POSTINC, to use post-increments instead (Intel?) + * - Make MATCH copy in inflate() much faster for when inflate_fast() not used + * - Use local copies of stream next and avail values, as well as local bit + * buffer and bit count in inflate()--for speed when inflate_fast() not used + * + * 1.2.beta4 1 Jan 2003 + * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings + * - Move a comment on output buffer sizes from inffast.c to inflate.c + * - Add comments in inffast.c to introduce the inflate_fast() routine + * - Rearrange window copies in inflate_fast() for speed and simplification + * - Unroll last copy for window match in inflate_fast() + * - Use local copies of window variables in inflate_fast() for speed + * - Pull out common wnext == 0 case for speed in inflate_fast() + * - Make op and len in inflate_fast() unsigned for consistency + * - Add FAR to lcode and dcode declarations in inflate_fast() + * - Simplified bad distance check in inflate_fast() + * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new + * source file infback.c to provide a call-back interface to inflate for + * programs like gzip and unzip -- uses window as output buffer to avoid + * window copying + * + * 1.2.beta5 1 Jan 2003 + * - Improved inflateBack() interface to allow the caller to provide initial + * input in strm. + * - Fixed stored blocks bug in inflateBack() + * + * 1.2.beta6 4 Jan 2003 + * - Added comments in inffast.c on effectiveness of POSTINC + * - Typecasting all around to reduce compiler warnings + * - Changed loops from while (1) or do {} while (1) to for (;;), again to + * make compilers happy + * - Changed type of window in inflateBackInit() to unsigned char * + * + * 1.2.beta7 27 Jan 2003 + * - Changed many types to unsigned or unsigned short to avoid warnings + * - Added inflateCopy() function + * + * 1.2.0 9 Mar 2003 + * - Changed inflateBack() interface to provide separate opaque descriptors + * for the in() and out() functions + * - Changed inflateBack() argument and in_func typedef to swap the length + * and buffer address return values for the input function + * - Check next_in and next_out for Z_NULL on entry to inflate() + * + * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifdef MAKEFIXED +# ifndef BUILDFIXED +# define BUILDFIXED +# endif +#endif + +/* function prototypes */ +local void fixedtables OF((struct inflate_state FAR *state)); +local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, + unsigned copy)); +#ifdef BUILDFIXED + void makefixed OF((void)); +#endif +local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf, + unsigned len)); + +int ZEXPORT inflateResetKeep(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + strm->total_in = strm->total_out = state->total = 0; + strm->msg = Z_NULL; + if (state->wrap) /* to support ill-conceived Java test suite */ + strm->adler = state->wrap & 1; + state->mode = HEAD; + state->last = 0; + state->havedict = 0; + state->dmax = 32768U; + state->head = Z_NULL; + state->hold = 0; + state->bits = 0; + state->lencode = state->distcode = state->next = state->codes; + state->sane = 1; + state->back = -1; + Tracev((stderr, "inflate: reset\n")); + return Z_OK; +} + +int ZEXPORT inflateReset(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->wsize = 0; + state->whave = 0; + state->wnext = 0; + return inflateResetKeep(strm); +} + +int ZEXPORT inflateReset2(strm, windowBits) +z_streamp strm; +int windowBits; +{ + int wrap; + struct inflate_state FAR *state; + + /* get the state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } + else { + wrap = (windowBits >> 4) + 1; +#ifdef GUNZIP + if (windowBits < 48) + windowBits &= 15; +#endif + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) + return Z_STREAM_ERROR; + if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) { + ZFREE(strm, state->window); + state->window = Z_NULL; + } + + /* update state and reset the rest of it */ + state->wrap = wrap; + state->wbits = (unsigned)windowBits; + return inflateReset(strm); +} + +int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size) +z_streamp strm; +int windowBits; +const char *version; +int stream_size; +{ + int ret; + struct inflate_state FAR *state; + + if (version == Z_NULL || version[0] != ZLIB_VERSION[0] || + stream_size != (int)(sizeof(z_stream))) + return Z_VERSION_ERROR; + if (strm == Z_NULL) return Z_STREAM_ERROR; + strm->msg = Z_NULL; /* in case we return an error */ + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + state = (struct inflate_state FAR *) + ZALLOC(strm, 1, sizeof(struct inflate_state)); + if (state == Z_NULL) return Z_MEM_ERROR; + Tracev((stderr, "inflate: allocated\n")); + strm->state = (struct internal_state FAR *)state; + state->window = Z_NULL; + ret = inflateReset2(strm, windowBits); + if (ret != Z_OK) { + ZFREE(strm, state); + strm->state = Z_NULL; + } + return ret; +} + +int ZEXPORT inflateInit_(strm, version, stream_size) +z_streamp strm; +const char *version; +int stream_size; +{ + return inflateInit2_(strm, DEF_WBITS, version, stream_size); +} + +int ZEXPORT inflatePrime(strm, bits, value) +z_streamp strm; +int bits; +int value; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (bits < 0) { + state->hold = 0; + state->bits = 0; + return Z_OK; + } + if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR; + value &= (1L << bits) - 1; + state->hold += value << state->bits; + state->bits += bits; + return Z_OK; +} + +/* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ +local void fixedtables(state) +struct inflate_state FAR *state; +{ +#ifdef BUILDFIXED + static int virgin = 1; + static code *lenfix, *distfix; + static code fixed[544]; + + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + unsigned sym, bits; + static code *next; + + /* literal/length table */ + sym = 0; + while (sym < 144) state->lens[sym++] = 8; + while (sym < 256) state->lens[sym++] = 9; + while (sym < 280) state->lens[sym++] = 7; + while (sym < 288) state->lens[sym++] = 8; + next = fixed; + lenfix = next; + bits = 9; + inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work); + + /* distance table */ + sym = 0; + while (sym < 32) state->lens[sym++] = 5; + distfix = next; + bits = 5; + inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work); + + /* do this just once */ + virgin = 0; + } +#else /* !BUILDFIXED */ +# include "inffixed.h" +#endif /* BUILDFIXED */ + state->lencode = lenfix; + state->lenbits = 9; + state->distcode = distfix; + state->distbits = 5; +} + +#ifdef MAKEFIXED +#include + +/* + Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also + defines BUILDFIXED, so the tables are built on the fly. makefixed() writes + those tables to stdout, which would be piped to inffixed.h. A small program + can simply call makefixed to do this: + + void makefixed(void); + + int main(void) + { + makefixed(); + return 0; + } + + Then that can be linked with zlib built with MAKEFIXED defined and run: + + a.out > inffixed.h + */ +void makefixed() +{ + unsigned low, size; + struct inflate_state state; + + fixedtables(&state); + puts(" /* inffixed.h -- table for decoding fixed codes"); + puts(" * Generated automatically by makefixed()."); + puts(" */"); + puts(""); + puts(" /* WARNING: this file should *not* be used by applications."); + puts(" It is part of the implementation of this library and is"); + puts(" subject to change. Applications should only use zlib.h."); + puts(" */"); + puts(""); + size = 1U << 9; + printf(" static const code lenfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 7) == 0) printf("\n "); + printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op, + state.lencode[low].bits, state.lencode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); + size = 1U << 5; + printf("\n static const code distfix[%u] = {", size); + low = 0; + for (;;) { + if ((low % 6) == 0) printf("\n "); + printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits, + state.distcode[low].val); + if (++low == size) break; + putchar(','); + } + puts("\n };"); +} +#endif /* MAKEFIXED */ + +/* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ +local int updatewindow(strm, end, copy) +z_streamp strm; +const Bytef *end; +unsigned copy; +{ + struct inflate_state FAR *state; + unsigned dist; + + state = (struct inflate_state FAR *)strm->state; + + /* if it hasn't been done already, allocate space for the window */ + if (state->window == Z_NULL) { + state->window = (unsigned char FAR *) + ZALLOC(strm, 1U << state->wbits, + sizeof(unsigned char)); + if (state->window == Z_NULL) return 1; + } + + /* if window not in use yet, initialize */ + if (state->wsize == 0) { + state->wsize = 1U << state->wbits; + state->wnext = 0; + state->whave = 0; + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state->wsize) { + zmemcpy(state->window, end - state->wsize, state->wsize); + state->wnext = 0; + state->whave = state->wsize; + } + else { + dist = state->wsize - state->wnext; + if (dist > copy) dist = copy; + zmemcpy(state->window + state->wnext, end - copy, dist); + copy -= dist; + if (copy) { + zmemcpy(state->window, end - copy, copy); + state->wnext = copy; + state->whave = state->wsize; + } + else { + state->wnext += dist; + if (state->wnext == state->wsize) state->wnext = 0; + if (state->whave < state->wsize) state->whave += dist; + } + } + return 0; +} + +/* Macros for inflate(): */ + +/* check function to use adler32() for zlib or crc32() for gzip */ +#ifdef GUNZIP +# define UPDATE(check, buf, len) \ + (state->flags ? crc32(check, buf, len) : adler32(check, buf, len)) +#else +# define UPDATE(check, buf, len) adler32(check, buf, len) +#endif + +/* check macros for header crc */ +#ifdef GUNZIP +# define CRC2(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + check = crc32(check, hbuf, 2); \ + } while (0) + +# define CRC4(check, word) \ + do { \ + hbuf[0] = (unsigned char)(word); \ + hbuf[1] = (unsigned char)((word) >> 8); \ + hbuf[2] = (unsigned char)((word) >> 16); \ + hbuf[3] = (unsigned char)((word) >> 24); \ + check = crc32(check, hbuf, 4); \ + } while (0) +#endif + +/* Load registers with state in inflate() for speed */ +#define LOAD() \ + do { \ + put = strm->next_out; \ + left = strm->avail_out; \ + next = strm->next_in; \ + have = strm->avail_in; \ + hold = state->hold; \ + bits = state->bits; \ + } while (0) + +/* Restore state from registers in inflate() */ +#define RESTORE() \ + do { \ + strm->next_out = put; \ + strm->avail_out = left; \ + strm->next_in = next; \ + strm->avail_in = have; \ + state->hold = hold; \ + state->bits = bits; \ + } while (0) + +/* Clear the input bit accumulator */ +#define INITBITS() \ + do { \ + hold = 0; \ + bits = 0; \ + } while (0) + +/* Get a byte of input into the bit accumulator, or return from inflate() + if there is no input available. */ +#define PULLBYTE() \ + do { \ + if (have == 0) goto inf_leave; \ + have--; \ + hold += (unsigned long)(*next++) << bits; \ + bits += 8; \ + } while (0) + +/* Assure that there are at least n bits in the bit accumulator. If there is + not enough available input to do that, then return from inflate(). */ +#define NEEDBITS(n) \ + do { \ + while (bits < (unsigned)(n)) \ + PULLBYTE(); \ + } while (0) + +/* Return the low n bits of the bit accumulator (n < 16) */ +#define BITS(n) \ + ((unsigned)hold & ((1U << (n)) - 1)) + +/* Remove n bits from the bit accumulator */ +#define DROPBITS(n) \ + do { \ + hold >>= (n); \ + bits -= (unsigned)(n); \ + } while (0) + +/* Remove zero to seven bits as needed to go to a byte boundary */ +#define BYTEBITS() \ + do { \ + hold >>= bits & 7; \ + bits -= bits & 7; \ + } while (0) + +/* + inflate() uses a state machine to process as much input data and generate as + much output data as possible before returning. The state machine is + structured roughly as follows: + + for (;;) switch (state) { + ... + case STATEn: + if (not enough input data or output space to make progress) + return; + ... make progress ... + state = STATEm; + break; + ... + } + + so when inflate() is called again, the same case is attempted again, and + if the appropriate resources are provided, the machine proceeds to the + next state. The NEEDBITS() macro is usually the way the state evaluates + whether it can proceed or should return. NEEDBITS() does the return if + the requested bits are not available. The typical use of the BITS macros + is: + + NEEDBITS(n); + ... do something with BITS(n) ... + DROPBITS(n); + + where NEEDBITS(n) either returns from inflate() if there isn't enough + input left to load n bits into the accumulator, or it continues. BITS(n) + gives the low n bits in the accumulator. When done, DROPBITS(n) drops + the low n bits off the accumulator. INITBITS() clears the accumulator + and sets the number of available bits to zero. BYTEBITS() discards just + enough bits to put the accumulator on a byte boundary. After BYTEBITS() + and a NEEDBITS(8), then BITS(8) would return the next byte in the stream. + + NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return + if there is no input available. The decoding of variable length codes uses + PULLBYTE() directly in order to pull just enough bytes to decode the next + code, and no more. + + Some states loop until they get enough input, making sure that enough + state information is maintained to continue the loop where it left off + if NEEDBITS() returns in the loop. For example, want, need, and keep + would all have to actually be part of the saved state in case NEEDBITS() + returns: + + case STATEw: + while (want < need) { + NEEDBITS(n); + keep[want++] = BITS(n); + DROPBITS(n); + } + state = STATEx; + case STATEx: + + As shown above, if the next state is also the next case, then the break + is omitted. + + A state may also return if there is not enough output space available to + complete that state. Those states are copying stored data, writing a + literal byte, and copying a matching string. + + When returning, a "goto inf_leave" is used to update the total counters, + update the check value, and determine whether any progress has been made + during that inflate() call in order to return the proper return code. + Progress is defined as a change in either strm->avail_in or strm->avail_out. + When there is a window, goto inf_leave will update the window with the last + output written. If a goto inf_leave occurs in the middle of decompression + and there is no window currently, goto inf_leave will create one and copy + output to the window for the next call of inflate(). + + In this implementation, the flush parameter of inflate() only affects the + return code (per zlib.h). inflate() always writes as much as possible to + strm->next_out, given the space available and the provided input--the effect + documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers + the allocation of and copying into a sliding window until necessary, which + provides the effect documented in zlib.h for Z_FINISH when the entire input + stream available. So the only thing the flush parameter actually does is: + when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it + will return Z_BUF_ERROR if it has not reached the end of the stream. + */ + +int ZEXPORT inflate(strm, flush) +z_streamp strm; +int flush; +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *next; /* next input */ + unsigned char FAR *put; /* next output */ + unsigned have, left; /* available input and output */ + unsigned long hold; /* bit buffer */ + unsigned bits; /* bits in bit buffer */ + unsigned in, out; /* save starting available input and output */ + unsigned copy; /* number of stored or match bytes to copy */ + unsigned char FAR *from; /* where to copy match bytes from */ + code here; /* current decoding table entry */ + code last; /* parent table entry */ + unsigned len; /* length to copy for repeats, bits to drop */ + int ret; /* return code */ +#ifdef GUNZIP + unsigned char hbuf[4]; /* buffer for gzip header crc calculation */ +#endif + static const unsigned short order[19] = /* permutation of code lengths */ + {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; + + if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0)) + return Z_STREAM_ERROR; + + state = (struct inflate_state FAR *)strm->state; + if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */ + LOAD(); + in = have; + out = left; + ret = Z_OK; + for (;;) + switch (state->mode) { + case HEAD: + if (state->wrap == 0) { + state->mode = TYPEDO; + break; + } + NEEDBITS(16); +#ifdef GUNZIP + if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */ + state->check = crc32(0L, Z_NULL, 0); + CRC2(state->check, hold); + INITBITS(); + state->mode = FLAGS; + break; + } + state->flags = 0; /* expect zlib header */ + if (state->head != Z_NULL) + state->head->done = -1; + if (!(state->wrap & 1) || /* check if zlib header allowed */ +#else + if ( +#endif + ((BITS(8) << 8) + (hold >> 8)) % 31) { + strm->msg = (char *)"incorrect header check"; + state->mode = BAD; + break; + } + if (BITS(4) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + DROPBITS(4); + len = BITS(4) + 8; + if (state->wbits == 0) + state->wbits = len; + else if (len > state->wbits) { + strm->msg = (char *)"invalid window size"; + state->mode = BAD; + break; + } + state->dmax = 1U << len; + Tracev((stderr, "inflate: zlib header ok\n")); + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = hold & 0x200 ? DICTID : TYPE; + INITBITS(); + break; +#ifdef GUNZIP + case FLAGS: + NEEDBITS(16); + state->flags = (int)(hold); + if ((state->flags & 0xff) != Z_DEFLATED) { + strm->msg = (char *)"unknown compression method"; + state->mode = BAD; + break; + } + if (state->flags & 0xe000) { + strm->msg = (char *)"unknown header flags set"; + state->mode = BAD; + break; + } + if (state->head != Z_NULL) + state->head->text = (int)((hold >> 8) & 1); + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = TIME; + case TIME: + NEEDBITS(32); + if (state->head != Z_NULL) + state->head->time = hold; + if (state->flags & 0x0200) CRC4(state->check, hold); + INITBITS(); + state->mode = OS; + case OS: + NEEDBITS(16); + if (state->head != Z_NULL) { + state->head->xflags = (int)(hold & 0xff); + state->head->os = (int)(hold >> 8); + } + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + state->mode = EXLEN; + case EXLEN: + if (state->flags & 0x0400) { + NEEDBITS(16); + state->length = (unsigned)(hold); + if (state->head != Z_NULL) + state->head->extra_len = (unsigned)hold; + if (state->flags & 0x0200) CRC2(state->check, hold); + INITBITS(); + } + else if (state->head != Z_NULL) + state->head->extra = Z_NULL; + state->mode = EXTRA; + case EXTRA: + if (state->flags & 0x0400) { + copy = state->length; + if (copy > have) copy = have; + if (copy) { + if (state->head != Z_NULL && + state->head->extra != Z_NULL) { + len = state->head->extra_len - state->length; + zmemcpy(state->head->extra + len, next, + len + copy > state->head->extra_max ? + state->head->extra_max - len : copy); + } + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + state->length -= copy; + } + if (state->length) goto inf_leave; + } + state->length = 0; + state->mode = NAME; + case NAME: + if (state->flags & 0x0800) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->name != Z_NULL && + state->length < state->head->name_max) + state->head->name[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->name = Z_NULL; + state->length = 0; + state->mode = COMMENT; + case COMMENT: + if (state->flags & 0x1000) { + if (have == 0) goto inf_leave; + copy = 0; + do { + len = (unsigned)(next[copy++]); + if (state->head != Z_NULL && + state->head->comment != Z_NULL && + state->length < state->head->comm_max) + state->head->comment[state->length++] = len; + } while (len && copy < have); + if (state->flags & 0x0200) + state->check = crc32(state->check, next, copy); + have -= copy; + next += copy; + if (len) goto inf_leave; + } + else if (state->head != Z_NULL) + state->head->comment = Z_NULL; + state->mode = HCRC; + case HCRC: + if (state->flags & 0x0200) { + NEEDBITS(16); + if (hold != (state->check & 0xffff)) { + strm->msg = (char *)"header crc mismatch"; + state->mode = BAD; + break; + } + INITBITS(); + } + if (state->head != Z_NULL) { + state->head->hcrc = (int)((state->flags >> 9) & 1); + state->head->done = 1; + } + strm->adler = state->check = crc32(0L, Z_NULL, 0); + state->mode = TYPE; + break; +#endif + case DICTID: + NEEDBITS(32); + strm->adler = state->check = ZSWAP32(hold); + INITBITS(); + state->mode = DICT; + case DICT: + if (state->havedict == 0) { + RESTORE(); + return Z_NEED_DICT; + } + strm->adler = state->check = adler32(0L, Z_NULL, 0); + state->mode = TYPE; + case TYPE: + if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave; + case TYPEDO: + if (state->last) { + BYTEBITS(); + state->mode = CHECK; + break; + } + NEEDBITS(3); + state->last = BITS(1); + DROPBITS(1); + switch (BITS(2)) { + case 0: /* stored block */ + Tracev((stderr, "inflate: stored block%s\n", + state->last ? " (last)" : "")); + state->mode = STORED; + break; + case 1: /* fixed block */ + fixedtables(state); + Tracev((stderr, "inflate: fixed codes block%s\n", + state->last ? " (last)" : "")); + state->mode = LEN_; /* decode codes */ + if (flush == Z_TREES) { + DROPBITS(2); + goto inf_leave; + } + break; + case 2: /* dynamic block */ + Tracev((stderr, "inflate: dynamic codes block%s\n", + state->last ? " (last)" : "")); + state->mode = TABLE; + break; + case 3: + strm->msg = (char *)"invalid block type"; + state->mode = BAD; + } + DROPBITS(2); + break; + case STORED: + BYTEBITS(); /* go to byte boundary */ + NEEDBITS(32); + if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) { + strm->msg = (char *)"invalid stored block lengths"; + state->mode = BAD; + break; + } + state->length = (unsigned)hold & 0xffff; + Tracev((stderr, "inflate: stored length %u\n", + state->length)); + INITBITS(); + state->mode = COPY_; + if (flush == Z_TREES) goto inf_leave; + case COPY_: + state->mode = COPY; + case COPY: + copy = state->length; + if (copy) { + if (copy > have) copy = have; + if (copy > left) copy = left; + if (copy == 0) goto inf_leave; + zmemcpy(put, next, copy); + have -= copy; + next += copy; + left -= copy; + put += copy; + state->length -= copy; + break; + } + Tracev((stderr, "inflate: stored end\n")); + state->mode = TYPE; + break; + case TABLE: + NEEDBITS(14); + state->nlen = BITS(5) + 257; + DROPBITS(5); + state->ndist = BITS(5) + 1; + DROPBITS(5); + state->ncode = BITS(4) + 4; + DROPBITS(4); +#ifndef PKZIP_BUG_WORKAROUND + if (state->nlen > 286 || state->ndist > 30) { + strm->msg = (char *)"too many length or distance symbols"; + state->mode = BAD; + break; + } +#endif + Tracev((stderr, "inflate: table sizes ok\n")); + state->have = 0; + state->mode = LENLENS; + case LENLENS: + while (state->have < state->ncode) { + NEEDBITS(3); + state->lens[order[state->have++]] = (unsigned short)BITS(3); + DROPBITS(3); + } + while (state->have < 19) + state->lens[order[state->have++]] = 0; + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 7; + ret = inflate_table(CODES, state->lens, 19, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid code lengths set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: code lengths ok\n")); + state->have = 0; + state->mode = CODELENS; + case CODELENS: + while (state->have < state->nlen + state->ndist) { + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.val < 16) { + DROPBITS(here.bits); + state->lens[state->have++] = here.val; + } + else { + if (here.val == 16) { + NEEDBITS(here.bits + 2); + DROPBITS(here.bits); + if (state->have == 0) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + len = state->lens[state->have - 1]; + copy = 3 + BITS(2); + DROPBITS(2); + } + else if (here.val == 17) { + NEEDBITS(here.bits + 3); + DROPBITS(here.bits); + len = 0; + copy = 3 + BITS(3); + DROPBITS(3); + } + else { + NEEDBITS(here.bits + 7); + DROPBITS(here.bits); + len = 0; + copy = 11 + BITS(7); + DROPBITS(7); + } + if (state->have + copy > state->nlen + state->ndist) { + strm->msg = (char *)"invalid bit length repeat"; + state->mode = BAD; + break; + } + while (copy--) + state->lens[state->have++] = (unsigned short)len; + } + } + + /* handle error breaks in while */ + if (state->mode == BAD) break; + + /* check for end-of-block code (better have one) */ + if (state->lens[256] == 0) { + strm->msg = (char *)"invalid code -- missing end-of-block"; + state->mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state->next = state->codes; + state->lencode = (const code FAR *)(state->next); + state->lenbits = 9; + ret = inflate_table(LENS, state->lens, state->nlen, &(state->next), + &(state->lenbits), state->work); + if (ret) { + strm->msg = (char *)"invalid literal/lengths set"; + state->mode = BAD; + break; + } + state->distcode = (const code FAR *)(state->next); + state->distbits = 6; + ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist, + &(state->next), &(state->distbits), state->work); + if (ret) { + strm->msg = (char *)"invalid distances set"; + state->mode = BAD; + break; + } + Tracev((stderr, "inflate: codes ok\n")); + state->mode = LEN_; + if (flush == Z_TREES) goto inf_leave; + case LEN_: + state->mode = LEN; + case LEN: + if (have >= 6 && left >= 258) { + RESTORE(); + inflate_fast(strm, out); + LOAD(); + if (state->mode == TYPE) + state->back = -1; + break; + } + state->back = 0; + for (;;) { + here = state->lencode[BITS(state->lenbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if (here.op && (here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->lencode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + state->length = (unsigned)here.val; + if ((int)(here.op) == 0) { + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + state->mode = LIT; + break; + } + if (here.op & 32) { + Tracevv((stderr, "inflate: end of block\n")); + state->back = -1; + state->mode = TYPE; + break; + } + if (here.op & 64) { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + state->extra = (unsigned)(here.op) & 15; + state->mode = LENEXT; + case LENEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->length += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } + Tracevv((stderr, "inflate: length %u\n", state->length)); + state->was = state->length; + state->mode = DIST; + case DIST: + for (;;) { + here = state->distcode[BITS(state->distbits)]; + if ((unsigned)(here.bits) <= bits) break; + PULLBYTE(); + } + if ((here.op & 0xf0) == 0) { + last = here; + for (;;) { + here = state->distcode[last.val + + (BITS(last.bits + last.op) >> last.bits)]; + if ((unsigned)(last.bits + here.bits) <= bits) break; + PULLBYTE(); + } + DROPBITS(last.bits); + state->back += last.bits; + } + DROPBITS(here.bits); + state->back += here.bits; + if (here.op & 64) { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + state->offset = (unsigned)here.val; + state->extra = (unsigned)(here.op) & 15; + state->mode = DISTEXT; + case DISTEXT: + if (state->extra) { + NEEDBITS(state->extra); + state->offset += BITS(state->extra); + DROPBITS(state->extra); + state->back += state->extra; + } +#ifdef INFLATE_STRICT + if (state->offset > state->dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + Tracevv((stderr, "inflate: distance %u\n", state->offset)); + state->mode = MATCH; + case MATCH: + if (left == 0) goto inf_leave; + copy = out - left; + if (state->offset > copy) { /* copy from window */ + copy = state->offset - copy; + if (copy > state->whave) { + if (state->sane) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + Trace((stderr, "inflate.c too far\n")); + copy -= state->whave; + if (copy > state->length) copy = state->length; + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = 0; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; +#endif + } + if (copy > state->wnext) { + copy -= state->wnext; + from = state->window + (state->wsize - copy); + } + else + from = state->window + (state->wnext - copy); + if (copy > state->length) copy = state->length; + } + else { /* copy from output */ + from = put - state->offset; + copy = state->length; + } + if (copy > left) copy = left; + left -= copy; + state->length -= copy; + do { + *put++ = *from++; + } while (--copy); + if (state->length == 0) state->mode = LEN; + break; + case LIT: + if (left == 0) goto inf_leave; + *put++ = (unsigned char)(state->length); + left--; + state->mode = LEN; + break; + case CHECK: + if (state->wrap) { + NEEDBITS(32); + out -= left; + strm->total_out += out; + state->total += out; + if (out) + strm->adler = state->check = + UPDATE(state->check, put - out, out); + out = left; + if (( +#ifdef GUNZIP + state->flags ? hold : +#endif + ZSWAP32(hold)) != state->check) { + strm->msg = (char *)"incorrect data check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: check matches trailer\n")); + } +#ifdef GUNZIP + state->mode = LENGTH; + case LENGTH: + if (state->wrap && state->flags) { + NEEDBITS(32); + if (hold != (state->total & 0xffffffffUL)) { + strm->msg = (char *)"incorrect length check"; + state->mode = BAD; + break; + } + INITBITS(); + Tracev((stderr, "inflate: length matches trailer\n")); + } +#endif + state->mode = DONE; + case DONE: + ret = Z_STREAM_END; + goto inf_leave; + case BAD: + ret = Z_DATA_ERROR; + goto inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + default: + return Z_STREAM_ERROR; + } + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + inf_leave: + RESTORE(); + if (state->wsize || (out != strm->avail_out && state->mode < BAD && + (state->mode < CHECK || flush != Z_FINISH))) + if (updatewindow(strm, strm->next_out, out - strm->avail_out)) { + state->mode = MEM; + return Z_MEM_ERROR; + } + in -= strm->avail_in; + out -= strm->avail_out; + strm->total_in += in; + strm->total_out += out; + state->total += out; + if (state->wrap && out) + strm->adler = state->check = + UPDATE(state->check, strm->next_out - out, out); + strm->data_type = state->bits + (state->last ? 64 : 0) + + (state->mode == TYPE ? 128 : 0) + + (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0); + if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK) + ret = Z_BUF_ERROR; + return ret; +} + +int ZEXPORT inflateEnd(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->window != Z_NULL) ZFREE(strm, state->window); + ZFREE(strm, strm->state); + strm->state = Z_NULL; + Tracev((stderr, "inflate: end\n")); + return Z_OK; +} + +int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength) +z_streamp strm; +Bytef *dictionary; +uInt *dictLength; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + + /* copy dictionary */ + if (state->whave && dictionary != Z_NULL) { + zmemcpy(dictionary, state->window + state->wnext, + state->whave - state->wnext); + zmemcpy(dictionary + state->whave - state->wnext, + state->window, state->wnext); + } + if (dictLength != Z_NULL) + *dictLength = state->whave; + return Z_OK; +} + +int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength) +z_streamp strm; +const Bytef *dictionary; +uInt dictLength; +{ + struct inflate_state FAR *state; + unsigned long dictid; + int ret; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (state->wrap != 0 && state->mode != DICT) + return Z_STREAM_ERROR; + + /* check for correct dictionary identifier */ + if (state->mode == DICT) { + dictid = adler32(0L, Z_NULL, 0); + dictid = adler32(dictid, dictionary, dictLength); + if (dictid != state->check) + return Z_DATA_ERROR; + } + + /* copy dictionary to window using updatewindow(), which will amend the + existing dictionary if appropriate */ + ret = updatewindow(strm, dictionary + dictLength, dictLength); + if (ret) { + state->mode = MEM; + return Z_MEM_ERROR; + } + state->havedict = 1; + Tracev((stderr, "inflate: dictionary set\n")); + return Z_OK; +} + +int ZEXPORT inflateGetHeader(strm, head) +z_streamp strm; +gz_headerp head; +{ + struct inflate_state FAR *state; + + /* check state */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if ((state->wrap & 2) == 0) return Z_STREAM_ERROR; + + /* save header structure */ + state->head = head; + head->done = 0; + return Z_OK; +} + +/* + Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found + or when out of input. When called, *have is the number of pattern bytes + found in order so far, in 0..3. On return *have is updated to the new + state. If on return *have equals four, then the pattern was found and the + return value is how many bytes were read including the last byte of the + pattern. If *have is less than four, then the pattern has not been found + yet and the return value is len. In the latter case, syncsearch() can be + called again with more data and the *have state. *have is initialized to + zero for the first call. + */ +local unsigned syncsearch(have, buf, len) +unsigned FAR *have; +const unsigned char FAR *buf; +unsigned len; +{ + unsigned got; + unsigned next; + + got = *have; + next = 0; + while (next < len && got < 4) { + if ((int)(buf[next]) == (got < 2 ? 0 : 0xff)) + got++; + else if (buf[next]) + got = 0; + else + got = 4 - got; + next++; + } + *have = got; + return next; +} + +int ZEXPORT inflateSync(strm) +z_streamp strm; +{ + unsigned len; /* number of bytes to look at or looked at */ + unsigned long in, out; /* temporary to save total_in and total_out */ + unsigned char buf[4]; /* to restore bit buffer to byte string */ + struct inflate_state FAR *state; + + /* check parameters */ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR; + + /* if first time, start search in bit buffer */ + if (state->mode != SYNC) { + state->mode = SYNC; + state->hold <<= state->bits & 7; + state->bits -= state->bits & 7; + len = 0; + while (state->bits >= 8) { + buf[len++] = (unsigned char)(state->hold); + state->hold >>= 8; + state->bits -= 8; + } + state->have = 0; + syncsearch(&(state->have), buf, len); + } + + /* search available input */ + len = syncsearch(&(state->have), strm->next_in, strm->avail_in); + strm->avail_in -= len; + strm->next_in += len; + strm->total_in += len; + + /* return no joy or set up to restart inflate() on a new block */ + if (state->have != 4) return Z_DATA_ERROR; + in = strm->total_in; out = strm->total_out; + inflateReset(strm); + strm->total_in = in; strm->total_out = out; + state->mode = TYPE; + return Z_OK; +} + +/* + Returns true if inflate is currently at the end of a block generated by + Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP + implementation to provide an additional safety check. PPP uses + Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored + block. When decompressing, PPP checks that at the end of input packet, + inflate is waiting for these length bytes. + */ +int ZEXPORT inflateSyncPoint(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + return state->mode == STORED && state->bits == 0; +} + +int ZEXPORT inflateCopy(dest, source) +z_streamp dest; +z_streamp source; +{ + struct inflate_state FAR *state; + struct inflate_state FAR *copy; + unsigned char FAR *window; + unsigned wsize; + + /* check input */ + if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL || + source->zalloc == (alloc_func)0 || source->zfree == (free_func)0) + return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)source->state; + + /* allocate space */ + copy = (struct inflate_state FAR *) + ZALLOC(source, 1, sizeof(struct inflate_state)); + if (copy == Z_NULL) return Z_MEM_ERROR; + window = Z_NULL; + if (state->window != Z_NULL) { + window = (unsigned char FAR *) + ZALLOC(source, 1U << state->wbits, sizeof(unsigned char)); + if (window == Z_NULL) { + ZFREE(source, copy); + return Z_MEM_ERROR; + } + } + + /* copy state */ + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state)); + if (state->lencode >= state->codes && + state->lencode <= state->codes + ENOUGH - 1) { + copy->lencode = copy->codes + (state->lencode - state->codes); + copy->distcode = copy->codes + (state->distcode - state->codes); + } + copy->next = copy->codes + (state->next - state->codes); + if (window != Z_NULL) { + wsize = 1U << state->wbits; + zmemcpy(window, state->window, wsize); + } + copy->window = window; + dest->state = (struct internal_state FAR *)copy; + return Z_OK; +} + +int ZEXPORT inflateUndermine(strm, subvert) +z_streamp strm; +int subvert; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + state = (struct inflate_state FAR *)strm->state; + state->sane = !subvert; +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + return Z_OK; +#else + state->sane = 1; + return Z_DATA_ERROR; +#endif +} + +long ZEXPORT inflateMark(strm) +z_streamp strm; +{ + struct inflate_state FAR *state; + + if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16; + state = (struct inflate_state FAR *)strm->state; + return ((long)(state->back) << 16) + + (state->mode == COPY ? state->length : + (state->mode == MATCH ? state->was - state->length : 0)); +} diff --git a/armsrc/inflate.h b/armsrc/inflate.h new file mode 100644 index 00000000..95f4986d --- /dev/null +++ b/armsrc/inflate.h @@ -0,0 +1,122 @@ +/* inflate.h -- internal inflate state definition + * Copyright (C) 1995-2009 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer decoding by inflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip decoding + should be left enabled. */ +#ifndef NO_GZIP +# define GUNZIP +#endif + +/* Possible inflate modes between inflate() calls */ +typedef enum { + HEAD, /* i: waiting for magic header */ + FLAGS, /* i: waiting for method and flags (gzip) */ + TIME, /* i: waiting for modification time (gzip) */ + OS, /* i: waiting for extra flags and operating system (gzip) */ + EXLEN, /* i: waiting for extra length (gzip) */ + EXTRA, /* i: waiting for extra bytes (gzip) */ + NAME, /* i: waiting for end of file name (gzip) */ + COMMENT, /* i: waiting for end of comment (gzip) */ + HCRC, /* i: waiting for header crc (gzip) */ + DICTID, /* i: waiting for dictionary check value */ + DICT, /* waiting for inflateSetDictionary() call */ + TYPE, /* i: waiting for type bits, including last-flag bit */ + TYPEDO, /* i: same, but skip check to exit inflate on new block */ + STORED, /* i: waiting for stored size (length and complement) */ + COPY_, /* i/o: same as COPY below, but only first time in */ + COPY, /* i/o: waiting for input or output to copy stored block */ + TABLE, /* i: waiting for dynamic block table lengths */ + LENLENS, /* i: waiting for code length code lengths */ + CODELENS, /* i: waiting for length/lit and distance code lengths */ + LEN_, /* i: same as LEN below, but only first time in */ + LEN, /* i: waiting for length/lit/eob code */ + LENEXT, /* i: waiting for length extra bits */ + DIST, /* i: waiting for distance code */ + DISTEXT, /* i: waiting for distance extra bits */ + MATCH, /* o: waiting for output space to copy string */ + LIT, /* o: waiting for output space to write literal */ + CHECK, /* i: waiting for 32-bit check value */ + LENGTH, /* i: waiting for 32-bit length (gzip) */ + DONE, /* finished check, done -- remain here until reset */ + BAD, /* got a data error -- remain here until reset */ + MEM, /* got an inflate() memory error -- remain here until reset */ + SYNC /* looking for synchronization bytes to restart inflate() */ +} inflate_mode; + +/* + State transitions between above modes - + + (most modes can go to BAD or MEM on error -- not shown for clarity) + + Process header: + HEAD -> (gzip) or (zlib) or (raw) + (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT -> + HCRC -> TYPE + (zlib) -> DICTID or TYPE + DICTID -> DICT -> TYPE + (raw) -> TYPEDO + Read deflate blocks: + TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK + STORED -> COPY_ -> COPY -> TYPE + TABLE -> LENLENS -> CODELENS -> LEN_ + LEN_ -> LEN + Read deflate codes in fixed or dynamic block: + LEN -> LENEXT or LIT or TYPE + LENEXT -> DIST -> DISTEXT -> MATCH -> LEN + LIT -> LEN + Process trailer: + CHECK -> LENGTH -> DONE + */ + +/* state maintained between inflate() calls. Approximately 10K bytes. */ +struct inflate_state { + inflate_mode mode; /* current inflate mode */ + int last; /* true if processing last block */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + int havedict; /* true if dictionary provided */ + int flags; /* gzip header method and flags (0 if zlib) */ + unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */ + unsigned long check; /* protected copy of check value */ + unsigned long total; /* protected copy of output count */ + gz_headerp head; /* where to save gzip header information */ + /* sliding window */ + unsigned wbits; /* log base 2 of requested window size */ + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if needed */ + /* bit accumulator */ + unsigned long hold; /* input bit accumulator */ + unsigned bits; /* number of bits in "in" */ + /* for string and stored block copying */ + unsigned length; /* literal or length of data to copy */ + unsigned offset; /* distance back to copy string from */ + /* for table and code decoding */ + unsigned extra; /* extra bits needed */ + /* fixed and dynamic code tables */ + code const FAR *lencode; /* starting table for length/literal codes */ + code const FAR *distcode; /* starting table for distance codes */ + unsigned lenbits; /* index bits for lencode */ + unsigned distbits; /* index bits for distcode */ + /* dynamic table building */ + unsigned ncode; /* number of code length code lengths */ + unsigned nlen; /* number of length code lengths */ + unsigned ndist; /* number of distance code lengths */ + unsigned have; /* number of code lengths in lens[] */ + code FAR *next; /* next available space in codes[] */ + unsigned short lens[320]; /* temporary storage for code lengths */ + unsigned short work[288]; /* work area for code table building */ + code codes[ENOUGH]; /* space for code tables */ + int sane; /* if false, allow invalid distance too far */ + int back; /* bits back of last unprocessed length/lit */ + unsigned was; /* initial length of match */ +}; diff --git a/armsrc/inftrees.h b/armsrc/inftrees.h new file mode 100644 index 00000000..baa53a0b --- /dev/null +++ b/armsrc/inftrees.h @@ -0,0 +1,62 @@ +/* inftrees.h -- header to use inftrees.c + * Copyright (C) 1995-2005, 2010 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* Structure for decoding tables. Each entry provides either the + information needed to do the operation requested by the code that + indexed that table entry, or it provides a pointer to another + table that indexes more bits of the code. op indicates whether + the entry is a pointer to another table, a literal, a length or + distance, an end-of-block, or an invalid code. For a table + pointer, the low four bits of op is the number of index bits of + that table. For a length or distance, the low four bits of op + is the number of extra bits to get after the code. bits is + the number of bits in this code or part of the code to drop off + of the bit buffer. val is the actual byte to output in the case + of a literal, the base length or distance, or the offset from + the current table to the next table. Each entry is four bytes. */ +typedef struct { + unsigned char op; /* operation, extra bits, table bits */ + unsigned char bits; /* bits in this part of the code */ + unsigned short val; /* offset in table or code value */ +} code; + +/* op values as set by inflate_table(): + 00000000 - literal + 0000tttt - table link, tttt != 0 is the number of table index bits + 0001eeee - length or distance, eeee is the number of extra bits + 01100000 - end of block + 01000000 - invalid code + */ + +/* Maximum size of the dynamic table. The maximum number of code structures is + 1444, which is the sum of 852 for literal/length codes and 592 for distance + codes. These values were found by exhaustive searches using the program + examples/enough.c found in the zlib distribtution. The arguments to that + program are the number of symbols, the initial root table size, and the + maximum bit length of a code. "enough 286 9 15" for literal/length codes + returns returns 852, and "enough 30 6 15" for distance codes returns 592. + The initial root table size (9 or 6) is found in the fifth argument of the + inflate_table() calls in inflate.c and infback.c. If the root table size is + changed, then these maximum sizes would be need to be recalculated and + updated. */ +#define ENOUGH_LENS 852 +#define ENOUGH_DISTS 592 +#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS) + +/* Type of code to build for inflate_table() */ +typedef enum { + CODES, + LENS, + DISTS +} codetype; + +int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work)); diff --git a/armsrc/ldscript b/armsrc/ldscript index 840b8196..ce7a330e 100644 --- a/armsrc/ldscript +++ b/armsrc/ldscript @@ -51,6 +51,7 @@ SECTIONS __data_src_start__ = LOADADDR(.data); __data_start__ = ADDR(.data); __data_end__ = __data_start__ + SIZEOF(.data); + __os_size__ = SIZEOF(.text) + SIZEOF(.data) + SIZEOF(.rodata); .bss : { __bss_start__ = .; diff --git a/armsrc/zconf.h b/armsrc/zconf.h new file mode 100644 index 00000000..9987a775 --- /dev/null +++ b/armsrc/zconf.h @@ -0,0 +1,511 @@ +/* zconf.h -- configuration of the zlib compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#ifndef ZCONF_H +#define ZCONF_H + +/* + * If you *really* need a unique prefix for all types and library functions, + * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. + * Even better than compiling with -DZ_PREFIX would be to use configure to set + * this permanently in zconf.h using "./configure --zprefix". + */ +#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */ +# define Z_PREFIX_SET + +/* all linked symbols */ +# define _dist_code z__dist_code +# define _length_code z__length_code +# define _tr_align z__tr_align +# define _tr_flush_bits z__tr_flush_bits +# define _tr_flush_block z__tr_flush_block +# define _tr_init z__tr_init +# define _tr_stored_block z__tr_stored_block +# define _tr_tally z__tr_tally +# define adler32 z_adler32 +# define adler32_combine z_adler32_combine +# define adler32_combine64 z_adler32_combine64 +# ifndef Z_SOLO +# define compress z_compress +# define compress2 z_compress2 +# define compressBound z_compressBound +# endif +# define crc32 z_crc32 +# define crc32_combine z_crc32_combine +# define crc32_combine64 z_crc32_combine64 +# define deflate z_deflate +# define deflateBound z_deflateBound +# define deflateCopy z_deflateCopy +# define deflateEnd z_deflateEnd +# define deflateInit2_ z_deflateInit2_ +# define deflateInit_ z_deflateInit_ +# define deflateParams z_deflateParams +# define deflatePending z_deflatePending +# define deflatePrime z_deflatePrime +# define deflateReset z_deflateReset +# define deflateResetKeep z_deflateResetKeep +# define deflateSetDictionary z_deflateSetDictionary +# define deflateSetHeader z_deflateSetHeader +# define deflateTune z_deflateTune +# define deflate_copyright z_deflate_copyright +# define get_crc_table z_get_crc_table +# ifndef Z_SOLO +# define gz_error z_gz_error +# define gz_intmax z_gz_intmax +# define gz_strwinerror z_gz_strwinerror +# define gzbuffer z_gzbuffer +# define gzclearerr z_gzclearerr +# define gzclose z_gzclose +# define gzclose_r z_gzclose_r +# define gzclose_w z_gzclose_w +# define gzdirect z_gzdirect +# define gzdopen z_gzdopen +# define gzeof z_gzeof +# define gzerror z_gzerror +# define gzflush z_gzflush +# define gzgetc z_gzgetc +# define gzgetc_ z_gzgetc_ +# define gzgets z_gzgets +# define gzoffset z_gzoffset +# define gzoffset64 z_gzoffset64 +# define gzopen z_gzopen +# define gzopen64 z_gzopen64 +# ifdef _WIN32 +# define gzopen_w z_gzopen_w +# endif +# define gzprintf z_gzprintf +# define gzvprintf z_gzvprintf +# define gzputc z_gzputc +# define gzputs z_gzputs +# define gzread z_gzread +# define gzrewind z_gzrewind +# define gzseek z_gzseek +# define gzseek64 z_gzseek64 +# define gzsetparams z_gzsetparams +# define gztell z_gztell +# define gztell64 z_gztell64 +# define gzungetc z_gzungetc +# define gzwrite z_gzwrite +# endif +# define inflate z_inflate +# define inflateBack z_inflateBack +# define inflateBackEnd z_inflateBackEnd +# define inflateBackInit_ z_inflateBackInit_ +# define inflateCopy z_inflateCopy +# define inflateEnd z_inflateEnd +# define inflateGetHeader z_inflateGetHeader +# define inflateInit2_ z_inflateInit2_ +# define inflateInit_ z_inflateInit_ +# define inflateMark z_inflateMark +# define inflatePrime z_inflatePrime +# define inflateReset z_inflateReset +# define inflateReset2 z_inflateReset2 +# define inflateSetDictionary z_inflateSetDictionary +# define inflateGetDictionary z_inflateGetDictionary +# define inflateSync z_inflateSync +# define inflateSyncPoint z_inflateSyncPoint +# define inflateUndermine z_inflateUndermine +# define inflateResetKeep z_inflateResetKeep +# define inflate_copyright z_inflate_copyright +# define inflate_fast z_inflate_fast +# define inflate_table z_inflate_table +# ifndef Z_SOLO +# define uncompress z_uncompress +# endif +# define zError z_zError +# ifndef Z_SOLO +# define zcalloc z_zcalloc +# define zcfree z_zcfree +# endif +# define zlibCompileFlags z_zlibCompileFlags +# define zlibVersion z_zlibVersion + +/* all zlib typedefs in zlib.h and zconf.h */ +# define Byte z_Byte +# define Bytef z_Bytef +# define alloc_func z_alloc_func +# define charf z_charf +# define free_func z_free_func +# ifndef Z_SOLO +# define gzFile z_gzFile +# endif +# define gz_header z_gz_header +# define gz_headerp z_gz_headerp +# define in_func z_in_func +# define intf z_intf +# define out_func z_out_func +# define uInt z_uInt +# define uIntf z_uIntf +# define uLong z_uLong +# define uLongf z_uLongf +# define voidp z_voidp +# define voidpc z_voidpc +# define voidpf z_voidpf + +/* all zlib structs in zlib.h and zconf.h */ +# define gz_header_s z_gz_header_s +# define internal_state z_internal_state + +#endif + +#if defined(__MSDOS__) && !defined(MSDOS) +# define MSDOS +#endif +#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2) +# define OS2 +#endif +#if defined(_WINDOWS) && !defined(WINDOWS) +# define WINDOWS +#endif +#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__) +# ifndef WIN32 +# define WIN32 +# endif +#endif +#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32) +# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__) +# ifndef SYS16BIT +# define SYS16BIT +# endif +# endif +#endif + +/* + * Compile with -DMAXSEG_64K if the alloc function cannot allocate more + * than 64k bytes at a time (needed on systems with 16-bit int). + */ +#ifdef SYS16BIT +# define MAXSEG_64K +#endif +#ifdef MSDOS +# define UNALIGNED_OK +#endif + +#ifdef __STDC_VERSION__ +# ifndef STDC +# define STDC +# endif +# if __STDC_VERSION__ >= 199901L +# ifndef STDC99 +# define STDC99 +# endif +# endif +#endif +#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus)) +# define STDC +#endif +#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__)) +# define STDC +#endif +#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32)) +# define STDC +#endif +#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__)) +# define STDC +#endif + +#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */ +# define STDC +#endif + +#ifndef STDC +# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */ +# define const /* note: need a more gentle solution here */ +# endif +#endif + +#if defined(ZLIB_CONST) && !defined(z_const) +# define z_const const +#else +# define z_const +#endif + +/* Some Mac compilers merge all .h files incorrectly: */ +#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__) +# define NO_DUMMY_DECL +#endif + +/* Maximum value for memLevel in deflateInit2 */ +#ifndef MAX_MEM_LEVEL +# ifdef MAXSEG_64K +# define MAX_MEM_LEVEL 8 +# else +# define MAX_MEM_LEVEL 9 +# endif +#endif + +/* Maximum value for windowBits in deflateInit2 and inflateInit2. + * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files + * created by gzip. (Files created by minigzip can still be extracted by + * gzip.) + */ +#ifndef MAX_WBITS +# define MAX_WBITS 15 /* 32K LZ77 window */ +#endif + +/* The memory requirements for deflate are (in bytes): + (1 << (windowBits+2)) + (1 << (memLevel+9)) + that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values) + plus a few kilobytes for small objects. For example, if you want to reduce + the default memory requirements from 256K to 128K, compile with + make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7" + Of course this will generally degrade compression (there's no free lunch). + + The memory requirements for inflate are (in bytes) 1 << windowBits + that is, 32K for windowBits=15 (default value) plus a few kilobytes + for small objects. +*/ + + /* Type declarations */ + +#ifndef OF /* function prototypes */ +# ifdef STDC +# define OF(args) args +# else +# define OF(args) () +# endif +#endif + +#ifndef Z_ARG /* function prototypes for stdarg */ +# if defined(STDC) || defined(Z_HAVE_STDARG_H) +# define Z_ARG(args) args +# else +# define Z_ARG(args) () +# endif +#endif + +/* The following definitions for FAR are needed only for MSDOS mixed + * model programming (small or medium model with some far allocations). + * This was tested only with MSC; for other MSDOS compilers you may have + * to define NO_MEMCPY in zutil.h. If you don't need the mixed model, + * just define FAR to be empty. + */ +#ifdef SYS16BIT +# if defined(M_I86SM) || defined(M_I86MM) + /* MSC small or medium model */ +# define SMALL_MEDIUM +# ifdef _MSC_VER +# define FAR _far +# else +# define FAR far +# endif +# endif +# if (defined(__SMALL__) || defined(__MEDIUM__)) + /* Turbo C small or medium model */ +# define SMALL_MEDIUM +# ifdef __BORLANDC__ +# define FAR _far +# else +# define FAR far +# endif +# endif +#endif + +#if defined(WINDOWS) || defined(WIN32) + /* If building or using zlib as a DLL, define ZLIB_DLL. + * This is not mandatory, but it offers a little performance increase. + */ +# ifdef ZLIB_DLL +# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500)) +# ifdef ZLIB_INTERNAL +# define ZEXTERN extern __declspec(dllexport) +# else +# define ZEXTERN extern __declspec(dllimport) +# endif +# endif +# endif /* ZLIB_DLL */ + /* If building or using zlib with the WINAPI/WINAPIV calling convention, + * define ZLIB_WINAPI. + * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI. + */ +# ifdef ZLIB_WINAPI +# ifdef FAR +# undef FAR +# endif +# include + /* No need for _export, use ZLIB.DEF instead. */ + /* For complete Windows compatibility, use WINAPI, not __stdcall. */ +# define ZEXPORT WINAPI +# ifdef WIN32 +# define ZEXPORTVA WINAPIV +# else +# define ZEXPORTVA FAR CDECL +# endif +# endif +#endif + +#if defined (__BEOS__) +# ifdef ZLIB_DLL +# ifdef ZLIB_INTERNAL +# define ZEXPORT __declspec(dllexport) +# define ZEXPORTVA __declspec(dllexport) +# else +# define ZEXPORT __declspec(dllimport) +# define ZEXPORTVA __declspec(dllimport) +# endif +# endif +#endif + +#ifndef ZEXTERN +# define ZEXTERN extern +#endif +#ifndef ZEXPORT +# define ZEXPORT +#endif +#ifndef ZEXPORTVA +# define ZEXPORTVA +#endif + +#ifndef FAR +# define FAR +#endif + +#if !defined(__MACTYPES__) +typedef unsigned char Byte; /* 8 bits */ +#endif +typedef unsigned int uInt; /* 16 bits or more */ +typedef unsigned long uLong; /* 32 bits or more */ + +#ifdef SMALL_MEDIUM + /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */ +# define Bytef Byte FAR +#else + typedef Byte FAR Bytef; +#endif +typedef char FAR charf; +typedef int FAR intf; +typedef uInt FAR uIntf; +typedef uLong FAR uLongf; + +#ifdef STDC + typedef void const *voidpc; + typedef void FAR *voidpf; + typedef void *voidp; +#else + typedef Byte const *voidpc; + typedef Byte FAR *voidpf; + typedef Byte *voidp; +#endif + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +# include +# if (UINT_MAX == 0xffffffffUL) +# define Z_U4 unsigned +# elif (ULONG_MAX == 0xffffffffUL) +# define Z_U4 unsigned long +# elif (USHRT_MAX == 0xffffffffUL) +# define Z_U4 unsigned short +# endif +#endif + +#ifdef Z_U4 + typedef Z_U4 z_crc_t; +#else + typedef unsigned long z_crc_t; +#endif + +#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_UNISTD_H +#endif + +#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */ +# define Z_HAVE_STDARG_H +#endif + +#ifdef STDC +# ifndef Z_SOLO +# include /* for off_t */ +# endif +#endif + +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +# include /* for va_list */ +# endif +#endif + +#ifdef _WIN32 +# ifndef Z_SOLO +# include /* for wchar_t */ +# endif +#endif + +/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and + * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even + * though the former does not conform to the LFS document), but considering + * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as + * equivalently requesting no 64-bit operations + */ +#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1 +# undef _LARGEFILE64_SOURCE +#endif + +#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H) +# define Z_HAVE_UNISTD_H +#endif +#ifndef Z_SOLO +# if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE) +# include /* for SEEK_*, off_t, and _LFS64_LARGEFILE */ +# ifdef VMS +# include /* for off_t */ +# endif +# ifndef z_off_t +# define z_off_t off_t +# endif +# endif +#endif + +#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0 +# define Z_LFS64 +#endif + +#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64) +# define Z_LARGE64 +#endif + +#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64) +# define Z_WANT64 +#endif + +#if !defined(SEEK_SET) && !defined(Z_SOLO) +# define SEEK_SET 0 /* Seek from beginning of file. */ +# define SEEK_CUR 1 /* Seek from current position. */ +# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */ +#endif + +#ifndef z_off_t +# define z_off_t long +#endif + +#if !defined(_WIN32) && defined(Z_LARGE64) +# define z_off64_t off64_t +#else +# if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO) +# define z_off64_t __int64 +# else +# define z_off64_t z_off_t +# endif +#endif + +/* MVS linker does not support external names larger than 8 bytes */ +#if defined(__MVS__) + #pragma map(deflateInit_,"DEIN") + #pragma map(deflateInit2_,"DEIN2") + #pragma map(deflateEnd,"DEEND") + #pragma map(deflateBound,"DEBND") + #pragma map(inflateInit_,"ININ") + #pragma map(inflateInit2_,"ININ2") + #pragma map(inflateEnd,"INEND") + #pragma map(inflateSync,"INSY") + #pragma map(inflateSetDictionary,"INSEDI") + #pragma map(compressBound,"CMBND") + #pragma map(inflate_table,"INTABL") + #pragma map(inflate_fast,"INFA") + #pragma map(inflate_copyright,"INCOPY") +#endif + +#endif /* ZCONF_H */ diff --git a/armsrc/zlib.h b/armsrc/zlib.h new file mode 100644 index 00000000..3e0c7672 --- /dev/null +++ b/armsrc/zlib.h @@ -0,0 +1,1768 @@ +/* zlib.h -- interface of the 'zlib' general purpose compression library + version 1.2.8, April 28th, 2013 + + Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + + + The data format used by the zlib library is described by RFCs (Request for + Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950 + (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). +*/ + +#ifndef ZLIB_H +#define ZLIB_H + +#include "zconf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define ZLIB_VERSION "1.2.8" +#define ZLIB_VERNUM 0x1280 +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 8 +#define ZLIB_VER_SUBREVISION 0 + +/* + The 'zlib' compression library provides in-memory compression and + decompression functions, including integrity checks of the uncompressed data. + This version of the library supports only one compression method (deflation) + but other algorithms will be added later and will have the same stream + interface. + + Compression can be done in a single step if the buffers are large enough, + or can be done by repeated calls of the compression function. In the latter + case, the application must provide more input and/or consume the output + (providing more output space) before each call. + + The compressed data format used by default by the in-memory functions is + the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped + around a deflate stream, which is itself documented in RFC 1951. + + The library also supports reading and writing files in gzip (.gz) format + with an interface similar to that of stdio using the functions that start + with "gz". The gzip format is different from the zlib format. gzip is a + gzip wrapper, documented in RFC 1952, wrapped around a deflate stream. + + This library can optionally read and write gzip streams in memory as well. + + The zlib format was designed to be compact and fast for use in memory + and on communications channels. The gzip format was designed for single- + file compression on file systems, has a larger header than zlib to maintain + directory information, and uses a different, slower check method than zlib. + + The library does not install any signal handler. The decoder checks + the consistency of the compressed data, so the library should never crash + even in case of corrupted input. +*/ + +typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); +typedef void (*free_func) OF((voidpf opaque, voidpf address)); + +struct internal_state; + +typedef struct z_stream_s { + z_const Bytef *next_in; /* next input byte */ + uInt avail_in; /* number of bytes available at next_in */ + uLong total_in; /* total number of input bytes read so far */ + + Bytef *next_out; /* next output byte should be put there */ + uInt avail_out; /* remaining free space at next_out */ + uLong total_out; /* total number of bytes output so far */ + + z_const char *msg; /* last error message, NULL if no error */ + struct internal_state FAR *state; /* not visible by applications */ + + alloc_func zalloc; /* used to allocate the internal state */ + free_func zfree; /* used to free the internal state */ + voidpf opaque; /* private data object passed to zalloc and zfree */ + + int data_type; /* best guess about the data type: binary or text */ + uLong adler; /* adler32 value of the uncompressed data */ + uLong reserved; /* reserved for future use */ +} z_stream; + +typedef z_stream FAR *z_streamp; + +/* + gzip header information passed to and from zlib routines. See RFC 1952 + for more details on the meanings of these fields. +*/ +typedef struct gz_header_s { + int text; /* true if compressed data believed to be text */ + uLong time; /* modification time */ + int xflags; /* extra flags (not used when writing a gzip file) */ + int os; /* operating system */ + Bytef *extra; /* pointer to extra field or Z_NULL if none */ + uInt extra_len; /* extra field length (valid if extra != Z_NULL) */ + uInt extra_max; /* space at extra (only when reading header) */ + Bytef *name; /* pointer to zero-terminated file name or Z_NULL */ + uInt name_max; /* space at name (only when reading header) */ + Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */ + uInt comm_max; /* space at comment (only when reading header) */ + int hcrc; /* true if there was or will be a header crc */ + int done; /* true when done reading gzip header (not used + when writing a gzip file) */ +} gz_header; + +typedef gz_header FAR *gz_headerp; + +/* + The application must update next_in and avail_in when avail_in has dropped + to zero. It must update next_out and avail_out when avail_out has dropped + to zero. The application must initialize zalloc, zfree and opaque before + calling the init function. All other fields are set by the compression + library and must not be updated by the application. + + The opaque value provided by the application will be passed as the first + parameter for calls of zalloc and zfree. This can be useful for custom + memory management. The compression library attaches no meaning to the + opaque value. + + zalloc must return Z_NULL if there is not enough memory for the object. + If zlib is used in a multi-threaded application, zalloc and zfree must be + thread safe. + + On 16-bit systems, the functions zalloc and zfree must be able to allocate + exactly 65536 bytes, but will not be required to allocate more than this if + the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS, pointers + returned by zalloc for objects of exactly 65536 bytes *must* have their + offset normalized to zero. The default allocation function provided by this + library ensures this (see zutil.c). To reduce memory requirements and avoid + any allocation of 64K objects, at the expense of compression ratio, compile + the library with -DMAX_WBITS=14 (see zconf.h). + + The fields total_in and total_out can be used for statistics or progress + reports. After compression, total_in holds the total size of the + uncompressed data and may be saved for use in the decompressor (particularly + if the decompressor wants to decompress everything in a single step). +*/ + + /* constants */ + +#define Z_NO_FLUSH 0 +#define Z_PARTIAL_FLUSH 1 +#define Z_SYNC_FLUSH 2 +#define Z_FULL_FLUSH 3 +#define Z_FINISH 4 +#define Z_BLOCK 5 +#define Z_TREES 6 +/* Allowed flush values; see deflate() and inflate() below for details */ + +#define Z_OK 0 +#define Z_STREAM_END 1 +#define Z_NEED_DICT 2 +#define Z_ERRNO (-1) +#define Z_STREAM_ERROR (-2) +#define Z_DATA_ERROR (-3) +#define Z_MEM_ERROR (-4) +#define Z_BUF_ERROR (-5) +#define Z_VERSION_ERROR (-6) +/* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + +#define Z_NO_COMPRESSION 0 +#define Z_BEST_SPEED 1 +#define Z_BEST_COMPRESSION 9 +#define Z_DEFAULT_COMPRESSION (-1) +/* compression levels */ + +#define Z_FILTERED 1 +#define Z_HUFFMAN_ONLY 2 +#define Z_RLE 3 +#define Z_FIXED 4 +#define Z_DEFAULT_STRATEGY 0 +/* compression strategy; see deflateInit2() below for details */ + +#define Z_BINARY 0 +#define Z_TEXT 1 +#define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ +#define Z_UNKNOWN 2 +/* Possible values of the data_type field (though see inflate()) */ + +#define Z_DEFLATED 8 +/* The deflate compression method (the only one supported in this version) */ + +#define Z_NULL 0 /* for initializing zalloc, zfree, opaque */ + +#define zlib_version zlibVersion() +/* for compatibility with versions < 1.0.2 */ + + + /* basic functions */ + +ZEXTERN const char * ZEXPORT zlibVersion OF((void)); +/* The application can compare zlibVersion and ZLIB_VERSION for consistency. + If the first character differs, the library code actually used is not + compatible with the zlib.h header file used by the application. This check + is automatically made by deflateInit and inflateInit. + */ + +/* +ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); + + Initializes the internal stream state for compression. The fields + zalloc, zfree and opaque must be initialized before by the caller. If + zalloc and zfree are set to Z_NULL, deflateInit updates them to use default + allocation functions. + + The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: + 1 gives best speed, 9 gives best compression, 0 gives no compression at all + (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION + requests a default compromise between speed and compression (currently + equivalent to level 6). + + deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if level is not a valid compression level, or + Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible + with the version assumed by the caller (ZLIB_VERSION). msg is set to null + if there is no error message. deflateInit does not perform any compression: + this will be done by deflate(). +*/ + + +ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush)); +/* + deflate compresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. deflate performs one or both of the + following actions: + + - Compress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in and avail_in are updated and + processing will resume at this point for the next call of deflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. This action is forced if the parameter flush is non zero. + Forcing flush frequently degrades the compression ratio, so this parameter + should be set only when necessary (in interactive applications). Some + output may be provided even if flush is not set. + + Before the call of deflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating avail_in or avail_out accordingly; avail_out should + never be zero before the call. The application can consume the compressed + output when it wants, for example when the output buffer is full (avail_out + == 0), or after each call of deflate(). If deflate returns Z_OK and with + zero avail_out, it must be called again after making room in the output + buffer because there might be more output pending. + + Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to + decide how much data to accumulate before producing output, in order to + maximize compression. + + If the parameter flush is set to Z_SYNC_FLUSH, all pending output is + flushed to the output buffer and the output is aligned on a byte boundary, so + that the decompressor can get all input data available so far. (In + particular avail_in is zero after the call if enough output space has been + provided before the call.) Flushing may degrade compression for some + compression algorithms and so it should be used only when necessary. This + completes the current deflate block and follows it with an empty stored block + that is three bits plus filler bits to the next byte, followed by four bytes + (00 00 ff ff). + + If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the + output buffer, but the output is not aligned to a byte boundary. All of the + input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. + This completes the current deflate block and follows it with an empty fixed + codes block that is 10 bits long. This assures that enough bytes are output + in order for the decompressor to finish the block before the empty fixed code + block. + + If flush is set to Z_BLOCK, a deflate block is completed and emitted, as + for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to + seven bits of the current block are held to be written as the next byte after + the next deflate block is completed. In this case, the decompressor may not + be provided enough bits at this point in order to complete decompression of + the data provided so far to the compressor. It may need to wait for the next + block to be emitted. This is for advanced applications that need to control + the emission of deflate blocks. + + If flush is set to Z_FULL_FLUSH, all output is flushed as with + Z_SYNC_FLUSH, and the compression state is reset so that decompression can + restart from this point if previous compressed data has been damaged or if + random access is desired. Using Z_FULL_FLUSH too often can seriously degrade + compression. + + If deflate returns with avail_out == 0, this function must be called again + with the same value of the flush parameter and more output space (updated + avail_out), until the flush is complete (deflate returns with non-zero + avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that + avail_out is greater than six to avoid repeated flush markers due to + avail_out == 0 on return. + + If the parameter flush is set to Z_FINISH, pending input is processed, + pending output is flushed and deflate returns with Z_STREAM_END if there was + enough output space; if deflate returns with Z_OK, this function must be + called again with Z_FINISH and more output space (updated avail_out) but no + more input data, until it returns with Z_STREAM_END or an error. After + deflate has returned Z_STREAM_END, the only possible operations on the stream + are deflateReset or deflateEnd. + + Z_FINISH can be used immediately after deflateInit if all the compression + is to be done in a single step. In this case, avail_out must be at least the + value returned by deflateBound (see below). Then deflate is guaranteed to + return Z_STREAM_END. If not enough output space is provided, deflate will + not return Z_STREAM_END, and it must be called again as described above. + + deflate() sets strm->adler to the adler32 checksum of all input read + so far (that is, total_in bytes). + + deflate() may update strm->data_type if it can make a good guess about + the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered + binary. This field is only for information purposes and does not affect the + compression algorithm in any manner. + + deflate() returns Z_OK if some progress has been made (more input + processed or more output produced), Z_STREAM_END if all input has been + consumed and all output has been produced (only when flush is set to + Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example + if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible + (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not + fatal, and deflate() can be called again with more input and more output + space to continue compressing. +*/ + + +ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the + stream state was inconsistent, Z_DATA_ERROR if the stream was freed + prematurely (some input or output was discarded). In the error case, msg + may be set but then points to a static string (which must not be + deallocated). +*/ + + +/* +ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); + + Initializes the internal stream state for decompression. The fields + next_in, avail_in, zalloc, zfree and opaque must be initialized before by + the caller. If next_in is not Z_NULL and avail_in is large enough (the + exact value depends on the compression method), inflateInit determines the + compression method from the zlib header and allocates all data structures + accordingly; otherwise the allocation will be deferred to the first call of + inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to + use default allocation functions. + + inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit() does not process any header information -- that is deferred + until inflate() is called. +*/ + + +ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush)); +/* + inflate decompresses as much data as possible, and stops when the input + buffer becomes empty or the output buffer becomes full. It may introduce + some output latency (reading input without producing any output) except when + forced to flush. + + The detailed semantics are as follows. inflate performs one or both of the + following actions: + + - Decompress more input starting at next_in and update next_in and avail_in + accordingly. If not all input can be processed (because there is not + enough room in the output buffer), next_in is updated and processing will + resume at this point for the next call of inflate(). + + - Provide more output starting at next_out and update next_out and avail_out + accordingly. inflate() provides as much output as possible, until there is + no more input data or no more space in the output buffer (see below about + the flush parameter). + + Before the call of inflate(), the application should ensure that at least + one of the actions is possible, by providing more input and/or consuming more + output, and updating the next_* and avail_* values accordingly. The + application can consume the uncompressed output when it wants, for example + when the output buffer is full (avail_out == 0), or after each call of + inflate(). If inflate returns Z_OK and with zero avail_out, it must be + called again after making room in the output buffer because there might be + more output pending. + + The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, + Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much + output as possible to the output buffer. Z_BLOCK requests that inflate() + stop if and when it gets to the next deflate block boundary. When decoding + the zlib or gzip format, this will cause inflate() to return immediately + after the header and before the first block. When doing a raw inflate, + inflate() will go ahead and process the first block, and will return when it + gets to the end of that block, or when it runs out of data. + + The Z_BLOCK option assists in appending to or combining deflate streams. + Also to assist in this, on return inflate() will set strm->data_type to the + number of unused bits in the last byte taken from strm->next_in, plus 64 if + inflate() is currently decoding the last block in the deflate stream, plus + 128 if inflate() returned immediately after decoding an end-of-block code or + decoding the complete header up to just before the first byte of the deflate + stream. The end-of-block will not be indicated until all of the uncompressed + data from that block has been written to strm->next_out. The number of + unused bits may in general be greater than seven, except when bit 7 of + data_type is set, in which case the number of unused bits will be less than + eight. data_type is set as noted here every time inflate() returns for all + flush options, and so can be used to determine the amount of currently + consumed input in bits. + + The Z_TREES option behaves as Z_BLOCK does, but it also returns when the + end of each deflate block header is reached, before any actual data in that + block is decoded. This allows the caller to determine the length of the + deflate block header for later use in random access within a deflate block. + 256 is added to the value of strm->data_type when inflate() returns + immediately after reaching the end of the deflate block header. + + inflate() should normally be called until it returns Z_STREAM_END or an + error. However if all decompression is to be performed in a single step (a + single call of inflate), the parameter flush should be set to Z_FINISH. In + this case all pending input is processed and all pending output is flushed; + avail_out must be large enough to hold all of the uncompressed data for the + operation to complete. (The size of the uncompressed data may have been + saved by the compressor for this purpose.) The use of Z_FINISH is not + required to perform an inflation in one step. However it may be used to + inform inflate that a faster approach can be used for the single inflate() + call. Z_FINISH also informs inflate to not maintain a sliding window if the + stream completes, which reduces inflate's memory footprint. If the stream + does not complete, either because not all of the stream is provided or not + enough output space is provided, then a sliding window will be allocated and + inflate() can be called again to continue the operation as if Z_NO_FLUSH had + been used. + + In this implementation, inflate() always flushes as much output as + possible to the output buffer, and always uses the faster approach on the + first call. So the effects of the flush parameter in this implementation are + on the return value of inflate() as noted below, when inflate() returns early + when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of + memory for a sliding window when Z_FINISH is used. + + If a preset dictionary is needed after this call (see inflateSetDictionary + below), inflate sets strm->adler to the Adler-32 checksum of the dictionary + chosen by the compressor and returns Z_NEED_DICT; otherwise it sets + strm->adler to the Adler-32 checksum of all output produced so far (that is, + total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described + below. At the end of the stream, inflate() checks that its computed adler32 + checksum is equal to that saved by the compressor and returns Z_STREAM_END + only if the checksum is correct. + + inflate() can decompress and check either zlib-wrapped or gzip-wrapped + deflate data. The header type is detected automatically, if requested when + initializing with inflateInit2(). Any information contained in the gzip + header is not retained, so applications that need that information should + instead use raw inflate, see inflateInit2() below, or inflateBack() and + perform their own processing of the gzip header and trailer. When processing + gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output + producted so far. The CRC-32 is checked against the gzip trailer. + + inflate() returns Z_OK if some progress has been made (more input processed + or more output produced), Z_STREAM_END if the end of the compressed data has + been reached and all uncompressed output has been produced, Z_NEED_DICT if a + preset dictionary is needed at this point, Z_DATA_ERROR if the input data was + corrupted (input stream not conforming to the zlib format or incorrect check + value), Z_STREAM_ERROR if the stream structure was inconsistent (for example + next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory, + Z_BUF_ERROR if no progress is possible or if there was not enough room in the + output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and + inflate() can be called again with more input and more output space to + continue decompressing. If Z_DATA_ERROR is returned, the application may + then call inflateSync() to look for a good compression block if a partial + recovery of the data is desired. +*/ + + +ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm)); +/* + All dynamically allocated data structures for this stream are freed. + This function discards any unprocessed input and does not flush any pending + output. + + inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state + was inconsistent. In the error case, msg may be set but then points to a + static string (which must not be deallocated). +*/ + + + /* Advanced functions */ + +/* + The following functions are needed only in some special applications. +*/ + +/* +ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, + int level, + int method, + int windowBits, + int memLevel, + int strategy)); + + This is another version of deflateInit with more compression options. The + fields next_in, zalloc, zfree and opaque must be initialized before by the + caller. + + The method parameter is the compression method. It must be Z_DEFLATED in + this version of the library. + + The windowBits parameter is the base two logarithm of the window size + (the size of the history buffer). It should be in the range 8..15 for this + version of the library. Larger values of this parameter result in better + compression at the expense of memory usage. The default value is 15 if + deflateInit is used instead. + + windowBits can also be -8..-15 for raw deflate. In this case, -windowBits + determines the window size. deflate() will then generate raw deflate data + with no zlib header or trailer, and will not compute an adler32 check value. + + windowBits can also be greater than 15 for optional gzip encoding. Add + 16 to windowBits to write a simple gzip header and trailer around the + compressed data instead of a zlib wrapper. The gzip header will have no + file name, no extra data, no comment, no modification time (set to zero), no + header crc, and the operating system will be set to 255 (unknown). If a + gzip stream is being written, strm->adler is a crc32 instead of an adler32. + + The memLevel parameter specifies how much memory should be allocated + for the internal compression state. memLevel=1 uses minimum memory but is + slow and reduces compression ratio; memLevel=9 uses maximum memory for + optimal speed. The default value is 8. See zconf.h for total memory usage + as a function of windowBits and memLevel. + + The strategy parameter is used to tune the compression algorithm. Use the + value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a + filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no + string match), or Z_RLE to limit match distances to one (run-length + encoding). Filtered data consists mostly of small values with a somewhat + random distribution. In this case, the compression algorithm is tuned to + compress them better. The effect of Z_FILTERED is to force more Huffman + coding and less string matching; it is somewhat intermediate between + Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as + fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The + strategy parameter only affects the compression ratio but not the + correctness of the compressed output even if it is not set appropriately. + Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler + decoder for special applications. + + deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid + method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is + incompatible with the version assumed by the caller (ZLIB_VERSION). msg is + set to null if there is no error message. deflateInit2 does not perform any + compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the compression dictionary from the given byte sequence + without producing any compressed output. When using the zlib format, this + function must be called immediately after deflateInit, deflateInit2 or + deflateReset, and before any call of deflate. When doing raw deflate, this + function must be called either before any call of deflate, or immediately + after the completion of a deflate block, i.e. after all input has been + consumed and all output has been delivered when using any of the flush + options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH. The + compressor and decompressor must use exactly the same dictionary (see + inflateSetDictionary). + + The dictionary should consist of strings (byte sequences) that are likely + to be encountered later in the data to be compressed, with the most commonly + used strings preferably put towards the end of the dictionary. Using a + dictionary is most useful when the data to be compressed is short and can be + predicted with good accuracy; the data can then be compressed better than + with the default empty dictionary. + + Depending on the size of the compression data structures selected by + deflateInit or deflateInit2, a part of the dictionary may in effect be + discarded, for example if the dictionary is larger than the window size + provided in deflateInit or deflateInit2. Thus the strings most likely to be + useful should be put at the end of the dictionary, not at the front. In + addition, the current implementation of deflate will use at most the window + size minus 262 bytes of the provided dictionary. + + Upon return of this function, strm->adler is set to the adler32 value + of the dictionary; the decompressor may later use this value to determine + which dictionary has been used by the compressor. (The adler32 value + applies to the whole dictionary even if only a subset of the dictionary is + actually used by the compressor.) If a raw deflate was requested, then the + adler32 value is not computed and strm->adler is not set. + + deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent (for example if deflate has already been called for this stream + or if not at a block boundary for raw deflate). deflateSetDictionary does + not perform any compression: this will be done by deflate(). +*/ + +ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when several compression strategies will be + tried, for example when there are several ways of pre-processing the input + data with a filter. The streams that will be discarded should then be freed + by calling deflateEnd. Note that deflateCopy duplicates the internal + compression state which can be quite large, so this strategy is slow and can + consume lots of memory. + + deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm)); +/* + This function is equivalent to deflateEnd followed by deflateInit, + but does not free and reallocate all the internal compression state. The + stream will keep the same compression level and any other attributes that + may have been set by deflateInit2. + + deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, + int level, + int strategy)); +/* + Dynamically update the compression level and compression strategy. The + interpretation of level and strategy is as in deflateInit2. This can be + used to switch between compression and straight copy of the input data, or + to switch to a different kind of input data requiring a different strategy. + If the compression level is changed, the input available so far is + compressed with the old level (and may be flushed); the new level will take + effect only at the next call of deflate(). + + Before the call of deflateParams, the stream state must be set as for + a call of deflate(), since the currently available input may have to be + compressed and flushed. In particular, strm->avail_out must be non-zero. + + deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source + stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if + strm->avail_out was zero. +*/ + +ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm, + int good_length, + int max_lazy, + int nice_length, + int max_chain)); +/* + Fine tune deflate's internal compression parameters. This should only be + used by someone who understands the algorithm used by zlib's deflate for + searching for the best matching string, and even then only by the most + fanatic optimizer trying to squeeze out the last compressed bit for their + specific input data. Read the deflate.c source code for the meaning of the + max_lazy, good_length, nice_length, and max_chain parameters. + + deflateTune() can be called after deflateInit() or deflateInit2(), and + returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream. + */ + +ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm, + uLong sourceLen)); +/* + deflateBound() returns an upper bound on the compressed size after + deflation of sourceLen bytes. It must be called after deflateInit() or + deflateInit2(), and after deflateSetHeader(), if used. This would be used + to allocate an output buffer for deflation in a single pass, and so would be + called before deflate(). If that first deflate() call is provided the + sourceLen input bytes, an output buffer allocated to the size returned by + deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed + to return Z_STREAM_END. Note that it is possible for the compressed size to + be larger than the value returned by deflateBound() if flush options other + than Z_FINISH or Z_NO_FLUSH are used. +*/ + +ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm, + unsigned *pending, + int *bits)); +/* + deflatePending() returns the number of bytes and bits of output that have + been generated, but not yet provided in the available output. The bytes not + provided would be due to the available output space having being consumed. + The number of bits of output not provided are between 0 and 7, where they + await more bits to join them in order to fill out a full byte. If pending + or bits are Z_NULL, then those values are not set. + + deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. + */ + +ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + deflatePrime() inserts bits in the deflate output stream. The intent + is that this function is used to start off the deflate output with the bits + leftover from a previous deflate stream when appending to it. As such, this + function can only be used for raw deflate, and must be used before the first + deflate() call after a deflateInit2() or deflateReset(). bits must be less + than or equal to 16, and that many of the least significant bits of value + will be inserted in the output. + + deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough + room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm, + gz_headerp head)); +/* + deflateSetHeader() provides gzip header information for when a gzip + stream is requested by deflateInit2(). deflateSetHeader() may be called + after deflateInit2() or deflateReset() and before the first call of + deflate(). The text, time, os, extra field, name, and comment information + in the provided gz_header structure are written to the gzip header (xflag is + ignored -- the extra flags are set according to the compression level). The + caller must assure that, if not Z_NULL, name and comment are terminated with + a zero byte, and that if extra is not Z_NULL, that extra_len bytes are + available there. If hcrc is true, a gzip header crc is included. Note that + the current versions of the command-line version of gzip (up through version + 1.3.x) do not support header crc's, and will report that it is a "multi-part + gzip file" and give up. + + If deflateSetHeader is not used, the default gzip header has text false, + the time set to zero, and os set to 255, with no extra, name, or comment + fields. The gzip header is returned to the default state by deflateReset(). + + deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, + int windowBits)); + + This is another version of inflateInit with an extra parameter. The + fields next_in, avail_in, zalloc, zfree and opaque must be initialized + before by the caller. + + The windowBits parameter is the base two logarithm of the maximum window + size (the size of the history buffer). It should be in the range 8..15 for + this version of the library. The default value is 15 if inflateInit is used + instead. windowBits must be greater than or equal to the windowBits value + provided to deflateInit2() while compressing, or it must be equal to 15 if + deflateInit2() was not used. If a compressed stream with a larger window + size is given as input, inflate() will return with the error code + Z_DATA_ERROR instead of trying to allocate a larger window. + + windowBits can also be zero to request that inflate use the window size in + the zlib header of the compressed stream. + + windowBits can also be -8..-15 for raw inflate. In this case, -windowBits + determines the window size. inflate() will then process raw deflate data, + not looking for a zlib or gzip header, not generating a check value, and not + looking for any check values for comparison at the end of the stream. This + is for use with other formats that use the deflate compressed data format + such as zip. Those formats provide their own check values. If a custom + format is developed using the raw deflate format for compressed data, it is + recommended that a check value such as an adler32 or a crc32 be applied to + the uncompressed data as is done in the zlib, gzip, and zip formats. For + most applications, the zlib format should be used as is. Note that comments + above on the use in deflateInit2() applies to the magnitude of windowBits. + + windowBits can also be greater than 15 for optional gzip decoding. Add + 32 to windowBits to enable zlib and gzip decoding with automatic header + detection, or add 16 to decode only the gzip format (the zlib format will + return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is a + crc32 instead of an adler32. + + inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_VERSION_ERROR if the zlib library version is incompatible with the + version assumed by the caller, or Z_STREAM_ERROR if the parameters are + invalid, such as a null pointer to the structure. msg is set to null if + there is no error message. inflateInit2 does not perform any decompression + apart from possibly reading the zlib header if present: actual decompression + will be done by inflate(). (So next_in and avail_in may be modified, but + next_out and avail_out are unused and unchanged.) The current implementation + of inflateInit2() does not process any header information -- that is + deferred until inflate() is called. +*/ + +ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm, + const Bytef *dictionary, + uInt dictLength)); +/* + Initializes the decompression dictionary from the given uncompressed byte + sequence. This function must be called immediately after a call of inflate, + if that call returned Z_NEED_DICT. The dictionary chosen by the compressor + can be determined from the adler32 value returned by that call of inflate. + The compressor and decompressor must use exactly the same dictionary (see + deflateSetDictionary). For raw inflate, this function can be called at any + time to set the dictionary. If the provided dictionary is smaller than the + window and there is already data in the window, then the provided dictionary + will amend what's there. The application must insure that the dictionary + that was used for compression is provided. + + inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a + parameter is invalid (e.g. dictionary being Z_NULL) or the stream state is + inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the + expected one (incorrect adler32 value). inflateSetDictionary does not + perform any decompression: this will be done by subsequent calls of + inflate(). +*/ + +ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm, + Bytef *dictionary, + uInt *dictLength)); +/* + Returns the sliding dictionary being maintained by inflate. dictLength is + set to the number of bytes in the dictionary, and that many bytes are copied + to dictionary. dictionary must have enough space, where 32768 bytes is + always enough. If inflateGetDictionary() is called with dictionary equal to + Z_NULL, then only the dictionary length is returned, and nothing is copied. + Similary, if dictLength is Z_NULL, then it is not set. + + inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the + stream state is inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); +/* + Skips invalid compressed data until a possible full flush point (see above + for the description of deflate with Z_FULL_FLUSH) can be found, or until all + available input is skipped. No output is provided. + + inflateSync searches for a 00 00 FF FF pattern in the compressed data. + All full flush points have this pattern, but not all occurrences of this + pattern are full flush points. + + inflateSync returns Z_OK if a possible full flush point has been found, + Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point + has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. + In the success case, the application may save the current current value of + total_in which indicates where valid compressed data was found. In the + error case, the application may repeatedly call inflateSync, providing more + input each time, until success or end of the input data. +*/ + +ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest, + z_streamp source)); +/* + Sets the destination stream as a complete copy of the source stream. + + This function can be useful when randomly accessing a large stream. The + first pass through the stream can periodically record the inflate state, + allowing restarting inflate at those points when randomly accessing the + stream. + + inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_STREAM_ERROR if the source stream state was inconsistent + (such as zalloc being Z_NULL). msg is left unchanged in both source and + destination. +*/ + +ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm)); +/* + This function is equivalent to inflateEnd followed by inflateInit, + but does not free and reallocate all the internal decompression state. The + stream will keep attributes that may have been set by inflateInit2. + + inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL). +*/ + +ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm, + int windowBits)); +/* + This function is the same as inflateReset, but it also permits changing + the wrap and window size requests. The windowBits parameter is interpreted + the same as it is for inflateInit2. + + inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent (such as zalloc or state being Z_NULL), or if + the windowBits parameter is invalid. +*/ + +ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm, + int bits, + int value)); +/* + This function inserts bits in the inflate input stream. The intent is + that this function is used to start inflating at a bit position in the + middle of a byte. The provided bits will be used before any bytes are used + from next_in. This function should only be used with raw inflate, and + should be used before the first inflate() call after inflateInit2() or + inflateReset(). bits must be less than or equal to 16, and that many of the + least significant bits of value will be inserted in the input. + + If bits is negative, then the input stream bit buffer is emptied. Then + inflatePrime() can be called again to put bits in the buffer. This is used + to clear out bits leftover after feeding inflate a block description prior + to feeding inflate codes. + + inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm)); +/* + This function returns two values, one in the lower 16 bits of the return + value, and the other in the remaining upper bits, obtained by shifting the + return value down 16 bits. If the upper value is -1 and the lower value is + zero, then inflate() is currently decoding information outside of a block. + If the upper value is -1 and the lower value is non-zero, then inflate is in + the middle of a stored block, with the lower value equaling the number of + bytes from the input remaining to copy. If the upper value is not -1, then + it is the number of bits back from the current bit position in the input of + the code (literal or length/distance pair) currently being processed. In + that case the lower value is the number of bytes already emitted for that + code. + + A code is being processed if inflate is waiting for more input to complete + decoding of the code, or if it has completed decoding but is waiting for + more output space to write the literal or match data. + + inflateMark() is used to mark locations in the input data for random + access, which may be at bit positions, and to note those cases where the + output of a code may span boundaries of random access blocks. The current + location in the input stream can be determined from avail_in and data_type + as noted in the description for the Z_BLOCK flush parameter for inflate. + + inflateMark returns the value noted above or -1 << 16 if the provided + source stream state was inconsistent. +*/ + +ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm, + gz_headerp head)); +/* + inflateGetHeader() requests that gzip header information be stored in the + provided gz_header structure. inflateGetHeader() may be called after + inflateInit2() or inflateReset(), and before the first call of inflate(). + As inflate() processes the gzip stream, head->done is zero until the header + is completed, at which time head->done is set to one. If a zlib stream is + being decoded, then head->done is set to -1 to indicate that there will be + no gzip header information forthcoming. Note that Z_BLOCK or Z_TREES can be + used to force inflate() to return immediately after header processing is + complete and before any actual data is decompressed. + + The text, time, xflags, and os fields are filled in with the gzip header + contents. hcrc is set to true if there is a header CRC. (The header CRC + was valid if done is set to one.) If extra is not Z_NULL, then extra_max + contains the maximum number of bytes to write to extra. Once done is true, + extra_len contains the actual extra field length, and extra contains the + extra field, or that field truncated if extra_max is less than extra_len. + If name is not Z_NULL, then up to name_max characters are written there, + terminated with a zero unless the length is greater than name_max. If + comment is not Z_NULL, then up to comm_max characters are written there, + terminated with a zero unless the length is greater than comm_max. When any + of extra, name, or comment are not Z_NULL and the respective field is not + present in the header, then that field is set to Z_NULL to signal its + absence. This allows the use of deflateSetHeader() with the returned + structure to duplicate the header. However if those fields are set to + allocated memory, then the application will need to save those pointers + elsewhere so that they can be eventually freed. + + If inflateGetHeader is not used, then the header information is simply + discarded. The header is always checked for validity, including the header + CRC if present. inflateReset() will reset the process to discard the header + information. The application would need to call inflateGetHeader() again to + retrieve the header from the next gzip stream. + + inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source + stream state was inconsistent. +*/ + +/* +ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits, + unsigned char FAR *window)); + + Initialize the internal stream state for decompression using inflateBack() + calls. The fields zalloc, zfree and opaque in strm must be initialized + before the call. If zalloc and zfree are Z_NULL, then the default library- + derived memory allocation routines are used. windowBits is the base two + logarithm of the window size, in the range 8..15. window is a caller + supplied buffer of that size. Except for special applications where it is + assured that deflate was used with small window sizes, windowBits must be 15 + and a 32K byte window must be supplied to be able to decompress general + deflate streams. + + See inflateBack() for the usage of these routines. + + inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of + the parameters are invalid, Z_MEM_ERROR if the internal state could not be + allocated, or Z_VERSION_ERROR if the version of the library does not match + the version of the header file. +*/ + +typedef unsigned (*in_func) OF((void FAR *, + z_const unsigned char FAR * FAR *)); +typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned)); + +ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm, + in_func in, void FAR *in_desc, + out_func out, void FAR *out_desc)); +/* + inflateBack() does a raw inflate with a single call using a call-back + interface for input and output. This is potentially more efficient than + inflate() for file i/o applications, in that it avoids copying between the + output and the sliding window by simply making the window itself the output + buffer. inflate() can be faster on modern CPUs when used with large + buffers. inflateBack() trusts the application to not change the output + buffer passed by the output function, at least until inflateBack() returns. + + inflateBackInit() must be called first to allocate the internal state + and to initialize the state with the user-provided window buffer. + inflateBack() may then be used multiple times to inflate a complete, raw + deflate stream with each call. inflateBackEnd() is then called to free the + allocated state. + + A raw deflate stream is one with no zlib or gzip header or trailer. + This routine would normally be used in a utility that reads zip or gzip + files and writes out uncompressed files. The utility would decode the + header and process the trailer on its own, hence this routine expects only + the raw deflate stream to decompress. This is different from the normal + behavior of inflate(), which expects either a zlib or gzip header and + trailer around the deflate stream. + + inflateBack() uses two subroutines supplied by the caller that are then + called by inflateBack() for input and output. inflateBack() calls those + routines until it reads a complete deflate stream and writes out all of the + uncompressed data, or until it encounters an error. The function's + parameters and return types are defined above in the in_func and out_func + typedefs. inflateBack() will call in(in_desc, &buf) which should return the + number of bytes of provided input, and a pointer to that input in buf. If + there is no input available, in() must return zero--buf is ignored in that + case--and inflateBack() will return a buffer error. inflateBack() will call + out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out() + should return zero on success, or non-zero on failure. If out() returns + non-zero, inflateBack() will return with an error. Neither in() nor out() + are permitted to change the contents of the window provided to + inflateBackInit(), which is also the buffer that out() uses to write from. + The length written by out() will be at most the window size. Any non-zero + amount of input may be provided by in(). + + For convenience, inflateBack() can be provided input on the first call by + setting strm->next_in and strm->avail_in. If that input is exhausted, then + in() will be called. Therefore strm->next_in must be initialized before + calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called + immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in + must also be initialized, and then if strm->avail_in is not zero, input will + initially be taken from strm->next_in[0 .. strm->avail_in - 1]. + + The in_desc and out_desc parameters of inflateBack() is passed as the + first parameter of in() and out() respectively when they are called. These + descriptors can be optionally used to pass any information that the caller- + supplied in() and out() functions need to do their job. + + On return, inflateBack() will set strm->next_in and strm->avail_in to + pass back any unused input that was provided by the last in() call. The + return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR + if in() or out() returned an error, Z_DATA_ERROR if there was a format error + in the deflate stream (in which case strm->msg is set to indicate the nature + of the error), or Z_STREAM_ERROR if the stream was not properly initialized. + In the case of Z_BUF_ERROR, an input or output error can be distinguished + using strm->next_in which will be Z_NULL only if in() returned an error. If + strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning + non-zero. (in() will always be called before out(), so strm->next_in is + assured to be defined if out() returns non-zero.) Note that inflateBack() + cannot return Z_OK. +*/ + +ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm)); +/* + All memory allocated by inflateBackInit() is freed. + + inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream + state was inconsistent. +*/ + +ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void)); +/* Return flags indicating compile-time options. + + Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other: + 1.0: size of uInt + 3.2: size of uLong + 5.4: size of voidpf (pointer) + 7.6: size of z_off_t + + Compiler, assembler, and debug options: + 8: DEBUG + 9: ASMV or ASMINF -- use ASM code + 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention + 11: 0 (reserved) + + One-time table building (smaller code, but not thread-safe if true): + 12: BUILDFIXED -- build static block decoding tables when needed + 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed + 14,15: 0 (reserved) + + Library content (indicates missing functionality): + 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking + deflate code when not needed) + 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect + and decode gzip streams (to avoid linking crc code) + 18-19: 0 (reserved) + + Operation variations (changes in library functionality): + 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate + 21: FASTEST -- deflate algorithm with only one, lowest compression level + 22,23: 0 (reserved) + + The sprintf variant used by gzprintf (zero is best): + 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format + 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure! + 26: 0 = returns value, 1 = void -- 1 means inferred string length returned + + Remainder: + 27-31: 0 (reserved) + */ + +#ifndef Z_SOLO + + /* utility functions */ + +/* + The following utility functions are implemented on top of the basic + stream-oriented functions. To simplify the interface, some default options + are assumed (compression level and memory usage, standard memory allocation + functions). The source code of these utility functions can be modified if + you need special options. +*/ + +ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Compresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer. +*/ + +ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen, + int level)); +/* + Compresses the source buffer into the destination buffer. The level + parameter has the same meaning as in deflateInit. sourceLen is the byte + length of the source buffer. Upon entry, destLen is the total size of the + destination buffer, which must be at least the value returned by + compressBound(sourceLen). Upon exit, destLen is the actual size of the + compressed buffer. + + compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough + memory, Z_BUF_ERROR if there was not enough room in the output buffer, + Z_STREAM_ERROR if the level parameter is invalid. +*/ + +ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen)); +/* + compressBound() returns an upper bound on the compressed size after + compress() or compress2() on sourceLen bytes. It would be used before a + compress() or compress2() call to allocate the destination buffer. +*/ + +ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen, + const Bytef *source, uLong sourceLen)); +/* + Decompresses the source buffer into the destination buffer. sourceLen is + the byte length of the source buffer. Upon entry, destLen is the total size + of the destination buffer, which must be large enough to hold the entire + uncompressed data. (The size of the uncompressed data must have been saved + previously by the compressor and transmitted to the decompressor by some + mechanism outside the scope of this compression library.) Upon exit, destLen + is the actual size of the uncompressed buffer. + + uncompress returns Z_OK if success, Z_MEM_ERROR if there was not + enough memory, Z_BUF_ERROR if there was not enough room in the output + buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete. In + the case where there is not enough room, uncompress() will fill the output + buffer with the uncompressed data up to that point. +*/ + + /* gzip file access functions */ + +/* + This library supports reading and writing files in gzip (.gz) format with + an interface similar to that of stdio, using the functions that start with + "gz". The gzip format is different from the zlib format. gzip is a gzip + wrapper, documented in RFC 1952, wrapped around a deflate stream. +*/ + +typedef struct gzFile_s *gzFile; /* semi-opaque gzip file descriptor */ + +/* +ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode)); + + Opens a gzip (.gz) file for reading or writing. The mode parameter is as + in fopen ("rb" or "wb") but can also include a compression level ("wb9") or + a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only + compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F' + for fixed code compression as in "wb9F". (See the description of + deflateInit2 for more information about the strategy parameter.) 'T' will + request transparent writing or appending with no compression and not using + the gzip format. + + "a" can be used instead of "w" to request that the gzip stream that will + be written be appended to the file. "+" will result in an error, since + reading and writing to the same gzip file is not supported. The addition of + "x" when writing will create the file exclusively, which fails if the file + already exists. On systems that support it, the addition of "e" when + reading or writing will set the flag to close the file on an execve() call. + + These functions, as well as gzip, will read and decode a sequence of gzip + streams in a file. The append function of gzopen() can be used to create + such a file. (Also see gzflush() for another way to do this.) When + appending, gzopen does not test whether the file begins with a gzip stream, + nor does it look for the end of the gzip streams to begin appending. gzopen + will simply append a gzip stream to the existing file. + + gzopen can be used to read a file which is not in gzip format; in this + case gzread will directly read from the file without decompression. When + reading, this will be detected automatically by looking for the magic two- + byte gzip header. + + gzopen returns NULL if the file could not be opened, if there was + insufficient memory to allocate the gzFile state, or if an invalid mode was + specified (an 'r', 'w', or 'a' was not provided, or '+' was provided). + errno can be checked to determine if the reason gzopen failed was that the + file could not be opened. +*/ + +ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode)); +/* + gzdopen associates a gzFile with the file descriptor fd. File descriptors + are obtained from calls like open, dup, creat, pipe or fileno (if the file + has been previously opened with fopen). The mode parameter is as in gzopen. + + The next call of gzclose on the returned gzFile will also close the file + descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor + fd. If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd, + mode);. The duplicated descriptor should be saved to avoid a leak, since + gzdopen does not close fd if it fails. If you are using fileno() to get the + file descriptor from a FILE *, then you will have to use dup() to avoid + double-close()ing the file descriptor. Both gzclose() and fclose() will + close the associated file descriptor, so they need to have different file + descriptors. + + gzdopen returns NULL if there was insufficient memory to allocate the + gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not + provided, or '+' was provided), or if fd is -1. The file descriptor is not + used until the next gz* read, write, seek, or close operation, so gzdopen + will not detect if fd is invalid (unless fd is -1). +*/ + +ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size)); +/* + Set the internal buffer size used by this library's functions. The + default buffer size is 8192 bytes. This function must be called after + gzopen() or gzdopen(), and before any other calls that read or write the + file. The buffer memory allocation is always deferred to the first read or + write. Two buffers are allocated, either both of the specified size when + writing, or one of the specified size and the other twice that size when + reading. A larger buffer size of, for example, 64K or 128K bytes will + noticeably increase the speed of decompression (reading). + + The new buffer size also affects the maximum length for gzprintf(). + + gzbuffer() returns 0 on success, or -1 on failure, such as being called + too late. +*/ + +ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy)); +/* + Dynamically update the compression level or strategy. See the description + of deflateInit2 for the meaning of these parameters. + + gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not + opened for writing. +*/ + +ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len)); +/* + Reads the given number of uncompressed bytes from the compressed file. If + the input file is not in gzip format, gzread copies the given number of + bytes into the buffer directly from the file. + + After reaching the end of a gzip stream in the input, gzread will continue + to read, looking for another gzip stream. Any number of gzip streams may be + concatenated in the input file, and will all be decompressed by gzread(). + If something other than a gzip stream is encountered after a gzip stream, + that remaining trailing garbage is ignored (and no error is returned). + + gzread can be used to read a gzip file that is being concurrently written. + Upon reaching the end of the input, gzread will return with the available + data. If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then + gzclearerr can be used to clear the end of file indicator in order to permit + gzread to be tried again. Z_OK indicates that a gzip stream was completed + on the last gzread. Z_BUF_ERROR indicates that the input file ended in the + middle of a gzip stream. Note that gzread does not return -1 in the event + of an incomplete gzip stream. This error is deferred until gzclose(), which + will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip + stream. Alternatively, gzerror can be used before gzclose to detect this + case. + + gzread returns the number of uncompressed bytes actually read, less than + len for end of file, or -1 for error. +*/ + +ZEXTERN int ZEXPORT gzwrite OF((gzFile file, + voidpc buf, unsigned len)); +/* + Writes the given number of uncompressed bytes into the compressed file. + gzwrite returns the number of uncompressed bytes written or 0 in case of + error. +*/ + +ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...)); +/* + Converts, formats, and writes the arguments to the compressed file under + control of the format string, as in fprintf. gzprintf returns the number of + uncompressed bytes actually written, or 0 in case of error. The number of + uncompressed bytes written is limited to 8191, or one less than the buffer + size given to gzbuffer(). The caller should assure that this limit is not + exceeded. If it is exceeded, then gzprintf() will return an error (0) with + nothing written. In this case, there may also be a buffer overflow with + unpredictable consequences, which is possible only if zlib was compiled with + the insecure functions sprintf() or vsprintf() because the secure snprintf() + or vsnprintf() functions were not available. This can be determined using + zlibCompileFlags(). +*/ + +ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s)); +/* + Writes the given null-terminated string to the compressed file, excluding + the terminating null character. + + gzputs returns the number of characters written, or -1 in case of error. +*/ + +ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len)); +/* + Reads bytes from the compressed file until len-1 characters are read, or a + newline character is read and transferred to buf, or an end-of-file + condition is encountered. If any characters are read or if len == 1, the + string is terminated with a null character. If no characters are read due + to an end-of-file or len < 1, then the buffer is left untouched. + + gzgets returns buf which is a null-terminated string, or it returns NULL + for end-of-file or in case of error. If there was an error, the contents at + buf are indeterminate. +*/ + +ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c)); +/* + Writes c, converted to an unsigned char, into the compressed file. gzputc + returns the value that was written, or -1 in case of error. +*/ + +ZEXTERN int ZEXPORT gzgetc OF((gzFile file)); +/* + Reads one byte from the compressed file. gzgetc returns this byte or -1 + in case of end of file or error. This is implemented as a macro for speed. + As such, it does not do all of the checking the other functions do. I.e. + it does not check to see if file is NULL, nor whether the structure file + points to has been clobbered or not. +*/ + +ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file)); +/* + Push one character back onto the stream to be read as the first character + on the next read. At least one character of push-back is allowed. + gzungetc() returns the character pushed, or -1 on failure. gzungetc() will + fail if c is -1, and may fail if a character has been pushed but not read + yet. If gzungetc is used immediately after gzopen or gzdopen, at least the + output buffer size of pushed characters is allowed. (See gzbuffer above.) + The pushed character will be discarded if the stream is repositioned with + gzseek() or gzrewind(). +*/ + +ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush)); +/* + Flushes all pending output into the compressed file. The parameter flush + is as in the deflate() function. The return value is the zlib error number + (see function gzerror below). gzflush is only permitted when writing. + + If the flush parameter is Z_FINISH, the remaining data is written and the + gzip stream is completed in the output. If gzwrite() is called again, a new + gzip stream will be started in the output. gzread() is able to read such + concatented gzip streams. + + gzflush should be called only when strictly necessary because it will + degrade compression if called too often. +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, + z_off_t offset, int whence)); + + Sets the starting position for the next gzread or gzwrite on the given + compressed file. The offset represents a number of bytes in the + uncompressed data stream. The whence parameter is defined as in lseek(2); + the value SEEK_END is not supported. + + If the file is opened for reading, this function is emulated but can be + extremely slow. If the file is opened for writing, only forward seeks are + supported; gzseek then compresses a sequence of zeroes up to the new + starting position. + + gzseek returns the resulting offset location as measured in bytes from + the beginning of the uncompressed stream, or -1 in case of error, in + particular if the file is opened for writing and the new starting position + would be before the current position. +*/ + +ZEXTERN int ZEXPORT gzrewind OF((gzFile file)); +/* + Rewinds the given file. This function is supported only for reading. + + gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file)); + + Returns the starting position for the next gzread or gzwrite on the given + compressed file. This position represents a number of bytes in the + uncompressed data stream, and is zero when starting, even if appending or + reading a gzip stream from the middle of a file using gzdopen(). + + gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR) +*/ + +/* +ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file)); + + Returns the current offset in the file being read or written. This offset + includes the count of bytes that precede the gzip stream, for example when + appending or when using gzdopen() for reading. When reading, the offset + does not include as yet unused buffered input. This information can be used + for a progress indicator. On error, gzoffset() returns -1. +*/ + +ZEXTERN int ZEXPORT gzeof OF((gzFile file)); +/* + Returns true (1) if the end-of-file indicator has been set while reading, + false (0) otherwise. Note that the end-of-file indicator is set only if the + read tried to go past the end of the input, but came up short. Therefore, + just like feof(), gzeof() may return false even if there is no more data to + read, in the event that the last read request was for the exact number of + bytes remaining in the input file. This will happen if the input file size + is an exact multiple of the buffer size. + + If gzeof() returns true, then the read functions will return no more data, + unless the end-of-file indicator is reset by gzclearerr() and the input file + has grown since the previous end of file was detected. +*/ + +ZEXTERN int ZEXPORT gzdirect OF((gzFile file)); +/* + Returns true (1) if file is being copied directly while reading, or false + (0) if file is a gzip stream being decompressed. + + If the input file is empty, gzdirect() will return true, since the input + does not contain a gzip stream. + + If gzdirect() is used immediately after gzopen() or gzdopen() it will + cause buffers to be allocated to allow reading the file to determine if it + is a gzip file. Therefore if gzbuffer() is used, it should be called before + gzdirect(). + + When writing, gzdirect() returns true (1) if transparent writing was + requested ("wT" for the gzopen() mode), or false (0) otherwise. (Note: + gzdirect() is not needed when writing. Transparent writing must be + explicitly requested, so the application already knows the answer. When + linking statically, using gzdirect() will include all of the zlib code for + gzip file reading and decompression, which may not be desired.) +*/ + +ZEXTERN int ZEXPORT gzclose OF((gzFile file)); +/* + Flushes all pending output if necessary, closes the compressed file and + deallocates the (de)compression state. Note that once file is closed, you + cannot call gzerror with file, since its structures have been deallocated. + gzclose must not be called more than once on the same file, just as free + must not be called more than once on the same allocation. + + gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a + file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the + last read ended in the middle of a gzip stream, or Z_OK on success. +*/ + +ZEXTERN int ZEXPORT gzclose_r OF((gzFile file)); +ZEXTERN int ZEXPORT gzclose_w OF((gzFile file)); +/* + Same as gzclose(), but gzclose_r() is only for use when reading, and + gzclose_w() is only for use when writing or appending. The advantage to + using these instead of gzclose() is that they avoid linking in zlib + compression or decompression code that is not used when only reading or only + writing respectively. If gzclose() is used, then both compression and + decompression code will be included the application when linking to a static + zlib library. +*/ + +ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum)); +/* + Returns the error message for the last error which occurred on the given + compressed file. errnum is set to zlib error number. If an error occurred + in the file system and not in the compression library, errnum is set to + Z_ERRNO and the application may consult errno to get the exact error code. + + The application must not modify the returned string. Future calls to + this function may invalidate the previously returned string. If file is + closed, then the string previously returned by gzerror will no longer be + available. + + gzerror() should be used to distinguish errors from end-of-file for those + functions above that do not distinguish those cases in their return values. +*/ + +ZEXTERN void ZEXPORT gzclearerr OF((gzFile file)); +/* + Clears the error and end-of-file flags for file. This is analogous to the + clearerr() function in stdio. This is useful for continuing to read a gzip + file that is being written concurrently. +*/ + +#endif /* !Z_SOLO */ + + /* checksum functions */ + +/* + These functions are not related to compression but are exported + anyway because they might be useful in applications using the compression + library. +*/ + +ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len)); +/* + Update a running Adler-32 checksum with the bytes buf[0..len-1] and + return the updated checksum. If buf is Z_NULL, this function returns the + required initial value for the checksum. + + An Adler-32 checksum is almost as reliable as a CRC32 but can be computed + much faster. + + Usage example: + + uLong adler = adler32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + adler = adler32(adler, buffer, length); + } + if (adler != original_adler) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2, + z_off_t len2)); + + Combine two Adler-32 checksums into one. For two sequences of bytes, seq1 + and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for + each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of + seq1 and seq2 concatenated, requiring only adler1, adler2, and len2. Note + that the z_off_t type (like off_t) is a signed integer. If len2 is + negative, the result has no meaning or utility. +*/ + +ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len)); +/* + Update a running CRC-32 with the bytes buf[0..len-1] and return the + updated CRC-32. If buf is Z_NULL, this function returns the required + initial value for the crc. Pre- and post-conditioning (one's complement) is + performed within this function so it shouldn't be done by the application. + + Usage example: + + uLong crc = crc32(0L, Z_NULL, 0); + + while (read_buffer(buffer, length) != EOF) { + crc = crc32(crc, buffer, length); + } + if (crc != original_crc) error(); +*/ + +/* +ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2)); + + Combine two CRC-32 check values into one. For two sequences of bytes, + seq1 and seq2 with lengths len1 and len2, CRC-32 check values were + calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32 + check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and + len2. +*/ + + + /* various hacks, don't look :) */ + +/* deflateInit and inflateInit are macros to allow checking the zlib version + * and the compiler's view of z_stream: + */ +ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method, + int windowBits, int memLevel, + int strategy, const char *version, + int stream_size)); +ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits, + const char *version, int stream_size)); +ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits, + unsigned char FAR *window, + const char *version, + int stream_size)); +#define deflateInit(strm, level) \ + deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit(strm) \ + inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream)) +#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \ + deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\ + (strategy), ZLIB_VERSION, (int)sizeof(z_stream)) +#define inflateInit2(strm, windowBits) \ + inflateInit2_((strm), (windowBits), ZLIB_VERSION, \ + (int)sizeof(z_stream)) +#define inflateBackInit(strm, windowBits, window) \ + inflateBackInit_((strm), (windowBits), (window), \ + ZLIB_VERSION, (int)sizeof(z_stream)) + +#ifndef Z_SOLO + +/* gzgetc() macro and its supporting function and exposed data structure. Note + * that the real internal state is much larger than the exposed structure. + * This abbreviated structure exposes just enough for the gzgetc() macro. The + * user should not mess with these exposed elements, since their names or + * behavior could change in the future, perhaps even capriciously. They can + * only be used by the gzgetc() macro. You have been warned. + */ +struct gzFile_s { + unsigned have; + unsigned char *next; + z_off64_t pos; +}; +ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file)); /* backward compatibility */ +#ifdef Z_PREFIX_SET +# undef z_gzgetc +# define z_gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#else +# define gzgetc(g) \ + ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g)) +#endif + +/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or + * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if + * both are true, the application gets the *64 functions, and the regular + * functions are changed to 64 bits) -- in case these are set on systems + * without large file support, _LFS64_LARGEFILE must also be true + */ +#ifdef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int)); + ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t)); +#endif + +#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64) +# ifdef Z_PREFIX_SET +# define z_gzopen z_gzopen64 +# define z_gzseek z_gzseek64 +# define z_gztell z_gztell64 +# define z_gzoffset z_gzoffset64 +# define z_adler32_combine z_adler32_combine64 +# define z_crc32_combine z_crc32_combine64 +# else +# define gzopen gzopen64 +# define gzseek gzseek64 +# define gztell gztell64 +# define gzoffset gzoffset64 +# define adler32_combine adler32_combine64 +# define crc32_combine crc32_combine64 +# endif +# ifndef Z_LARGE64 + ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +# endif +#else + ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *)); + ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int)); + ZEXTERN z_off_t ZEXPORT gztell OF((gzFile)); + ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile)); + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); +#endif + +#else /* Z_SOLO */ + + ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t)); + +#endif /* !Z_SOLO */ + +/* hack for buggy compilers */ +#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL) + struct internal_state {int dummy;}; +#endif + +/* undocumented functions */ +ZEXTERN const char * ZEXPORT zError OF((int)); +ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp)); +ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table OF((void)); +ZEXTERN int ZEXPORT inflateUndermine OF((z_streamp, int)); +ZEXTERN int ZEXPORT inflateResetKeep OF((z_streamp)); +ZEXTERN int ZEXPORT deflateResetKeep OF((z_streamp)); +#if defined(_WIN32) && !defined(Z_SOLO) +ZEXTERN gzFile ZEXPORT gzopen_w OF((const wchar_t *path, + const char *mode)); +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifndef Z_SOLO +ZEXTERN int ZEXPORTVA gzvprintf Z_ARG((gzFile file, + const char *format, + va_list va)); +# endif +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ZLIB_H */ diff --git a/armsrc/zutil.h b/armsrc/zutil.h new file mode 100644 index 00000000..24ab06b1 --- /dev/null +++ b/armsrc/zutil.h @@ -0,0 +1,253 @@ +/* zutil.h -- internal interface and configuration of the compression library + * Copyright (C) 1995-2013 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef ZUTIL_H +#define ZUTIL_H + +#ifdef HAVE_HIDDEN +# define ZLIB_INTERNAL __attribute__((visibility ("hidden"))) +#else +# define ZLIB_INTERNAL +#endif + +#include "zlib.h" + +#if defined(STDC) && !defined(Z_SOLO) +# if !(defined(_WIN32_WCE) && defined(_MSC_VER)) +# include +# endif +# include +# include +#endif + +#ifdef Z_SOLO + typedef long ptrdiff_t; /* guess -- will be caught if guess is wrong */ +#endif + +#ifndef local +# define local static +#endif +/* compile with -Dlocal if your debugger can't find static symbols */ + +typedef unsigned char uch; +typedef uch FAR uchf; +typedef unsigned short ush; +typedef ush FAR ushf; +typedef unsigned long ulg; + +extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */ +/* (size given to avoid silly warnings with Visual C++) */ + +#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)] + +#define ERR_RETURN(strm,err) \ + return (strm->msg = ERR_MSG(err), (err)) +/* To be used only when the state is known to be valid */ + + /* common constants */ + +#ifndef DEF_WBITS +# define DEF_WBITS MAX_WBITS +#endif +/* default windowBits for decompression. MAX_WBITS is for compression only */ + +#if MAX_MEM_LEVEL >= 8 +# define DEF_MEM_LEVEL 8 +#else +# define DEF_MEM_LEVEL MAX_MEM_LEVEL +#endif +/* default memLevel */ + +#define STORED_BLOCK 0 +#define STATIC_TREES 1 +#define DYN_TREES 2 +/* The three kinds of block type */ + +#define MIN_MATCH 3 +#define MAX_MATCH 258 +/* The minimum and maximum match lengths */ + +#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */ + + /* target dependencies */ + +#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32)) +# define OS_CODE 0x00 +# ifndef Z_SOLO +# if defined(__TURBOC__) || defined(__BORLANDC__) +# if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__)) + /* Allow compilation with ANSI keywords only enabled */ + void _Cdecl farfree( void *block ); + void *_Cdecl farmalloc( unsigned long nbytes ); +# else +# include +# endif +# else /* MSC or DJGPP */ +# include +# endif +# endif +#endif + +#ifdef AMIGA +# define OS_CODE 0x01 +#endif + +#if defined(VAXC) || defined(VMS) +# define OS_CODE 0x02 +# define F_OPEN(name, mode) \ + fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512") +#endif + +#if defined(ATARI) || defined(atarist) +# define OS_CODE 0x05 +#endif + +#ifdef OS2 +# define OS_CODE 0x06 +# if defined(M_I86) && !defined(Z_SOLO) +# include +# endif +#endif + +#if defined(MACOS) || defined(TARGET_OS_MAC) +# define OS_CODE 0x07 +# ifndef Z_SOLO +# if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os +# include /* for fdopen */ +# else +# ifndef fdopen +# define fdopen(fd,mode) NULL /* No fdopen() */ +# endif +# endif +# endif +#endif + +#ifdef TOPS20 +# define OS_CODE 0x0a +#endif + +#ifdef WIN32 +# ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */ +# define OS_CODE 0x0b +# endif +#endif + +#ifdef __50SERIES /* Prime/PRIMOS */ +# define OS_CODE 0x0f +#endif + +#if defined(_BEOS_) || defined(RISCOS) +# define fdopen(fd,mode) NULL /* No fdopen() */ +#endif + +#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX +# if defined(_WIN32_WCE) +# define fdopen(fd,mode) NULL /* No fdopen() */ +# ifndef _PTRDIFF_T_DEFINED + typedef int ptrdiff_t; +# define _PTRDIFF_T_DEFINED +# endif +# else +# define fdopen(fd,type) _fdopen(fd,type) +# endif +#endif + +#if defined(__BORLANDC__) && !defined(MSDOS) + #pragma warn -8004 + #pragma warn -8008 + #pragma warn -8066 +#endif + +/* provide prototypes for these when building zlib without LFS */ +#if !defined(_WIN32) && \ + (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0) + ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t)); + ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t)); +#endif + + /* common defaults */ + +#ifndef OS_CODE +# define OS_CODE 0x03 /* assume Unix */ +#endif + +#ifndef F_OPEN +# define F_OPEN(name, mode) fopen((name), (mode)) +#endif + + /* functions */ + +#if defined(pyr) || defined(Z_SOLO) +# define NO_MEMCPY +#endif +#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__) + /* Use our own functions for small and medium model with MSC <= 5.0. + * You may have to use the same strategy for Borland C (untested). + * The __SC__ check is for Symantec. + */ +# define NO_MEMCPY +#endif +#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY) +# define HAVE_MEMCPY +#endif +#ifdef HAVE_MEMCPY +# ifdef SMALL_MEDIUM /* MSDOS small or medium model */ +# define zmemcpy _fmemcpy +# define zmemcmp _fmemcmp +# define zmemzero(dest, len) _fmemset(dest, 0, len) +# else +# define zmemcpy memcpy +# define zmemcmp memcmp +# define zmemzero(dest, len) memset(dest, 0, len) +# endif +#else + void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len)); + int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len)); + void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len)); +#endif + +/* Diagnostic functions */ +#ifdef DEBUG +# include + extern int ZLIB_INTERNAL z_verbose; + extern void ZLIB_INTERNAL z_error OF((char *m)); +# define Assert(cond,msg) {if(!(cond)) z_error(msg);} +# define Trace(x) {if (z_verbose>=0) fprintf x ;} +# define Tracev(x) {if (z_verbose>0) fprintf x ;} +# define Tracevv(x) {if (z_verbose>1) fprintf x ;} +# define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;} +# define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;} +#else +# define Assert(cond,msg) +# define Trace(x) +# define Tracev(x) +# define Tracevv(x) +# define Tracec(c,x) +# define Tracecv(c,x) +#endif + +#ifndef Z_SOLO + voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items, + unsigned size)); + void ZLIB_INTERNAL zcfree OF((voidpf opaque, voidpf ptr)); +#endif + +#define ZALLOC(strm, items, size) \ + (*((strm)->zalloc))((strm)->opaque, (items), (size)) +#define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr)) +#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} + +/* Reverse the bytes in a 32-bit value */ +#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \ + (((q) & 0xff00) << 8) + (((q) & 0xff) << 24)) + +#endif /* ZUTIL_H */ diff --git a/client/Makefile b/client/Makefile index 7954d1ea..44ca8a96 100644 --- a/client/Makefile +++ b/client/Makefile @@ -12,7 +12,8 @@ CXX=g++ VPATH = ../common OBJDIR = obj -LDLIBS = -L/opt/local/lib -L/usr/local/lib ../liblua/liblua.a -lreadline -lpthread -lm +LDLIBS = -L/opt/local/lib -L/usr/local/lib -lreadline -lpthread -lm +LUALIB = ../liblua/liblua.a LDFLAGS = $(COMMON_FLAGS) CFLAGS = -std=c99 -I. -I../include -I../common -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -g -O4 LUAPLATFORM = generic @@ -108,15 +109,15 @@ COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) CMDOBJS = $(CMDSRCS:%.c=$(OBJDIR)/%.o) RM = rm -f -BINS = proxmark3 flasher #snooper cli +BINS = proxmark3 flasher fpga_compress #snooper cli CLEAN = cli cli.exe flasher flasher.exe proxmark3 proxmark3.exe snooper snooper.exe $(CMDOBJS) $(OBJDIR)/*.o *.o *.moc.cpp all: lua_build $(BINS) all-static: LDLIBS:=-static $(LDLIBS) -all-static: snooper cli flasher +all-static: snooper cli flasher fpga_compress -proxmark3: LDLIBS+=$(QTLDLIBS) +proxmark3: LDLIBS+=$(QTLDLIBS) $(LUALIB) proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(QTGUI) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ @@ -129,6 +130,9 @@ cli: $(OBJDIR)/cli.o $(COREOBJS) $(CMDOBJS) $(OBJDIR)/guidummy.o flasher: $(OBJDIR)/flash.o $(OBJDIR)/flasher.o $(COREOBJS) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ +fpga_compress: $(OBJDIR)/fpga_compress.o + $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ + $(OBJDIR)/%.o: %.c $(CC) $(CFLAGS) -c -o $@ $< diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c new file mode 100644 index 00000000..e76b3fb5 --- /dev/null +++ b/client/cmdhftopaz.c @@ -0,0 +1,408 @@ +//----------------------------------------------------------------------------- +// Copyright (C) 2015 Piwi +// +// 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. +//----------------------------------------------------------------------------- +// High frequency Topaz (NFC Type 1) commands +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include "cmdmain.h" +#include "cmdparser.h" +#include "cmdhftopaz.h" +#include "cmdhf14a.h" +#include "ui.h" +#include "mifare.h" +#include "proxmark3.h" +#include "iso14443crc.h" +#include "protocols.h" + +#define TOPAZ_MAX_MEMORY 2048 + +static struct { + uint8_t HR01[2]; + uint8_t uid[7]; + uint8_t size; + uint8_t data_blocks[TOPAZ_MAX_MEMORY/8][8]; + uint8_t *dynamic_lock_areas; + uint8_t *dynamic_reserved_areas; +} topaz_tag; + + +static void topaz_switch_on_field(void) +{ + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_SELECT | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, 0, 0}}; + SendCommand(&c); +} + + +static void topaz_switch_off_field(void) +{ + UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; + SendCommand(&c); +} + + +static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) +{ + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, len, 0}}; + memcpy(c.d.asBytes, cmd, len); + SendCommand(&c); + + UsbCommand resp; + WaitForResponse(CMD_ACK, &resp); + + if (resp.arg[0] > 0) { + memcpy(response, resp.d.asBytes, resp.arg[0]); + } + + return resp.arg[0]; +} + + +static int topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) +{ + if (len > 1) { + uint8_t first, second; + ComputeCrc14443(CRC_14443_B, cmd, len-2, &first, &second); + cmd[len-2] = first; + cmd[len-1] = second; + } + + return topaz_send_cmd_raw(cmd, len, response); +} + + +static int topaz_select(uint8_t *atqa, uint8_t *rid_response) +{ + // ToDo: implement anticollision + + uint8_t wupa_cmd[] = {TOPAZ_WUPA}; + uint8_t rid_cmd[] = {TOPAZ_RID, 0, 0, 0, 0, 0, 0, 0, 0}; + + topaz_switch_on_field(); + + if (!topaz_send_cmd(wupa_cmd, sizeof(wupa_cmd), atqa)) { + topaz_switch_off_field(); + return -1; // WUPA failed + } + + if (!topaz_send_cmd(rid_cmd, sizeof(rid_cmd), rid_response)) { + topaz_switch_off_field(); + return -2; // RID failed + } + + return 0; // OK +} + + +static int topaz_rall(uint8_t *uid, uint8_t *response) +{ + uint8_t rall_cmd[] = {TOPAZ_RALL, 0, 0, 0, 0, 0, 0, 0, 0}; + + memcpy(&rall_cmd[3], uid, 4); + if (!topaz_send_cmd(rall_cmd, sizeof(rall_cmd), response)) { + topaz_switch_off_field(); + return -1; // RALL failed + } + + return 0; +} + + +static bool topaz_block_is_locked(uint8_t blockno, uint8_t *lockbits) +{ + if(lockbits[blockno/8] >> (blockno % 8) & 0x01) { + return true; + } else { + return false; + } +} + + +static int topaz_print_CC(uint8_t *data) +{ + if(data[0] != 0xe1) { + return -1; // no NDEF message + } + + PrintAndLog("Capability Container: %02x %02x %02x %02x", data[0], data[1], data[2], data[3]); + PrintAndLog(" %02x: NDEF Magic Number", data[0]); + PrintAndLog(" %02x: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); + PrintAndLog(" %02x: Physical Memory Size of this tag: %d bytes", data[2], (data[2] + 1) * 8); + PrintAndLog(" %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; +} + + +static void get_TLV(uint8_t **TLV_ptr, uint8_t *tag, uint16_t *length, uint8_t **value) +{ + *length = 0; + *value = NULL; + + *tag = **TLV_ptr; + *TLV_ptr += 1; + switch (*tag) { + case 0x00: // NULL TLV. + case 0xFE: // Terminator TLV. + break; + case 0x01: // Lock Control TLV + case 0x02: // Reserved Memory TLV + case 0x03: // NDEF message TLV + case 0xFD: // proprietary TLV + *length = **TLV_ptr; + *TLV_ptr += 1; + if (*length == 0xff) { + *length = **TLV_ptr << 8; + *TLV_ptr += 1; + *length |= **TLV_ptr; + *TLV_ptr += 1; + } + *value = *TLV_ptr; + *TLV_ptr += *length; + break; + default: // RFU + break; + } +} + + +static bool topaz_print_lock_control_TLVs(uint8_t *memory) +{ + uint8_t *TLV_ptr = memory; + uint8_t tag = 0; + uint16_t length; + uint8_t *value; + bool lock_TLV_present = false; + + 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, &tag, &length, &value); + if (tag == 0x01) { // the Lock Control TLV + uint8_t pages_addr = value[0] >> 4; + uint8_t byte_offset = value[0] & 0x0f; + uint8_t size_in_bits = value[1] ? value[1] : 256; + uint8_t bytes_per_page = 1 << (value[2] & 0x0f); + uint8_t bytes_locked_per_bit = 1 << (value[2] >> 4); + PrintAndLog("Lock Area of %d bits at byte offset 0x%02x. Each Lock Bit locks %d bytes.", + size_in_bits, + pages_addr * bytes_per_page + byte_offset, + bytes_locked_per_bit); + lock_TLV_present = true; + } + } + + if (!lock_TLV_present) { + PrintAndLog("(No Lock Control TLV present)"); + return -1; + } else { + return 0; + } +} + + +static int topaz_print_reserved_memory_control_TLVs(uint8_t *memory) +{ + uint8_t *TLV_ptr = memory; + uint8_t tag = 0; + uint16_t length; + uint8_t *value; + bool reserved_memory_control_TLV_present = false; + + while(*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { + // all Reserved Memory Control TLVs shall be present before the NDEF message TLV, the proprietary TLV (and the Terminator TLV) + get_TLV(&TLV_ptr, &tag, &length, &value); + if (tag == 0x02) { // the Reserved Memory Control TLV + uint8_t pages_addr = value[0] >> 4; + uint8_t byte_offset = value[0] & 0x0f; + uint8_t size_in_bytes = value[1] ? value[1] : 256; + uint8_t bytes_per_page = 1 << (value[2] & 0x0f); + PrintAndLog("Reserved Memory of %d bytes at byte offset 0x%02x.", + size_in_bytes, + pages_addr * bytes_per_page + byte_offset); + reserved_memory_control_TLV_present = true; + } + } + + if (!reserved_memory_control_TLV_present) { + PrintAndLog("(No Reserved Memory Control TLV present)"); + return -1; + } else { + return 0; + } +} + + +static void topaz_print_lifecycle_state(uint8_t *data) +{ + +} + + +static void topaz_print_NDEF(uint8_t *data) +{ + +} + + +int CmdHFTopazReader(const char *Cmd) +{ + int status; + uint8_t atqa[2]; + uint8_t rid_response[8]; + uint8_t *uid_echo = &rid_response[2]; + uint8_t rall_response[124]; + + status = topaz_select(atqa, rid_response); + + if (status == -1) { + PrintAndLog("Error: couldn't receive ATQA"); + return -1; + } + + PrintAndLog("ATQA : %02x %02x", atqa[1], atqa[0]); + if (atqa[1] != 0x0c && atqa[0] != 0x00) { + PrintAndLog("Tag doesn't support the Topaz protocol."); + topaz_switch_off_field(); + return -1; + } + + if (status == -2) { + PrintAndLog("Error: tag didn't answer to RID"); + topaz_switch_off_field(); + return -1; + } + + topaz_tag.HR01[0] = rid_response[0]; + topaz_tag.HR01[1] = rid_response[1]; + + // ToDo: CRC check + PrintAndLog("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) == 0x10 ? "static" : "dynamic"); + PrintAndLog("HR1 : %02x", rid_response[1]); + + status = topaz_rall(uid_echo, rall_response); + + if(status == -1) { + PrintAndLog("Error: tag didn't answer to RALL"); + topaz_switch_off_field(); + return -1; + } + + memcpy(topaz_tag.uid, rall_response+2, 7); + PrintAndLog("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]); + PrintAndLog(" UID[6] (Manufacturer Byte) = %02x, Manufacturer: %s", + topaz_tag.uid[6], + getTagInfo(topaz_tag.uid[6])); + + memcpy(topaz_tag.data_blocks, rall_response+2, 0x10*8); + PrintAndLog(""); + PrintAndLog("Static Data blocks 00 to 0c:"); + PrintAndLog("block# | offset | Data | Locked?"); + char line[80]; + for (uint16_t i = 0; i <= 0x0c; i++) { + for (uint16_t j = 0; j < 8; j++) { + sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[i][j] /*rall_response[2 + 8*i + j]*/); + } + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, topaz_block_is_locked(i, &topaz_tag.data_blocks[0x0d][0]) ? "yes" : "no"); + } + + PrintAndLog(""); + PrintAndLog("Static Reserved block 0d:"); + for (uint16_t j = 0; j < 8; j++) { + sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0d][j]); + } + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); + + PrintAndLog(""); + PrintAndLog("Static Lockbits and OTP Bytes:"); + for (uint16_t j = 0; j < 8; j++) { + sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0e][j]); + } + PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0e, 0x0e*8, line, "n/a"); + + PrintAndLog(""); + + status = topaz_print_CC(&topaz_tag.data_blocks[1][0]); + + if (status == -1) { + PrintAndLog("No NDEF message present"); + topaz_switch_off_field(); + return 0; + } + + PrintAndLog(""); + bool lock_TLV_present = topaz_print_lock_control_TLVs(&topaz_tag.data_blocks[1][4]); + + PrintAndLog(""); + bool reserved_mem_present = topaz_print_reserved_memory_control_TLVs(&topaz_tag.data_blocks[1][4]); + + 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; +} + + +int CmdHFTopazSim(const char *Cmd) +{ + PrintAndLog("not yet implemented"); + return 0; +} + + +int CmdHFTopazCmdRaw(const char *Cmd) +{ + PrintAndLog("not yet implemented"); + return 0; +} + + +static int CmdHelp(const char *Cmd); + + +static command_t CommandTable[] = +{ + {"help", CmdHelp, 1, "This help"}, + {"reader", CmdHFTopazReader, 0, "Act like a Topaz reader"}, + {"sim", CmdHFTopazSim, 0, " -- Simulate Topaz tag"}, + {"snoop", CmdHF14ASnoop, 0, "Eavesdrop a Topaz reader-tag communication"}, + {"raw", CmdHFTopazCmdRaw, 0, "Send raw hex data to tag"}, + {NULL, NULL, 0, NULL} +}; + + +int CmdHFTopaz(const char *Cmd) { + // flush + WaitForResponseTimeout(CMD_ACK,NULL,100); + + // parse + CmdsParse(CommandTable, Cmd); + return 0; +} + +static int CmdHelp(const char *Cmd) +{ + CmdsHelp(CommandTable); + return 0; +} + + diff --git a/client/cmdhw.c b/client/cmdhw.c index 5ec0aa60..78695346 100644 --- a/client/cmdhw.c +++ b/client/cmdhw.c @@ -23,9 +23,11 @@ static int CmdHelp(const char *Cmd); -static void lookupChipID(uint32_t iChipID) +static void lookupChipID(uint32_t iChipID, uint32_t mem_used) { char asBuff[100]; + uint32_t mem_avail = 0; + switch(iChipID) { case 0x270B0A40: @@ -103,37 +105,43 @@ static void lookupChipID(uint32_t iChipID) switch((iChipID&0xF00)>>8) { case 0: - sprintf(asBuff,"None"); + mem_avail = 0; break; case 1: - sprintf(asBuff,"8K bytes"); + mem_avail = 8; break; case 2: - sprintf(asBuff,"16K bytes"); + mem_avail = 16; break; case 3: - sprintf(asBuff,"32K bytes"); + mem_avail = 32; break; case 5: - sprintf(asBuff,"64K bytes"); + mem_avail = 64; break; case 7: - sprintf(asBuff,"128K bytes"); + mem_avail = 128; break; case 9: - sprintf(asBuff,"256K bytes"); + mem_avail = 256; break; case 10: - sprintf(asBuff,"512K bytes"); + mem_avail = 512; break; case 12: - sprintf(asBuff,"1024K bytes"); + mem_avail = 1024; break; case 14: - sprintf(asBuff,"2048K bytes"); + mem_avail = 2048; break; } - PrintAndLog("Nonvolatile Program Memory Size: %s",asBuff); + PrintAndLog("Nonvolatile Program Memory Size: %dK bytes. Used: %d bytes (%2.0f\%). Free: %d bytes (%2.0f\%).", + mem_avail, + mem_used, + mem_avail == 0 ? 0 : (float)mem_used/(mem_avail*1024)*100, + mem_avail*1024 - mem_used, + mem_avail == 0 ? 0 : (float)(mem_avail*1024-mem_used)/(mem_avail*1024)*100 + ); switch((iChipID&0xF000)>>12) { case 0: @@ -400,7 +408,7 @@ int CmdVersion(const char *Cmd) UsbCommand resp; SendCommand(&c); if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { - lookupChipID(resp.arg[0]); + lookupChipID(resp.arg[0], resp.arg[1]); } return 0; } diff --git a/client/fpga_compress.c b/client/fpga_compress.c new file mode 100644 index 00000000..9e0946b2 --- /dev/null +++ b/client/fpga_compress.c @@ -0,0 +1,221 @@ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- +// Flasher frontend tool +//----------------------------------------------------------------------------- + +#include +#include +#include +#include "sleep.h" +#include "proxmark3.h" +#include "flash.h" +#include "uart.h" +#include "usb_cmd.h" + +#define MAX(a,b) ((a)>(b)?(a):(b)) + +struct huffman_record { + int16_t symbol; + uint16_t count; + uint8_t code_size; + uint8_t code; + struct huffman_record *left; + struct huffman_record *right; + struct huffman_record *next; + }; + +typedef struct huffman_record huffman_record_t; + +#define FPGA_CONFIG_SIZE 42175 +static uint8_t fpga_config[FPGA_CONFIG_SIZE]; +static huffman_record_t leaf_nodes[256]; +static uint8_t start_code[256]; + +static void usage(char *argv0) +{ + fprintf(stderr, "Usage: %s [-d] \n\n", argv0); + fprintf(stderr, "\t-d\tdecompress\n\n"); +} + + +void add_to_heap(huffman_record_t **heap, huffman_record_t *new_record) +{ + huffman_record_t *succ = *heap; + huffman_record_t *pred = NULL; + +// fprintf(stderr, "Adding symbol %d, count %d\n", new_record->symbol, new_record->count); + + while (succ != NULL && new_record->count > succ->count) { + pred = succ; + succ = succ->next; + } + + // insert new record + new_record->next = succ; + if (pred == NULL) { // first record in heap + *heap = new_record; + } else { + pred->next = new_record; + } +} + + +uint16_t set_codesize(huffman_record_t *tree_ptr, uint8_t depth) +{ + uint16_t max_size = depth; + tree_ptr->code_size = depth; + if (tree_ptr->left != NULL) { + max_size = MAX(set_codesize(tree_ptr->left, depth+1), max_size); + } + if (tree_ptr->right != NULL) { + max_size = MAX(set_codesize(tree_ptr->right, depth+1), max_size); + } + return max_size; +} + +int huffman_encode(FILE *infile, FILE *outfile) +{ + int i; + + // init leaf_nodes: + for (i = 0; i < 256; i++) { + leaf_nodes[i].count = 0; + leaf_nodes[i].symbol = i; + leaf_nodes[i].left = NULL; + leaf_nodes[i].right = NULL; + leaf_nodes[i].next = NULL; + } + + // read the input file into fpga_config[] and count occurrences of each symbol: + i = 0; + while(!feof(infile)) { + uint8_t c; + c = fgetc(infile); + fpga_config[i++] = c; + leaf_nodes[c].count++; + if (i > FPGA_CONFIG_SIZE+1) { + fprintf(stderr, "Input file too big (> %d bytes). This is probably not a PM3 FPGA config file.", FPGA_CONFIG_SIZE); + fclose(infile); + fclose(outfile); + return -1; + } + } + + fprintf(stderr, "\nStatistics: (symbol: count)\n"); + for (i = 0; i < 256; i++) { + fprintf(stderr, "%3d: %5d\n", i, leaf_nodes[i].count); + } + + // build the Huffman tree: + huffman_record_t *heap_ptr = NULL; + + for (i = 0; i < 256; i++) { + add_to_heap(&heap_ptr, &leaf_nodes[i]); + } + + fprintf(stderr, "\nSorted statistics: (symbol: count)\n"); + for (huffman_record_t *p = heap_ptr; p != NULL; p = p->next) { + fprintf(stderr, "%3d: %5d\n", p->symbol, p->count); + } + + for (i = 0; i < 255; i++) { + // remove and combine the first two nodes + huffman_record_t *p1, *p2; + p1 = heap_ptr; + p2 = heap_ptr->next; + heap_ptr = p2->next; + huffman_record_t *new_node = malloc(sizeof(huffman_record_t)); + new_node->left = p1; + new_node->right = p2; + new_node->count = p1->count + p2->count; + add_to_heap(&heap_ptr, new_node); + } + + uint16_t max_codesize = set_codesize(heap_ptr, 0); + + fprintf(stderr, "\nStatistics: (symbol: count, codesize)\n"); + uint32_t compressed_size = 0; + for (i = 0; i < 256; i++) { + fprintf(stderr, "%3d: %5d, %d\n", leaf_nodes[i].symbol, leaf_nodes[i].count, leaf_nodes[i].code_size); + compressed_size += leaf_nodes[i].count * leaf_nodes[i].code_size; + } + fprintf(stderr, "Compressed size = %ld (%f% of original size)", (compressed_size+7)/8, (float)(compressed_size)/(FPGA_CONFIG_SIZE * 8) * 100); + fprintf(stderr, "Max Codesize = %d bits", max_codesize); + + uint8_t code = 0; + for (i = max_codesize; i > 0; i--) { + code = (code + 1) >> 1; + start_code[i] = code; + for (uint16_t j = 0; j < 256; j++) { + if (leaf_nodes[j].code_size == i) { + leaf_nodes[j].code = code; + code++; + } + } + } + + + fprintf(stderr, "\nStatistics: (symbol: count, codesize, code)\n"); + for (i = 0; i < 256; i++) { + fprintf(stderr, "%3d: %5d, %d, %02x\n", leaf_nodes[i].symbol, leaf_nodes[i].count, leaf_nodes[i].code_size, leaf_nodes[i].code); + } + + fclose(infile); + fclose(outfile); + + return 0; +} + +int huffman_decode(FILE *infile, FILE *outfile) +{ + return 0; +} + + +int main(int argc, char **argv) +{ + bool decode = false; + char *infilename; + char *outfilename; + + if (argc < 3) { + usage(argv[0]); + return -1; + } + + if (argc > 3) { + if (!strcmp(argv[1], "-d")) { + decode = true; + infilename = argv[2]; + outfilename = argv[3]; + } else { + usage(argv[0]); + return -1; + } + } else { + infilename = argv[1]; + outfilename = argv[2]; + } + + FILE *infile = fopen(infilename, "rb"); + if (infile == NULL) { + fprintf(stderr, "Error. Cannot open input file %s", infilename); + return -1; + } + + FILE *outfile = fopen(outfilename, "wb"); + if (outfile == NULL) { + fprintf(stderr, "Error. Cannot open output file %s", outfilename); + fclose(infile); + return -1; + } + + if (decode) { + return huffman_decode(infile, outfile); + } else { + return huffman_encode(infile, outfile); + } +} From add4d470469b74bb2495431a7963e39eb80d17ab Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 15 Apr 2015 19:16:00 +0200 Subject: [PATCH 073/132] add: compress fpga images during compile, uncompress at run time --- .gitignore | 1 + Makefile | 1 - armsrc/Makefile | 20 ++- armsrc/adler32.c | 179 ++++++++++++++++++++++ armsrc/apps.h | 55 +------ armsrc/fpga_hf.bit.gz | Bin 19160 -> 0 bytes armsrc/fpga_lf.bit.gz | Bin 18299 -> 0 bytes armsrc/fpgaloader.c | 186 +++++++++++++--------- armsrc/fpgaloader.h | 64 ++++++++ armsrc/inffast.c | 340 +++++++++++++++++++++++++++++++++++++++++ armsrc/inftrees.c | 302 ++++++++++++++++++++++++++++++++++++ armsrc/zutil.c | 324 +++++++++++++++++++++++++++++++++++++++ common/Makefile.common | 1 + 13 files changed, 1343 insertions(+), 130 deletions(-) create mode 100644 armsrc/adler32.c delete mode 100644 armsrc/fpga_hf.bit.gz delete mode 100644 armsrc/fpga_lf.bit.gz create mode 100644 armsrc/fpgaloader.h create mode 100644 armsrc/inffast.c create mode 100644 armsrc/inftrees.c create mode 100644 armsrc/zutil.c diff --git a/.gitignore b/.gitignore index 07669e14..51dcefc5 100644 --- a/.gitignore +++ b/.gitignore @@ -12,6 +12,7 @@ *.bin *.dll *.moc.cpp +*.gz *.exe proxmark proxmark3 diff --git a/Makefile b/Makefile index b558da2d..dfcbaecf 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,5 @@ include common/Makefile.common -GZIP=gzip FLASH_PORT=/dev/ttyACM0 all clean: %: bootrom/% armsrc/% client/% recovery/% diff --git a/armsrc/Makefile b/armsrc/Makefile index 3fd93ac3..c7d85f1a 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -10,7 +10,7 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line #in the next section to remove that particular feature from compilation -APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -fno-strict-aliasing -ffunction-sections -fdata-sections +APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -DZ_SOLO -fno-strict-aliasing -ffunction-sections -fdata-sections #-DWITH_LCD #SRC_LCD = fonts.c LCD.c @@ -31,7 +31,11 @@ THUMBSRC = start.c \ string.c \ usb_cdc.c \ cmd.c \ - inflate.c + inflate.c \ + zutil.c \ + adler32.c \ + inftrees.c \ + inffast.c # These are to be compiled in ARM mode ARMSRC = fpgaloader.c \ @@ -57,11 +61,14 @@ OBJS = $(OBJDIR)/osimage.s19 all: $(OBJS) -$(OBJDIR)/fpga_lf.o: fpga_lf.bit - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary____fpga_fpga_lf_bit_start=_binary_fpga_lf_bit_start --redefine-sym _binary____fpga_fpga_lf_bit_end=_binary_fpga_lf_bit_end --prefix-sections=fpga_lf_bit $^ $@ +$(OBJDIR)/fpga_lf.o: $(OBJDIR)/fpga_lf.bit.gz + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_lf_bit_gz_start=_binary_fpga_lf_bit_start --redefine-sym _binary_obj_fpga_lf_bit_gz_end=_binary_fpga_lf_bit_end --prefix-sections=fpga_lf_bit $^ $@ -$(OBJDIR)/fpga_hf.o: fpga_hf.bit - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary____fpga_fpga_hf_bit_start=_binary_fpga_hf_bit_start --redefine-sym _binary____fpga_fpga_hf_bit_end=_binary_fpga_hf_bit_end --prefix-sections=fpga_hf_bit $^ $@ +$(OBJDIR)/fpga_hf.o: $(OBJDIR)/fpga_hf.bit.gz + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_hf_bit_gz_start=_binary_fpga_hf_bit_start --redefine-sym _binary_obj_fpga_hf_bit_gz_end=_binary_fpga_hf_bit_end --prefix-sections=fpga_hf_bit $^ $@ + +$(OBJDIR)/%.bit.gz: %.bit + $(GZIP) --best -c $^ >$@ $(OBJDIR)/fullimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_lf.o $(OBJDIR)/fpga_hf.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) @@ -82,6 +89,7 @@ clean: $(DELETE) $(OBJDIR)$(PATHSEP)*.s19 $(DELETE) $(OBJDIR)$(PATHSEP)*.map $(DELETE) $(OBJDIR)$(PATHSEP)*.d + $(DELETE) $(OBJDIR)$(PATHSEP)*.gz $(DELETE) version.c .PHONY: all clean help diff --git a/armsrc/adler32.c b/armsrc/adler32.c new file mode 100644 index 00000000..a868f073 --- /dev/null +++ b/armsrc/adler32.c @@ -0,0 +1,179 @@ +/* adler32.c -- compute the Adler-32 checksum of a data stream + * Copyright (C) 1995-2011 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" + +#define local static + +local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2)); + +#define BASE 65521 /* largest prime smaller than 65536 */ +#define NMAX 5552 +/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */ + +#define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;} +#define DO2(buf,i) DO1(buf,i); DO1(buf,i+1); +#define DO4(buf,i) DO2(buf,i); DO2(buf,i+2); +#define DO8(buf,i) DO4(buf,i); DO4(buf,i+4); +#define DO16(buf) DO8(buf,0); DO8(buf,8); + +/* use NO_DIVIDE if your processor does not do division in hardware -- + try it both ways to see which is faster */ +#ifdef NO_DIVIDE +/* note that this assumes BASE is 65521, where 65536 % 65521 == 15 + (thank you to John Reiser for pointing this out) */ +# define CHOP(a) \ + do { \ + unsigned long tmp = a >> 16; \ + a &= 0xffffUL; \ + a += (tmp << 4) - tmp; \ + } while (0) +# define MOD28(a) \ + do { \ + CHOP(a); \ + if (a >= BASE) a -= BASE; \ + } while (0) +# define MOD(a) \ + do { \ + CHOP(a); \ + MOD28(a); \ + } while (0) +# define MOD63(a) \ + do { /* this assumes a is not negative */ \ + z_off64_t tmp = a >> 32; \ + a &= 0xffffffffL; \ + a += (tmp << 8) - (tmp << 5) + tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + tmp = a >> 16; \ + a &= 0xffffL; \ + a += (tmp << 4) - tmp; \ + if (a >= BASE) a -= BASE; \ + } while (0) +#else +# define MOD(a) a %= BASE +# define MOD28(a) a %= BASE +# define MOD63(a) a %= BASE +#endif + +/* ========================================================================= */ +uLong ZEXPORT adler32(adler, buf, len) + uLong adler; + const Bytef *buf; + uInt len; +{ + unsigned long sum2; + unsigned n; + + /* split Adler-32 into component sums */ + sum2 = (adler >> 16) & 0xffff; + adler &= 0xffff; + + /* in case user likes doing a byte at a time, keep it fast */ + if (len == 1) { + adler += buf[0]; + if (adler >= BASE) + adler -= BASE; + sum2 += adler; + if (sum2 >= BASE) + sum2 -= BASE; + return adler | (sum2 << 16); + } + + /* initial Adler-32 value (deferred check for len == 1 speed) */ + if (buf == Z_NULL) + return 1L; + + /* in case short lengths are provided, keep it somewhat fast */ + if (len < 16) { + while (len--) { + adler += *buf++; + sum2 += adler; + } + if (adler >= BASE) + adler -= BASE; + MOD28(sum2); /* only added so many BASE's */ + return adler | (sum2 << 16); + } + + /* do length NMAX blocks -- requires just one modulo operation */ + while (len >= NMAX) { + len -= NMAX; + n = NMAX / 16; /* NMAX is divisible by 16 */ + do { + DO16(buf); /* 16 sums unrolled */ + buf += 16; + } while (--n); + MOD(adler); + MOD(sum2); + } + + /* do remaining bytes (less than NMAX, still just one modulo) */ + if (len) { /* avoid modulos if none remaining */ + while (len >= 16) { + len -= 16; + DO16(buf); + buf += 16; + } + while (len--) { + adler += *buf++; + sum2 += adler; + } + MOD(adler); + MOD(sum2); + } + + /* return recombined sums */ + return adler | (sum2 << 16); +} + +/* ========================================================================= */ +local uLong adler32_combine_(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + unsigned long sum1; + unsigned long sum2; + unsigned rem; + + /* for negative len, return invalid adler32 as a clue for debugging */ + if (len2 < 0) + return 0xffffffffUL; + + /* the derivation of this formula is left as an exercise for the reader */ + MOD63(len2); /* assumes len2 >= 0 */ + rem = (unsigned)len2; + sum1 = adler1 & 0xffff; + sum2 = rem * sum1; + MOD(sum2); + sum1 += (adler2 & 0xffff) + BASE - 1; + sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem; + if (sum1 >= BASE) sum1 -= BASE; + if (sum1 >= BASE) sum1 -= BASE; + if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1); + if (sum2 >= BASE) sum2 -= BASE; + return sum1 | (sum2 << 16); +} + +/* ========================================================================= */ +uLong ZEXPORT adler32_combine(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} + +uLong ZEXPORT adler32_combine64(adler1, adler2, len2) + uLong adler1; + uLong adler2; + z_off64_t len2; +{ + return adler32_combine_(adler1, adler2, len2); +} diff --git a/armsrc/apps.h b/armsrc/apps.h index fa081d21..98be05a3 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -19,6 +19,7 @@ #include "mifare.h" #include "../common/crc32.h" #include "BigBuf.h" +#include "fpgaloader.h" extern const uint8_t OddByteParity[256]; extern int rsamples; // = 0; @@ -50,60 +51,6 @@ void ListenReaderField(int limit); extern int ToSendMax; extern uint8_t ToSend[]; -/// fpga.h -void FpgaSendCommand(uint16_t cmd, uint16_t v); -void FpgaWriteConfWord(uint8_t v); -void FpgaDownloadAndGo(int bitstream_version); -int FpgaGatherBitstreamVersion(); -void FpgaGatherVersion(int bitstream_version, char *dst, int len); -void FpgaSetupSsc(void); -void SetupSpi(int mode); -bool FpgaSetupSscDma(uint8_t *buf, int len); -#define FpgaDisableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; -#define FpgaEnableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; -void SetAdcMuxFor(uint32_t whichGpio); - -// Definitions for the FPGA commands. -#define FPGA_CMD_SET_CONFREG (1<<12) -#define FPGA_CMD_SET_DIVISOR (2<<12) -#define FPGA_CMD_SET_USER_BYTE1 (3<<12) -// Definitions for the FPGA configuration word. -// LF -#define FPGA_MAJOR_MODE_LF_ADC (0<<5) -#define FPGA_MAJOR_MODE_LF_EDGE_DETECT (1<<5) -#define FPGA_MAJOR_MODE_LF_PASSTHRU (2<<5) -// HF -#define FPGA_MAJOR_MODE_HF_READER_TX (0<<5) -#define FPGA_MAJOR_MODE_HF_READER_RX_XCORR (1<<5) -#define FPGA_MAJOR_MODE_HF_SIMULATOR (2<<5) -#define FPGA_MAJOR_MODE_HF_ISO14443A (3<<5) -// BOTH -#define FPGA_MAJOR_MODE_OFF (7<<5) -// Options for LF_ADC -#define FPGA_LF_ADC_READER_FIELD (1<<0) -// Options for LF_EDGE_DETECT -#define FPGA_CMD_SET_EDGE_DETECT_THRESHOLD FPGA_CMD_SET_USER_BYTE1 -#define FPGA_LF_EDGE_DETECT_READER_FIELD (1<<0) -#define FPGA_LF_EDGE_DETECT_TOGGLE_MODE (1<<1) -// Options for the HF reader, tx to tag -#define FPGA_HF_READER_TX_SHALLOW_MOD (1<<0) -// Options for the HF reader, correlating against rx from tag -#define FPGA_HF_READER_RX_XCORR_848_KHZ (1<<0) -#define FPGA_HF_READER_RX_XCORR_SNOOP (1<<1) -#define FPGA_HF_READER_RX_XCORR_QUARTER_FREQ (1<<2) -// Options for the HF simulated tag, how to modulate -#define FPGA_HF_SIMULATOR_NO_MODULATION (0<<0) -#define FPGA_HF_SIMULATOR_MODULATE_BPSK (1<<0) -#define FPGA_HF_SIMULATOR_MODULATE_212K (2<<0) -#define FPGA_HF_SIMULATOR_MODULATE_424K (4<<0) -#define FPGA_HF_SIMULATOR_MODULATE_424K_8BIT 0x5//101 - -// Options for ISO14443A -#define FPGA_HF_ISO14443A_SNIFFER (0<<0) -#define FPGA_HF_ISO14443A_TAGSIM_LISTEN (1<<0) -#define FPGA_HF_ISO14443A_TAGSIM_MOD (2<<0) -#define FPGA_HF_ISO14443A_READER_LISTEN (3<<0) -#define FPGA_HF_ISO14443A_READER_MOD (4<<0) /// lfops.h extern uint8_t decimation; diff --git a/armsrc/fpga_hf.bit.gz b/armsrc/fpga_hf.bit.gz deleted file mode 100644 index 0cbb214d2cd73816870d583a0890aa3f64142f8d..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 19160 zcmV*AKySYviwFpM^BYwH17>h%VP9xwE@EkP0PVdGbX3=MH@fe+SMt@|E6qiSRPn!D zjbvv`M$#Y=Ot3t<2<%R68YYR;(r%H|nSu5VY zKDu+xJ@=g7{_Xucd!Wic?fwryS_|{P)cq%G|F`vDYV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^liFMrN@Y5bFmtILhtcS+IT0t*O^Yje0(W&*@yFa)0HkFc)(@!R!sQAA|pz z_p=>zM=^ifx4EO^H~dGxAO6>WIaYdL59-(AaP#{bBDe#094ZPqgT zpRtzVf8JVV{|nag=5Wz{=3L84@m@FQTJG~c!C$kM<#28)KU~ZIuWR$4f5Ko&O#HL! z_u#|Nho28WAAUakeE9kB^Wo>i&)ohJ6aJF*;nVo=^Wo>i&xfB6KOcTR{QUpV7ou40 nJ5CscxJeF!RrTBbooHVX23soJ=jeYeeWL#tJ0n*RzoY;Fa!6#A diff --git a/armsrc/fpga_lf.bit.gz b/armsrc/fpga_lf.bit.gz deleted file mode 100644 index d736beed49b3f8d06886758910df578f539042f7..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 18299 zcmWh!1w)iw6IGG!Zg@dO5$Tp#X(c3-j+O52+Li9^2BoByMsjHoq`{@TyIGcvkM9TE z`^+@)PDq$KQaWjix_e0}|v1ap$cR7}Of9SyyJ|-Nkc7GK0#2T4j%XuNK z7*xGJZvGJhJB*49zG7Q?X7N)@73X#Aj927OF)?zwA&TMJz2!p$j3R46)c0Y`zd(3R zRGO2z#Q$j3AGGH^ezqDMJ^UL5elmT+x0fJ+nK{9@Ua|6?E(bg?gFURb3YJ}82aw3B zffsY(&feT=FV{&Xvnf=ZjgoCllJ!WuWfe9{)5f@TIMRDqpB^7{1OwL4gJl@8r$*1d z>*I5(VYDfe*`7KZ=01r*i&BAsNl*GP(30nwiNWC#g$5Com^VhqviCO=YkiFq2LGFg9{hUUJ~{f+qonZVe*S7bx!4m|6%{^MWFVT(ULG66d3zhAuE1^%<^}j6 z?@%hs^g;ZSFwxluLbSW@^Df?4eN!=76=YvWC^A~g^)G40?a`^9P;4_>hrozD^fo=M ztDvu8(}gK}dIRK39(k9Ni^7w{kKwLP$@7X;`o=YzW%s(Wd948(Z0vBA4RhGC5@Bt= zY+E^`36J?CS!RXEbh2LQYyDCuU%tq4SJ&#l!QOcJ@i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+A0l>S>1Q^ec$VXv}u6xZ@SXWrI#gcdj^pOZrXg z%jwr|SYK|x(#i^{3RZKyFwH2w!xXxJgrlY{H7u#vuQFI_hEsA4JU`7CbpFB?*pu99#|<-ugl~#@GPic)HSLI zN%Q3Bjms*h8_wU7lK%oMAULjea5-SC`hNwNgK+E^e-Xsx=9zH${h4t&Xt?*V9@s@E z8tP=IF|$I?I9I#|c}Sy53K^z*#l^uM64aYfUF|XI)Lyer@9klA(2G}QdQQ9)!`vT! z^-1PL&w*c>hFG`7EABnM(~ASgI#Scv#YLU{}TRn|8*_@^FIkNBqsjb{t5Wt=YyXQem?m5 z;OB#%4}L!Q`QT^fc!`O4$@E{B!Lq`tuaxuu><1qsLl_d_f8}$SWM+7c{@Z8|J?CHD zo_}laN35w8In +#include +#include +#include "fpgaloader.h" #include "proxmark3.h" -#include "apps.h" #include "util.h" #include "string.h" +#include "BigBuf.h" +#include "zlib.h" + +extern void Dbprintf(const char *fmt, ...); // remember which version of the bitstream we have already downloaded to the FPGA static int downloaded_bitstream = FPGA_BITSTREAM_ERR; @@ -23,9 +31,8 @@ extern uint8_t _binary_fpga_hf_bit_start, _binary_fpga_hf_bit_end; static uint8_t *fpga_image_ptr = NULL; static const uint8_t _bitparse_fixed_header[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x00, 0x00, 0x01}; -static const uint8_t _gzip_header[] = {0x1f, 0x8b, 0x08}; // including compression method 0x08 (deflate) -#define GZIP_HEADER_SIZE sizeof(_gzip_header) #define FPGA_BITSTREAM_FIXED_HEADER_SIZE sizeof(_bitparse_fixed_header) +#define OUTPUT_BUFFER_LEN 80 //----------------------------------------------------------------------------- // Set up the Serial Peripheral Interface as master @@ -164,15 +171,86 @@ bool FpgaSetupSscDma(uint8_t *buf, int len) } -void reset_fpga_stream(uint8_t *image_start) +uint8_t get_from_fpga_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) { - fpga_image_ptr = image_start; + if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data + compressed_fpga_stream->next_out = output_buffer; + compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; + fpga_image_ptr = output_buffer; + int res = inflate(compressed_fpga_stream, Z_SYNC_FLUSH); + // if (res != Z_OK && res != Z_STREAM_END) { + Dbprintf("inflate returned: %d, %s", res, compressed_fpga_stream->msg); + // } + } + + Dbprintf("get_from_fpga_stream() returns %02x", *fpga_image_ptr); + return *fpga_image_ptr++; } -uint8_t get_from_fpga_stream(void) +static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size) { - return *fpga_image_ptr++; + Dbprintf("zlib requested %d bytes", items*size); + return BigBuf_malloc(items*size); +} + + +static void fpga_inflate_free(voidpf opaque, voidpf address) +{ + Dbprintf("zlib wants to free memory"); + BigBuf_free_keep_EM(); +} + + +void init_fpga_inflate(z_streamp compressed_fpga_stream, uint8_t *fpga_image_start, uint32_t fpga_image_size, uint8_t *output_buffer) +{ + // initialize z_stream structure for inflate: + compressed_fpga_stream->next_in = fpga_image_start; + compressed_fpga_stream->avail_in = fpga_image_size; + compressed_fpga_stream->next_out = output_buffer; + compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; + compressed_fpga_stream->zalloc = &fpga_inflate_malloc; + compressed_fpga_stream->zfree = &fpga_inflate_free; + + // initialize inflate to automatically detect header: + int res = inflateInit2(compressed_fpga_stream, 15+32); + + fpga_image_ptr = output_buffer; + + Dbprintf("InflateInit returned %d", res); + Dbprintf("fpga_image_ptr pointing at %02x %02x %02x %02x", fpga_image_ptr[0], fpga_image_ptr[1], fpga_image_ptr[2], fpga_image_ptr[3]); + Dbprintf("zstream->next_in pointing at %02x %02x %02x %02x", compressed_fpga_stream->next_in[0], compressed_fpga_stream->next_in[1], compressed_fpga_stream->next_in[2], compressed_fpga_stream->next_in[3]); +} + + +bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +{ + uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; + uint8_t *fpga_image_start; + uint32_t fpga_image_size; + + if (bitstream_version == FPGA_BITSTREAM_LF) { + fpga_image_start = &_binary_fpga_lf_bit_start; + fpga_image_size = (uint32_t)&_binary_fpga_lf_bit_end - (uint32_t)&_binary_fpga_lf_bit_start; + } else if (bitstream_version == FPGA_BITSTREAM_HF) { + fpga_image_start = &_binary_fpga_hf_bit_start; + fpga_image_size = (uint32_t)&_binary_fpga_hf_bit_end - (uint32_t)&_binary_fpga_hf_bit_start; + } else { + return false; + } + + init_fpga_inflate(compressed_fpga_stream, fpga_image_start, fpga_image_size, output_buffer); + + for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { + header[i] = get_from_fpga_stream(compressed_fpga_stream, output_buffer); + } + + // Check for a valid .bit file (starts with _bitparse_fixed_header) + if(memcmp(_bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) { + return true; + } else { + return false; + } } @@ -190,8 +268,11 @@ static void DownloadFPGA_byte(unsigned char w) } // Download the fpga image starting at current stream position with length FpgaImageLen bytes -static void DownloadFPGA(int FpgaImageLen) +static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { + Dbprintf("Would have loaded FPGA"); + return; + int i=0; AT91C_BASE_PIOA->PIO_OER = GPIO_FPGA_ON; @@ -244,7 +325,7 @@ static void DownloadFPGA(int FpgaImageLen) } while(FpgaImageLen-->0) { - DownloadFPGA_byte(get_from_fpga_stream()); + DownloadFPGA_byte(get_from_fpga_stream(compressed_fpga_stream, output_buffer)); } // continue to clock FPGA until ready signal goes high @@ -269,13 +350,13 @@ static void DownloadFPGA(int FpgaImageLen) * (big endian), bytes content. Except for section 'e' which has 4 bytes * length. */ -int bitparse_find_section(char section_name, unsigned int *section_length) +int bitparse_find_section(char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { int result = 0; #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section uint16_t numbytes = 0; while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) { - char current_name = get_from_fpga_stream(); + char current_name = get_from_fpga_stream(compressed_fpga_stream, output_buffer); numbytes++; unsigned int current_length = 0; if(current_name < 'a' || current_name > 'e') { @@ -286,12 +367,12 @@ int bitparse_find_section(char section_name, unsigned int *section_length) switch(current_name) { case 'e': /* Four byte length field */ - current_length += get_from_fpga_stream() << 24; - current_length += get_from_fpga_stream() << 16; + current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 24; + current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 16; numbytes += 2; default: /* Fall through, two byte length field */ - current_length += get_from_fpga_stream() << 8; - current_length += get_from_fpga_stream() << 0; + current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 8; + current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 0; numbytes += 2; } @@ -308,7 +389,7 @@ int bitparse_find_section(char section_name, unsigned int *section_length) } for (uint16_t i = 0; i < current_length && numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH; i++) { - get_from_fpga_stream(); + get_from_fpga_stream(compressed_fpga_stream, output_buffer); numbytes++; } } @@ -316,11 +397,6 @@ int bitparse_find_section(char section_name, unsigned int *section_length) return result; } -void init_fpga_inflate(void) -{ - // initialize zlib for inflate -} - //----------------------------------------------------------------------------- // Find out which FPGA image format is stored in flash, then call DownloadFPGA @@ -328,71 +404,42 @@ void init_fpga_inflate(void) //----------------------------------------------------------------------------- void FpgaDownloadAndGo(int bitstream_version) { - uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; + z_stream compressed_fpga_stream; + uint8_t output_buffer[OUTPUT_BUFFER_LEN]; // check whether or not the bitstream is already loaded if (downloaded_bitstream == bitstream_version) return; - if (bitstream_version == FPGA_BITSTREAM_LF) { - reset_fpga_stream(&_binary_fpga_lf_bit_start); - } else if (bitstream_version == FPGA_BITSTREAM_HF) { - reset_fpga_stream(&_binary_fpga_hf_bit_start); - } else + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; - - uint16_t i = 0; - for (; i < GZIP_HEADER_SIZE; i++) { - header[i] = get_from_fpga_stream(); } - // Check for compressed new flash image format (starts with gzip header) - if(memcmp(_gzip_header, header, GZIP_HEADER_SIZE) == 0) { - init_fpga_inflate(); - } - - for (; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { - header[i] = get_from_fpga_stream(); - } - - // Check for the new flash image format: Should have the .bit file at &_binary_fpga_bit_start - if(memcmp(_bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) { - unsigned int bitstream_length; - if(bitparse_find_section('e', &bitstream_length)) { - DownloadFPGA(bitstream_length); - downloaded_bitstream = bitstream_version; - return; /* All done */ - } + unsigned int bitstream_length; + if(bitparse_find_section('e', &bitstream_length, &compressed_fpga_stream, output_buffer)) { + DownloadFPGA(bitstream_length, &compressed_fpga_stream, output_buffer); + downloaded_bitstream = bitstream_version; + return; /* All done */ } } -int FpgaGatherBitstreamVersion() -{ - return downloaded_bitstream; -} void FpgaGatherVersion(int bitstream_version, char *dst, int len) { unsigned int fpga_info_len; char tempstr[40]; + z_stream compressed_fpga_stream; + uint8_t output_buffer[OUTPUT_BUFFER_LEN]; dst[0] = '\0'; - if (bitstream_version == FPGA_BITSTREAM_LF) { - reset_fpga_stream(&_binary_fpga_lf_bit_start); - } else if (bitstream_version == FPGA_BITSTREAM_HF) { - reset_fpga_stream(&_binary_fpga_hf_bit_start); - } else + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; - - - for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { - get_from_fpga_stream(); } - if(bitparse_find_section('a', &fpga_info_len)) { + if(bitparse_find_section('a', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(); + char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } @@ -403,30 +450,30 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) strncat(dst, "HF ", len-1); } strncat(dst, "FPGA image built", len-1); - if(bitparse_find_section('b', &fpga_info_len)) { + if(bitparse_find_section('b', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { strncat(dst, " for ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(); + char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } } strncat(dst, tempstr, len-1); } - if(bitparse_find_section('c', &fpga_info_len)) { + if(bitparse_find_section('c', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { strncat(dst, " on ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(); + char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } } strncat(dst, tempstr, len-1); } - if(bitparse_find_section('d', &fpga_info_len)) { + if(bitparse_find_section('d', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { strncat(dst, " at ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(); + char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } @@ -435,6 +482,7 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) } } + //----------------------------------------------------------------------------- // Send a 16 bit command/data pair to the FPGA. // The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0 diff --git a/armsrc/fpgaloader.h b/armsrc/fpgaloader.h new file mode 100644 index 00000000..6981b216 --- /dev/null +++ b/armsrc/fpgaloader.h @@ -0,0 +1,64 @@ +//----------------------------------------------------------------------------- +// Jonathan Westhues, April 2006 +// iZsh , 2014 +// +// 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. +//----------------------------------------------------------------------------- +// Routines to load the FPGA image, and then to configure the FPGA's major +// mode once it is configured. +//----------------------------------------------------------------------------- + +void FpgaSendCommand(uint16_t cmd, uint16_t v); +void FpgaWriteConfWord(uint8_t v); +void FpgaDownloadAndGo(int bitstream_version); +void FpgaGatherVersion(int bitstream_version, char *dst, int len); +void FpgaSetupSsc(void); +void SetupSpi(int mode); +bool FpgaSetupSscDma(uint8_t *buf, int len); +#define FpgaDisableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; +#define FpgaEnableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; +void SetAdcMuxFor(uint32_t whichGpio); + +// Definitions for the FPGA commands. +#define FPGA_CMD_SET_CONFREG (1<<12) +#define FPGA_CMD_SET_DIVISOR (2<<12) +#define FPGA_CMD_SET_USER_BYTE1 (3<<12) +// Definitions for the FPGA configuration word. +// LF +#define FPGA_MAJOR_MODE_LF_ADC (0<<5) +#define FPGA_MAJOR_MODE_LF_EDGE_DETECT (1<<5) +#define FPGA_MAJOR_MODE_LF_PASSTHRU (2<<5) +// HF +#define FPGA_MAJOR_MODE_HF_READER_TX (0<<5) +#define FPGA_MAJOR_MODE_HF_READER_RX_XCORR (1<<5) +#define FPGA_MAJOR_MODE_HF_SIMULATOR (2<<5) +#define FPGA_MAJOR_MODE_HF_ISO14443A (3<<5) +// BOTH +#define FPGA_MAJOR_MODE_OFF (7<<5) +// Options for LF_ADC +#define FPGA_LF_ADC_READER_FIELD (1<<0) +// Options for LF_EDGE_DETECT +#define FPGA_CMD_SET_EDGE_DETECT_THRESHOLD FPGA_CMD_SET_USER_BYTE1 +#define FPGA_LF_EDGE_DETECT_READER_FIELD (1<<0) +#define FPGA_LF_EDGE_DETECT_TOGGLE_MODE (1<<1) +// Options for the HF reader, tx to tag +#define FPGA_HF_READER_TX_SHALLOW_MOD (1<<0) +// Options for the HF reader, correlating against rx from tag +#define FPGA_HF_READER_RX_XCORR_848_KHZ (1<<0) +#define FPGA_HF_READER_RX_XCORR_SNOOP (1<<1) +#define FPGA_HF_READER_RX_XCORR_QUARTER_FREQ (1<<2) +// Options for the HF simulated tag, how to modulate +#define FPGA_HF_SIMULATOR_NO_MODULATION (0<<0) +#define FPGA_HF_SIMULATOR_MODULATE_BPSK (1<<0) +#define FPGA_HF_SIMULATOR_MODULATE_212K (2<<0) +#define FPGA_HF_SIMULATOR_MODULATE_424K (4<<0) +#define FPGA_HF_SIMULATOR_MODULATE_424K_8BIT 0x5//101 + +// Options for ISO14443A +#define FPGA_HF_ISO14443A_SNIFFER (0<<0) +#define FPGA_HF_ISO14443A_TAGSIM_LISTEN (1<<0) +#define FPGA_HF_ISO14443A_TAGSIM_MOD (2<<0) +#define FPGA_HF_ISO14443A_READER_LISTEN (3<<0) +#define FPGA_HF_ISO14443A_READER_MOD (4<<0) diff --git a/armsrc/inffast.c b/armsrc/inffast.c new file mode 100644 index 00000000..bda59ceb --- /dev/null +++ b/armsrc/inffast.c @@ -0,0 +1,340 @@ +/* inffast.c -- fast decoding + * Copyright (C) 1995-2008, 2010, 2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" +#include "inflate.h" +#include "inffast.h" + +#ifndef ASMINF + +/* Allow machine dependent optimization for post-increment or pre-increment. + Based on testing to date, + Pre-increment preferred for: + - PowerPC G3 (Adler) + - MIPS R5000 (Randers-Pehrson) + Post-increment preferred for: + - none + No measurable difference: + - Pentium III (Anderson) + - M68060 (Nikl) + */ +#ifdef POSTINC +# define OFF 0 +# define PUP(a) *(a)++ +#else +# define OFF 1 +# define PUP(a) *++(a) +#endif + +/* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state->mode == LEN + strm->avail_in >= 6 + strm->avail_out >= 258 + start >= strm->avail_out + state->bits < 8 + + On return, state->mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm->avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm->avail_out >= 258 for each loop to avoid checking for + output space. + */ +void ZLIB_INTERNAL inflate_fast(strm, start) +z_streamp strm; +unsigned start; /* inflate()'s starting value for strm->avail_out */ +{ + struct inflate_state FAR *state; + z_const unsigned char FAR *in; /* local strm->next_in */ + z_const unsigned char FAR *last; /* have enough input while in < last */ + unsigned char FAR *out; /* local strm->next_out */ + unsigned char FAR *beg; /* inflate()'s initial strm->next_out */ + unsigned char FAR *end; /* while out < end, enough space available */ +#ifdef INFLATE_STRICT + unsigned dmax; /* maximum distance from zlib header */ +#endif + unsigned wsize; /* window size or zero if not using window */ + unsigned whave; /* valid bytes in the window */ + unsigned wnext; /* window write index */ + unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */ + unsigned long hold; /* local strm->hold */ + unsigned bits; /* local strm->bits */ + code const FAR *lcode; /* local strm->lencode */ + code const FAR *dcode; /* local strm->distcode */ + unsigned lmask; /* mask for first level of length codes */ + unsigned dmask; /* mask for first level of distance codes */ + code here; /* retrieved table entry */ + unsigned op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + unsigned len; /* match length, unused bytes */ + unsigned dist; /* match distance */ + unsigned char FAR *from; /* where to copy match from */ + + /* copy state to local variables */ + state = (struct inflate_state FAR *)strm->state; + in = strm->next_in - OFF; + last = in + (strm->avail_in - 5); + out = strm->next_out - OFF; + beg = out - (start - strm->avail_out); + end = out + (strm->avail_out - 257); +#ifdef INFLATE_STRICT + dmax = state->dmax; +#endif + wsize = state->wsize; + whave = state->whave; + wnext = state->wnext; + window = state->window; + hold = state->hold; + bits = state->bits; + lcode = state->lencode; + dcode = state->distcode; + lmask = (1U << state->lenbits) - 1; + dmask = (1U << state->distbits) - 1; + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + do { + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = lcode[hold & lmask]; + dolen: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op == 0) { /* literal */ + Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + "inflate: literal '%c'\n" : + "inflate: literal 0x%02x\n", here.val)); + PUP(out) = (unsigned char)(here.val); + } + else if (op & 16) { /* length base */ + len = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + len += (unsigned)hold & ((1U << op) - 1); + hold >>= op; + bits -= op; + } + Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + here = dcode[hold & dmask]; + dodist: + op = (unsigned)(here.bits); + hold >>= op; + bits -= op; + op = (unsigned)(here.op); + if (op & 16) { /* distance base */ + dist = (unsigned)(here.val); + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + if (bits < op) { + hold += (unsigned long)(PUP(in)) << bits; + bits += 8; + } + } + dist += (unsigned)hold & ((1U << op) - 1); +#ifdef INFLATE_STRICT + if (dist > dmax) { + strm->msg = (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#endif + hold >>= op; + bits -= op; + Tracevv((stderr, "inflate: distance %u\n", dist)); + op = (unsigned)(out - beg); /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state->sane) { + strm->msg = + (char *)"invalid distance too far back"; + state->mode = BAD; + break; + } +#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + if (len <= op - whave) { + do { + PUP(out) = 0; + } while (--len); + continue; + } + len -= op - whave; + do { + PUP(out) = 0; + } while (--op > whave); + if (op == 0) { + from = out - dist; + do { + PUP(out) = PUP(from); + } while (--len); + continue; + } +#endif + } + from = window - OFF; + if (wnext == 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = window - OFF; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + PUP(out) = PUP(from); + } while (--op); + from = out - dist; /* rest from output */ + } + } + while (len > 2) { + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + else { + from = out - dist; /* copy direct from output */ + do { /* minimum length is three */ + PUP(out) = PUP(from); + PUP(out) = PUP(from); + PUP(out) = PUP(from); + len -= 3; + } while (len > 2); + if (len) { + PUP(out) = PUP(from); + if (len > 1) + PUP(out) = PUP(from); + } + } + } + else if ((op & 64) == 0) { /* 2nd level distance code */ + here = dcode[here.val + (hold & ((1U << op) - 1))]; + goto dodist; + } + else { + strm->msg = (char *)"invalid distance code"; + state->mode = BAD; + break; + } + } + else if ((op & 64) == 0) { /* 2nd level length code */ + here = lcode[here.val + (hold & ((1U << op) - 1))]; + goto dolen; + } + else if (op & 32) { /* end-of-block */ + Tracevv((stderr, "inflate: end of block\n")); + state->mode = TYPE; + break; + } + else { + strm->msg = (char *)"invalid literal/length code"; + state->mode = BAD; + break; + } + } while (in < last && out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + in -= len; + bits -= len << 3; + hold &= (1U << bits) - 1; + + /* update state and return */ + strm->next_in = in + OFF; + strm->next_out = out + OFF; + strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last)); + strm->avail_out = (unsigned)(out < end ? + 257 + (end - out) : 257 - (out - end)); + state->hold = hold; + state->bits = bits; + return; +} + +/* + inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe): + - Using bit fields for code structure + - Different op definition to avoid & for extra bits (do & for table bits) + - Three separate decoding do-loops for direct, window, and wnext == 0 + - Special case for distance > 1 copies to do overlapped load and store copy + - Explicit branch predictions (based on measured branch probabilities) + - Deferring match copy and interspersed it with decoding subsequent codes + - Swapping literal/length else + - Swapping window/direct else + - Larger unrolled copy loops (three is about right) + - Moving len -= 3 statement into middle of loop + */ + +#endif /* !ASMINF */ diff --git a/armsrc/inftrees.c b/armsrc/inftrees.c new file mode 100644 index 00000000..d8c53250 --- /dev/null +++ b/armsrc/inftrees.c @@ -0,0 +1,302 @@ +/* inftrees.c -- generate Huffman trees for efficient decoding + * Copyright (C) 1995-2013 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +#include "zutil.h" +#include "inftrees.h" + +#define MAXBITS 15 + +const char inflate_copyright[] = + " inflate 1.2.8 Copyright 1995-2013 Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* + Build a set of tables to decode the provided canonical Huffman code. + The code lengths are lens[0..codes-1]. The result starts at *table, + whose indices are 0..2^bits-1. work is a writable array of at least + lens shorts, which is used as a work area. type is the type of code + to be generated, CODES, LENS, or DISTS. On return, zero is success, + -1 is an invalid code, and +1 means that ENOUGH isn't enough. table + on return points to the next available entry's address. bits is the + requested root table index bits, and on return it is the actual root + table index bits. It will differ if the request is greater than the + longest code or if it is less than the shortest code. + */ +int ZLIB_INTERNAL inflate_table(codetype type, unsigned short FAR *lens, + unsigned codes, code FAR * FAR *table, + unsigned FAR *bits, unsigned short FAR *work) +{ + unsigned len; /* a code's length in bits */ + unsigned sym; /* index of code symbols */ + unsigned min, max; /* minimum and maximum code lengths */ + unsigned root; /* number of index bits for root table */ + unsigned curr; /* number of index bits for current table */ + unsigned drop; /* code bits to drop for sub-table */ + int left; /* number of prefix codes available */ + unsigned used; /* code entries in table used */ + unsigned huff; /* Huffman code */ + unsigned incr; /* for incrementing code, index */ + unsigned fill; /* index for replicating entries */ + unsigned low; /* low bits for current root entry */ + unsigned mask; /* mask for low root bits */ + code here; /* table entry for duplication */ + code FAR *next; /* next available space in table */ + const unsigned short FAR *base; /* base value table to use */ + const unsigned short FAR *extra; /* extra bits table to use */ + int end; /* use base and extra for symbol > end */ + unsigned short count[MAXBITS+1]; /* number of codes of each length */ + unsigned short offs[MAXBITS+1]; /* offsets in table for each length */ + static const unsigned short lbase[31] = { /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; + static const unsigned short lext[31] = { /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78}; + static const unsigned short dbase[32] = { /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0}; + static const unsigned short dext[32] = { /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64}; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) + count[len] = 0; + for (sym = 0; sym < codes; sym++) + count[lens[sym]]++; + + /* bound code lengths, force root to be within code lengths */ + root = *bits; + for (max = MAXBITS; max >= 1; max--) + if (count[max] != 0) break; + if (root > max) root = max; + if (max == 0) { /* no symbols to code at all */ + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)1; + here.val = (unsigned short)0; + *(*table)++ = here; /* make a table to force an error */ + *(*table)++ = here; + *bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) + if (count[min] != 0) break; + if (root < min) root = min; + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) return -1; /* over-subscribed */ + } + if (left > 0 && (type == CODES || max != 1)) + return -1; /* incomplete set */ + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) + offs[len + 1] = offs[len] + count[len]; + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) + if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym; + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + switch (type) { + case CODES: + base = extra = work; /* dummy value--not used */ + end = 19; + break; + case LENS: + base = lbase; + base -= 257; + extra = lext; + extra -= 257; + end = 256; + break; + default: /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize state for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = *table; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = (unsigned)(-1); /* trigger new sub-table when len > root */ + used = 1U << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here.bits = (unsigned char)(len - drop); + if ((int)(work[sym]) < end) { + here.op = (unsigned char)0; + here.val = work[sym]; + } + else if ((int)(work[sym]) > end) { + here.op = (unsigned char)(extra[work[sym]]); + here.val = base[work[sym]]; + } + else { + here.op = (unsigned char)(32 + 64); /* end of block */ + here.val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1U << (len - drop); + fill = 1U << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + next[(huff >> drop) + fill] = here; + } while (fill != 0); + + /* backwards increment the len-bit code huff */ + incr = 1U << (len - 1); + while (huff & incr) + incr >>= 1; + if (incr != 0) { + huff &= incr - 1; + huff += incr; + } + else + huff = 0; + + /* go to next symbol, update count, len */ + sym++; + if (--(count[len]) == 0) { + if (len == max) break; + len = lens[work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) != low) { + /* if first time, transition to sub-tables */ + if (drop == 0) + drop = root; + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = (int)(1 << curr); + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) break; + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1U << curr; + if ((type == LENS && used > ENOUGH_LENS) || + (type == DISTS && used > ENOUGH_DISTS)) + return 1; + + /* point entry in root table to sub-table */ + low = huff & mask; + (*table)[low].op = (unsigned char)curr; + (*table)[low].bits = (unsigned char)root; + (*table)[low].val = (unsigned short)(next - *table); + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff != 0) { + here.op = (unsigned char)64; /* invalid code marker */ + here.bits = (unsigned char)(len - drop); + here.val = (unsigned short)0; + next[huff] = here; + } + + /* set return parameters */ + *table += used; + *bits = root; + return 0; +} diff --git a/armsrc/zutil.c b/armsrc/zutil.c new file mode 100644 index 00000000..23d2ebef --- /dev/null +++ b/armsrc/zutil.c @@ -0,0 +1,324 @@ +/* zutil.c -- target dependent utility functions for the compression library + * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly. + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* @(#) $Id$ */ + +#include "zutil.h" +#ifndef Z_SOLO +# include "gzguts.h" +#endif + +#ifndef NO_DUMMY_DECL +struct internal_state {int dummy;}; /* for buggy compilers */ +#endif + +z_const char * const z_errmsg[10] = { +"need dictionary", /* Z_NEED_DICT 2 */ +"stream end", /* Z_STREAM_END 1 */ +"", /* Z_OK 0 */ +"file error", /* Z_ERRNO (-1) */ +"stream error", /* Z_STREAM_ERROR (-2) */ +"data error", /* Z_DATA_ERROR (-3) */ +"insufficient memory", /* Z_MEM_ERROR (-4) */ +"buffer error", /* Z_BUF_ERROR (-5) */ +"incompatible version",/* Z_VERSION_ERROR (-6) */ +""}; + + +const char * ZEXPORT zlibVersion() +{ + return ZLIB_VERSION; +} + +uLong ZEXPORT zlibCompileFlags() +{ + uLong flags; + + flags = 0; + switch ((int)(sizeof(uInt))) { + case 2: break; + case 4: flags += 1; break; + case 8: flags += 2; break; + default: flags += 3; + } + switch ((int)(sizeof(uLong))) { + case 2: break; + case 4: flags += 1 << 2; break; + case 8: flags += 2 << 2; break; + default: flags += 3 << 2; + } + switch ((int)(sizeof(voidpf))) { + case 2: break; + case 4: flags += 1 << 4; break; + case 8: flags += 2 << 4; break; + default: flags += 3 << 4; + } + switch ((int)(sizeof(z_off_t))) { + case 2: break; + case 4: flags += 1 << 6; break; + case 8: flags += 2 << 6; break; + default: flags += 3 << 6; + } +#ifdef DEBUG + flags += 1 << 8; +#endif +#if defined(ASMV) || defined(ASMINF) + flags += 1 << 9; +#endif +#ifdef ZLIB_WINAPI + flags += 1 << 10; +#endif +#ifdef BUILDFIXED + flags += 1 << 12; +#endif +#ifdef DYNAMIC_CRC_TABLE + flags += 1 << 13; +#endif +#ifdef NO_GZCOMPRESS + flags += 1L << 16; +#endif +#ifdef NO_GZIP + flags += 1L << 17; +#endif +#ifdef PKZIP_BUG_WORKAROUND + flags += 1L << 20; +#endif +#ifdef FASTEST + flags += 1L << 21; +#endif +#if defined(STDC) || defined(Z_HAVE_STDARG_H) +# ifdef NO_vsnprintf + flags += 1L << 25; +# ifdef HAS_vsprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_vsnprintf_void + flags += 1L << 26; +# endif +# endif +#else + flags += 1L << 24; +# ifdef NO_snprintf + flags += 1L << 25; +# ifdef HAS_sprintf_void + flags += 1L << 26; +# endif +# else +# ifdef HAS_snprintf_void + flags += 1L << 26; +# endif +# endif +#endif + return flags; +} + +#ifdef DEBUG + +# ifndef verbose +# define verbose 0 +# endif +int ZLIB_INTERNAL z_verbose = verbose; + +void ZLIB_INTERNAL z_error (m) + char *m; +{ + fprintf(stderr, "%s\n", m); + exit(1); +} +#endif + +/* exported to allow conversion of error code to string for compress() and + * uncompress() + */ +const char * ZEXPORT zError(err) + int err; +{ + return ERR_MSG(err); +} + +#if defined(_WIN32_WCE) + /* The Microsoft C Run-Time Library for Windows CE doesn't have + * errno. We define it as a global variable to simplify porting. + * Its value is always 0 and should not be used. + */ + int errno = 0; +#endif + +#ifndef HAVE_MEMCPY + +void ZLIB_INTERNAL zmemcpy(dest, source, len) + Bytef* dest; + const Bytef* source; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = *source++; /* ??? to be unrolled */ + } while (--len != 0); +} + +int ZLIB_INTERNAL zmemcmp(s1, s2, len) + const Bytef* s1; + const Bytef* s2; + uInt len; +{ + uInt j; + + for (j = 0; j < len; j++) { + if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1; + } + return 0; +} + +void ZLIB_INTERNAL zmemzero(dest, len) + Bytef* dest; + uInt len; +{ + if (len == 0) return; + do { + *dest++ = 0; /* ??? to be unrolled */ + } while (--len != 0); +} +#endif + +#ifndef Z_SOLO + +#ifdef SYS16BIT + +#ifdef __TURBOC__ +/* Turbo C in 16-bit mode */ + +# define MY_ZCALLOC + +/* Turbo C malloc() does not allow dynamic allocation of 64K bytes + * and farmalloc(64K) returns a pointer with an offset of 8, so we + * must fix the pointer. Warning: the pointer must be put back to its + * original form in order to free it, use zcfree(). + */ + +#define MAX_PTR 10 +/* 10*64K = 640K */ + +local int next_ptr = 0; + +typedef struct ptr_table_s { + voidpf org_ptr; + voidpf new_ptr; +} ptr_table; + +local ptr_table table[MAX_PTR]; +/* This table is used to remember the original form of pointers + * to large buffers (64K). Such pointers are normalized with a zero offset. + * Since MSDOS is not a preemptive multitasking OS, this table is not + * protected from concurrent access. This hack doesn't work anyway on + * a protected system like OS/2. Use Microsoft C instead. + */ + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size) +{ + voidpf buf = opaque; /* just to make some compilers happy */ + ulg bsize = (ulg)items*size; + + /* If we allocate less than 65520 bytes, we assume that farmalloc + * will return a usable pointer which doesn't have to be normalized. + */ + if (bsize < 65520L) { + buf = farmalloc(bsize); + if (*(ush*)&buf != 0) return buf; + } else { + buf = farmalloc(bsize + 16L); + } + if (buf == NULL || next_ptr >= MAX_PTR) return NULL; + table[next_ptr].org_ptr = buf; + + /* Normalize the pointer to seg:0 */ + *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4; + *(ush*)&buf = 0; + table[next_ptr++].new_ptr = buf; + return buf; +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + int n; + if (*(ush*)&ptr != 0) { /* object < 64K */ + farfree(ptr); + return; + } + /* Find the original pointer */ + for (n = 0; n < next_ptr; n++) { + if (ptr != table[n].new_ptr) continue; + + farfree(table[n].org_ptr); + while (++n < next_ptr) { + table[n-1] = table[n]; + } + next_ptr--; + return; + } + ptr = opaque; /* just to make some compilers happy */ + Assert(0, "zcfree: ptr not found"); +} + +#endif /* __TURBOC__ */ + + +#ifdef M_I86 +/* Microsoft C in 16-bit mode */ + +# define MY_ZCALLOC + +#if (!defined(_MSC_VER) || (_MSC_VER <= 600)) +# define _halloc halloc +# define _hfree hfree +#endif + +voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + return _halloc((long)items, size); +} + +void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr) +{ + if (opaque) opaque = 0; /* to make compiler happy */ + _hfree(ptr); +} + +#endif /* M_I86 */ + +#endif /* SYS16BIT */ + + +#ifndef MY_ZCALLOC /* Any system without a special alloc function */ + +#ifndef STDC +extern voidp malloc OF((uInt size)); +extern voidp calloc OF((uInt items, uInt size)); +extern void free OF((voidpf ptr)); +#endif + +voidpf ZLIB_INTERNAL zcalloc (opaque, items, size) + voidpf opaque; + unsigned items; + unsigned size; +{ + if (opaque) items += size - size; /* make compiler happy */ + return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + (voidpf)calloc(items, size); +} + +void ZLIB_INTERNAL zcfree (opaque, ptr) + voidpf opaque; + voidpf ptr; +{ + free(ptr); + if (opaque) return; /* make compiler happy */ +} + +#endif /* MY_ZCALLOC */ + +#endif /* !Z_SOLO */ diff --git a/common/Makefile.common b/common/Makefile.common index 2b2bb2fb..d7e3457f 100644 --- a/common/Makefile.common +++ b/common/Makefile.common @@ -25,6 +25,7 @@ CC = $(CROSS)gcc AS = $(CROSS)as LD = $(CROSS)ld OBJCOPY = $(CROSS)objcopy +GZIP=gzip OBJDIR = obj From 25056d8b470d9e4b71c9205faf617e4b3f80df33 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Tue, 21 Apr 2015 21:34:33 +0200 Subject: [PATCH 074/132] Finish support for compressed FPGA images in fpgaloader.c - move zlib source files to separate directory zlib - rename zlib/crc32.[ch] to zlib/z_crc32.[ch] --- armsrc/Makefile | 18 +- armsrc/fpgaloader.c | 78 ++++--- common/Makefile.common | 11 +- {armsrc => zlib}/adler32.c | 0 {armsrc => zlib}/inffast.c | 0 {armsrc => zlib}/inffast.h | 0 {armsrc => zlib}/inffixed.h | 0 {armsrc => zlib}/inflate.c | 0 {armsrc => zlib}/inflate.h | 0 {armsrc => zlib}/inftrees.c | 0 {armsrc => zlib}/inftrees.h | 0 zlib/z_crc32.c | 425 ++++++++++++++++++++++++++++++++++ zlib/z_crc32.h | 441 ++++++++++++++++++++++++++++++++++++ {armsrc => zlib}/zconf.h | 0 {armsrc => zlib}/zlib.h | 0 {armsrc => zlib}/zutil.c | 0 {armsrc => zlib}/zutil.h | 0 17 files changed, 923 insertions(+), 50 deletions(-) rename {armsrc => zlib}/adler32.c (100%) rename {armsrc => zlib}/inffast.c (100%) rename {armsrc => zlib}/inffast.h (100%) rename {armsrc => zlib}/inffixed.h (100%) rename {armsrc => zlib}/inflate.c (100%) rename {armsrc => zlib}/inflate.h (100%) rename {armsrc => zlib}/inftrees.c (100%) rename {armsrc => zlib}/inftrees.h (100%) create mode 100644 zlib/z_crc32.c create mode 100644 zlib/z_crc32.h rename {armsrc => zlib}/zconf.h (100%) rename {armsrc => zlib}/zlib.h (100%) rename {armsrc => zlib}/zutil.c (100%) rename {armsrc => zlib}/zutil.h (100%) diff --git a/armsrc/Makefile b/armsrc/Makefile index c7d85f1a..51da9dab 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -10,7 +10,8 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line #in the next section to remove that particular feature from compilation -APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -DZ_SOLO -fno-strict-aliasing -ffunction-sections -fdata-sections +APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -DZ_SOLO -DZ_PREFIX \ + -fno-strict-aliasing -ffunction-sections -fdata-sections #-DWITH_LCD #SRC_LCD = fonts.c LCD.c @@ -19,23 +20,21 @@ SRC_ISO15693 = iso15693.c iso15693tools.c SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c SRC_ISO14443b = iso14443.c SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c -SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c +SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c +SRC_ZLIB = inflate.c inffast.c inftrees.c z_crc32.c adler32.c zutil.c +# Compile these in thumb mode (small size) THUMBSRC = start.c \ $(SRC_LCD) \ $(SRC_ISO15693) \ $(SRC_LF) \ + $(SRC_ZLIB) \ appmain.c \ printf.c \ util.c \ string.c \ usb_cdc.c \ - cmd.c \ - inflate.c \ - zutil.c \ - adler32.c \ - inftrees.c \ - inffast.c + cmd.c # These are to be compiled in ARM mode ARMSRC = fpgaloader.c \ @@ -53,6 +52,9 @@ ARMSRC = fpgaloader.c \ # stdint.h provided locally until GCC 4.5 becomes C99 compliant APP_CFLAGS += -I. +# zlib includes: +APP_CFLAGS += -I../zlib + # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common/Makefile.common diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c index 26e512af..be0d87d6 100644 --- a/armsrc/fpgaloader.c +++ b/armsrc/fpgaloader.c @@ -171,19 +171,21 @@ bool FpgaSetupSscDma(uint8_t *buf, int len) } -uint8_t get_from_fpga_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) +static int get_from_fpga_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) { if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data compressed_fpga_stream->next_out = output_buffer; compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; fpga_image_ptr = output_buffer; int res = inflate(compressed_fpga_stream, Z_SYNC_FLUSH); - // if (res != Z_OK && res != Z_STREAM_END) { + if (res != Z_OK) { Dbprintf("inflate returned: %d, %s", res, compressed_fpga_stream->msg); - // } + } + if (res < 0) { + return res; + } } - Dbprintf("get_from_fpga_stream() returns %02x", *fpga_image_ptr); return *fpga_image_ptr++; } @@ -197,33 +199,12 @@ static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size) static void fpga_inflate_free(voidpf opaque, voidpf address) { - Dbprintf("zlib wants to free memory"); + Dbprintf("zlib frees memory"); BigBuf_free_keep_EM(); } -void init_fpga_inflate(z_streamp compressed_fpga_stream, uint8_t *fpga_image_start, uint32_t fpga_image_size, uint8_t *output_buffer) -{ - // initialize z_stream structure for inflate: - compressed_fpga_stream->next_in = fpga_image_start; - compressed_fpga_stream->avail_in = fpga_image_size; - compressed_fpga_stream->next_out = output_buffer; - compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; - compressed_fpga_stream->zalloc = &fpga_inflate_malloc; - compressed_fpga_stream->zfree = &fpga_inflate_free; - - // initialize inflate to automatically detect header: - int res = inflateInit2(compressed_fpga_stream, 15+32); - - fpga_image_ptr = output_buffer; - - Dbprintf("InflateInit returned %d", res); - Dbprintf("fpga_image_ptr pointing at %02x %02x %02x %02x", fpga_image_ptr[0], fpga_image_ptr[1], fpga_image_ptr[2], fpga_image_ptr[3]); - Dbprintf("zstream->next_in pointing at %02x %02x %02x %02x", compressed_fpga_stream->next_in[0], compressed_fpga_stream->next_in[1], compressed_fpga_stream->next_in[2], compressed_fpga_stream->next_in[3]); -} - - -bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; uint8_t *fpga_image_start; @@ -239,7 +220,18 @@ bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, return false; } - init_fpga_inflate(compressed_fpga_stream, fpga_image_start, fpga_image_size, output_buffer); + // initialize z_stream structure for inflate: + compressed_fpga_stream->next_in = fpga_image_start; + compressed_fpga_stream->avail_in = fpga_image_size; + compressed_fpga_stream->next_out = output_buffer; + compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; + compressed_fpga_stream->zalloc = &fpga_inflate_malloc; + compressed_fpga_stream->zfree = &fpga_inflate_free; + + // initialize inflate with WindowBits=15 and to automatically detect header: + inflateInit2(compressed_fpga_stream, 15+32); + + fpga_image_ptr = output_buffer; for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { header[i] = get_from_fpga_stream(compressed_fpga_stream, output_buffer); @@ -270,9 +262,9 @@ static void DownloadFPGA_byte(unsigned char w) // Download the fpga image starting at current stream position with length FpgaImageLen bytes static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { - Dbprintf("Would have loaded FPGA"); - return; + Dbprintf("DownloadFPGA(len: %d)", FpgaImageLen); + int i=0; AT91C_BASE_PIOA->PIO_OER = GPIO_FPGA_ON; @@ -324,10 +316,17 @@ static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uin return; } - while(FpgaImageLen-->0) { - DownloadFPGA_byte(get_from_fpga_stream(compressed_fpga_stream, output_buffer)); + for(i = 0; i < FpgaImageLen; i++) { + int b = get_from_fpga_stream(compressed_fpga_stream, output_buffer); + if (b < 0) { + Dbprintf("Error %d during FpgaDownload", b); + break; + } + DownloadFPGA_byte(b); } - + + Dbprintf("%d bytes loaded into FPGA", i); + // continue to clock FPGA until ready signal goes high i=100000; while ( (i--) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_DONE ) ) ) { @@ -350,7 +349,7 @@ static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uin * (big endian), bytes content. Except for section 'e' which has 4 bytes * length. */ -int bitparse_find_section(char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +static int bitparse_find_section(char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { int result = 0; #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section @@ -414,13 +413,15 @@ void FpgaDownloadAndGo(int bitstream_version) if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; } - + unsigned int bitstream_length; if(bitparse_find_section('e', &bitstream_length, &compressed_fpga_stream, output_buffer)) { DownloadFPGA(bitstream_length, &compressed_fpga_stream, output_buffer); downloaded_bitstream = bitstream_version; - return; /* All done */ } + + inflateEnd(&compressed_fpga_stream); + } @@ -432,7 +433,7 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) uint8_t output_buffer[OUTPUT_BUFFER_LEN]; dst[0] = '\0'; - + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; } @@ -480,6 +481,9 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) } strncat(dst, tempstr, len-1); } + + inflateEnd(&compressed_fpga_stream); + } diff --git a/common/Makefile.common b/common/Makefile.common index d7e3457f..a71237ca 100644 --- a/common/Makefile.common +++ b/common/Makefile.common @@ -62,8 +62,8 @@ DETECTED_OS=Windows endif -# Also search prerequisites in the common directory (for usb.c), and the fpga directory (for fpga.bit) -VPATH = . ../common/ ../fpga/ +# Also search prerequisites in the common directory (for usb.c), the fpga directory (for fpga.bit), and the zlib directory +VPATH = . ../common/ ../fpga/ ../zlib/ INCLUDES = ../include/proxmark3.h ../include/at91sam7s512.h ../include/config_gpio.h ../include/usb_cmd.h $(APP_INCLUDES) @@ -72,9 +72,9 @@ LDFLAGS = -nostartfiles -nodefaultlibs -Wl,-gc-sections -n LIBS = -lgcc -THUMBOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(THUMBSRC)) -ARMOBJ = $(ARMSRC:%.c=$(OBJDIR)/%.o) -ASMOBJ = $(patsubst %.s,$(OBJDIR)/%.o,$(ASMSRC)) +THUMBOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(notdir $(THUMBSRC))) +ARMOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(notdir $(ARMSRC))) +ASMOBJ = $(patsubst %.s,$(OBJDIR)/%.o,$(notdir $(ASMSRC))) VERSIONOBJ = $(OBJDIR)/version.o $(THUMBOBJ): $(OBJDIR)/%.o: %.c $(INCLUDES) @@ -110,6 +110,7 @@ DEPENDENCY_FILES = $(patsubst %.c,$(OBJDIR)/%.d,$(notdir $(THUMBSRC))) \ $(patsubst %.s,$(OBJDIR)/%.d,$(notdir $(ASMSRC))) $(DEPENDENCY_FILES): Makefile ../common/Makefile.common + $(patsubst %.o,%.d,$(THUMBOBJ) $(ARMOBJ)): $(OBJDIR)/%.d: %.c @$(CC) -MM -MT "$(@) $(@:.d=.o)" $(CFLAGS) $< > $@ $(patsubst %.o,%.d,$(ASMOBJ)):$(OBJDIR)/%.d: %.s diff --git a/armsrc/adler32.c b/zlib/adler32.c similarity index 100% rename from armsrc/adler32.c rename to zlib/adler32.c diff --git a/armsrc/inffast.c b/zlib/inffast.c similarity index 100% rename from armsrc/inffast.c rename to zlib/inffast.c diff --git a/armsrc/inffast.h b/zlib/inffast.h similarity index 100% rename from armsrc/inffast.h rename to zlib/inffast.h diff --git a/armsrc/inffixed.h b/zlib/inffixed.h similarity index 100% rename from armsrc/inffixed.h rename to zlib/inffixed.h diff --git a/armsrc/inflate.c b/zlib/inflate.c similarity index 100% rename from armsrc/inflate.c rename to zlib/inflate.c diff --git a/armsrc/inflate.h b/zlib/inflate.h similarity index 100% rename from armsrc/inflate.h rename to zlib/inflate.h diff --git a/armsrc/inftrees.c b/zlib/inftrees.c similarity index 100% rename from armsrc/inftrees.c rename to zlib/inftrees.c diff --git a/armsrc/inftrees.h b/zlib/inftrees.h similarity index 100% rename from armsrc/inftrees.h rename to zlib/inftrees.h diff --git a/zlib/z_crc32.c b/zlib/z_crc32.c new file mode 100644 index 00000000..4e7a2f77 --- /dev/null +++ b/zlib/z_crc32.c @@ -0,0 +1,425 @@ +/* crc32.c -- compute the CRC-32 of a data stream + * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + * + * Thanks to Rodney Brown for his contribution of faster + * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing + * tables for updating the shift register in one step with three exclusive-ors + * instead of four steps with four exclusive-ors. This results in about a + * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. + */ + +/* @(#) $Id$ */ + +/* + Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore + protection on the static variables used to control the first-use generation + of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should + first call get_crc_table() to initialize the tables before allowing more than + one thread to use crc32(). + + DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out z_crc32.h. + */ + +#ifdef MAKECRCH +# include +# ifndef DYNAMIC_CRC_TABLE +# define DYNAMIC_CRC_TABLE +# endif /* !DYNAMIC_CRC_TABLE */ +#endif /* MAKECRCH */ + +#include "zutil.h" /* for STDC and FAR definitions */ + +#define local static + +/* Definitions for doing the crc four data bytes at a time. */ +#if !defined(NOBYFOUR) && defined(Z_U4) +# define BYFOUR +#endif +#ifdef BYFOUR + local unsigned long crc32_little OF((unsigned long, + const unsigned char FAR *, unsigned)); + local unsigned long crc32_big OF((unsigned long, + const unsigned char FAR *, unsigned)); +# define TBLS 8 +#else +# define TBLS 1 +#endif /* BYFOUR */ + +/* Local functions for crc concatenation */ +local unsigned long gf2_matrix_times OF((unsigned long *mat, + unsigned long vec)); +local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); +local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); + + +#ifdef DYNAMIC_CRC_TABLE + +local volatile int crc_table_empty = 1; +local z_crc_t FAR crc_table[TBLS][256]; +local void make_crc_table OF((void)); +#ifdef MAKECRCH + local void write_table OF((FILE *, const z_crc_t FAR *)); +#endif /* MAKECRCH */ +/* + Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: + x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. + + Polynomials over GF(2) are represented in binary, one bit per coefficient, + with the lowest powers in the most significant bit. Then adding polynomials + is just exclusive-or, and multiplying a polynomial by x is a right shift by + one. If we call the above polynomial p, and represent a byte as the + polynomial q, also with the lowest power in the most significant bit (so the + byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, + where a mod b means the remainder after dividing a by b. + + This calculation is done using the shift-register method of multiplying and + taking the remainder. The register is initialized to zero, and for each + incoming bit, x^32 is added mod p to the register if the bit is a one (where + x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by + x (which is shifting right by one and adding x^32 mod p if the bit shifted + out is a one). We start with the highest power (least significant bit) of + q and repeat for all eight bits of q. + + The first table is simply the CRC of all possible eight bit values. This is + all the information needed to generate CRCs on data a byte at a time for all + combinations of CRC register values and incoming bytes. The remaining tables + allow for word-at-a-time CRC calculation for both big-endian and little- + endian machines, where a word is four bytes. +*/ +local void make_crc_table() +{ + z_crc_t c; + int n, k; + z_crc_t poly; /* polynomial exclusive-or pattern */ + /* terms of polynomial defining this crc (except x^32): */ + static volatile int first = 1; /* flag to limit concurrent making */ + static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; + + /* See if another task is already doing this (not thread-safe, but better + than nothing -- significantly reduces duration of vulnerability in + case the advice about DYNAMIC_CRC_TABLE is ignored) */ + if (first) { + first = 0; + + /* make exclusive-or pattern from polynomial (0xedb88320UL) */ + poly = 0; + for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) + poly |= (z_crc_t)1 << (31 - p[n]); + + /* generate a crc for every 8-bit value */ + for (n = 0; n < 256; n++) { + c = (z_crc_t)n; + for (k = 0; k < 8; k++) + c = c & 1 ? poly ^ (c >> 1) : c >> 1; + crc_table[0][n] = c; + } + +#ifdef BYFOUR + /* generate crc for each value followed by one, two, and three zeros, + and then the byte reversal of those as well as the first table */ + for (n = 0; n < 256; n++) { + c = crc_table[0][n]; + crc_table[4][n] = ZSWAP32(c); + for (k = 1; k < 4; k++) { + c = crc_table[0][c & 0xff] ^ (c >> 8); + crc_table[k][n] = c; + crc_table[k + 4][n] = ZSWAP32(c); + } + } +#endif /* BYFOUR */ + + crc_table_empty = 0; + } + else { /* not first */ + /* wait for the other guy to finish (not efficient, but rare) */ + while (crc_table_empty) + ; + } + +#ifdef MAKECRCH + /* write out CRC tables to z_crc32.h */ + { + FILE *out; + + out = fopen("z_crc32.h", "w"); + if (out == NULL) return; + fprintf(out, "/* z_crc32.h -- tables for rapid CRC calculation\n"); + fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); + fprintf(out, "local const z_crc_t FAR "); + fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); + write_table(out, crc_table[0]); +# ifdef BYFOUR + fprintf(out, "#ifdef BYFOUR\n"); + for (k = 1; k < 8; k++) { + fprintf(out, " },\n {\n"); + write_table(out, crc_table[k]); + } + fprintf(out, "#endif\n"); +# endif /* BYFOUR */ + fprintf(out, " }\n};\n"); + fclose(out); + } +#endif /* MAKECRCH */ +} + +#ifdef MAKECRCH +local void write_table(out, table) + FILE *out; + const z_crc_t FAR *table; +{ + int n; + + for (n = 0; n < 256; n++) + fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", + (unsigned long)(table[n]), + n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); +} +#endif /* MAKECRCH */ + +#else /* !DYNAMIC_CRC_TABLE */ +/* ======================================================================== + * Tables of CRC-32s of all single-byte values, made by make_crc_table(). + */ +#include "z_crc32.h" +#endif /* DYNAMIC_CRC_TABLE */ + +/* ========================================================================= + * This function can be used by asm versions of crc32() + */ +const z_crc_t FAR * ZEXPORT get_crc_table() +{ +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + return (const z_crc_t FAR *)crc_table; +} + +/* ========================================================================= */ +#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) +#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 + +/* ========================================================================= */ +unsigned long ZEXPORT crc32(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + uInt len; +{ + if (buf == Z_NULL) return 0UL; + +#ifdef DYNAMIC_CRC_TABLE + if (crc_table_empty) + make_crc_table(); +#endif /* DYNAMIC_CRC_TABLE */ + +#ifdef BYFOUR + if (sizeof(void *) == sizeof(ptrdiff_t)) { + z_crc_t endian; + + endian = 1; + if (*((unsigned char *)(&endian))) + return crc32_little(crc, buf, len); + else + return crc32_big(crc, buf, len); + } +#endif /* BYFOUR */ + crc = crc ^ 0xffffffffUL; + while (len >= 8) { + DO8; + len -= 8; + } + if (len) do { + DO1; + } while (--len); + return crc ^ 0xffffffffUL; +} + +#ifdef BYFOUR + +/* ========================================================================= */ +#define DOLIT4 c ^= *buf4++; \ + c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ + crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] +#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 + +/* ========================================================================= */ +local unsigned long crc32_little(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = (z_crc_t)crc; + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + while (len >= 32) { + DOLIT32; + len -= 32; + } + while (len >= 4) { + DOLIT4; + len -= 4; + } + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); + } while (--len); + c = ~c; + return (unsigned long)c; +} + +/* ========================================================================= */ +#define DOBIG4 c ^= *++buf4; \ + c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ + crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] +#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 + +/* ========================================================================= */ +local unsigned long crc32_big(crc, buf, len) + unsigned long crc; + const unsigned char FAR *buf; + unsigned len; +{ + register z_crc_t c; + register const z_crc_t FAR *buf4; + + c = ZSWAP32((z_crc_t)crc); + c = ~c; + while (len && ((ptrdiff_t)buf & 3)) { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + len--; + } + + buf4 = (const z_crc_t FAR *)(const void FAR *)buf; + buf4--; + while (len >= 32) { + DOBIG32; + len -= 32; + } + while (len >= 4) { + DOBIG4; + len -= 4; + } + buf4++; + buf = (const unsigned char FAR *)buf4; + + if (len) do { + c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); + } while (--len); + c = ~c; + return (unsigned long)(ZSWAP32(c)); +} + +#endif /* BYFOUR */ + +#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ + +/* ========================================================================= */ +local unsigned long gf2_matrix_times(mat, vec) + unsigned long *mat; + unsigned long vec; +{ + unsigned long sum; + + sum = 0; + while (vec) { + if (vec & 1) + sum ^= *mat; + vec >>= 1; + mat++; + } + return sum; +} + +/* ========================================================================= */ +local void gf2_matrix_square(square, mat) + unsigned long *square; + unsigned long *mat; +{ + int n; + + for (n = 0; n < GF2_DIM; n++) + square[n] = gf2_matrix_times(mat, mat[n]); +} + +/* ========================================================================= */ +local uLong crc32_combine_(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + int n; + unsigned long row; + unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ + unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ + + /* degenerate case (also disallow negative lengths) */ + if (len2 <= 0) + return crc1; + + /* put operator for one zero bit in odd */ + odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ + row = 1; + for (n = 1; n < GF2_DIM; n++) { + odd[n] = row; + row <<= 1; + } + + /* put operator for two zero bits in even */ + gf2_matrix_square(even, odd); + + /* put operator for four zero bits in odd */ + gf2_matrix_square(odd, even); + + /* apply len2 zeros to crc1 (first square will put the operator for one + zero byte, eight zero bits, in even) */ + do { + /* apply zeros operator for this bit of len2 */ + gf2_matrix_square(even, odd); + if (len2 & 1) + crc1 = gf2_matrix_times(even, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + if (len2 == 0) + break; + + /* another iteration of the loop with odd and even swapped */ + gf2_matrix_square(odd, even); + if (len2 & 1) + crc1 = gf2_matrix_times(odd, crc1); + len2 >>= 1; + + /* if no more bits set, then done */ + } while (len2 != 0); + + /* return combined crc */ + crc1 ^= crc2; + return crc1; +} + +/* ========================================================================= */ +uLong ZEXPORT crc32_combine(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} + +uLong ZEXPORT crc32_combine64(crc1, crc2, len2) + uLong crc1; + uLong crc2; + z_off64_t len2; +{ + return crc32_combine_(crc1, crc2, len2); +} diff --git a/zlib/z_crc32.h b/zlib/z_crc32.h new file mode 100644 index 00000000..9e0c7781 --- /dev/null +++ b/zlib/z_crc32.h @@ -0,0 +1,441 @@ +/* crc32.h -- tables for rapid CRC calculation + * Generated automatically by crc32.c + */ + +local const z_crc_t FAR crc_table[TBLS][256] = +{ + { + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +#ifdef BYFOUR + }, + { + 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, + 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, + 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, + 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, + 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, + 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, + 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, + 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, + 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, + 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, + 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, + 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, + 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, + 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, + 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, + 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, + 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, + 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, + 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, + 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, + 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, + 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, + 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, + 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, + 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, + 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, + 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, + 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, + 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, + 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, + 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, + 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, + 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, + 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, + 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, + 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, + 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, + 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, + 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, + 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, + 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, + 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, + 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, + 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, + 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, + 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, + 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, + 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, + 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, + 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, + 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, + 0x9324fd72UL + }, + { + 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, + 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, + 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, + 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, + 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, + 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, + 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, + 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, + 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, + 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, + 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, + 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, + 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, + 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, + 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, + 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, + 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, + 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, + 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, + 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, + 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, + 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, + 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, + 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, + 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, + 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, + 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, + 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, + 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, + 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, + 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, + 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, + 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, + 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, + 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, + 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, + 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, + 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, + 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, + 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, + 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, + 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, + 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, + 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, + 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, + 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, + 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, + 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, + 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, + 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, + 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, + 0xbe9834edUL + }, + { + 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, + 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, + 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, + 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, + 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, + 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, + 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, + 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, + 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, + 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, + 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, + 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, + 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, + 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, + 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, + 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, + 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, + 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, + 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, + 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, + 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, + 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, + 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, + 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, + 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, + 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, + 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, + 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, + 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, + 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, + 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, + 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, + 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, + 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, + 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, + 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, + 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, + 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, + 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, + 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, + 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, + 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, + 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, + 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, + 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, + 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, + 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, + 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, + 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, + 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, + 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, + 0xde0506f1UL + }, + { + 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, + 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, + 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, + 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, + 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, + 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, + 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, + 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, + 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, + 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, + 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, + 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, + 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, + 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, + 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, + 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, + 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, + 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, + 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, + 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, + 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, + 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, + 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, + 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, + 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, + 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, + 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, + 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, + 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, + 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, + 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, + 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, + 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, + 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, + 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, + 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, + 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, + 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, + 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, + 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, + 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, + 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, + 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, + 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, + 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, + 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, + 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, + 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, + 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, + 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, + 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, + 0x8def022dUL + }, + { + 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, + 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, + 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, + 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, + 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, + 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, + 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, + 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, + 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, + 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, + 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, + 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, + 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, + 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, + 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, + 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, + 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, + 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, + 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, + 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, + 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, + 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, + 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, + 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, + 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, + 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, + 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, + 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, + 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, + 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, + 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, + 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, + 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, + 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, + 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, + 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, + 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, + 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, + 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, + 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, + 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, + 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, + 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, + 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, + 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, + 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, + 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, + 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, + 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, + 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, + 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, + 0x72fd2493UL + }, + { + 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, + 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, + 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, + 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, + 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, + 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, + 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, + 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, + 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, + 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, + 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, + 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, + 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, + 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, + 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, + 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, + 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, + 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, + 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, + 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, + 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, + 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, + 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, + 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, + 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, + 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, + 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, + 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, + 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, + 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, + 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, + 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, + 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, + 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, + 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, + 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, + 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, + 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, + 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, + 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, + 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, + 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, + 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, + 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, + 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, + 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, + 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, + 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, + 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, + 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, + 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, + 0xed3498beUL + }, + { + 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, + 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, + 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, + 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, + 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, + 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, + 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, + 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, + 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, + 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, + 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, + 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, + 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, + 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, + 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, + 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, + 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, + 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, + 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, + 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, + 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, + 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, + 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, + 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, + 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, + 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, + 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, + 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, + 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, + 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, + 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, + 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, + 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, + 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, + 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, + 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, + 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, + 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, + 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, + 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, + 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, + 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, + 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, + 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, + 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, + 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, + 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, + 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, + 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, + 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, + 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, + 0xf10605deUL +#endif + } +}; diff --git a/armsrc/zconf.h b/zlib/zconf.h similarity index 100% rename from armsrc/zconf.h rename to zlib/zconf.h diff --git a/armsrc/zlib.h b/zlib/zlib.h similarity index 100% rename from armsrc/zlib.h rename to zlib/zlib.h diff --git a/armsrc/zutil.c b/zlib/zutil.c similarity index 100% rename from armsrc/zutil.c rename to zlib/zutil.c diff --git a/armsrc/zutil.h b/zlib/zutil.h similarity index 100% rename from armsrc/zutil.h rename to zlib/zutil.h From f39198789b82c1dd545743778f9d2633a2af8bd8 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Sun, 26 Apr 2015 10:49:03 +0200 Subject: [PATCH 075/132] replaced gzip with an own compressor tool (fpga_compress.c, based on zlib) This allows to remove the gzip header support and the z_crc32.[ch] files (which saves more than 2KBytes of the ARM's flash memory) --- .gitignore | 2 +- Makefile | 14 +- armsrc/Makefile | 51 +- armsrc/fpgaloader.c | 3 +- client/Makefile | 10 +- client/fpga_compress.c | 193 ++-- common/Makefile.common | 2 +- recovery/Makefile | 8 +- zlib/deflate.c | 1967 ++++++++++++++++++++++++++++++++++++++++ zlib/deflate.h | 346 +++++++ zlib/trees.c | 1226 +++++++++++++++++++++++++ zlib/trees.h | 128 +++ zlib/z_crc32.c | 425 --------- zlib/z_crc32.h | 441 --------- 14 files changed, 3759 insertions(+), 1057 deletions(-) create mode 100644 zlib/deflate.c create mode 100644 zlib/deflate.h create mode 100644 zlib/trees.c create mode 100644 zlib/trees.h delete mode 100644 zlib/z_crc32.c delete mode 100644 zlib/z_crc32.h diff --git a/.gitignore b/.gitignore index 51dcefc5..880c092f 100644 --- a/.gitignore +++ b/.gitignore @@ -12,7 +12,7 @@ *.bin *.dll *.moc.cpp -*.gz +*.z *.exe proxmark proxmark3 diff --git a/Makefile b/Makefile index dfcbaecf..afbaad9e 100644 --- a/Makefile +++ b/Makefile @@ -2,7 +2,7 @@ include common/Makefile.common FLASH_PORT=/dev/ttyACM0 -all clean: %: bootrom/% armsrc/% client/% recovery/% +all clean: %: client/% bootrom/% armsrc/% recovery/% bootrom/%: FORCE $(MAKE) -C bootrom $(patsubst bootrom/%,%,$@) @@ -14,8 +14,8 @@ recovery/%: FORCE $(MAKE) -C recovery $(patsubst recovery/%,%,$@) FORCE: # Dummy target to force remake in the subdirectories, even if files exist (this Makefile doesn't know about the prerequisites) +.PHONY: all clean help _test flash-bootrom flash-os flash-all FORCE -.PHONY: all clean help _test flash-bootrom flash-os flash-fpga flash-both flash-all FORCE help: @echo Multi-OS Makefile, you are running on $(DETECTED_OS) @echo Possible targets: @@ -23,9 +23,7 @@ help: @echo + client - Make only the OS-specific host directory @echo + flash-bootrom - Make bootrom and flash it @echo + flash-os - Make armsrc and flash os (includes fpga) - @echo + flash-fpga - (Deprecated:) Make armsrc and flash fpga - @echo + flash-both - Make armsrc and flash os and fpga image - @echo + flash-all - Make bootrom and armsrc and flash bootrom, os and fpga image + @echo + flash-all - Make bootrom and armsrc and flash bootrom and os image @echo + clean - Clean in bootrom, armsrc and the OS-specific host directory client: client/all @@ -36,12 +34,6 @@ flash-bootrom: bootrom/obj/bootrom.elf $(FLASH_TOOL) flash-os: armsrc/obj/osimage.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$<) -#flash-fpga: armsrc/obj/fpgaimage.elf $(FLASH_TOOL) -# $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$<) - -flash-both: armsrc/obj/osimage.elf $(FLASH_TOOL) - $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$(filter-out $(FLASH_TOOL),$^)) - flash-all: bootrom/obj/bootrom.elf armsrc/obj/osimage.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) -b $(subst /,$(PATHSEP),$(filter-out $(FLASH_TOOL),$^)) diff --git a/armsrc/Makefile b/armsrc/Makefile index 51da9dab..9efbb1ad 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -10,7 +10,7 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line #in the next section to remove that particular feature from compilation -APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -DZ_SOLO -DZ_PREFIX \ +APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE \ -fno-strict-aliasing -ffunction-sections -fdata-sections #-DWITH_LCD @@ -21,7 +21,17 @@ SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c SRC_ISO14443b = iso14443.c SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c -SRC_ZLIB = inflate.c inffast.c inftrees.c z_crc32.c adler32.c zutil.c + +#the zlib source files required for decompressing the fpga config at run time +SRC_ZLIB = inflate.c inffast.c inftrees.c adler32.c zutil.c +#additional defines required to compile zlib +ZLIB_CFLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP +APP_CFLAGS += $(ZLIB_CFLAGS) +# zlib includes: +APP_CFLAGS += -I../zlib + +# stdint.h provided locally until GCC 4.5 becomes C99 compliant +APP_CFLAGS += -I. # Compile these in thumb mode (small size) THUMBSRC = start.c \ @@ -49,57 +59,42 @@ ARMSRC = fpgaloader.c \ BigBuf.c \ optimized_cipher.c -# stdint.h provided locally until GCC 4.5 becomes C99 compliant -APP_CFLAGS += -I. - -# zlib includes: -APP_CFLAGS += -I../zlib - # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common/Makefile.common OBJS = $(OBJDIR)/osimage.s19 -#$(OBJDIR)/fpgaimage.s19 +FPGA_COMPRESSOR = ../client/fpga_compress all: $(OBJS) -$(OBJDIR)/fpga_lf.o: $(OBJDIR)/fpga_lf.bit.gz - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_lf_bit_gz_start=_binary_fpga_lf_bit_start --redefine-sym _binary_obj_fpga_lf_bit_gz_end=_binary_fpga_lf_bit_end --prefix-sections=fpga_lf_bit $^ $@ +$(OBJDIR)/fpga_lf.o: $(OBJDIR)/fpga_lf.bit.z + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_lf_bit_z_start=_binary_fpga_lf_bit_start --redefine-sym _binary_obj_fpga_lf_bit_z_end=_binary_fpga_lf_bit_end --prefix-sections=fpga_lf_bit $^ $@ -$(OBJDIR)/fpga_hf.o: $(OBJDIR)/fpga_hf.bit.gz - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_hf_bit_gz_start=_binary_fpga_hf_bit_start --redefine-sym _binary_obj_fpga_hf_bit_gz_end=_binary_fpga_hf_bit_end --prefix-sections=fpga_hf_bit $^ $@ +$(OBJDIR)/fpga_hf.o: $(OBJDIR)/fpga_hf.bit.z + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_hf_bit_z_start=_binary_fpga_hf_bit_start --redefine-sym _binary_obj_fpga_hf_bit_z_end=_binary_fpga_hf_bit_end --prefix-sections=fpga_hf_bit $^ $@ -$(OBJDIR)/%.bit.gz: %.bit - $(GZIP) --best -c $^ >$@ +$(OBJDIR)/%.bit.z: %.bit $(FPGA_COMPRESSOR) + $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ -$(OBJDIR)/fullimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_lf.o $(OBJDIR)/fpga_hf.o $(THUMBOBJ) $(ARMOBJ) +$(OBJDIR)/osimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_lf.o $(OBJDIR)/fpga_hf.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) -#$(OBJDIR)/fpgaimage.elf: $(OBJDIR)/fullimage.elf -# $(OBJCOPY) -F elf32-littlearm --only-section .fpgaimage $^ $@ - -$(OBJDIR)/osimage.elf: $(OBJDIR)/fullimage.elf - $(OBJCOPY) -F elf32-littlearm $^ $@ - tarbin: $(OBJS) $(TAR) $(TARFLAGS) ../proxmark3-$(platform)-bin.tar $(OBJS:%=armsrc/%) $(OBJS:%.s19=armsrc/%.elf) - clean: $(DELETE) $(OBJDIR)$(PATHSEP)*.o $(DELETE) $(OBJDIR)$(PATHSEP)*.elf $(DELETE) $(OBJDIR)$(PATHSEP)*.s19 $(DELETE) $(OBJDIR)$(PATHSEP)*.map $(DELETE) $(OBJDIR)$(PATHSEP)*.d - $(DELETE) $(OBJDIR)$(PATHSEP)*.gz + $(DELETE) $(OBJDIR)$(PATHSEP)*.z $(DELETE) version.c .PHONY: all clean help help: @echo Multi-OS Makefile, you are running on $(DETECTED_OS) @echo Possible targets: - @echo + all - Make both: - @echo + $(OBJDIR)/osimage.s19 - The OS image - @echo + $(OBJDIR)/fpgaimage.s19 - The FPGA image - @echo + clean - Clean $(OBJDIR) + @echo + all - Build the OS image $(OBJDIR)/osimage.s19 + @echo + clean - Clean $(OBJDIR) diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c index be0d87d6..573aac3a 100644 --- a/armsrc/fpgaloader.c +++ b/armsrc/fpgaloader.c @@ -228,8 +228,7 @@ static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_s compressed_fpga_stream->zalloc = &fpga_inflate_malloc; compressed_fpga_stream->zfree = &fpga_inflate_free; - // initialize inflate with WindowBits=15 and to automatically detect header: - inflateInit2(compressed_fpga_stream, 15+32); + inflateInit2(compressed_fpga_stream, 15); fpga_image_ptr = output_buffer; diff --git a/client/Makefile b/client/Makefile index 44ca8a96..da0c2728 100644 --- a/client/Makefile +++ b/client/Makefile @@ -9,13 +9,13 @@ include ../common/Makefile.common CC=gcc CXX=g++ #COMMON_FLAGS = -m32 -VPATH = ../common +VPATH = ../common ../zlib OBJDIR = obj LDLIBS = -L/opt/local/lib -L/usr/local/lib -lreadline -lpthread -lm LUALIB = ../liblua/liblua.a LDFLAGS = $(COMMON_FLAGS) -CFLAGS = -std=c99 -I. -I../include -I../common -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -g -O4 +CFLAGS = -std=c99 -I. -I../include -I../common -I../zlib -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -DZ_SOLO -DZ_PREFIX -DNO_GZIP -g -O4 LUAPLATFORM = generic ifneq (,$(findstring MINGW,$(platform))) @@ -104,9 +104,11 @@ CMDSRCS = nonce2key/crapto1.c\ aes.c\ protocols.c\ +ZLIBSRCS = deflate.c adler32.c trees.c zutil.c COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) CMDOBJS = $(CMDSRCS:%.c=$(OBJDIR)/%.o) +ZLIBOBJS = $(ZLIBSRCS:%.c=$(OBJDIR)/%.o) RM = rm -f BINS = proxmark3 flasher fpga_compress #snooper cli @@ -116,7 +118,7 @@ all: lua_build $(BINS) all-static: LDLIBS:=-static $(LDLIBS) all-static: snooper cli flasher fpga_compress - + proxmark3: LDLIBS+=$(QTLDLIBS) $(LUALIB) proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(QTGUI) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ @@ -130,7 +132,7 @@ cli: $(OBJDIR)/cli.o $(COREOBJS) $(CMDOBJS) $(OBJDIR)/guidummy.o flasher: $(OBJDIR)/flash.o $(OBJDIR)/flasher.o $(COREOBJS) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ -fpga_compress: $(OBJDIR)/fpga_compress.o +fpga_compress: $(OBJDIR)/fpga_compress.o $(ZLIBOBJS) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ $(OBJDIR)/%.o: %.c diff --git a/client/fpga_compress.c b/client/fpga_compress.c index 9e0946b2..db1ef81b 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -9,85 +9,41 @@ #include #include #include -#include "sleep.h" -#include "proxmark3.h" -#include "flash.h" -#include "uart.h" -#include "usb_cmd.h" +#include +#include "zlib.h" #define MAX(a,b) ((a)>(b)?(a):(b)) -struct huffman_record { - int16_t symbol; - uint16_t count; - uint8_t code_size; - uint8_t code; - struct huffman_record *left; - struct huffman_record *right; - struct huffman_record *next; - }; - -typedef struct huffman_record huffman_record_t; +// zlib configuration +#define COMPRESS_LEVEL 9 // use best possible compression #define FPGA_CONFIG_SIZE 42175 static uint8_t fpga_config[FPGA_CONFIG_SIZE]; -static huffman_record_t leaf_nodes[256]; -static uint8_t start_code[256]; static void usage(char *argv0) { - fprintf(stderr, "Usage: %s [-d] \n\n", argv0); - fprintf(stderr, "\t-d\tdecompress\n\n"); + fprintf(stderr, "Usage: %s \n\n", argv0); } -void add_to_heap(huffman_record_t **heap, huffman_record_t *new_record) +static voidpf fpga_deflate_malloc(voidpf opaque, uInt items, uInt size) { - huffman_record_t *succ = *heap; - huffman_record_t *pred = NULL; - -// fprintf(stderr, "Adding symbol %d, count %d\n", new_record->symbol, new_record->count); - - while (succ != NULL && new_record->count > succ->count) { - pred = succ; - succ = succ->next; - } - - // insert new record - new_record->next = succ; - if (pred == NULL) { // first record in heap - *heap = new_record; - } else { - pred->next = new_record; - } + fprintf(stderr, "zlib requested %d bytes\n", items*size); + return malloc(items*size); } - -uint16_t set_codesize(huffman_record_t *tree_ptr, uint8_t depth) -{ - uint16_t max_size = depth; - tree_ptr->code_size = depth; - if (tree_ptr->left != NULL) { - max_size = MAX(set_codesize(tree_ptr->left, depth+1), max_size); - } - if (tree_ptr->right != NULL) { - max_size = MAX(set_codesize(tree_ptr->right, depth+1), max_size); - } - return max_size; -} -int huffman_encode(FILE *infile, FILE *outfile) +static void fpga_deflate_free(voidpf opaque, voidpf address) { - int i; - - // init leaf_nodes: - for (i = 0; i < 256; i++) { - leaf_nodes[i].count = 0; - leaf_nodes[i].symbol = i; - leaf_nodes[i].left = NULL; - leaf_nodes[i].right = NULL; - leaf_nodes[i].next = NULL; - } + fprintf(stderr, "zlib frees memory\n"); + return free(address); +} + + +int zlib_compress(FILE *infile, FILE *outfile) +{ + int i, ret; + z_stream compressed_fpga_stream; // read the input file into fpga_config[] and count occurrences of each symbol: i = 0; @@ -95,7 +51,6 @@ int huffman_encode(FILE *infile, FILE *outfile) uint8_t c; c = fgetc(infile); fpga_config[i++] = c; - leaf_nodes[c].count++; if (i > FPGA_CONFIG_SIZE+1) { fprintf(stderr, "Input file too big (> %d bytes). This is probably not a PM3 FPGA config file.", FPGA_CONFIG_SIZE); fclose(infile); @@ -103,98 +58,60 @@ int huffman_encode(FILE *infile, FILE *outfile) return -1; } } + + // initialize zlib structures + compressed_fpga_stream.next_in = fpga_config; + compressed_fpga_stream.avail_in = i; + compressed_fpga_stream.zalloc = fpga_deflate_malloc; + compressed_fpga_stream.zfree = fpga_deflate_free; - fprintf(stderr, "\nStatistics: (symbol: count)\n"); - for (i = 0; i < 256; i++) { - fprintf(stderr, "%3d: %5d\n", i, leaf_nodes[i].count); - } - - // build the Huffman tree: - huffman_record_t *heap_ptr = NULL; - - for (i = 0; i < 256; i++) { - add_to_heap(&heap_ptr, &leaf_nodes[i]); - } - - fprintf(stderr, "\nSorted statistics: (symbol: count)\n"); - for (huffman_record_t *p = heap_ptr; p != NULL; p = p->next) { - fprintf(stderr, "%3d: %5d\n", p->symbol, p->count); - } - - for (i = 0; i < 255; i++) { - // remove and combine the first two nodes - huffman_record_t *p1, *p2; - p1 = heap_ptr; - p2 = heap_ptr->next; - heap_ptr = p2->next; - huffman_record_t *new_node = malloc(sizeof(huffman_record_t)); - new_node->left = p1; - new_node->right = p2; - new_node->count = p1->count + p2->count; - add_to_heap(&heap_ptr, new_node); + // estimate the size of the compressed output + unsigned int outsize_max = deflateBound(&compressed_fpga_stream, compressed_fpga_stream.avail_in); + uint8_t *outbuf = malloc(outsize_max); + compressed_fpga_stream.next_out = outbuf; + compressed_fpga_stream.avail_out = outsize_max; + fprintf(stderr, "Allocated %d bytes for output file (estimated upper bound)\n", outsize_max); + + ret = deflateInit(&compressed_fpga_stream, COMPRESS_LEVEL); + + if (ret == Z_OK) { + ret = deflate(&compressed_fpga_stream, Z_FINISH); } - uint16_t max_codesize = set_codesize(heap_ptr, 0); + fprintf(stderr, "produced %d bytes of output\n", compressed_fpga_stream.total_out); - fprintf(stderr, "\nStatistics: (symbol: count, codesize)\n"); - uint32_t compressed_size = 0; - for (i = 0; i < 256; i++) { - fprintf(stderr, "%3d: %5d, %d\n", leaf_nodes[i].symbol, leaf_nodes[i].count, leaf_nodes[i].code_size); - compressed_size += leaf_nodes[i].count * leaf_nodes[i].code_size; - } - fprintf(stderr, "Compressed size = %ld (%f% of original size)", (compressed_size+7)/8, (float)(compressed_size)/(FPGA_CONFIG_SIZE * 8) * 100); - fprintf(stderr, "Max Codesize = %d bits", max_codesize); - - uint8_t code = 0; - for (i = max_codesize; i > 0; i--) { - code = (code + 1) >> 1; - start_code[i] = code; - for (uint16_t j = 0; j < 256; j++) { - if (leaf_nodes[j].code_size == i) { - leaf_nodes[j].code = code; - code++; - } + if (ret != Z_STREAM_END) { + fprintf(stderr, "Error in deflate(): %d %s\n", ret, compressed_fpga_stream.msg); + free(outbuf); + deflateEnd(&compressed_fpga_stream); + fclose(infile); + fclose(outfile); + return -1; } - } - - - fprintf(stderr, "\nStatistics: (symbol: count, codesize, code)\n"); - for (i = 0; i < 256; i++) { - fprintf(stderr, "%3d: %5d, %d, %02x\n", leaf_nodes[i].symbol, leaf_nodes[i].count, leaf_nodes[i].code_size, leaf_nodes[i].code); - } + for (i = 0; i < compressed_fpga_stream.total_out; i++) { + fputc(outbuf[i], outfile); + } + + free(outbuf); + deflateEnd(&compressed_fpga_stream); fclose(infile); fclose(outfile); - + return 0; + } -int huffman_decode(FILE *infile, FILE *outfile) -{ - return 0; -} int main(int argc, char **argv) { - bool decode = false; char *infilename; char *outfilename; - if (argc < 3) { + if (argc != 3) { usage(argv[0]); return -1; - } - - if (argc > 3) { - if (!strcmp(argv[1], "-d")) { - decode = true; - infilename = argv[2]; - outfilename = argv[3]; - } else { - usage(argv[0]); - return -1; - } } else { infilename = argv[1]; outfilename = argv[2]; @@ -213,9 +130,5 @@ int main(int argc, char **argv) return -1; } - if (decode) { - return huffman_decode(infile, outfile); - } else { - return huffman_encode(infile, outfile); - } + return zlib_compress(infile, outfile); } diff --git a/common/Makefile.common b/common/Makefile.common index a71237ca..98ff4d0d 100644 --- a/common/Makefile.common +++ b/common/Makefile.common @@ -63,7 +63,7 @@ endif # Also search prerequisites in the common directory (for usb.c), the fpga directory (for fpga.bit), and the zlib directory -VPATH = . ../common/ ../fpga/ ../zlib/ +VPATH = . ../common ../fpga ../zlib INCLUDES = ../include/proxmark3.h ../include/at91sam7s512.h ../include/config_gpio.h ../include/usb_cmd.h $(APP_INCLUDES) diff --git a/recovery/Makefile b/recovery/Makefile index bb8e3a76..4cf3f3a9 100644 --- a/recovery/Makefile +++ b/recovery/Makefile @@ -1,17 +1,17 @@ include ../common/Makefile.common -BINS = bootrom.bin fullimage.bin proxmark3_recovery.bin +BINS = bootrom.bin osimage.bin proxmark3_recovery.bin all: $(BINS) bootrom.bin: ../bootrom/obj/bootrom.elf $(OBJCOPY) --gap-fill=0xff --pad-to 0x00102000 -O binary $^ $@ -fullimage.bin: ../armsrc/obj/fullimage.elf +osimage.bin: ../armsrc/obj/osimage.elf $(OBJCOPY) --gap-fill=0xff -O binary $^ $@ -proxmark3_recovery.bin: bootrom.bin fullimage.bin - cat bootrom.bin fullimage.bin > $@ +proxmark3_recovery.bin: bootrom.bin osimage.bin + cat bootrom.bin osimage.bin > $@ clean: rm -f $(BINS) diff --git a/zlib/deflate.c b/zlib/deflate.c new file mode 100644 index 00000000..69695770 --- /dev/null +++ b/zlib/deflate.c @@ -0,0 +1,1967 @@ +/* deflate.c -- compress data using the deflation algorithm + * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process depends on being able to identify portions + * of the input text which are identical to earlier input (within a + * sliding window trailing behind the input currently being processed). + * + * The most straightforward technique turns out to be the fastest for + * most input files: try all possible matches and select the longest. + * The key feature of this algorithm is that insertions into the string + * dictionary are very simple and thus fast, and deletions are avoided + * completely. Insertions are performed at each input character, whereas + * string matches are performed only when the previous match ends. So it + * is preferable to spend more time in matches to allow very fast string + * insertions and avoid deletions. The matching algorithm for small + * strings is inspired from that of Rabin & Karp. A brute force approach + * is used to find longer strings when a small match has been found. + * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze + * (by Leonid Broukhis). + * A previous version of this file used a more sophisticated algorithm + * (by Fiala and Greene) which is guaranteed to run in linear amortized + * time, but has a larger average cost, uses more memory and is patented. + * However the F&G algorithm may be faster for some highly redundant + * files if the parameter max_chain_length (described below) is too large. + * + * ACKNOWLEDGEMENTS + * + * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and + * I found it in 'freeze' written by Leonid Broukhis. + * Thanks to many people for bug reports and testing. + * + * REFERENCES + * + * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification". + * Available in http://tools.ietf.org/html/rfc1951 + * + * A description of the Rabin and Karp algorithm is given in the book + * "Algorithms" by R. Sedgewick, Addison-Wesley, p252. + * + * Fiala,E.R., and Greene,D.H. + * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595 + * + */ + +/* @(#) $Id$ */ + +#include "deflate.h" + +const char deflate_copyright[] = + " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler "; +/* + If you use the zlib library in a product, an acknowledgment is welcome + in the documentation of your product. If for some reason you cannot + include such an acknowledgment, I would appreciate that you keep this + copyright string in the executable of your product. + */ + +/* =========================================================================== + * Function prototypes. + */ +typedef enum { + need_more, /* block not completed, need more input or more output */ + block_done, /* block flush performed */ + finish_started, /* finish started, need only more output at next deflate */ + finish_done /* finish done, accept no more input or output */ +} block_state; + +typedef block_state (*compress_func) OF((deflate_state *s, int flush)); +/* Compression function. Returns the block state after the call. */ + +local void fill_window OF((deflate_state *s)); +local block_state deflate_stored OF((deflate_state *s, int flush)); +local block_state deflate_fast OF((deflate_state *s, int flush)); +#ifndef FASTEST +local block_state deflate_slow OF((deflate_state *s, int flush)); +#endif +local block_state deflate_rle OF((deflate_state *s, int flush)); +local block_state deflate_huff OF((deflate_state *s, int flush)); +local void lm_init OF((deflate_state *s)); +local void putShortMSB OF((deflate_state *s, uInt b)); +local void flush_pending OF((z_streamp strm)); +local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size)); +#ifdef ASMV + void match_init OF((void)); /* asm code initialization */ + uInt longest_match OF((deflate_state *s, IPos cur_match)); +#else +local uInt longest_match OF((deflate_state *s, IPos cur_match)); +#endif + +#ifdef DEBUG +local void check_match OF((deflate_state *s, IPos start, IPos match, + int length)); +#endif + +/* =========================================================================== + * Local data + */ + +#define NIL 0 +/* Tail of hash chains */ + +#ifndef TOO_FAR +# define TOO_FAR 4096 +#endif +/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */ + +/* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ +typedef struct config_s { + ush good_length; /* reduce lazy search above this match length */ + ush max_lazy; /* do not perform lazy search above this match length */ + ush nice_length; /* quit search above this match length */ + ush max_chain; + compress_func func; +} config; + +#ifdef FASTEST +local const config configuration_table[2] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */ +#else +local const config configuration_table[10] = { +/* good lazy nice chain */ +/* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */ +/* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */ +/* 2 */ {4, 5, 16, 8, deflate_fast}, +/* 3 */ {4, 6, 32, 32, deflate_fast}, + +/* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */ +/* 5 */ {8, 16, 32, 32, deflate_slow}, +/* 6 */ {8, 16, 128, 128, deflate_slow}, +/* 7 */ {8, 32, 128, 256, deflate_slow}, +/* 8 */ {32, 128, 258, 1024, deflate_slow}, +/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */ +#endif + +/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4 + * For deflate_fast() (levels <= 3) good is ignored and lazy has a different + * meaning. + */ + +#define EQUAL 0 +/* result of memcmp for equal strings */ + +#ifndef NO_DUMMY_DECL +struct static_tree_desc_s {int dummy;}; /* for buggy compilers */ +#endif + +/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */ +#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0)) + +/* =========================================================================== + * Update a hash value with the given input byte + * IN assertion: all calls to to UPDATE_HASH are made with consecutive + * input characters, so that a running hash key can be computed from the + * previous key instead of complete recalculation each time. + */ +#define UPDATE_HASH(s,h,c) (h = (((h)<hash_shift) ^ (c)) & s->hash_mask) + + +/* =========================================================================== + * Insert string str in the dictionary and set match_head to the previous head + * of the hash chain (the most recent string with same hash key). Return + * the previous length of the hash chain. + * If this file is compiled with -DFASTEST, the compression level is forced + * to 1, and no hash chains are maintained. + * IN assertion: all calls to to INSERT_STRING are made with consecutive + * input characters and the first MIN_MATCH bytes of str are valid + * (except for the last MIN_MATCH-1 bytes of the input file). + */ +#ifdef FASTEST +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#else +#define INSERT_STRING(s, str, match_head) \ + (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \ + match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \ + s->head[s->ins_h] = (Pos)(str)) +#endif + +/* =========================================================================== + * Initialize the hash table (avoiding 64K overflow for 16 bit systems). + * prev[] will be initialized on the fly. + */ +#define CLEAR_HASH(s) \ + s->head[s->hash_size-1] = NIL; \ + zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head)); + +/* ========================================================================= */ +int ZEXPORT deflateInit_(strm, level, version, stream_size) + z_streamp strm; + int level; + const char *version; + int stream_size; +{ + return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, + Z_DEFAULT_STRATEGY, version, stream_size); + /* To do: ignore strm->next_in if we use it as window */ +} + +/* ========================================================================= */ +int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, + version, stream_size) + z_streamp strm; + int level; + int method; + int windowBits; + int memLevel; + int strategy; + const char *version; + int stream_size; +{ + deflate_state *s; + int wrap = 1; + static const char my_version[] = ZLIB_VERSION; + + ushf *overlay; + /* We overlay pending_buf and d_buf+l_buf. This works since the average + * output size for (length,distance) codes is <= 24 bits. + */ + + if (version == Z_NULL || version[0] != my_version[0] || + stream_size != sizeof(z_stream)) { + return Z_VERSION_ERROR; + } + if (strm == Z_NULL) return Z_STREAM_ERROR; + + strm->msg = Z_NULL; + if (strm->zalloc == (alloc_func)0) { +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zalloc = zcalloc; + strm->opaque = (voidpf)0; +#endif + } + if (strm->zfree == (free_func)0) +#ifdef Z_SOLO + return Z_STREAM_ERROR; +#else + strm->zfree = zcfree; +#endif + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } +#ifdef GZIP + else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } +#endif + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */ + s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); + if (s == Z_NULL) return Z_MEM_ERROR; + strm->state = (struct internal_state FAR *)s; + s->strm = strm; + + s->wrap = wrap; + s->gzhead = Z_NULL; + s->w_bits = windowBits; + s->w_size = 1 << s->w_bits; + s->w_mask = s->w_size - 1; + + s->hash_bits = memLevel + 7; + s->hash_size = 1 << s->hash_bits; + s->hash_mask = s->hash_size - 1; + s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH); + + s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte)); + s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos)); + s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos)); + + s->high_water = 0; /* nothing written to s->window yet */ + + s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + s->pending_buf = (uchf *) overlay; + s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L); + + if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL || + s->pending_buf == Z_NULL) { + s->status = FINISH_STATE; + strm->msg = ERR_MSG(Z_MEM_ERROR); + deflateEnd (strm); + return Z_MEM_ERROR; + } + s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + + s->level = level; + s->strategy = strategy; + s->method = (Byte)method; + + return deflateReset(strm); +} + +/* ========================================================================= */ +int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength) + z_streamp strm; + const Bytef *dictionary; + uInt dictLength; +{ + deflate_state *s; + uInt str, n; + int wrap; + unsigned avail; + z_const unsigned char *next; + + if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL) + return Z_STREAM_ERROR; + s = strm->state; + wrap = s->wrap; + if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead) + return Z_STREAM_ERROR; + + /* when using zlib wrappers, compute Adler-32 for provided dictionary */ + if (wrap == 1) + strm->adler = adler32(strm->adler, dictionary, dictLength); + s->wrap = 0; /* avoid computing Adler-32 in read_buf */ + + /* if dictionary would fill window, just replace the history */ + if (dictLength >= s->w_size) { + if (wrap == 0) { /* already empty otherwise */ + CLEAR_HASH(s); + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + dictionary += dictLength - s->w_size; /* use the tail */ + dictLength = s->w_size; + } + + /* insert dictionary into window and hash */ + avail = strm->avail_in; + next = strm->next_in; + strm->avail_in = dictLength; + strm->next_in = (z_const Bytef *)dictionary; + fill_window(s); + while (s->lookahead >= MIN_MATCH) { + str = s->strstart; + n = s->lookahead - (MIN_MATCH-1); + do { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + } while (--n); + s->strstart = str; + s->lookahead = MIN_MATCH-1; + fill_window(s); + } + s->strstart += s->lookahead; + s->block_start = (long)s->strstart; + s->insert = s->lookahead; + s->lookahead = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + strm->next_in = next; + strm->avail_in = avail; + s->wrap = wrap; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateResetKeep (strm) + z_streamp strm; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) { + return Z_STREAM_ERROR; + } + + strm->total_in = strm->total_out = 0; + strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */ + strm->data_type = Z_UNKNOWN; + + s = (deflate_state *)strm->state; + s->pending = 0; + s->pending_out = s->pending_buf; + + if (s->wrap < 0) { + s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */ + } + s->status = s->wrap ? INIT_STATE : BUSY_STATE; + strm->adler = +#ifdef GZIP + s->wrap == 2 ? crc32(0L, Z_NULL, 0) : +#endif + adler32(0L, Z_NULL, 0); + s->last_flush = Z_NO_FLUSH; + + _tr_init(s); + + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateReset (strm) + z_streamp strm; +{ + int ret; + + ret = deflateResetKeep(strm); + if (ret == Z_OK) + lm_init(strm->state); + return ret; +} + +/* ========================================================================= */ +int ZEXPORT deflateSetHeader (strm, head) + z_streamp strm; + gz_headerp head; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (strm->state->wrap != 2) return Z_STREAM_ERROR; + strm->state->gzhead = head; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePending (strm, pending, bits) + unsigned *pending; + int *bits; + z_streamp strm; +{ + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + if (pending != Z_NULL) + *pending = strm->state->pending; + if (bits != Z_NULL) + *bits = strm->state->bi_valid; + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflatePrime (strm, bits, value) + z_streamp strm; + int bits; + int value; +{ + deflate_state *s; + int put; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3)) + return Z_BUF_ERROR; + do { + put = Buf_size - s->bi_valid; + if (put > bits) + put = bits; + s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid); + s->bi_valid += put; + _tr_flush_bits(s); + value >>= put; + bits -= put; + } while (bits); + return Z_OK; +} + +/* ========================================================================= */ +int ZEXPORT deflateParams(strm, level, strategy) + z_streamp strm; + int level; + int strategy; +{ + deflate_state *s; + compress_func func; + int err = Z_OK; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + +#ifdef FASTEST + if (level != 0) level = 1; +#else + if (level == Z_DEFAULT_COMPRESSION) level = 6; +#endif + if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { + return Z_STREAM_ERROR; + } + func = configuration_table[s->level].func; + + if ((strategy != s->strategy || func != configuration_table[level].func) && + strm->total_in != 0) { + /* Flush the last buffer: */ + err = deflate(strm, Z_BLOCK); + if (err == Z_BUF_ERROR && s->pending == 0) + err = Z_OK; + } + if (s->level != level) { + s->level = level; + s->max_lazy_match = configuration_table[level].max_lazy; + s->good_match = configuration_table[level].good_length; + s->nice_match = configuration_table[level].nice_length; + s->max_chain_length = configuration_table[level].max_chain; + } + s->strategy = strategy; + return err; +} + +/* ========================================================================= */ +int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain) + z_streamp strm; + int good_length; + int max_lazy; + int nice_length; + int max_chain; +{ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + s = strm->state; + s->good_match = good_length; + s->max_lazy_match = max_lazy; + s->nice_match = nice_length; + s->max_chain_length = max_chain; + return Z_OK; +} + +/* ========================================================================= + * For the default windowBits of 15 and memLevel of 8, this function returns + * a close to exact, as well as small, upper bound on the compressed size. + * They are coded as constants here for a reason--if the #define's are + * changed, then this function needs to be changed as well. The return + * value for 15 and 8 only works for those exact settings. + * + * For any setting other than those defaults for windowBits and memLevel, + * the value returned is a conservative worst case for the maximum expansion + * resulting from using fixed blocks instead of stored blocks, which deflate + * can emit on compressed data for some combinations of the parameters. + * + * This function could be more sophisticated to provide closer upper bounds for + * every combination of windowBits and memLevel. But even the conservative + * upper bound of about 14% expansion does not seem onerous for output buffer + * allocation. + */ +uLong ZEXPORT deflateBound(strm, sourceLen) + z_streamp strm; + uLong sourceLen; +{ + deflate_state *s; + uLong complen, wraplen; + Bytef *str; + + /* conservative upper bound for compressed data */ + complen = sourceLen + + ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5; + + /* if can't get parameters, return conservative bound plus zlib wrapper */ + if (strm == Z_NULL || strm->state == Z_NULL) + return complen + 6; + + /* compute wrapper length */ + s = strm->state; + switch (s->wrap) { + case 0: /* raw deflate */ + wraplen = 0; + break; + case 1: /* zlib wrapper */ + wraplen = 6 + (s->strstart ? 4 : 0); + break; + case 2: /* gzip wrapper */ + wraplen = 18; + if (s->gzhead != Z_NULL) { /* user-supplied gzip header */ + if (s->gzhead->extra != Z_NULL) + wraplen += 2 + s->gzhead->extra_len; + str = s->gzhead->name; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + str = s->gzhead->comment; + if (str != Z_NULL) + do { + wraplen++; + } while (*str++); + if (s->gzhead->hcrc) + wraplen += 2; + } + break; + default: /* for compiler happiness */ + wraplen = 6; + } + + /* if not default parameters, return conservative bound */ + if (s->w_bits != 15 || s->hash_bits != 8 + 7) + return complen + wraplen; + + /* default settings: return tight bound for that case */ + return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + + (sourceLen >> 25) + 13 - 6 + wraplen; +} + +/* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ +local void putShortMSB (s, b) + deflate_state *s; + uInt b; +{ + put_byte(s, (Byte)(b >> 8)); + put_byte(s, (Byte)(b & 0xff)); +} + +/* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->next_out buffer and copying into it. + * (See also read_buf()). + */ +local void flush_pending(strm) + z_streamp strm; +{ + unsigned len; + deflate_state *s = strm->state; + + _tr_flush_bits(s); + len = s->pending; + if (len > strm->avail_out) len = strm->avail_out; + if (len == 0) return; + + zmemcpy(strm->next_out, s->pending_out, len); + strm->next_out += len; + s->pending_out += len; + strm->total_out += len; + strm->avail_out -= len; + s->pending -= len; + if (s->pending == 0) { + s->pending_out = s->pending_buf; + } +} + +/* ========================================================================= */ +int ZEXPORT deflate (strm, flush) + z_streamp strm; + int flush; +{ + int old_flush; /* value of flush param for previous deflate call */ + deflate_state *s; + + if (strm == Z_NULL || strm->state == Z_NULL || + flush > Z_BLOCK || flush < 0) { + return Z_STREAM_ERROR; + } + s = strm->state; + + if (strm->next_out == Z_NULL || + (strm->next_in == Z_NULL && strm->avail_in != 0) || + (s->status == FINISH_STATE && flush != Z_FINISH)) { + ERR_RETURN(strm, Z_STREAM_ERROR); + } + if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); + + s->strm = strm; /* just in case */ + old_flush = s->last_flush; + s->last_flush = flush; + + /* Write the header */ + if (s->status == INIT_STATE) { +#ifdef GZIP + if (s->wrap == 2) { + strm->adler = crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (s->gzhead == Z_NULL) { + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s->status = BUSY_STATE; + } + else { + put_byte(s, (s->gzhead->text ? 1 : 0) + + (s->gzhead->hcrc ? 2 : 0) + + (s->gzhead->extra == Z_NULL ? 0 : 4) + + (s->gzhead->name == Z_NULL ? 0 : 8) + + (s->gzhead->comment == Z_NULL ? 0 : 16) + ); + put_byte(s, (Byte)(s->gzhead->time & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff)); + put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff)); + put_byte(s, s->level == 9 ? 2 : + (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ? + 4 : 0)); + put_byte(s, s->gzhead->os & 0xff); + if (s->gzhead->extra != Z_NULL) { + put_byte(s, s->gzhead->extra_len & 0xff); + put_byte(s, (s->gzhead->extra_len >> 8) & 0xff); + } + if (s->gzhead->hcrc) + strm->adler = crc32(strm->adler, s->pending_buf, + s->pending); + s->gzindex = 0; + s->status = EXTRA_STATE; + } + } + else +#endif + { + uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8; + uInt level_flags; + + if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2) + level_flags = 0; + else if (s->level < 6) + level_flags = 1; + else if (s->level == 6) + level_flags = 2; + else + level_flags = 3; + header |= (level_flags << 6); + if (s->strstart != 0) header |= PRESET_DICT; + header += 31 - (header % 31); + + s->status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s->strstart != 0) { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + strm->adler = adler32(0L, Z_NULL, 0); + } + } +#ifdef GZIP + if (s->status == EXTRA_STATE) { + if (s->gzhead->extra != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + + while (s->gzindex < (s->gzhead->extra_len & 0xffff)) { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) + break; + } + put_byte(s, s->gzhead->extra[s->gzindex]); + s->gzindex++; + } + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (s->gzindex == s->gzhead->extra_len) { + s->gzindex = 0; + s->status = NAME_STATE; + } + } + else + s->status = NAME_STATE; + } + if (s->status == NAME_STATE) { + if (s->gzhead->name != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->name[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) { + s->gzindex = 0; + s->status = COMMENT_STATE; + } + } + else + s->status = COMMENT_STATE; + } + if (s->status == COMMENT_STATE) { + if (s->gzhead->comment != Z_NULL) { + uInt beg = s->pending; /* start of bytes to update crc */ + int val; + + do { + if (s->pending == s->pending_buf_size) { + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + flush_pending(strm); + beg = s->pending; + if (s->pending == s->pending_buf_size) { + val = 1; + break; + } + } + val = s->gzhead->comment[s->gzindex++]; + put_byte(s, val); + } while (val != 0); + if (s->gzhead->hcrc && s->pending > beg) + strm->adler = crc32(strm->adler, s->pending_buf + beg, + s->pending - beg); + if (val == 0) + s->status = HCRC_STATE; + } + else + s->status = HCRC_STATE; + } + if (s->status == HCRC_STATE) { + if (s->gzhead->hcrc) { + if (s->pending + 2 > s->pending_buf_size) + flush_pending(strm); + if (s->pending + 2 <= s->pending_buf_size) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + strm->adler = crc32(0L, Z_NULL, 0); + s->status = BUSY_STATE; + } + } + else + s->status = BUSY_STATE; + } +#endif + + /* Flush as much pending output as possible */ + if (s->pending != 0) { + flush_pending(strm); + if (strm->avail_out == 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s->last_flush = -1; + return Z_OK; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) && + flush != Z_FINISH) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* User must not provide more input after the first FINISH: */ + if (s->status == FINISH_STATE && strm->avail_in != 0) { + ERR_RETURN(strm, Z_BUF_ERROR); + } + + /* Start a new block or continue the current one. + */ + if (strm->avail_in != 0 || s->lookahead != 0 || + (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { + block_state bstate; + + bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) : + (s->strategy == Z_RLE ? deflate_rle(s, flush) : + (*(configuration_table[s->level].func))(s, flush)); + + if (bstate == finish_started || bstate == finish_done) { + s->status = FINISH_STATE; + } + if (bstate == need_more || bstate == finish_started) { + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ + } + return Z_OK; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate == block_done) { + if (flush == Z_PARTIAL_FLUSH) { + _tr_align(s); + } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ + _tr_stored_block(s, (char*)0, 0L, 0); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush == Z_FULL_FLUSH) { + CLEAR_HASH(s); /* forget history */ + if (s->lookahead == 0) { + s->strstart = 0; + s->block_start = 0L; + s->insert = 0; + } + } + } + flush_pending(strm); + if (strm->avail_out == 0) { + s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK; + } + } + } + Assert(strm->avail_out > 0, "bug2"); + + if (flush != Z_FINISH) return Z_OK; + if (s->wrap <= 0) return Z_STREAM_END; + + /* Write the trailer */ +#ifdef GZIP + if (s->wrap == 2) { + put_byte(s, (Byte)(strm->adler & 0xff)); + put_byte(s, (Byte)((strm->adler >> 8) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 16) & 0xff)); + put_byte(s, (Byte)((strm->adler >> 24) & 0xff)); + put_byte(s, (Byte)(strm->total_in & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 8) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 16) & 0xff)); + put_byte(s, (Byte)((strm->total_in >> 24) & 0xff)); + } + else +#endif + { + putShortMSB(s, (uInt)(strm->adler >> 16)); + putShortMSB(s, (uInt)(strm->adler & 0xffff)); + } + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */ + return s->pending != 0 ? Z_OK : Z_STREAM_END; +} + +/* ========================================================================= */ +int ZEXPORT deflateEnd (strm) + z_streamp strm; +{ + int status; + + if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR; + + status = strm->state->status; + if (status != INIT_STATE && + status != EXTRA_STATE && + status != NAME_STATE && + status != COMMENT_STATE && + status != HCRC_STATE && + status != BUSY_STATE && + status != FINISH_STATE) { + return Z_STREAM_ERROR; + } + + /* Deallocate in reverse order of allocations: */ + TRY_FREE(strm, strm->state->pending_buf); + TRY_FREE(strm, strm->state->head); + TRY_FREE(strm, strm->state->prev); + TRY_FREE(strm, strm->state->window); + + ZFREE(strm, strm->state); + strm->state = Z_NULL; + + return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK; +} + +/* ========================================================================= + * Copy the source state to the destination state. + * To simplify the source, this is not supported for 16-bit MSDOS (which + * doesn't have enough memory anyway to duplicate compression states). + */ +int ZEXPORT deflateCopy (dest, source) + z_streamp dest; + z_streamp source; +{ +#ifdef MAXSEG_64K + return Z_STREAM_ERROR; +#else + deflate_state *ds; + deflate_state *ss; + ushf *overlay; + + + if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) { + return Z_STREAM_ERROR; + } + + ss = source->state; + + zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream)); + + ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state)); + if (ds == Z_NULL) return Z_MEM_ERROR; + dest->state = (struct internal_state FAR *) ds; + zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state)); + ds->strm = dest; + + ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte)); + ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos)); + ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos)); + overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2); + ds->pending_buf = (uchf *) overlay; + + if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL || + ds->pending_buf == Z_NULL) { + deflateEnd (dest); + return Z_MEM_ERROR; + } + /* following zmemcpy do not work for 16-bit MSDOS */ + zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte)); + zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos)); + zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos)); + zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size); + + ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf); + ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush); + ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize; + + ds->l_desc.dyn_tree = ds->dyn_ltree; + ds->d_desc.dyn_tree = ds->dyn_dtree; + ds->bl_desc.dyn_tree = ds->bl_tree; + + return Z_OK; +#endif /* MAXSEG_64K */ +} + +/* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->next_in buffer and copying from it. + * (See also flush_pending()). + */ +local int read_buf(strm, buf, size) + z_streamp strm; + Bytef *buf; + unsigned size; +{ + unsigned len = strm->avail_in; + + if (len > size) len = size; + if (len == 0) return 0; + + strm->avail_in -= len; + + zmemcpy(buf, strm->next_in, len); + if (strm->state->wrap == 1) { + strm->adler = adler32(strm->adler, buf, len); + } +#ifdef GZIP + else if (strm->state->wrap == 2) { + strm->adler = crc32(strm->adler, buf, len); + } +#endif + strm->next_in += len; + strm->total_in += len; + + return (int)len; +} + +/* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ +local void lm_init (s) + deflate_state *s; +{ + s->window_size = (ulg)2L*s->w_size; + + CLEAR_HASH(s); + + /* Set the default configuration parameters: + */ + s->max_lazy_match = configuration_table[s->level].max_lazy; + s->good_match = configuration_table[s->level].good_length; + s->nice_match = configuration_table[s->level].nice_length; + s->max_chain_length = configuration_table[s->level].max_chain; + + s->strstart = 0; + s->block_start = 0L; + s->lookahead = 0; + s->insert = 0; + s->match_length = s->prev_length = MIN_MATCH-1; + s->match_available = 0; + s->ins_h = 0; +#ifndef FASTEST +#ifdef ASMV + match_init(); /* initialize the asm code */ +#endif +#endif +} + +#ifndef FASTEST +/* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ +#ifndef ASMV +/* For 80x86 and 680x0, an optimized version will be provided in match.asm or + * match.S. The code will be functionally equivalent. + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + unsigned chain_length = s->max_chain_length;/* max hash chain length */ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + int best_len = s->prev_length; /* best match length so far */ + int nice_match = s->nice_match; /* stop if match long enough */ + IPos limit = s->strstart > (IPos)MAX_DIST(s) ? + s->strstart - (IPos)MAX_DIST(s) : NIL; + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + Posf *prev = s->prev; + uInt wmask = s->w_mask; + +#ifdef UNALIGNED_OK + /* Compare two bytes at a time. Note: this is not always beneficial. + * Try with and without -DUNALIGNED_OK to check. + */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1; + register ush scan_start = *(ushf*)scan; + register ush scan_end = *(ushf*)(scan+best_len-1); +#else + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + register Byte scan_end1 = scan[best_len-1]; + register Byte scan_end = scan[best_len]; +#endif + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s->prev_length >= s->good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead; + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + Assert(cur_match < s->strstart, "no future"); + match = s->window + cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ +#if (defined(UNALIGNED_OK) && MAX_MATCH == 258) + /* This code assumes sizeof(unsigned short) == 2. Do not use + * UNALIGNED_OK if your compiler uses a different size. + */ + if (*(ushf*)(match+best_len-1) != scan_end || + *(ushf*)match != scan_start) continue; + + /* It is not necessary to compare scan[2] and match[2] since they are + * always equal when the other bytes match, given that the hash keys + * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at + * strstart+3, +5, ... up to strstart+257. We check for insufficient + * lookahead only every 4th comparison; the 128th check will be made + * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is + * necessary to put more guard bytes at the end of the window, or + * to check more often for insufficient lookahead. + */ + Assert(scan[2] == match[2], "scan[2]?"); + scan++, match++; + do { + } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + *(ushf*)(scan+=2) == *(ushf*)(match+=2) && + scan < strend); + /* The funny "do {}" generates better code on most compilers */ + + /* Here, scan <= window+strstart+257 */ + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + if (*scan == *match) scan++; + + len = (MAX_MATCH - 1) - (int)(strend-scan); + scan = strend - (MAX_MATCH-1); + +#else /* UNALIGNED_OK */ + + if (match[best_len] != scan_end || + match[best_len-1] != scan_end1 || + *match != *scan || + *++match != scan[1]) continue; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match++; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + scan = strend - MAX_MATCH; + +#endif /* UNALIGNED_OK */ + + if (len > best_len) { + s->match_start = cur_match; + best_len = len; + if (len >= nice_match) break; +#ifdef UNALIGNED_OK + scan_end = *(ushf*)(scan+best_len-1); +#else + scan_end1 = scan[best_len-1]; + scan_end = scan[best_len]; +#endif + } + } while ((cur_match = prev[cur_match & wmask]) > limit + && --chain_length != 0); + + if ((uInt)best_len <= s->lookahead) return (uInt)best_len; + return s->lookahead; +} +#endif /* ASMV */ + +#else /* FASTEST */ + +/* --------------------------------------------------------------------------- + * Optimized version for FASTEST only + */ +local uInt longest_match(s, cur_match) + deflate_state *s; + IPos cur_match; /* current match */ +{ + register Bytef *scan = s->window + s->strstart; /* current string */ + register Bytef *match; /* matched string */ + register int len; /* length of current match */ + register Bytef *strend = s->window + s->strstart + MAX_MATCH; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + Assert(cur_match < s->strstart, "no future"); + + match = s->window + cur_match; + + /* Return failure if the match length is less than 2: + */ + if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1; + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2, match += 2; + Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + } while (*++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + *++scan == *++match && *++scan == *++match && + scan < strend); + + Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (int)(strend - scan); + + if (len < MIN_MATCH) return MIN_MATCH - 1; + + s->match_start = cur_match; + return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead; +} + +#endif /* FASTEST */ + +#ifdef DEBUG +/* =========================================================================== + * Check that the match at match_start is indeed a match. + */ +local void check_match(s, start, match, length) + deflate_state *s; + IPos start, match; + int length; +{ + /* check that the match is indeed a match */ + if (zmemcmp(s->window + match, + s->window + start, length) != EQUAL) { + fprintf(stderr, " start %u, match %u, length %d\n", + start, match, length); + do { + fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); + } while (--length != 0); + z_error("invalid match"); + } + if (z_verbose > 1) { + fprintf(stderr,"\\[%d,%d]", start-match, length); + do { putc(s->window[start++], stderr); } while (--length != 0); + } +} +#else +# define check_match(s, start, match, length) +#endif /* DEBUG */ + +/* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ +local void fill_window(s) + deflate_state *s; +{ + register unsigned n, m; + register Posf *p; + unsigned more; /* Amount of free space at the end of the window. */ + uInt wsize = s->w_size; + + Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart); + + /* Deal with !@#$% 64K limit: */ + if (sizeof(int) <= 2) { + if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + more = wsize; + + } else if (more == (unsigned)(-1)) { + /* Very unlikely, but possible on 16 bit machine if + * strstart == 0 && lookahead == 1 (input done a byte at time) + */ + more--; + } + } + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s->strstart >= wsize+MAX_DIST(s)) { + + zmemcpy(s->window, s->window+wsize, (unsigned)wsize); + s->match_start -= wsize; + s->strstart -= wsize; /* we now have strstart >= MAX_DIST */ + s->block_start -= (long) wsize; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + n = s->hash_size; + p = &s->head[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + } while (--n); + + n = wsize; +#ifndef FASTEST + p = &s->prev[n]; + do { + m = *--p; + *p = (Pos)(m >= wsize ? m-wsize : NIL); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); +#endif + more += wsize; + } + if (s->strm->avail_in == 0) break; + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + Assert(more >= 2, "more < 2"); + + n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more); + s->lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s->lookahead + s->insert >= MIN_MATCH) { + uInt str = s->strstart - s->insert; + s->ins_h = s->window[str]; + UPDATE_HASH(s, s->ins_h, s->window[str + 1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + while (s->insert) { + UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); +#ifndef FASTEST + s->prev[str & s->w_mask] = s->head[s->ins_h]; +#endif + s->head[s->ins_h] = (Pos)str; + str++; + s->insert--; + if (s->lookahead + s->insert < MIN_MATCH) + break; + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + if (s->high_water < s->window_size) { + ulg curr = s->strstart + (ulg)(s->lookahead); + ulg init; + + if (s->high_water < curr) { + /* Previous high water mark below current data -- zero WIN_INIT + * bytes or up to end of window, whichever is less. + */ + init = s->window_size - curr; + if (init > WIN_INIT) + init = WIN_INIT; + zmemzero(s->window + curr, (unsigned)init); + s->high_water = curr + init; + } + else if (s->high_water < (ulg)curr + WIN_INIT) { + /* High water mark at or above current data, but below current data + * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + * to end of window, whichever is less. + */ + init = (ulg)curr + WIN_INIT - s->high_water; + if (init > s->window_size - s->high_water) + init = s->window_size - s->high_water; + zmemzero(s->window + s->high_water, (unsigned)init); + s->high_water += init; + } + } + + Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + "not enough room for search"); +} + +/* =========================================================================== + * Flush the current block, with given end-of-file flag. + * IN assertion: strstart is set to the end of the current match. + */ +#define FLUSH_BLOCK_ONLY(s, last) { \ + _tr_flush_block(s, (s->block_start >= 0L ? \ + (charf *)&s->window[(unsigned)s->block_start] : \ + (charf *)Z_NULL), \ + (ulg)((long)s->strstart - s->block_start), \ + (last)); \ + s->block_start = s->strstart; \ + flush_pending(s->strm); \ + Tracev((stderr,"[FLUSH]")); \ +} + +/* Same but force premature exit if necessary. */ +#define FLUSH_BLOCK(s, last) { \ + FLUSH_BLOCK_ONLY(s, last); \ + if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \ +} + +/* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ +local block_state deflate_stored(s, flush) + deflate_state *s; + int flush; +{ + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + ulg max_block_size = 0xffff; + ulg max_start; + + if (max_block_size > s->pending_buf_size - 5) { + max_block_size = s->pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s->lookahead <= 1) { + + Assert(s->strstart < s->w_size+MAX_DIST(s) || + s->block_start >= (long)s->w_size, "slide too late"); + + fill_window(s); + if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; + + if (s->lookahead == 0) break; /* flush the current block */ + } + Assert(s->block_start >= 0L, "block gone"); + + s->strstart += s->lookahead; + s->lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + max_start = s->block_start + max_block_size; + if (s->strstart == 0 || (ulg)s->strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s->lookahead = (uInt)(s->strstart - max_start); + s->strstart = (uInt)max_start; + FLUSH_BLOCK(s, 0); + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { + FLUSH_BLOCK(s, 0); + } + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if ((long)s->strstart > s->block_start) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ +local block_state deflate_fast(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of the hash chain */ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->match_start, s->match_length); + + _tr_tally_dist(s, s->strstart - s->match_start, + s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ +#ifndef FASTEST + if (s->match_length <= s->max_insert_length && + s->lookahead >= MIN_MATCH) { + s->match_length--; /* string at strstart already in table */ + do { + s->strstart++; + INSERT_STRING(s, s->strstart, hash_head); + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s->match_length != 0); + s->strstart++; + } else +#endif + { + s->strstart += s->match_length; + s->match_length = 0; + s->ins_h = s->window[s->strstart]; + UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]); +#if MIN_MATCH != 3 + Call UPDATE_HASH() MIN_MATCH-3 more times +#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +#ifndef FASTEST +/* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ +local block_state deflate_slow(s, flush) + deflate_state *s; + int flush; +{ + IPos hash_head; /* head of hash chain */ + int bflush; /* set if current block must be flushed */ + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s->lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = NIL; + if (s->lookahead >= MIN_MATCH) { + INSERT_STRING(s, s->strstart, hash_head); + } + + /* Find the longest match, discarding those <= prev_length. + */ + s->prev_length = s->match_length, s->prev_match = s->match_start; + s->match_length = MIN_MATCH-1; + + if (hash_head != NIL && s->prev_length < s->max_lazy_match && + s->strstart - hash_head <= MAX_DIST(s)) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s->match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + + if (s->match_length <= 5 && (s->strategy == Z_FILTERED +#if TOO_FAR <= 32767 + || (s->match_length == MIN_MATCH && + s->strstart - s->match_start > TOO_FAR) +#endif + )) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s->match_length = MIN_MATCH-1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) { + uInt max_insert = s->strstart + s->lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + check_match(s, s->strstart-1, s->prev_match, s->prev_length); + + _tr_tally_dist(s, s->strstart -1 - s->prev_match, + s->prev_length - MIN_MATCH, bflush); + + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s->lookahead -= s->prev_length-1; + s->prev_length -= 2; + do { + if (++s->strstart <= max_insert) { + INSERT_STRING(s, s->strstart, hash_head); + } + } while (--s->prev_length != 0); + s->match_available = 0; + s->match_length = MIN_MATCH-1; + s->strstart++; + + if (bflush) FLUSH_BLOCK(s, 0); + + } else if (s->match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + if (bflush) { + FLUSH_BLOCK_ONLY(s, 0); + } + s->strstart++; + s->lookahead--; + if (s->strm->avail_out == 0) return need_more; + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s->match_available = 1; + s->strstart++; + s->lookahead--; + } + } + Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s->match_available) { + Tracevv((stderr,"%c", s->window[s->strstart-1])); + _tr_tally_lit(s, s->window[s->strstart-1], bflush); + s->match_available = 0; + } + s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} +#endif /* FASTEST */ + +/* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ +local block_state deflate_rle(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + uInt prev; /* byte at distance one to match */ + Bytef *scan, *strend; /* scan goes up to strend for length of run */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s->lookahead <= MAX_MATCH) { + fill_window(s); + if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) { + return need_more; + } + if (s->lookahead == 0) break; /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s->match_length = 0; + if (s->lookahead >= MIN_MATCH && s->strstart > 0) { + scan = s->window + s->strstart - 1; + prev = *scan; + if (prev == *++scan && prev == *++scan && prev == *++scan) { + strend = s->window + s->strstart + MAX_MATCH; + do { + } while (prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + prev == *++scan && prev == *++scan && + scan < strend); + s->match_length = MAX_MATCH - (int)(strend - scan); + if (s->match_length > s->lookahead) + s->match_length = s->lookahead; + } + Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s->match_length >= MIN_MATCH) { + check_match(s, s->strstart, s->strstart - 1, s->match_length); + + _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush); + + s->lookahead -= s->match_length; + s->strstart += s->match_length; + s->match_length = 0; + } else { + /* No match, output a literal byte */ + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + } + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} + +/* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ +local block_state deflate_huff(s, flush) + deflate_state *s; + int flush; +{ + int bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s->lookahead == 0) { + fill_window(s); + if (s->lookahead == 0) { + if (flush == Z_NO_FLUSH) + return need_more; + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s->match_length = 0; + Tracevv((stderr,"%c", s->window[s->strstart])); + _tr_tally_lit (s, s->window[s->strstart], bflush); + s->lookahead--; + s->strstart++; + if (bflush) FLUSH_BLOCK(s, 0); + } + s->insert = 0; + if (flush == Z_FINISH) { + FLUSH_BLOCK(s, 1); + return finish_done; + } + if (s->last_lit) + FLUSH_BLOCK(s, 0); + return block_done; +} diff --git a/zlib/deflate.h b/zlib/deflate.h new file mode 100644 index 00000000..ce0299ed --- /dev/null +++ b/zlib/deflate.h @@ -0,0 +1,346 @@ +/* deflate.h -- internal compression state + * Copyright (C) 1995-2012 Jean-loup Gailly + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* WARNING: this file should *not* be used by applications. It is + part of the implementation of the compression library and is + subject to change. Applications should only use zlib.h. + */ + +/* @(#) $Id$ */ + +#ifndef DEFLATE_H +#define DEFLATE_H + +#include "zutil.h" + +/* define NO_GZIP when compiling if you want to disable gzip header and + trailer creation by deflate(). NO_GZIP would be used to avoid linking in + the crc code when it is not needed. For shared libraries, gzip encoding + should be left enabled. */ +#ifndef NO_GZIP +# define GZIP +#endif + +/* =========================================================================== + * Internal compression state. + */ + +#define LENGTH_CODES 29 +/* number of length codes, not counting the special END_BLOCK code */ + +#define LITERALS 256 +/* number of literal bytes 0..255 */ + +#define L_CODES (LITERALS+1+LENGTH_CODES) +/* number of Literal or Length codes, including the END_BLOCK code */ + +#define D_CODES 30 +/* number of distance codes */ + +#define BL_CODES 19 +/* number of codes used to transfer the bit lengths */ + +#define HEAP_SIZE (2*L_CODES+1) +/* maximum heap size */ + +#define MAX_BITS 15 +/* All codes must not exceed MAX_BITS bits */ + +#define Buf_size 16 +/* size of bit buffer in bi_buf */ + +#define INIT_STATE 42 +#define EXTRA_STATE 69 +#define NAME_STATE 73 +#define COMMENT_STATE 91 +#define HCRC_STATE 103 +#define BUSY_STATE 113 +#define FINISH_STATE 666 +/* Stream status */ + + +/* Data structure describing a single value and its code string. */ +typedef struct ct_data_s { + union { + ush freq; /* frequency count */ + ush code; /* bit string */ + } fc; + union { + ush dad; /* father node in Huffman tree */ + ush len; /* length of bit string */ + } dl; +} FAR ct_data; + +#define Freq fc.freq +#define Code fc.code +#define Dad dl.dad +#define Len dl.len + +typedef struct static_tree_desc_s static_tree_desc; + +typedef struct tree_desc_s { + ct_data *dyn_tree; /* the dynamic tree */ + int max_code; /* largest code with non zero frequency */ + static_tree_desc *stat_desc; /* the corresponding static tree */ +} FAR tree_desc; + +typedef ush Pos; +typedef Pos FAR Posf; +typedef unsigned IPos; + +/* A Pos is an index in the character window. We use short instead of int to + * save space in the various tables. IPos is used only for parameter passing. + */ + +typedef struct internal_state { + z_streamp strm; /* pointer back to this zlib stream */ + int status; /* as the name implies */ + Bytef *pending_buf; /* output still pending */ + ulg pending_buf_size; /* size of pending_buf */ + Bytef *pending_out; /* next pending byte to output to the stream */ + uInt pending; /* nb of bytes in the pending buffer */ + int wrap; /* bit 0 true for zlib, bit 1 true for gzip */ + gz_headerp gzhead; /* gzip header information to write */ + uInt gzindex; /* where in extra, name, or comment */ + Byte method; /* can only be DEFLATED */ + int last_flush; /* value of flush param for previous deflate call */ + + /* used by deflate.c: */ + + uInt w_size; /* LZ77 window size (32K by default) */ + uInt w_bits; /* log2(w_size) (8..16) */ + uInt w_mask; /* w_size - 1 */ + + Bytef *window; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. Also, it limits + * the window size to 64K, which is quite useful on MSDOS. + * To do: use the user input buffer as sliding window. + */ + + ulg window_size; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + Posf *prev; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + Posf *head; /* Heads of the hash chains or NIL. */ + + uInt ins_h; /* hash index of string to be inserted */ + uInt hash_size; /* number of elements in hash table */ + uInt hash_bits; /* log2(hash_size) */ + uInt hash_mask; /* hash_size-1 */ + + uInt hash_shift; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + long block_start; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + uInt match_length; /* length of best match */ + IPos prev_match; /* previous match */ + int match_available; /* set if previous match exists */ + uInt strstart; /* start of string to insert */ + uInt match_start; /* start of matching string */ + uInt lookahead; /* number of valid bytes ahead in window */ + + uInt prev_length; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + uInt max_chain_length; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + uInt max_lazy_match; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ +# define max_insert_length max_lazy_match + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + int level; /* compression level (1..9) */ + int strategy; /* favor or force Huffman coding*/ + + uInt good_match; + /* Use a faster search when the previous match is longer than this */ + + int nice_match; /* Stop searching when current match exceeds this */ + + /* used by trees.c: */ + /* Didn't use ct_data typedef below to suppress compiler warning */ + struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + struct tree_desc_s l_desc; /* desc. for literal tree */ + struct tree_desc_s d_desc; /* desc. for distance tree */ + struct tree_desc_s bl_desc; /* desc. for bit length tree */ + + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + int heap_len; /* number of elements in the heap */ + int heap_max; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all trees. + */ + + uch depth[2*L_CODES+1]; + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + uchf *l_buf; /* buffer for literals or lengths */ + + uInt lit_bufsize; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + uInt last_lit; /* running index in l_buf */ + + ushf *d_buf; + /* Buffer for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + ulg opt_len; /* bit length of current block with optimal trees */ + ulg static_len; /* bit length of current block with static trees */ + uInt matches; /* number of string matches in current block */ + uInt insert; /* bytes at end of window left to insert */ + +#ifdef DEBUG + ulg compressed_len; /* total bit length of compressed file mod 2^32 */ + ulg bits_sent; /* bit length of compressed data sent mod 2^32 */ +#endif + + ush bi_buf; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + int bi_valid; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + ulg high_water; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + +} FAR deflate_state; + +/* Output a byte on the stream. + * IN assertion: there is enough room in pending_buf. + */ +#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);} + + +#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1) +/* Minimum amount of lookahead, except at the end of the input file. + * See deflate.c for comments about the MIN_MATCH+1. + */ + +#define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD) +/* In order to simplify the code, particularly on 16 bit machines, match + * distances are limited to MAX_DIST instead of WSIZE. + */ + +#define WIN_INIT MAX_MATCH +/* Number of bytes after end of data in window to initialize in order to avoid + memory checker errors from longest match routines */ + + /* in trees.c */ +void ZLIB_INTERNAL _tr_init OF((deflate_state *s)); +int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); +void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); +void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_align OF((deflate_state *s)); +void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf, + ulg stored_len, int last)); + +#define d_code(dist) \ + ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)]) +/* Mapping from a distance to a distance code. dist is the distance - 1 and + * must not have side effects. _dist_code[256] and _dist_code[257] are never + * used. + */ + +#ifndef DEBUG +/* Inline versions of _tr_tally for speed: */ + +#if defined(GEN_TREES_H) || !defined(STDC) + extern uch ZLIB_INTERNAL _length_code[]; + extern uch ZLIB_INTERNAL _dist_code[]; +#else + extern const uch ZLIB_INTERNAL _length_code[]; + extern const uch ZLIB_INTERNAL _dist_code[]; +#endif + +# define _tr_tally_lit(s, c, flush) \ + { uch cc = (c); \ + s->d_buf[s->last_lit] = 0; \ + s->l_buf[s->last_lit++] = cc; \ + s->dyn_ltree[cc].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +# define _tr_tally_dist(s, distance, length, flush) \ + { uch len = (length); \ + ush dist = (distance); \ + s->d_buf[s->last_lit] = dist; \ + s->l_buf[s->last_lit++] = len; \ + dist--; \ + s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \ + s->dyn_dtree[d_code(dist)].Freq++; \ + flush = (s->last_lit == s->lit_bufsize-1); \ + } +#else +# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) +# define _tr_tally_dist(s, distance, length, flush) \ + flush = _tr_tally(s, distance, length) +#endif + +#endif /* DEFLATE_H */ diff --git a/zlib/trees.c b/zlib/trees.c new file mode 100644 index 00000000..1fd7759e --- /dev/null +++ b/zlib/trees.c @@ -0,0 +1,1226 @@ +/* trees.c -- output deflated data using Huffman coding + * Copyright (C) 1995-2012 Jean-loup Gailly + * detect_data_type() function provided freely by Cosmin Truta, 2006 + * For conditions of distribution and use, see copyright notice in zlib.h + */ + +/* + * ALGORITHM + * + * The "deflation" process uses several Huffman trees. The more + * common source values are represented by shorter bit sequences. + * + * Each code tree is stored in a compressed form which is itself + * a Huffman encoding of the lengths of all the code strings (in + * ascending order by source values). The actual code strings are + * reconstructed from the lengths in the inflate process, as described + * in the deflate specification. + * + * REFERENCES + * + * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification". + * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc + * + * Storer, James A. + * Data Compression: Methods and Theory, pp. 49-50. + * Computer Science Press, 1988. ISBN 0-7167-8156-5. + * + * Sedgewick, R. + * Algorithms, p290. + * Addison-Wesley, 1983. ISBN 0-201-06672-6. + */ + +/* @(#) $Id$ */ + +/* #define GEN_TREES_H */ + +#include "deflate.h" + +#ifdef DEBUG +# include +#endif + +/* =========================================================================== + * Constants + */ + +#define MAX_BL_BITS 7 +/* Bit length codes must not exceed MAX_BL_BITS bits */ + +#define END_BLOCK 256 +/* end of block literal code */ + +#define REP_3_6 16 +/* repeat previous bit length 3-6 times (2 bits of repeat count) */ + +#define REPZ_3_10 17 +/* repeat a zero length 3-10 times (3 bits of repeat count) */ + +#define REPZ_11_138 18 +/* repeat a zero length 11-138 times (7 bits of repeat count) */ + +local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */ + = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0}; + +local const int extra_dbits[D_CODES] /* extra bits for each distance code */ + = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13}; + +local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */ + = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7}; + +local const uch bl_order[BL_CODES] + = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15}; +/* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + +/* =========================================================================== + * Local data. These are initialized only once. + */ + +#define DIST_CODE_LEN 512 /* see definition of array dist_code below */ + +#if defined(GEN_TREES_H) || !defined(STDC) +/* non ANSI compilers may not accept trees.h */ + +local ct_data static_ltree[L_CODES+2]; +/* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + +local ct_data static_dtree[D_CODES]; +/* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + +uch _dist_code[DIST_CODE_LEN]; +/* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + +uch _length_code[MAX_MATCH-MIN_MATCH+1]; +/* length code for each normalized match length (0 == MIN_MATCH) */ + +local int base_length[LENGTH_CODES]; +/* First normalized length for each code (0 = MIN_MATCH) */ + +local int base_dist[D_CODES]; +/* First normalized distance for each code (0 = distance of 1) */ + +#else +# include "trees.h" +#endif /* GEN_TREES_H */ + +struct static_tree_desc_s { + const ct_data *static_tree; /* static tree or NULL */ + const intf *extra_bits; /* extra bits for each code or NULL */ + int extra_base; /* base index for extra_bits */ + int elems; /* max number of elements in the tree */ + int max_length; /* max bit length for the codes */ +}; + +local static_tree_desc static_l_desc = +{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS}; + +local static_tree_desc static_d_desc = +{static_dtree, extra_dbits, 0, D_CODES, MAX_BITS}; + +local static_tree_desc static_bl_desc = +{(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS}; + +/* =========================================================================== + * Local (static) routines in this file. + */ + +local void tr_static_init OF((void)); +local void init_block OF((deflate_state *s)); +local void pqdownheap OF((deflate_state *s, ct_data *tree, int k)); +local void gen_bitlen OF((deflate_state *s, tree_desc *desc)); +local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count)); +local void build_tree OF((deflate_state *s, tree_desc *desc)); +local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local void send_tree OF((deflate_state *s, ct_data *tree, int max_code)); +local int build_bl_tree OF((deflate_state *s)); +local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes, + int blcodes)); +local void compress_block OF((deflate_state *s, const ct_data *ltree, + const ct_data *dtree)); +local int detect_data_type OF((deflate_state *s)); +local unsigned bi_reverse OF((unsigned value, int length)); +local void bi_windup OF((deflate_state *s)); +local void bi_flush OF((deflate_state *s)); +local void copy_block OF((deflate_state *s, charf *buf, unsigned len, + int header)); + +#ifdef GEN_TREES_H +local void gen_trees_header OF((void)); +#endif + +#ifndef DEBUG +# define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len) + /* Send a code of the given tree. c and tree must not have side effects */ + +#else /* DEBUG */ +# define send_code(s, c, tree) \ + { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \ + send_bits(s, tree[c].Code, tree[c].Len); } +#endif + +/* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ +#define put_short(s, w) { \ + put_byte(s, (uch)((w) & 0xff)); \ + put_byte(s, (uch)((ush)(w) >> 8)); \ +} + +/* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ +#ifdef DEBUG +local void send_bits OF((deflate_state *s, int value, int length)); + +local void send_bits(s, value, length) + deflate_state *s; + int value; /* value to send */ + int length; /* number of bits */ +{ + Tracevv((stderr," l %2d v %4x ", length, value)); + Assert(length > 0 && length <= 15, "invalid length"); + s->bits_sent += (ulg)length; + + /* If not enough room in bi_buf, use (valid) bits from bi_buf and + * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid)) + * unused bits in value. + */ + if (s->bi_valid > (int)Buf_size - length) { + s->bi_buf |= (ush)value << s->bi_valid; + put_short(s, s->bi_buf); + s->bi_buf = (ush)value >> (Buf_size - s->bi_valid); + s->bi_valid += length - Buf_size; + } else { + s->bi_buf |= (ush)value << s->bi_valid; + s->bi_valid += length; + } +} +#else /* !DEBUG */ + +#define send_bits(s, value, length) \ +{ int len = length;\ + if (s->bi_valid > (int)Buf_size - len) {\ + int val = value;\ + s->bi_buf |= (ush)val << s->bi_valid;\ + put_short(s, s->bi_buf);\ + s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\ + s->bi_valid += len - Buf_size;\ + } else {\ + s->bi_buf |= (ush)(value) << s->bi_valid;\ + s->bi_valid += len;\ + }\ +} +#endif /* DEBUG */ + + +/* the arguments must not have side effects */ + +/* =========================================================================== + * Initialize the various 'constant' tables. + */ +local void tr_static_init() +{ +#if defined(GEN_TREES_H) || !defined(STDC) + static int static_init_done = 0; + int n; /* iterates over tree elements */ + int bits; /* bit counter */ + int length; /* length value */ + int code; /* code value */ + int dist; /* distance index */ + ush bl_count[MAX_BITS+1]; + /* number of codes at each bit length for an optimal tree */ + + if (static_init_done) return; + + /* For some embedded targets, global variables are not initialized: */ +#ifdef NO_INIT_GLOBAL_POINTERS + static_l_desc.static_tree = static_ltree; + static_l_desc.extra_bits = extra_lbits; + static_d_desc.static_tree = static_dtree; + static_d_desc.extra_bits = extra_dbits; + static_bl_desc.extra_bits = extra_blbits; +#endif + + /* Initialize the mapping length (0..255) -> length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES-1; code++) { + base_length[code] = length; + for (n = 0; n < (1< dist code (0..29) */ + dist = 0; + for (code = 0 ; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1<>= 7; /* from now on, all distances are divided by 128 */ + for ( ; code < D_CODES; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { + _dist_code[256 + dist++] = (uch)code; + } + } + Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0; + n = 0; + while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++; + while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++; + while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++; + while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++; + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES; n++) { + static_dtree[n].Len = 5; + static_dtree[n].Code = bi_reverse((unsigned)n, 5); + } + static_init_done = 1; + +# ifdef GEN_TREES_H + gen_trees_header(); +# endif +#endif /* defined(GEN_TREES_H) || !defined(STDC) */ +} + +/* =========================================================================== + * Genererate the file trees.h describing the static trees. + */ +#ifdef GEN_TREES_H +# ifndef DEBUG +# include +# endif + +# define SEPARATOR(i, last, width) \ + ((i) == (last)? "\n};\n\n" : \ + ((i) % (width) == (width)-1 ? ",\n" : ", ")) + +void gen_trees_header() +{ + FILE *header = fopen("trees.h", "w"); + int i; + + Assert (header != NULL, "Can't open trees.h"); + fprintf(header, + "/* header created automatically with -DGEN_TREES_H */\n\n"); + + fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); + for (i = 0; i < L_CODES+2; i++) { + fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, + static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); + } + + fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, + static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); + } + + fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n"); + for (i = 0; i < DIST_CODE_LEN; i++) { + fprintf(header, "%2u%s", _dist_code[i], + SEPARATOR(i, DIST_CODE_LEN-1, 20)); + } + + fprintf(header, + "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); + for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { + fprintf(header, "%2u%s", _length_code[i], + SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); + } + + fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); + for (i = 0; i < LENGTH_CODES; i++) { + fprintf(header, "%1u%s", base_length[i], + SEPARATOR(i, LENGTH_CODES-1, 20)); + } + + fprintf(header, "local const int base_dist[D_CODES] = {\n"); + for (i = 0; i < D_CODES; i++) { + fprintf(header, "%5u%s", base_dist[i], + SEPARATOR(i, D_CODES-1, 10)); + } + + fclose(header); +} +#endif /* GEN_TREES_H */ + +/* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ +void ZLIB_INTERNAL _tr_init(s) + deflate_state *s; +{ + tr_static_init(); + + s->l_desc.dyn_tree = s->dyn_ltree; + s->l_desc.stat_desc = &static_l_desc; + + s->d_desc.dyn_tree = s->dyn_dtree; + s->d_desc.stat_desc = &static_d_desc; + + s->bl_desc.dyn_tree = s->bl_tree; + s->bl_desc.stat_desc = &static_bl_desc; + + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->compressed_len = 0L; + s->bits_sent = 0L; +#endif + + /* Initialize the first block of the first file: */ + init_block(s); +} + +/* =========================================================================== + * Initialize a new block. + */ +local void init_block(s) + deflate_state *s; +{ + int n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0; + for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0; + for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0; + + s->dyn_ltree[END_BLOCK].Freq = 1; + s->opt_len = s->static_len = 0L; + s->last_lit = s->matches = 0; +} + +#define SMALLEST 1 +/* Index within the heap array of least frequent node in the Huffman tree */ + + +/* =========================================================================== + * Remove the smallest element from the heap and recreate the heap with + * one less element. Updates heap and heap_len. + */ +#define pqremove(s, tree, top) \ +{\ + top = s->heap[SMALLEST]; \ + s->heap[SMALLEST] = s->heap[s->heap_len--]; \ + pqdownheap(s, tree, SMALLEST); \ +} + +/* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ +#define smaller(tree, n, m, depth) \ + (tree[n].Freq < tree[m].Freq || \ + (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m])) + +/* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ +local void pqdownheap(s, tree, k) + deflate_state *s; + ct_data *tree; /* the tree to restore */ + int k; /* node to move down */ +{ + int v = s->heap[k]; + int j = k << 1; /* left son of k */ + while (j <= s->heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s->heap_len && + smaller(tree, s->heap[j+1], s->heap[j], s->depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s->heap[j], s->depth)) break; + + /* Exchange v with the smallest son */ + s->heap[k] = s->heap[j]; k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s->heap[k] = v; +} + +/* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ +local void gen_bitlen(s, desc) + deflate_state *s; + tree_desc *desc; /* the tree descriptor */ +{ + ct_data *tree = desc->dyn_tree; + int max_code = desc->max_code; + const ct_data *stree = desc->stat_desc->static_tree; + const intf *extra = desc->stat_desc->extra_bits; + int base = desc->stat_desc->extra_base; + int max_length = desc->stat_desc->max_length; + int h; /* heap index */ + int n, m; /* iterate over the tree elements */ + int bits; /* bit length */ + int xbits; /* extra bits */ + ush f; /* frequency */ + int overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0; + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */ + + for (h = s->heap_max+1; h < HEAP_SIZE; h++) { + n = s->heap[h]; + bits = tree[tree[n].Dad].Len + 1; + if (bits > max_length) bits = max_length, overflow++; + tree[n].Len = (ush)bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) continue; /* not a leaf node */ + + s->bl_count[bits]++; + xbits = 0; + if (n >= base) xbits = extra[n-base]; + f = tree[n].Freq; + s->opt_len += (ulg)f * (bits + xbits); + if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits); + } + if (overflow == 0) return; + + Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length-1; + while (s->bl_count[bits] == 0) bits--; + s->bl_count[bits]--; /* move one leaf down the tree */ + s->bl_count[bits+1] += 2; /* move one overflow item as its brother */ + s->bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits != 0; bits--) { + n = s->bl_count[bits]; + while (n != 0) { + m = s->heap[--h]; + if (m > max_code) continue; + if ((unsigned) tree[m].Len != (unsigned) bits) { + Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s->opt_len += ((long)bits - (long)tree[m].Len) + *(long)tree[m].Freq; + tree[m].Len = (ush)bits; + } + n--; + } + } +} + +/* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ +local void gen_codes (tree, max_code, bl_count) + ct_data *tree; /* the tree to decorate */ + int max_code; /* largest code with non zero frequency */ + ushf *bl_count; /* number of codes at each bit length */ +{ + ush next_code[MAX_BITS+1]; /* next code value for each bit length */ + ush code = 0; /* running code value */ + int bits; /* bit index */ + int n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS; bits++) { + next_code[bits] = code = (code + bl_count[bits-1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + Assert (code + bl_count[MAX_BITS]-1 == (1<dyn_tree; + const ct_data *stree = desc->stat_desc->static_tree; + int elems = desc->stat_desc->elems; + int n, m; /* iterate over heap elements */ + int max_code = -1; /* largest code with non zero frequency */ + int node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s->heap_len = 0, s->heap_max = HEAP_SIZE; + + for (n = 0; n < elems; n++) { + if (tree[n].Freq != 0) { + s->heap[++(s->heap_len)] = max_code = n; + s->depth[n] = 0; + } else { + tree[n].Len = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s->heap_len < 2) { + node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0); + tree[node].Freq = 1; + s->depth[node] = 0; + s->opt_len--; if (stree) s->static_len -= stree[node].Len; + /* node is 0 or 1 so it does not have extra bits */ + } + desc->max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n); + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + pqremove(s, tree, n); /* n = node of least frequency */ + m = s->heap[SMALLEST]; /* m = node of next least frequency */ + + s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */ + s->heap[--(s->heap_max)] = m; + + /* Create a new node father of n and m */ + tree[node].Freq = tree[n].Freq + tree[m].Freq; + s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ? + s->depth[n] : s->depth[m]) + 1); + tree[n].Dad = tree[m].Dad = (ush)node; +#ifdef DUMP_BL_TREE + if (tree == s->bl_tree) { + fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)", + node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq); + } +#endif + /* and insert the new node in the heap */ + s->heap[SMALLEST] = node++; + pqdownheap(s, tree, SMALLEST); + + } while (s->heap_len >= 2); + + s->heap[--(s->heap_max)] = s->heap[SMALLEST]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, (tree_desc *)desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes ((ct_data *)tree, max_code, s->bl_count); +} + +/* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ +local void scan_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + if (nextlen == 0) max_count = 138, min_count = 3; + tree[max_code+1].Len = (ush)0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + s->bl_tree[curlen].Freq += count; + } else if (curlen != 0) { + if (curlen != prevlen) s->bl_tree[curlen].Freq++; + s->bl_tree[REP_3_6].Freq++; + } else if (count <= 10) { + s->bl_tree[REPZ_3_10].Freq++; + } else { + s->bl_tree[REPZ_11_138].Freq++; + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ +local void send_tree (s, tree, max_code) + deflate_state *s; + ct_data *tree; /* the tree to be scanned */ + int max_code; /* and its largest code of non zero frequency */ +{ + int n; /* iterates over all tree elements */ + int prevlen = -1; /* last emitted length */ + int curlen; /* length of current code */ + int nextlen = tree[0].Len; /* length of next code */ + int count = 0; /* repeat count of the current code */ + int max_count = 7; /* max repeat count */ + int min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ /* guard already set */ + if (nextlen == 0) max_count = 138, min_count = 3; + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; nextlen = tree[n+1].Len; + if (++count < max_count && curlen == nextlen) { + continue; + } else if (count < min_count) { + do { send_code(s, curlen, s->bl_tree); } while (--count != 0); + + } else if (curlen != 0) { + if (curlen != prevlen) { + send_code(s, curlen, s->bl_tree); count--; + } + Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3); + + } else { + send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7); + } + count = 0; prevlen = curlen; + if (nextlen == 0) { + max_count = 138, min_count = 3; + } else if (curlen == nextlen) { + max_count = 6, min_count = 3; + } else { + max_count = 7, min_count = 4; + } + } +} + +/* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ +local int build_bl_tree(s) + deflate_state *s; +{ + int max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code); + scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, (tree_desc *)(&(s->bl_desc))); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { + if (s->bl_tree[bl_order[max_blindex]].Len != 0) break; + } + /* Update opt_len to include the bit length tree and counts */ + s->opt_len += 3*(max_blindex+1) + 5+5+4; + Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + s->opt_len, s->static_len)); + + return max_blindex; +} + +/* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ +local void send_all_trees(s, lcodes, dcodes, blcodes) + deflate_state *s; + int lcodes, dcodes, blcodes; /* number of codes for each tree */ +{ + int rank; /* index in bl_order */ + + Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + "too many codes"); + Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes-1, 5); + send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s->bl_tree[bl_order[rank]].Len, 3); + } + Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */ + Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */ + Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); +} + +/* =========================================================================== + * Send a stored block + */ +void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + send_bits(s, (STORED_BLOCK<<1)+last, 3); /* send block type */ +#ifdef DEBUG + s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L; + s->compressed_len += (stored_len + 4) << 3; +#endif + copy_block(s, buf, (unsigned)stored_len, 1); /* with header */ +} + +/* =========================================================================== + * Flush the bits in the bit buffer to pending output (leaves at most 7 bits) + */ +void ZLIB_INTERNAL _tr_flush_bits(s) + deflate_state *s; +{ + bi_flush(s); +} + +/* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ +void ZLIB_INTERNAL _tr_align(s) + deflate_state *s; +{ + send_bits(s, STATIC_TREES<<1, 3); + send_code(s, END_BLOCK, static_ltree); +#ifdef DEBUG + s->compressed_len += 10L; /* 3 for block type, 7 for EOB */ +#endif + bi_flush(s); +} + +/* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ +void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) + deflate_state *s; + charf *buf; /* input block, or NULL if too old */ + ulg stored_len; /* length of input block */ + int last; /* one if this is the last block for a file */ +{ + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + int max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s->level > 0) { + + /* Check if the file is binary or text */ + if (s->strm->data_type == Z_UNKNOWN) + s->strm->data_type = detect_data_type(s); + + /* Construct the literal and distance trees */ + build_tree(s, (tree_desc *)(&(s->l_desc))); + Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + + build_tree(s, (tree_desc *)(&(s->d_desc))); + Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s->opt_len+3+7)>>3; + static_lenb = (s->static_len+3+7)>>3; + + Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + s->last_lit)); + + if (static_lenb <= opt_lenb) opt_lenb = static_lenb; + + } else { + Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + +#ifdef FORCE_STORED + if (buf != (char*)0) { /* force stored block */ +#else + if (stored_len+4 <= opt_lenb && buf != (char*)0) { + /* 4: two words for the lengths */ +#endif + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + +#ifdef FORCE_STATIC + } else if (static_lenb >= 0) { /* force static trees */ +#else + } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) { +#endif + send_bits(s, (STATIC_TREES<<1)+last, 3); + compress_block(s, (const ct_data *)static_ltree, + (const ct_data *)static_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->static_len; +#endif + } else { + send_bits(s, (DYN_TREES<<1)+last, 3); + send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, + max_blindex+1); + compress_block(s, (const ct_data *)s->dyn_ltree, + (const ct_data *)s->dyn_dtree); +#ifdef DEBUG + s->compressed_len += 3 + s->opt_len; +#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. + */ + init_block(s); + + if (last) { + bi_windup(s); +#ifdef DEBUG + s->compressed_len += 7; /* align on byte boundary */ +#endif + } + Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + s->compressed_len-7*last)); +} + +/* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ +int ZLIB_INTERNAL _tr_tally (s, dist, lc) + deflate_state *s; + unsigned dist; /* distance of matched string */ + unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ +{ + s->d_buf[s->last_lit] = (ush)dist; + s->l_buf[s->last_lit++] = (uch)lc; + if (dist == 0) { + /* lc is the unmatched char */ + s->dyn_ltree[lc].Freq++; + } else { + s->matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + Assert((ush)dist < (ush)MAX_DIST(s) && + (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++; + s->dyn_dtree[d_code(dist)].Freq++; + } + +#ifdef TRUNCATE_BLOCK + /* Try to guess if it is profitable to stop the current block here */ + if ((s->last_lit & 0x1fff) == 0 && s->level > 2) { + /* Compute an upper bound for the compressed length */ + ulg out_length = (ulg)s->last_lit*8L; + ulg in_length = (ulg)((long)s->strstart - s->block_start); + int dcode; + for (dcode = 0; dcode < D_CODES; dcode++) { + out_length += (ulg)s->dyn_dtree[dcode].Freq * + (5L+extra_dbits[dcode]); + } + out_length >>= 3; + Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + s->last_lit, in_length, out_length, + 100L - out_length*100L/in_length)); + if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1; + } +#endif + return (s->last_lit == s->lit_bufsize-1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ +} + +/* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ +local void compress_block(s, ltree, dtree) + deflate_state *s; + const ct_data *ltree; /* literal tree */ + const ct_data *dtree; /* distance tree */ +{ + unsigned dist; /* distance of matched string */ + int lc; /* match length or unmatched char (if dist == 0) */ + unsigned lx = 0; /* running index in l_buf */ + unsigned code; /* the code to send */ + int extra; /* number of extra bits to send */ + + if (s->last_lit != 0) do { + dist = s->d_buf[lx]; + lc = s->l_buf[lx++]; + if (dist == 0) { + send_code(s, lc, ltree); /* send a literal byte */ + Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code+LITERALS+1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra != 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra != 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + "pendingBuf overflow"); + + } while (lx < s->last_lit); + + send_code(s, END_BLOCK, ltree); +} + +/* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ +local int detect_data_type(s) + deflate_state *s; +{ + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + unsigned long black_mask = 0xf3ffc07fUL; + int n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>= 1) + if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0)) + return Z_BINARY; + + /* Check for textual ("white-listed") bytes. */ + if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0 + || s->dyn_ltree[13].Freq != 0) + return Z_TEXT; + for (n = 32; n < LITERALS; n++) + if (s->dyn_ltree[n].Freq != 0) + return Z_TEXT; + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY; +} + +/* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ +local unsigned bi_reverse(code, len) + unsigned code; /* the value to invert */ + int len; /* its bit length */ +{ + register unsigned res = 0; + do { + res |= code & 1; + code >>= 1, res <<= 1; + } while (--len > 0); + return res >> 1; +} + +/* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ +local void bi_flush(s) + deflate_state *s; +{ + if (s->bi_valid == 16) { + put_short(s, s->bi_buf); + s->bi_buf = 0; + s->bi_valid = 0; + } else if (s->bi_valid >= 8) { + put_byte(s, (Byte)s->bi_buf); + s->bi_buf >>= 8; + s->bi_valid -= 8; + } +} + +/* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ +local void bi_windup(s) + deflate_state *s; +{ + if (s->bi_valid > 8) { + put_short(s, s->bi_buf); + } else if (s->bi_valid > 0) { + put_byte(s, (Byte)s->bi_buf); + } + s->bi_buf = 0; + s->bi_valid = 0; +#ifdef DEBUG + s->bits_sent = (s->bits_sent+7) & ~7; +#endif +} + +/* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ +local void copy_block(s, buf, len, header) + deflate_state *s; + charf *buf; /* the input data */ + unsigned len; /* its length */ + int header; /* true if block header must be written */ +{ + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, (ush)len); + put_short(s, (ush)~len); +#ifdef DEBUG + s->bits_sent += 2*16; +#endif + } +#ifdef DEBUG + s->bits_sent += (ulg)len<<3; +#endif + while (len--) { + put_byte(s, *buf++); + } +} diff --git a/zlib/trees.h b/zlib/trees.h new file mode 100644 index 00000000..d35639d8 --- /dev/null +++ b/zlib/trees.h @@ -0,0 +1,128 @@ +/* header created automatically with -DGEN_TREES_H */ + +local const ct_data static_ltree[L_CODES+2] = { +{{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}}, +{{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}}, +{{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}}, +{{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}}, +{{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}}, +{{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}}, +{{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}}, +{{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}}, +{{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}}, +{{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}}, +{{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}}, +{{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}}, +{{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}}, +{{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}}, +{{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}}, +{{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}}, +{{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}}, +{{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}}, +{{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}}, +{{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}}, +{{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}}, +{{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}}, +{{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}}, +{{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}}, +{{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}}, +{{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}}, +{{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}}, +{{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}}, +{{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}}, +{{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}}, +{{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}}, +{{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}}, +{{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}}, +{{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}}, +{{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}}, +{{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}}, +{{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}}, +{{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}}, +{{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}}, +{{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}}, +{{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}}, +{{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}}, +{{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}}, +{{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}}, +{{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}}, +{{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}}, +{{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}}, +{{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}}, +{{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}}, +{{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}}, +{{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}}, +{{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}}, +{{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}}, +{{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}}, +{{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}}, +{{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}}, +{{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}}, +{{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}} +}; + +local const ct_data static_dtree[D_CODES] = { +{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}}, +{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}}, +{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}}, +{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}}, +{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}}, +{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}} +}; + +const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = { + 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, + 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, +10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, +11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, +12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, +13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, +14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, +15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, +18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, +28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, +29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29 +}; + +const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= { + 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, +13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, +17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, +19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, +21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, +22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, +23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, +25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, +26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, +27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 +}; + +local const int base_length[LENGTH_CODES] = { +0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, +64, 80, 96, 112, 128, 160, 192, 224, 0 +}; + +local const int base_dist[D_CODES] = { + 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, + 32, 48, 64, 96, 128, 192, 256, 384, 512, 768, + 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 +}; + diff --git a/zlib/z_crc32.c b/zlib/z_crc32.c deleted file mode 100644 index 4e7a2f77..00000000 --- a/zlib/z_crc32.c +++ /dev/null @@ -1,425 +0,0 @@ -/* crc32.c -- compute the CRC-32 of a data stream - * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler - * For conditions of distribution and use, see copyright notice in zlib.h - * - * Thanks to Rodney Brown for his contribution of faster - * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing - * tables for updating the shift register in one step with three exclusive-ors - * instead of four steps with four exclusive-ors. This results in about a - * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3. - */ - -/* @(#) $Id$ */ - -/* - Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore - protection on the static variables used to control the first-use generation - of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should - first call get_crc_table() to initialize the tables before allowing more than - one thread to use crc32(). - - DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out z_crc32.h. - */ - -#ifdef MAKECRCH -# include -# ifndef DYNAMIC_CRC_TABLE -# define DYNAMIC_CRC_TABLE -# endif /* !DYNAMIC_CRC_TABLE */ -#endif /* MAKECRCH */ - -#include "zutil.h" /* for STDC and FAR definitions */ - -#define local static - -/* Definitions for doing the crc four data bytes at a time. */ -#if !defined(NOBYFOUR) && defined(Z_U4) -# define BYFOUR -#endif -#ifdef BYFOUR - local unsigned long crc32_little OF((unsigned long, - const unsigned char FAR *, unsigned)); - local unsigned long crc32_big OF((unsigned long, - const unsigned char FAR *, unsigned)); -# define TBLS 8 -#else -# define TBLS 1 -#endif /* BYFOUR */ - -/* Local functions for crc concatenation */ -local unsigned long gf2_matrix_times OF((unsigned long *mat, - unsigned long vec)); -local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat)); -local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2)); - - -#ifdef DYNAMIC_CRC_TABLE - -local volatile int crc_table_empty = 1; -local z_crc_t FAR crc_table[TBLS][256]; -local void make_crc_table OF((void)); -#ifdef MAKECRCH - local void write_table OF((FILE *, const z_crc_t FAR *)); -#endif /* MAKECRCH */ -/* - Generate tables for a byte-wise 32-bit CRC calculation on the polynomial: - x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1. - - Polynomials over GF(2) are represented in binary, one bit per coefficient, - with the lowest powers in the most significant bit. Then adding polynomials - is just exclusive-or, and multiplying a polynomial by x is a right shift by - one. If we call the above polynomial p, and represent a byte as the - polynomial q, also with the lowest power in the most significant bit (so the - byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p, - where a mod b means the remainder after dividing a by b. - - This calculation is done using the shift-register method of multiplying and - taking the remainder. The register is initialized to zero, and for each - incoming bit, x^32 is added mod p to the register if the bit is a one (where - x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by - x (which is shifting right by one and adding x^32 mod p if the bit shifted - out is a one). We start with the highest power (least significant bit) of - q and repeat for all eight bits of q. - - The first table is simply the CRC of all possible eight bit values. This is - all the information needed to generate CRCs on data a byte at a time for all - combinations of CRC register values and incoming bytes. The remaining tables - allow for word-at-a-time CRC calculation for both big-endian and little- - endian machines, where a word is four bytes. -*/ -local void make_crc_table() -{ - z_crc_t c; - int n, k; - z_crc_t poly; /* polynomial exclusive-or pattern */ - /* terms of polynomial defining this crc (except x^32): */ - static volatile int first = 1; /* flag to limit concurrent making */ - static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26}; - - /* See if another task is already doing this (not thread-safe, but better - than nothing -- significantly reduces duration of vulnerability in - case the advice about DYNAMIC_CRC_TABLE is ignored) */ - if (first) { - first = 0; - - /* make exclusive-or pattern from polynomial (0xedb88320UL) */ - poly = 0; - for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++) - poly |= (z_crc_t)1 << (31 - p[n]); - - /* generate a crc for every 8-bit value */ - for (n = 0; n < 256; n++) { - c = (z_crc_t)n; - for (k = 0; k < 8; k++) - c = c & 1 ? poly ^ (c >> 1) : c >> 1; - crc_table[0][n] = c; - } - -#ifdef BYFOUR - /* generate crc for each value followed by one, two, and three zeros, - and then the byte reversal of those as well as the first table */ - for (n = 0; n < 256; n++) { - c = crc_table[0][n]; - crc_table[4][n] = ZSWAP32(c); - for (k = 1; k < 4; k++) { - c = crc_table[0][c & 0xff] ^ (c >> 8); - crc_table[k][n] = c; - crc_table[k + 4][n] = ZSWAP32(c); - } - } -#endif /* BYFOUR */ - - crc_table_empty = 0; - } - else { /* not first */ - /* wait for the other guy to finish (not efficient, but rare) */ - while (crc_table_empty) - ; - } - -#ifdef MAKECRCH - /* write out CRC tables to z_crc32.h */ - { - FILE *out; - - out = fopen("z_crc32.h", "w"); - if (out == NULL) return; - fprintf(out, "/* z_crc32.h -- tables for rapid CRC calculation\n"); - fprintf(out, " * Generated automatically by crc32.c\n */\n\n"); - fprintf(out, "local const z_crc_t FAR "); - fprintf(out, "crc_table[TBLS][256] =\n{\n {\n"); - write_table(out, crc_table[0]); -# ifdef BYFOUR - fprintf(out, "#ifdef BYFOUR\n"); - for (k = 1; k < 8; k++) { - fprintf(out, " },\n {\n"); - write_table(out, crc_table[k]); - } - fprintf(out, "#endif\n"); -# endif /* BYFOUR */ - fprintf(out, " }\n};\n"); - fclose(out); - } -#endif /* MAKECRCH */ -} - -#ifdef MAKECRCH -local void write_table(out, table) - FILE *out; - const z_crc_t FAR *table; -{ - int n; - - for (n = 0; n < 256; n++) - fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", - (unsigned long)(table[n]), - n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", ")); -} -#endif /* MAKECRCH */ - -#else /* !DYNAMIC_CRC_TABLE */ -/* ======================================================================== - * Tables of CRC-32s of all single-byte values, made by make_crc_table(). - */ -#include "z_crc32.h" -#endif /* DYNAMIC_CRC_TABLE */ - -/* ========================================================================= - * This function can be used by asm versions of crc32() - */ -const z_crc_t FAR * ZEXPORT get_crc_table() -{ -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - return (const z_crc_t FAR *)crc_table; -} - -/* ========================================================================= */ -#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8) -#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1 - -/* ========================================================================= */ -unsigned long ZEXPORT crc32(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - uInt len; -{ - if (buf == Z_NULL) return 0UL; - -#ifdef DYNAMIC_CRC_TABLE - if (crc_table_empty) - make_crc_table(); -#endif /* DYNAMIC_CRC_TABLE */ - -#ifdef BYFOUR - if (sizeof(void *) == sizeof(ptrdiff_t)) { - z_crc_t endian; - - endian = 1; - if (*((unsigned char *)(&endian))) - return crc32_little(crc, buf, len); - else - return crc32_big(crc, buf, len); - } -#endif /* BYFOUR */ - crc = crc ^ 0xffffffffUL; - while (len >= 8) { - DO8; - len -= 8; - } - if (len) do { - DO1; - } while (--len); - return crc ^ 0xffffffffUL; -} - -#ifdef BYFOUR - -/* ========================================================================= */ -#define DOLIT4 c ^= *buf4++; \ - c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \ - crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24] -#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4 - -/* ========================================================================= */ -local unsigned long crc32_little(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register z_crc_t c; - register const z_crc_t FAR *buf4; - - c = (z_crc_t)crc; - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - len--; - } - - buf4 = (const z_crc_t FAR *)(const void FAR *)buf; - while (len >= 32) { - DOLIT32; - len -= 32; - } - while (len >= 4) { - DOLIT4; - len -= 4; - } - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8); - } while (--len); - c = ~c; - return (unsigned long)c; -} - -/* ========================================================================= */ -#define DOBIG4 c ^= *++buf4; \ - c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \ - crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24] -#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4 - -/* ========================================================================= */ -local unsigned long crc32_big(crc, buf, len) - unsigned long crc; - const unsigned char FAR *buf; - unsigned len; -{ - register z_crc_t c; - register const z_crc_t FAR *buf4; - - c = ZSWAP32((z_crc_t)crc); - c = ~c; - while (len && ((ptrdiff_t)buf & 3)) { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - len--; - } - - buf4 = (const z_crc_t FAR *)(const void FAR *)buf; - buf4--; - while (len >= 32) { - DOBIG32; - len -= 32; - } - while (len >= 4) { - DOBIG4; - len -= 4; - } - buf4++; - buf = (const unsigned char FAR *)buf4; - - if (len) do { - c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8); - } while (--len); - c = ~c; - return (unsigned long)(ZSWAP32(c)); -} - -#endif /* BYFOUR */ - -#define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */ - -/* ========================================================================= */ -local unsigned long gf2_matrix_times(mat, vec) - unsigned long *mat; - unsigned long vec; -{ - unsigned long sum; - - sum = 0; - while (vec) { - if (vec & 1) - sum ^= *mat; - vec >>= 1; - mat++; - } - return sum; -} - -/* ========================================================================= */ -local void gf2_matrix_square(square, mat) - unsigned long *square; - unsigned long *mat; -{ - int n; - - for (n = 0; n < GF2_DIM; n++) - square[n] = gf2_matrix_times(mat, mat[n]); -} - -/* ========================================================================= */ -local uLong crc32_combine_(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off64_t len2; -{ - int n; - unsigned long row; - unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */ - unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */ - - /* degenerate case (also disallow negative lengths) */ - if (len2 <= 0) - return crc1; - - /* put operator for one zero bit in odd */ - odd[0] = 0xedb88320UL; /* CRC-32 polynomial */ - row = 1; - for (n = 1; n < GF2_DIM; n++) { - odd[n] = row; - row <<= 1; - } - - /* put operator for two zero bits in even */ - gf2_matrix_square(even, odd); - - /* put operator for four zero bits in odd */ - gf2_matrix_square(odd, even); - - /* apply len2 zeros to crc1 (first square will put the operator for one - zero byte, eight zero bits, in even) */ - do { - /* apply zeros operator for this bit of len2 */ - gf2_matrix_square(even, odd); - if (len2 & 1) - crc1 = gf2_matrix_times(even, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - if (len2 == 0) - break; - - /* another iteration of the loop with odd and even swapped */ - gf2_matrix_square(odd, even); - if (len2 & 1) - crc1 = gf2_matrix_times(odd, crc1); - len2 >>= 1; - - /* if no more bits set, then done */ - } while (len2 != 0); - - /* return combined crc */ - crc1 ^= crc2; - return crc1; -} - -/* ========================================================================= */ -uLong ZEXPORT crc32_combine(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off_t len2; -{ - return crc32_combine_(crc1, crc2, len2); -} - -uLong ZEXPORT crc32_combine64(crc1, crc2, len2) - uLong crc1; - uLong crc2; - z_off64_t len2; -{ - return crc32_combine_(crc1, crc2, len2); -} diff --git a/zlib/z_crc32.h b/zlib/z_crc32.h deleted file mode 100644 index 9e0c7781..00000000 --- a/zlib/z_crc32.h +++ /dev/null @@ -1,441 +0,0 @@ -/* crc32.h -- tables for rapid CRC calculation - * Generated automatically by crc32.c - */ - -local const z_crc_t FAR crc_table[TBLS][256] = -{ - { - 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, - 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, - 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, - 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, - 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, - 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, - 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, - 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, - 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, - 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, - 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, - 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, - 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, - 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, - 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, - 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, - 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, - 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, - 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, - 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, - 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, - 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, - 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, - 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, - 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, - 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, - 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, - 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, - 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, - 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, - 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, - 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, - 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, - 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, - 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, - 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, - 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, - 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, - 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, - 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, - 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, - 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, - 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, - 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, - 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, - 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, - 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, - 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, - 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, - 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, - 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, - 0x2d02ef8dUL -#ifdef BYFOUR - }, - { - 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL, - 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL, - 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL, - 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL, - 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL, - 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL, - 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL, - 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL, - 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL, - 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL, - 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL, - 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL, - 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL, - 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL, - 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL, - 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL, - 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL, - 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL, - 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL, - 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL, - 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL, - 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL, - 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL, - 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL, - 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL, - 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL, - 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL, - 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL, - 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL, - 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL, - 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL, - 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL, - 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL, - 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL, - 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL, - 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL, - 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL, - 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL, - 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL, - 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL, - 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL, - 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL, - 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL, - 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL, - 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL, - 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL, - 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL, - 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL, - 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL, - 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL, - 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL, - 0x9324fd72UL - }, - { - 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL, - 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL, - 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL, - 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL, - 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL, - 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL, - 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL, - 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL, - 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL, - 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL, - 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL, - 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL, - 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL, - 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL, - 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL, - 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL, - 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL, - 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL, - 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL, - 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL, - 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL, - 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL, - 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL, - 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL, - 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL, - 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL, - 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL, - 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL, - 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL, - 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL, - 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL, - 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL, - 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL, - 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL, - 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL, - 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL, - 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL, - 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL, - 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL, - 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL, - 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL, - 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL, - 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL, - 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL, - 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL, - 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL, - 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL, - 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL, - 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL, - 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL, - 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL, - 0xbe9834edUL - }, - { - 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL, - 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL, - 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL, - 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL, - 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL, - 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL, - 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL, - 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL, - 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL, - 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL, - 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL, - 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL, - 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL, - 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL, - 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL, - 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL, - 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL, - 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL, - 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL, - 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL, - 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL, - 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL, - 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL, - 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL, - 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL, - 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL, - 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL, - 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL, - 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL, - 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL, - 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL, - 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL, - 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL, - 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL, - 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL, - 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL, - 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL, - 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL, - 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL, - 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL, - 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL, - 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL, - 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL, - 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL, - 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL, - 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL, - 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL, - 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL, - 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL, - 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL, - 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL, - 0xde0506f1UL - }, - { - 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL, - 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL, - 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL, - 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL, - 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL, - 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL, - 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL, - 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL, - 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL, - 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL, - 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL, - 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL, - 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL, - 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL, - 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL, - 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL, - 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL, - 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL, - 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL, - 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL, - 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL, - 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL, - 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL, - 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL, - 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL, - 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL, - 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL, - 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL, - 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL, - 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL, - 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL, - 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL, - 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL, - 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL, - 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL, - 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL, - 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL, - 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL, - 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL, - 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL, - 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL, - 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL, - 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL, - 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL, - 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL, - 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL, - 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL, - 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL, - 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL, - 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL, - 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL, - 0x8def022dUL - }, - { - 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL, - 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL, - 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL, - 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL, - 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL, - 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL, - 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL, - 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL, - 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL, - 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL, - 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL, - 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL, - 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL, - 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL, - 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL, - 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL, - 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL, - 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL, - 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL, - 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL, - 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL, - 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL, - 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL, - 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL, - 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL, - 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL, - 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL, - 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL, - 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL, - 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL, - 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL, - 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL, - 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL, - 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL, - 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL, - 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL, - 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL, - 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL, - 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL, - 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL, - 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL, - 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL, - 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL, - 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL, - 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL, - 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL, - 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL, - 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL, - 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL, - 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL, - 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL, - 0x72fd2493UL - }, - { - 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL, - 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL, - 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL, - 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL, - 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL, - 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL, - 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL, - 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL, - 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL, - 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL, - 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL, - 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL, - 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL, - 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL, - 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL, - 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL, - 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL, - 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL, - 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL, - 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL, - 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL, - 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL, - 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL, - 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL, - 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL, - 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL, - 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL, - 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL, - 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL, - 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL, - 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL, - 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL, - 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL, - 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL, - 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL, - 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL, - 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL, - 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL, - 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL, - 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL, - 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL, - 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL, - 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL, - 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL, - 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL, - 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL, - 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL, - 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL, - 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL, - 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL, - 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL, - 0xed3498beUL - }, - { - 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL, - 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL, - 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL, - 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL, - 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL, - 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL, - 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL, - 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL, - 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL, - 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL, - 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL, - 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL, - 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL, - 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL, - 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL, - 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL, - 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL, - 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL, - 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL, - 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL, - 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL, - 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL, - 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL, - 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL, - 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL, - 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL, - 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL, - 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL, - 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL, - 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL, - 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL, - 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL, - 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL, - 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL, - 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL, - 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL, - 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL, - 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL, - 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL, - 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL, - 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL, - 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL, - 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL, - 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL, - 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL, - 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL, - 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL, - 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL, - 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL, - 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL, - 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL, - 0xf10605deUL -#endif - } -}; From fb22897415bd3892374bb46012cf4e9d5c4cf965 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 29 Apr 2015 17:59:33 +0200 Subject: [PATCH 076/132] fpga_compress: interleave (combine) fpga_lf.bit and fpga_hf.bit before compression. fpga_loader.c: change to unweave fpga_lf and fpga_hf accordingly prepare fpga_compress, fpga_loader and Makefile to handle more than two FPGA config files revert removal of fullimage Makefile target. Remove osimage instead. --- Makefile | 4 +- armsrc/Makefile | 16 ++--- armsrc/fpgaloader.c | 82 ++++++++++++----------- armsrc/fpgaloader.h | 7 ++ armsrc/ldscript | 3 +- client/fpga_compress.c | 145 +++++++++++++++++++++++++++++------------ include/proxmark3.h | 4 -- recovery/Makefile | 8 +-- 8 files changed, 170 insertions(+), 99 deletions(-) diff --git a/Makefile b/Makefile index afbaad9e..0e065b41 100644 --- a/Makefile +++ b/Makefile @@ -31,10 +31,10 @@ client: client/all flash-bootrom: bootrom/obj/bootrom.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) -b $(subst /,$(PATHSEP),$<) -flash-os: armsrc/obj/osimage.elf $(FLASH_TOOL) +flash-os: armsrc/obj/fullimage.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$<) -flash-all: bootrom/obj/bootrom.elf armsrc/obj/osimage.elf $(FLASH_TOOL) +flash-all: bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) -b $(subst /,$(PATHSEP),$(filter-out $(FLASH_TOOL),$^)) newtarbin: diff --git a/armsrc/Makefile b/armsrc/Makefile index 9efbb1ad..b1ce4e4d 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -22,6 +22,9 @@ SRC_ISO14443b = iso14443.c SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c +#the FPGA bitstream files. Note: order matters! +FPGA_BITSTREAMS = fpga_lf.bit fpga_hf.bit + #the zlib source files required for decompressing the fpga config at run time SRC_ZLIB = inflate.c inffast.c inftrees.c adler32.c zutil.c #additional defines required to compile zlib @@ -67,16 +70,13 @@ FPGA_COMPRESSOR = ../client/fpga_compress all: $(OBJS) -$(OBJDIR)/fpga_lf.o: $(OBJDIR)/fpga_lf.bit.z - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_lf_bit_z_start=_binary_fpga_lf_bit_start --redefine-sym _binary_obj_fpga_lf_bit_z_end=_binary_fpga_lf_bit_end --prefix-sections=fpga_lf_bit $^ $@ +$(OBJDIR)/fpga_all.o: $(OBJDIR)/fpga_all.bit.z + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --prefix-sections=fpga_all_bit $^ $@ -$(OBJDIR)/fpga_hf.o: $(OBJDIR)/fpga_hf.bit.z - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary_obj_fpga_hf_bit_z_start=_binary_fpga_hf_bit_start --redefine-sym _binary_obj_fpga_hf_bit_z_end=_binary_fpga_hf_bit_end --prefix-sections=fpga_hf_bit $^ $@ - -$(OBJDIR)/%.bit.z: %.bit $(FPGA_COMPRESSOR) +$(OBJDIR)/fpga_all.bit.z: $(FPGA_BITSTREAMS) $(FPGA_COMPRESSOR) $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ -$(OBJDIR)/osimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_lf.o $(OBJDIR)/fpga_hf.o $(THUMBOBJ) $(ARMOBJ) +$(OBJDIR)/fullimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_all.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) tarbin: $(OBJS) @@ -95,6 +95,6 @@ clean: help: @echo Multi-OS Makefile, you are running on $(DETECTED_OS) @echo Possible targets: - @echo + all - Build the OS image $(OBJDIR)/osimage.s19 + @echo + all - Build the full image $(OBJDIR)/fullimage.s19 @echo + clean - Clean $(OBJDIR) diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c index 573aac3a..a2c9d1e4 100644 --- a/armsrc/fpgaloader.c +++ b/armsrc/fpgaloader.c @@ -26,13 +26,15 @@ extern void Dbprintf(const char *fmt, ...); static int downloaded_bitstream = FPGA_BITSTREAM_ERR; // this is where the bitstreams are located in memory: -extern uint8_t _binary_fpga_lf_bit_start, _binary_fpga_lf_bit_end; -extern uint8_t _binary_fpga_hf_bit_start, _binary_fpga_hf_bit_end; +extern uint8_t _binary_obj_fpga_all_bit_z_start, _binary_obj_fpga_all_bit_z_end; + static uint8_t *fpga_image_ptr = NULL; +static uint32_t uncompressed_bytes_cnt; static const uint8_t _bitparse_fixed_header[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x00, 0x00, 0x01}; #define FPGA_BITSTREAM_FIXED_HEADER_SIZE sizeof(_bitparse_fixed_header) -#define OUTPUT_BUFFER_LEN 80 +#define OUTPUT_BUFFER_LEN 80 +#define FPGA_INTERLEAVE_SIZE 288 //----------------------------------------------------------------------------- // Set up the Serial Peripheral Interface as master @@ -171,7 +173,7 @@ bool FpgaSetupSscDma(uint8_t *buf, int len) } -static int get_from_fpga_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) +static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) { if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data compressed_fpga_stream->next_out = output_buffer; @@ -186,10 +188,24 @@ static int get_from_fpga_stream(z_streamp compressed_fpga_stream, uint8_t *outpu } } + uncompressed_bytes_cnt++; + return *fpga_image_ptr++; } +static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +{ + while((uncompressed_bytes_cnt / FPGA_INTERLEAVE_SIZE) % FPGA_BITSTREAM_MAX != (bitstream_version - 1)) { + // skip undesired data belonging to other bitstream_versions + get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer); + } + + return get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer); + +} + + static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size) { Dbprintf("zlib requested %d bytes", items*size); @@ -207,22 +223,12 @@ static void fpga_inflate_free(voidpf opaque, voidpf address) static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; - uint8_t *fpga_image_start; - uint32_t fpga_image_size; - if (bitstream_version == FPGA_BITSTREAM_LF) { - fpga_image_start = &_binary_fpga_lf_bit_start; - fpga_image_size = (uint32_t)&_binary_fpga_lf_bit_end - (uint32_t)&_binary_fpga_lf_bit_start; - } else if (bitstream_version == FPGA_BITSTREAM_HF) { - fpga_image_start = &_binary_fpga_hf_bit_start; - fpga_image_size = (uint32_t)&_binary_fpga_hf_bit_end - (uint32_t)&_binary_fpga_hf_bit_start; - } else { - return false; - } - + uncompressed_bytes_cnt = 0; + // initialize z_stream structure for inflate: - compressed_fpga_stream->next_in = fpga_image_start; - compressed_fpga_stream->avail_in = fpga_image_size; + compressed_fpga_stream->next_in = &_binary_obj_fpga_all_bit_z_start; + compressed_fpga_stream->avail_in = &_binary_obj_fpga_all_bit_z_start - &_binary_obj_fpga_all_bit_z_end; compressed_fpga_stream->next_out = output_buffer; compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; compressed_fpga_stream->zalloc = &fpga_inflate_malloc; @@ -233,7 +239,7 @@ static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_s fpga_image_ptr = output_buffer; for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { - header[i] = get_from_fpga_stream(compressed_fpga_stream, output_buffer); + header[i] = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); } // Check for a valid .bit file (starts with _bitparse_fixed_header) @@ -259,7 +265,7 @@ static void DownloadFPGA_byte(unsigned char w) } // Download the fpga image starting at current stream position with length FpgaImageLen bytes -static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { Dbprintf("DownloadFPGA(len: %d)", FpgaImageLen); @@ -316,7 +322,7 @@ static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uin } for(i = 0; i < FpgaImageLen; i++) { - int b = get_from_fpga_stream(compressed_fpga_stream, output_buffer); + int b = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); if (b < 0) { Dbprintf("Error %d during FpgaDownload", b); break; @@ -348,13 +354,13 @@ static void DownloadFPGA(int FpgaImageLen, z_streamp compressed_fpga_stream, uin * (big endian), bytes content. Except for section 'e' which has 4 bytes * length. */ -static int bitparse_find_section(char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +static int bitparse_find_section(int bitstream_version, char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { int result = 0; #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section uint16_t numbytes = 0; while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) { - char current_name = get_from_fpga_stream(compressed_fpga_stream, output_buffer); + char current_name = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); numbytes++; unsigned int current_length = 0; if(current_name < 'a' || current_name > 'e') { @@ -365,12 +371,12 @@ static int bitparse_find_section(char section_name, unsigned int *section_length switch(current_name) { case 'e': /* Four byte length field */ - current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 24; - current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 16; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 24; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 16; numbytes += 2; default: /* Fall through, two byte length field */ - current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 8; - current_length += get_from_fpga_stream(compressed_fpga_stream, output_buffer) << 0; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 8; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 0; numbytes += 2; } @@ -387,7 +393,7 @@ static int bitparse_find_section(char section_name, unsigned int *section_length } for (uint16_t i = 0; i < current_length && numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH; i++) { - get_from_fpga_stream(compressed_fpga_stream, output_buffer); + get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); numbytes++; } } @@ -414,8 +420,8 @@ void FpgaDownloadAndGo(int bitstream_version) } unsigned int bitstream_length; - if(bitparse_find_section('e', &bitstream_length, &compressed_fpga_stream, output_buffer)) { - DownloadFPGA(bitstream_length, &compressed_fpga_stream, output_buffer); + if(bitparse_find_section(bitstream_version, 'e', &bitstream_length, &compressed_fpga_stream, output_buffer)) { + DownloadFPGA(bitstream_version, bitstream_length, &compressed_fpga_stream, output_buffer); downloaded_bitstream = bitstream_version; } @@ -437,9 +443,9 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) return; } - if(bitparse_find_section('a', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { + if(bitparse_find_section(bitstream_version, 'a', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); + char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } @@ -450,30 +456,30 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) strncat(dst, "HF ", len-1); } strncat(dst, "FPGA image built", len-1); - if(bitparse_find_section('b', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { + if(bitparse_find_section(bitstream_version, 'b', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { strncat(dst, " for ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); + char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } } strncat(dst, tempstr, len-1); } - if(bitparse_find_section('c', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { + if(bitparse_find_section(bitstream_version, 'c', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { strncat(dst, " on ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); + char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } } strncat(dst, tempstr, len-1); } - if(bitparse_find_section('d', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { + if(bitparse_find_section(bitstream_version, 'd', &fpga_info_len, &compressed_fpga_stream, output_buffer)) { strncat(dst, " at ", len-1); for (uint16_t i = 0; i < fpga_info_len; i++) { - char c = (char)get_from_fpga_stream(&compressed_fpga_stream, output_buffer); + char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer); if (i < sizeof(tempstr)) { tempstr[i] = c; } diff --git a/armsrc/fpgaloader.h b/armsrc/fpgaloader.h index 6981b216..0bad3809 100644 --- a/armsrc/fpgaloader.h +++ b/armsrc/fpgaloader.h @@ -21,6 +21,13 @@ bool FpgaSetupSscDma(uint8_t *buf, int len); #define FpgaEnableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; void SetAdcMuxFor(uint32_t whichGpio); +// definitions for multiple FPGA config files support +#define FPGA_BITSTREAM_MAX 2 // the total number of FPGA bitstreams (configs) +#define FPGA_BITSTREAM_ERR 0 +#define FPGA_BITSTREAM_LF 1 +#define FPGA_BITSTREAM_HF 2 + + // Definitions for the FPGA commands. #define FPGA_CMD_SET_CONFREG (1<<12) #define FPGA_CMD_SET_DIVISOR (2<<12) diff --git a/armsrc/ldscript b/armsrc/ldscript index ce7a330e..6175564d 100644 --- a/armsrc/ldscript +++ b/armsrc/ldscript @@ -34,8 +34,7 @@ SECTIONS .rodata : { *(.rodata) *(.rodata.*) - *(fpga_lf_bit.data) - *(fpga_hf_bit.data) + *(fpga_all_bit.data) KEEP(*(.version_information)) } >osimage :text diff --git a/client/fpga_compress.c b/client/fpga_compress.c index db1ef81b..d4376ccc 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -10,19 +10,36 @@ #include #include #include +#include #include "zlib.h" #define MAX(a,b) ((a)>(b)?(a):(b)) // zlib configuration #define COMPRESS_LEVEL 9 // use best possible compression +#define COMPRESS_WINDOW_BITS 15 // default = 15 for a window of 2^15 = 32KBytes +#define COMPRESS_MEM_LEVEL 9 // determines the amount of memory allocated during compression. Default = 8. Must be < 9 +/* 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_NICE_LENGTH 258 +#define COMPRESS_MAX_CHAIN 8192 -#define FPGA_CONFIG_SIZE 42175 -static uint8_t fpga_config[FPGA_CONFIG_SIZE]; +#define FPGA_INTERLEAVE_SIZE 288 // (the FPGA's internal config frame size is 288 bits. Interleaving with 288 bytes should give best compression) +#define FPGA_CONFIG_SIZE 42336 // our current fpga_[lh]f.bit files are 42175 bytes. Rounded up to next multiple of FPGA_INTERLEAVE_SIZE static void usage(char *argv0) { - fprintf(stderr, "Usage: %s \n\n", argv0); + fprintf(stderr, "Usage: %s ... \n\n", argv0); + fprintf(stderr, "Combines n FPGA bitstream files and compresses them into one.\n\n"); } @@ -40,40 +57,78 @@ static void fpga_deflate_free(voidpf opaque, voidpf address) } -int zlib_compress(FILE *infile, FILE *outfile) +static bool all_feof(FILE *infile[], uint8_t num_infiles) { - int i, ret; - z_stream compressed_fpga_stream; - - // read the input file into fpga_config[] and count occurrences of each symbol: - i = 0; - while(!feof(infile)) { - uint8_t c; - c = fgetc(infile); - fpga_config[i++] = c; - if (i > FPGA_CONFIG_SIZE+1) { - fprintf(stderr, "Input file too big (> %d bytes). This is probably not a PM3 FPGA config file.", FPGA_CONFIG_SIZE); - fclose(infile); - fclose(outfile); - return -1; + for (uint16_t i = 0; i < num_infiles; i++) { + if (!feof(infile[i])) { + return false; } } + + return true; +} + +int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) +{ + uint8_t *fpga_config; + uint32_t i; + int ret; + uint8_t c; + z_stream compressed_fpga_stream; + + fpga_config = malloc(num_infiles * FPGA_CONFIG_SIZE); + + // read the input files interleaving into fpga_config[] + i = 0; + do { + for(uint16_t j = 0; j < num_infiles; j++) { + for(uint16_t k = 0; k < FPGA_INTERLEAVE_SIZE; k++) { + c = fgetc(infile[j]); + if (!feof(infile[j])) fpga_config[i++] = c; else fpga_config[i++] = '\0'; + } + } + + if (i > num_infiles * FPGA_CONFIG_SIZE) { + fprintf(stderr, "Input files too big (total of %ld > %d bytes). These are probably not PM3 FPGA config files.", i, num_infiles*FPGA_CONFIG_SIZE); + for(uint16_t j = 0; j < num_infiles; j++) { + fclose(infile[j]); + } + return -1; + } + } while (!all_feof(infile, num_infiles)); + + fprintf(stderr, "Read a total of %ld bytes from %d files\n", i, num_infiles); + // initialize zlib structures compressed_fpga_stream.next_in = fpga_config; compressed_fpga_stream.avail_in = i; compressed_fpga_stream.zalloc = fpga_deflate_malloc; compressed_fpga_stream.zfree = fpga_deflate_free; + ret = deflateInit2(&compressed_fpga_stream, + COMPRESS_LEVEL, + Z_DEFLATED, + COMPRESS_WINDOW_BITS, + COMPRESS_MEM_LEVEL, + COMPRESS_STRATEGY); + // estimate the size of the compressed output unsigned int outsize_max = deflateBound(&compressed_fpga_stream, compressed_fpga_stream.avail_in); + fprintf(stderr, "Allocating %ld bytes for output file (estimated upper bound)\n", outsize_max); uint8_t *outbuf = malloc(outsize_max); compressed_fpga_stream.next_out = outbuf; compressed_fpga_stream.avail_out = outsize_max; - fprintf(stderr, "Allocated %d bytes for output file (estimated upper bound)\n", outsize_max); - ret = deflateInit(&compressed_fpga_stream, COMPRESS_LEVEL); - + + if (ret == Z_OK) { + ret = deflateTune(&compressed_fpga_stream, + COMPRESS_GOOD_LENGTH, + COMPRESS_MAX_LAZY, + COMPRESS_MAX_NICE_LENGTH, + COMPRESS_MAX_CHAIN); + } + if (ret == Z_OK) { ret = deflate(&compressed_fpga_stream, Z_FINISH); } @@ -84,8 +139,12 @@ int zlib_compress(FILE *infile, FILE *outfile) fprintf(stderr, "Error in deflate(): %d %s\n", ret, compressed_fpga_stream.msg); free(outbuf); deflateEnd(&compressed_fpga_stream); - fclose(infile); + for(uint16_t j = 0; j < num_infiles; j++) { + fclose(infile[j]); + } fclose(outfile); + free(infile); + free(fpga_config); return -1; } @@ -95,9 +154,13 @@ int zlib_compress(FILE *infile, FILE *outfile) free(outbuf); deflateEnd(&compressed_fpga_stream); - fclose(infile); + for(uint16_t j = 0; j < num_infiles; j++) { + fclose(infile[j]); + } fclose(outfile); - + free(infile); + free(fpga_config); + return 0; } @@ -106,29 +169,29 @@ int zlib_compress(FILE *infile, FILE *outfile) int main(int argc, char **argv) { - char *infilename; - char *outfilename; + FILE **infiles; + FILE *outfile; - if (argc != 3) { + if (argc == 1 || argc == 2) { usage(argv[0]); return -1; - } else { - infilename = argv[1]; - outfilename = argv[2]; - } + } + + infiles = calloc(argc-2, sizeof(FILE*)); + + for (uint16_t i = 0; i < argc-2; i++) { + infiles[i] = fopen(argv[i+1], "rb"); + if (infiles[i] == NULL) { + fprintf(stderr, "Error. Cannot open input file %s", argv[i+1]); + return -1; + } + } - FILE *infile = fopen(infilename, "rb"); - if (infile == NULL) { - fprintf(stderr, "Error. Cannot open input file %s", infilename); - return -1; - } - - FILE *outfile = fopen(outfilename, "wb"); + outfile = fopen(argv[argc-1], "wb"); if (outfile == NULL) { - fprintf(stderr, "Error. Cannot open output file %s", outfilename); - fclose(infile); + fprintf(stderr, "Error. Cannot open output file %s", argv[argc-1]); return -1; } - return zlib_compress(infile, outfile); + return zlib_compress(infiles, argc-2, outfile); } diff --git a/include/proxmark3.h b/include/proxmark3.h index b3530c64..4a59636e 100644 --- a/include/proxmark3.h +++ b/include/proxmark3.h @@ -61,10 +61,6 @@ #define SPI_FPGA_MODE 0 #define SPI_LCD_MODE 1 -#define FPGA_BITSTREAM_ERR 0 -#define FPGA_BITSTREAM_LF 1 -#define FPGA_BITSTREAM_HF 2 - #define TRUE 1 #define FALSE 0 diff --git a/recovery/Makefile b/recovery/Makefile index 4cf3f3a9..bb8e3a76 100644 --- a/recovery/Makefile +++ b/recovery/Makefile @@ -1,17 +1,17 @@ include ../common/Makefile.common -BINS = bootrom.bin osimage.bin proxmark3_recovery.bin +BINS = bootrom.bin fullimage.bin proxmark3_recovery.bin all: $(BINS) bootrom.bin: ../bootrom/obj/bootrom.elf $(OBJCOPY) --gap-fill=0xff --pad-to 0x00102000 -O binary $^ $@ -osimage.bin: ../armsrc/obj/osimage.elf +fullimage.bin: ../armsrc/obj/fullimage.elf $(OBJCOPY) --gap-fill=0xff -O binary $^ $@ -proxmark3_recovery.bin: bootrom.bin osimage.bin - cat bootrom.bin osimage.bin > $@ +proxmark3_recovery.bin: bootrom.bin fullimage.bin + cat bootrom.bin fullimage.bin > $@ clean: rm -f $(BINS) From 28b9facceaea4d2d4cb66ed240300157be42bcdc Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 30 Apr 2015 17:57:26 +0200 Subject: [PATCH 077/132] Tailor zlib to our needs: - disable support for fixed code blocks. Saves 2KByte code tables in ARM Flash memory --- armsrc/Makefile | 2 +- zlib/inflate.c | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/armsrc/Makefile b/armsrc/Makefile index b1ce4e4d..1771c8c4 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -28,7 +28,7 @@ FPGA_BITSTREAMS = fpga_lf.bit fpga_hf.bit #the zlib source files required for decompressing the fpga config at run time SRC_ZLIB = inflate.c inffast.c inftrees.c adler32.c zutil.c #additional defines required to compile zlib -ZLIB_CFLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP +ZLIB_CFLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED APP_CFLAGS += $(ZLIB_CFLAGS) # zlib includes: APP_CFLAGS += -I../zlib diff --git a/zlib/inflate.c b/zlib/inflate.c index 870f89bb..d2c666b0 100644 --- a/zlib/inflate.c +++ b/zlib/inflate.c @@ -92,7 +92,11 @@ #endif /* function prototypes */ +#ifdef ZLIB_PM3_TUNED +extern void Dbprintf(const char *fmt, ...); +#else local void fixedtables OF((struct inflate_state FAR *state)); +#endif local int updatewindow OF((z_streamp strm, const unsigned char FAR *end, unsigned copy)); #ifdef BUILDFIXED @@ -258,6 +262,7 @@ int value; used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ +#ifndef ZLIB_PM3_TUNED local void fixedtables(state) struct inflate_state FAR *state; { @@ -361,7 +366,7 @@ void makefixed() puts("\n };"); } #endif /* MAKEFIXED */ - +#endif /* ZLIB_PM3_TUNED */ /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called @@ -841,6 +846,10 @@ int flush; state->mode = STORED; break; case 1: /* fixed block */ +#ifdef ZLIB_PM3_TUNED + Dbprintf("FATAL error. Compressed FPGA files with fixed code blocks are not supported!"); + for(;;); +#else fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", state->last ? " (last)" : "")); @@ -849,6 +858,7 @@ int flush; DROPBITS(2); goto inf_leave; } +#endif break; case 2: /* dynamic block */ Tracev((stderr, "inflate: dynamic codes block%s\n", From 0fa01ec7da07559ab8ebbad1e4e9ec3ef2d85809 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Fri, 8 May 2015 08:17:40 +0200 Subject: [PATCH 078/132] Compress the .data section as well (saves another 4KBytes and comes for free) zlib tuning: prevent fpga_compress from generating fixed code blocks armsrc/Makefile: replace osimage with fullimage --- armsrc/Makefile | 24 +++++++++++++-- armsrc/appmain.c | 8 +++-- armsrc/ldscript | 5 ++-- armsrc/start.c | 66 +++++++++++++++++++++++++++++++++++++----- client/Makefile | 9 +++--- client/fpga_compress.c | 6 +++- zlib/trees.c | 7 +++-- 7 files changed, 103 insertions(+), 22 deletions(-) diff --git a/armsrc/Makefile b/armsrc/Makefile index 1771c8c4..8cd927d8 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -65,7 +65,7 @@ ARMSRC = fpgaloader.c \ # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common/Makefile.common -OBJS = $(OBJDIR)/osimage.s19 +OBJS = $(OBJDIR)/fullimage.s19 FPGA_COMPRESSOR = ../client/fpga_compress all: $(OBJS) @@ -75,10 +75,28 @@ $(OBJDIR)/fpga_all.o: $(OBJDIR)/fpga_all.bit.z $(OBJDIR)/fpga_all.bit.z: $(FPGA_BITSTREAMS) $(FPGA_COMPRESSOR) $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ - -$(OBJDIR)/fullimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_all.o $(THUMBOBJ) $(ARMOBJ) + +$(OBJDIR)/fullimage.stage1.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_all.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) +$(OBJDIR)/fullimage.nodata.bin: $(OBJDIR)/fullimage.stage1.elf + $(OBJCOPY) -O binary -I elf32-littlearm --remove-section .data $^ $@ + +$(OBJDIR)/fullimage.nodata.o: $(OBJDIR)/fullimage.nodata.bin + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --rename-section .data=stage1_image $^ $@ + +$(OBJDIR)/fullimage.data.bin: $(OBJDIR)/fullimage.stage1.elf + $(OBJCOPY) -O binary -I elf32-littlearm --only-section .data $^ $@ + +$(OBJDIR)/fullimage.data.bin.z: $(OBJDIR)/fullimage.data.bin $(FPGA_COMPRESSOR) + $(FPGA_COMPRESSOR) $(filter %.bin,$^) $@ + +$(OBJDIR)/fullimage.data.o: $(OBJDIR)/fullimage.data.bin.z + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --rename-section .data=compressed_data $^ $@ + +$(OBJDIR)/fullimage.elf: $(OBJDIR)/fullimage.nodata.o $(OBJDIR)/fullimage.data.o + $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ + tarbin: $(OBJS) $(TAR) $(TARFLAGS) ../proxmark3-$(platform)-bin.tar $(OBJS:%=armsrc/%) $(OBJS:%.s19=armsrc/%.elf) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 80ae4bc2..737873ad 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -310,7 +310,7 @@ void ReadMem(int addr) /* osimage version information is linked in */ extern struct version_information version_information; /* bootrom version information is pointed to from _bootphase1_version_pointer */ -extern char *_bootphase1_version_pointer, _flash_start, _flash_end, _bootrom_start, _bootrom_end, __os_size__; +extern char *_bootphase1_version_pointer, _flash_start, _flash_end, _bootrom_start, _bootrom_end, __data_src_start__; void SendVersion(void) { char temp[512]; /* Limited data payload in USB packets */ @@ -335,9 +335,11 @@ void SendVersion(void) DbpString(temp); FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp)); DbpString(temp); - + // Send Chip ID and used flash memory - cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), (uint32_t)&_bootrom_end - (uint32_t)&_bootrom_start + (uint32_t)&__os_size__, 0, NULL, 0); + uint32_t text_and_rodata_section_size = (uint32_t)&__data_src_start__ - (uint32_t)&_flash_start; + uint32_t compressed_data_section_size = common_area.arg1; + cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), text_and_rodata_section_size + compressed_data_section_size, 0, NULL, 0); } #ifdef WITH_LF diff --git a/armsrc/ldscript b/armsrc/ldscript index 6175564d..34da26bc 100644 --- a/armsrc/ldscript +++ b/armsrc/ldscript @@ -24,6 +24,7 @@ SECTIONS } >osimage :text .text : { + KEEP(*(stage1_image)) *(.text) *(.text.*) *(.eh_frame) @@ -36,11 +37,11 @@ SECTIONS *(.rodata.*) *(fpga_all_bit.data) KEEP(*(.version_information)) + . = ALIGN(8); } >osimage :text - . = ALIGN(4); - .data : { + KEEP(*(compressed_data)) *(.data) *(.data.*) *(.ramfunc) diff --git a/armsrc/start.c b/armsrc/start.c index d7332bda..f1e58ab0 100644 --- a/armsrc/start.c +++ b/armsrc/start.c @@ -11,23 +11,75 @@ #include "proxmark3.h" #include "apps.h" +#include "zlib.h" +#include "BigBuf.h" + +static uint8_t *next_free_memory; +extern struct common_area common_area; +extern char __data_src_start__, __data_start__, __data_end__, __bss_start__, __bss_end__; + + +static voidpf inflate_malloc(voidpf opaque, uInt items, uInt size) +{ + uint8_t *allocated_memory; + + allocated_memory = next_free_memory; + next_free_memory += items*size; + return allocated_memory; +} + + +static void inflate_free(voidpf opaque, voidpf address) +{ + // nothing to do + +} + +static void uncompress_data_section(void) +{ + z_stream data_section; + + next_free_memory = BigBuf_get_addr(); + + // initialize zstream structure + data_section.next_in = (uint8_t *) &__data_src_start__; + data_section.avail_in = &__data_end__ - &__data_start__; // uncompressed size. Wrong but doesn't matter. + data_section.next_out = (uint8_t *) &__data_start__; + data_section.avail_out = &__data_end__ - &__data_start__; // uncompressed size. Correct. + data_section.zalloc = &inflate_malloc; + data_section.zfree = &inflate_free; + data_section.opaque = NULL; + + // initialize zlib for inflate + inflateInit2(&data_section, 15); + + // uncompress data segment to RAM + inflate(&data_section, Z_FINISH); + + // save the size of the compressed data section + common_area.arg1 = data_section.total_in; +} + -extern char __data_start__, __data_src_start__, __data_end__, __bss_start__, __bss_end__; void __attribute__((section(".startos"))) Vector(void) { /* Stack should have been set up by the bootloader */ - char *src, *dst, *end; + // char *src; + char *dst, *end; + + uncompress_data_section(); /* Set up (that is: clear) BSS. */ dst = &__bss_start__; end = &__bss_end__; while(dst < end) *dst++ = 0; - /* Set up data segment: Copy from flash to ram */ - src = &__data_src_start__; - dst = &__data_start__; - end = &__data_end__; - while(dst < end) *dst++ = *src++; + // Set up data segment: Copy from flash to ram + // src = &__data_src_start__; + // dst = &__data_start__; + // end = &__data_end__; + // while(dst < end) *dst++ = *src++; + AppMain(); } diff --git a/client/Makefile b/client/Makefile index da0c2728..aa1d33c5 100644 --- a/client/Makefile +++ b/client/Makefile @@ -15,7 +15,7 @@ OBJDIR = obj LDLIBS = -L/opt/local/lib -L/usr/local/lib -lreadline -lpthread -lm LUALIB = ../liblua/liblua.a LDFLAGS = $(COMMON_FLAGS) -CFLAGS = -std=c99 -I. -I../include -I../common -I../zlib -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -DZ_SOLO -DZ_PREFIX -DNO_GZIP -g -O4 +CFLAGS = -std=c99 -I. -I../include -I../common -I../zlib -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -g -O4 LUAPLATFORM = generic ifneq (,$(findstring MINGW,$(platform))) @@ -43,7 +43,6 @@ else LUAPLATFORM = linux endif - ifneq ($(QTLDLIBS),) QTGUI = $(OBJDIR)/proxgui.o $(OBJDIR)/proxguiqt.o $(OBJDIR)/proxguiqt.moc.o CFLAGS += -DHAVE_GUI @@ -105,6 +104,8 @@ CMDSRCS = nonce2key/crapto1.c\ protocols.c\ ZLIBSRCS = deflate.c adler32.c trees.c zutil.c +ZLIB_FLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED + COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) CMDOBJS = $(CMDSRCS:%.c=$(OBJDIR)/%.o) @@ -133,10 +134,10 @@ flasher: $(OBJDIR)/flash.o $(OBJDIR)/flasher.o $(COREOBJS) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ fpga_compress: $(OBJDIR)/fpga_compress.o $(ZLIBOBJS) - $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ + $(CXX) $(CXXFLAGS) $(ZLIB_FLAGS) $^ $(LDLIBS) -o $@ $(OBJDIR)/%.o: %.c - $(CC) $(CFLAGS) -c -o $@ $< + $(CC) $(CFLAGS) $(ZLIB_FLAGS) -c -o $@ $< $(OBJDIR)/%.o: %.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< diff --git a/client/fpga_compress.c b/client/fpga_compress.c index d4376ccc..5164f6d4 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -85,7 +85,11 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) for(uint16_t j = 0; j < num_infiles; j++) { for(uint16_t k = 0; k < FPGA_INTERLEAVE_SIZE; k++) { c = fgetc(infile[j]); - if (!feof(infile[j])) fpga_config[i++] = c; else fpga_config[i++] = '\0'; + if (!feof(infile[j])) { + fpga_config[i++] = c; + } else if (num_infiles > 1) { + fpga_config[i++] = '\0'; + } } } diff --git a/zlib/trees.c b/zlib/trees.c index 1fd7759e..a4f04057 100644 --- a/zlib/trees.c +++ b/zlib/trees.c @@ -913,9 +913,10 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ +#ifndef ZLIB_PM3_TUNED /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { - +#endif /* Check if the file is binary or text */ if (s->strm->data_type == Z_UNKNOWN) s->strm->data_type = detect_data_type(s); @@ -945,6 +946,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, s->last_lit)); +#ifndef ZLIB_PM3_TUNED if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { @@ -978,7 +980,8 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) s->compressed_len += 3 + s->static_len; #endif } else { - send_bits(s, (DYN_TREES<<1)+last, 3); +#endif /* ZLIB_PM3_TUNED */ + send_bits(s, (DYN_TREES<<1)+last, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); compress_block(s, (const ct_data *)s->dyn_ltree, From 4b3f6d79ea9174d97f3f82177fa9ded4ad485172 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Mon, 18 May 2015 08:49:38 +0200 Subject: [PATCH 079/132] Add option -d (decompress) to fpga_compress. Allows testing. Improve zlib deflate (note: no change required to inflate). --- client/Makefile | 4 +- client/fpga_compress.c | 93 ++++++++++++++++++++++++++++++++-- zlib/deflate.c | 112 ++++++++++++++++++++++++++++++++++++++++- zlib/inflate.c | 4 +- zlib/trees.c | 2 + 5 files changed, 204 insertions(+), 11 deletions(-) diff --git a/client/Makefile b/client/Makefile index aa1d33c5..bc43408a 100644 --- a/client/Makefile +++ b/client/Makefile @@ -103,8 +103,8 @@ CMDSRCS = nonce2key/crapto1.c\ aes.c\ protocols.c\ -ZLIBSRCS = deflate.c adler32.c trees.c zutil.c -ZLIB_FLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED +ZLIBSRCS = deflate.c adler32.c trees.c zutil.c inflate.c inffast.c inftrees.c +ZLIB_FLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED -DDEBUG -Dverbose=1 COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) diff --git a/client/fpga_compress.c b/client/fpga_compress.c index 5164f6d4..68e9103c 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -45,14 +45,12 @@ static void usage(char *argv0) static voidpf fpga_deflate_malloc(voidpf opaque, uInt items, uInt size) { - fprintf(stderr, "zlib requested %d bytes\n", items*size); return malloc(items*size); } static void fpga_deflate_free(voidpf opaque, voidpf address) { - fprintf(stderr, "zlib frees memory\n"); return free(address); } @@ -119,7 +117,6 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) // estimate the size of the compressed output unsigned int outsize_max = deflateBound(&compressed_fpga_stream, compressed_fpga_stream.avail_in); - fprintf(stderr, "Allocating %ld bytes for output file (estimated upper bound)\n", outsize_max); uint8_t *outbuf = malloc(outsize_max); compressed_fpga_stream.next_out = outbuf; compressed_fpga_stream.avail_out = outsize_max; @@ -137,7 +134,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) ret = deflate(&compressed_fpga_stream, Z_FINISH); } - fprintf(stderr, "produced %d bytes of output\n", compressed_fpga_stream.total_out); + fprintf(stderr, "\ncompressed %d input bytes to %d output bytes\n", i, compressed_fpga_stream.total_out); if (ret != Z_STREAM_END) { fprintf(stderr, "Error in deflate(): %d %s\n", ret, compressed_fpga_stream.msg); @@ -170,6 +167,72 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) } +int zlib_decompress(FILE *infile, FILE *outfile) +{ + #define DECOMPRESS_BUF_SIZE 1024 + uint8_t outbuf[DECOMPRESS_BUF_SIZE]; + uint8_t inbuf[DECOMPRESS_BUF_SIZE]; + int ret; + + z_stream compressed_fpga_stream; + // initialize zlib structures + compressed_fpga_stream.next_in = inbuf; + compressed_fpga_stream.avail_in = 0; + compressed_fpga_stream.next_out = outbuf; + compressed_fpga_stream.avail_out = DECOMPRESS_BUF_SIZE; + compressed_fpga_stream.zalloc = fpga_deflate_malloc; + compressed_fpga_stream.zfree = fpga_deflate_free; + + ret = inflateInit2(&compressed_fpga_stream, 0); + + do { + if (compressed_fpga_stream.avail_in == 0) { + compressed_fpga_stream.next_in = inbuf; + uint16_t i = 0; + do { + uint8_t c = fgetc(infile); + if (!feof(infile)) { + inbuf[i++] = c; + compressed_fpga_stream.avail_in++; + } else { + break; + } + } while (i < DECOMPRESS_BUF_SIZE); + } + + ret = inflate(&compressed_fpga_stream, Z_SYNC_FLUSH); + + if (ret != Z_OK && ret != Z_STREAM_END) { + break; + } + + if (compressed_fpga_stream.avail_out == 0) { + for (uint16_t i = 0; i < DECOMPRESS_BUF_SIZE; i++) { + fputc(outbuf[i], outfile); + } + compressed_fpga_stream.avail_out = DECOMPRESS_BUF_SIZE; + compressed_fpga_stream.next_out = outbuf; + } + } while (ret == Z_OK); + + if (ret == Z_STREAM_END) { // reached end of input + uint16_t i = 0; + while (compressed_fpga_stream.avail_out < DECOMPRESS_BUF_SIZE) { + fputc(outbuf[i++], outfile); + compressed_fpga_stream.avail_out++; + } + fclose(outfile); + fclose(infile); + return 0; + } else { + fprintf(stderr, "Error. Inflate() returned error %d, %s", ret, compressed_fpga_stream.msg); + fclose(outfile); + fclose(infile); + return -1; + } + +} + int main(int argc, char **argv) { @@ -181,6 +244,26 @@ int main(int argc, char **argv) return -1; } + if (!strcmp(argv[1], "-d")) { + infiles = calloc(1, sizeof(FILE*)); + if (argc != 4) { + usage(argv[0]); + return -1; + } + infiles[0] = fopen(argv[2], "rb"); + if (infiles[0] == NULL) { + fprintf(stderr, "Error. Cannot open input file %s", argv[2]); + return -1; + } + outfile = fopen(argv[3], "wb"); + if (outfile == NULL) { + fprintf(stderr, "Error. Cannot open output file %s", argv[3]); + return -1; + } + return zlib_decompress(infiles[0], outfile); + } + + infiles = calloc(argc-2, sizeof(FILE*)); for (uint16_t i = 0; i < argc-2; i++) { @@ -195,7 +278,7 @@ int main(int argc, char **argv) if (outfile == NULL) { fprintf(stderr, "Error. Cannot open output file %s", argv[argc-1]); return -1; - } + } return zlib_compress(infiles, argc-2, outfile); } diff --git a/zlib/deflate.c b/zlib/deflate.c index 69695770..7c22a72b 100644 --- a/zlib/deflate.c +++ b/zlib/deflate.c @@ -1153,7 +1153,11 @@ local uInt longest_match(s, cur_match) register Bytef *scan = s->window + s->strstart; /* current string */ register Bytef *match; /* matched string */ register int len; /* length of current match */ +#ifdef ZLIB_PM3_TUNED + int best_len = MIN_MATCH-1; // lift the restriction on prev-length +#else int best_len = s->prev_length; /* best match length so far */ +#endif int nice_match = s->nice_match; /* stop if match long enough */ IPos limit = s->strstart > (IPos)MAX_DIST(s) ? s->strstart - (IPos)MAX_DIST(s) : NIL; @@ -1721,6 +1725,104 @@ local block_state deflate_fast(s, flush) return block_done; } + +#ifdef ZLIB_PM3_TUNED +local uInt try_harder(s, strstart, lookahead, hash_head, level) + deflate_state *s; + uInt strstart; + uInt lookahead; + IPos hash_head; + uInt level; +{ + uInt strstart_save = s->strstart; + s->strstart = strstart; + uInt lookahead_save = s->lookahead; + s->lookahead = lookahead; + uInt ins_h_save = s->ins_h; + uInt combined_gain; + uInt best_combined_gain = 0; + uInt match_length; + uInt prev_length = s->prev_length < MIN_MATCH ? 1 : s->prev_length; + uInt best_prev_length = prev_length; + uInt current_match_start = s->match_start; + uInt current_match_length = s->match_length; + + do { + if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) { + match_length = longest_match (s, hash_head); + /* longest_match() sets match_start */ + } else { + match_length = MIN_MATCH - 1; + } +#if TOO_FAR <= 32767 + if (match_length == MIN_MATCH && s->strstart - s->match_start > TOO_FAR) { + match_length = MIN_MATCH-1; + } +#endif + if (s->strstart == strstart) { // store match at current position + current_match_length = match_length; + current_match_start = s->match_start; + } + if (s->strstart - strstart + 1 < MIN_MATCH) { // previous match reduced to one or two literals + combined_gain = 0; // need one literal per byte: no gain (assuming 8 bits per literal) + } else { + combined_gain = s->strstart - strstart + 1 - MIN_MATCH; // (possibly truncated) previous_length - 3 literals + } + if (level > 1 && s->strstart+1 <= s->window_size - MIN_LOOKAHEAD) { // test one level more + s->prev_length = match_length; + uInt save_ins_h = s->ins_h; + UPDATE_HASH(s, s->ins_h, s->window[(s->strstart+1) + (MIN_MATCH-1)]); + combined_gain += try_harder(s, s->strstart+1, s->lookahead-1, s->head[s->ins_h], level-1); + s->ins_h = save_ins_h; + } else { + if (match_length < MIN_MATCH) { + combined_gain += 0; // no gain + } else { + combined_gain += match_length - MIN_MATCH; // match_length bytes coded as approx three literals + } + } + // if (combined_length > s->lookahead - 1) { + // combined_length = s->lookahead; + // } + if (combined_gain >= best_combined_gain) { // in case of a tie we prefer the longer prev_length + best_combined_gain = combined_gain; + best_prev_length = s->strstart - strstart + 1; + } + s->strstart++; + s->lookahead--; + UPDATE_HASH(s, s->ins_h, s->window[(s->strstart) + (MIN_MATCH-1)]); + hash_head = s->head[s->ins_h]; + // if (s->strstart - strstart + 1 == MIN_MATCH-1) { // a match with length == 2 is not possible + // s->strstart++; + // s->lookahead--; + // UPDATE_HASH(s, s->ins_h, s->window[(s->strstart) + (MIN_MATCH-1)]); + // 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; + s->match_length = current_match_length; + s->match_start = current_match_start; + if (prev_length >= MIN_MATCH) { + if (best_prev_length != prev_length && best_prev_length >= MIN_MATCH) { + printf("at %d, level %d: Reducing prev_length from %d to %d\n", s->strstart, level, prev_length, best_prev_length); + } + } + if (best_prev_length >= MIN_MATCH) { + s->prev_length = best_prev_length; + s->match_length = MIN_MATCH - 1; + } else { + s->prev_length = MIN_MATCH - 1; + } + return best_combined_gain; +} +#endif + + + #ifndef FASTEST /* =========================================================================== * Same as above, but achieves better compression. We use a lazy @@ -1757,11 +1859,16 @@ local block_state deflate_slow(s, flush) INSERT_STRING(s, s->strstart, hash_head); } - /* Find the longest match, discarding those <= prev_length. - */ + /* Find the longest match, discarding those <= prev_length. */ s->prev_length = s->match_length, s->prev_match = s->match_start; s->match_length = MIN_MATCH-1; +#ifdef ZLIB_PM3_TUNED + if (s->prev_length < s->max_lazy_match) { + try_harder(s, s->strstart, s->lookahead, hash_head, 1); + } + +#else if (hash_head != NIL && s->prev_length < s->max_lazy_match && s->strstart - hash_head <= MAX_DIST(s)) { /* To simplify the code, we prevent matches with the string @@ -1784,6 +1891,7 @@ local block_state deflate_slow(s, flush) s->match_length = MIN_MATCH-1; } } +#endif /* ZLIB_PM3_TUNED */ /* If there was a match at the previous step and the current * match is not better, output the previous match: */ diff --git a/zlib/inflate.c b/zlib/inflate.c index d2c666b0..417b2c41 100644 --- a/zlib/inflate.c +++ b/zlib/inflate.c @@ -847,8 +847,8 @@ int flush; break; case 1: /* fixed block */ #ifdef ZLIB_PM3_TUNED - Dbprintf("FATAL error. Compressed FPGA files with fixed code blocks are not supported!"); - for(;;); + strm->msg = (char *)"fixed block coding not supported"; + state->mode = BAD; #else fixedtables(state); Tracev((stderr, "inflate: fixed codes block%s\n", diff --git a/zlib/trees.c b/zlib/trees.c index a4f04057..8c521211 100644 --- a/zlib/trees.c +++ b/zlib/trees.c @@ -989,7 +989,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 } +#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. From 22342f6dfe53055955e9a849ad0bedb8b3e7c83b Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 26 May 2015 10:40:23 -0400 Subject: [PATCH 080/132] Add clearCommandBuffer before SendCommand adjust output of mfu rdbl to be consistent fix output of mfu dump in case startPage was specified. (also was missing "i" in second print...) --- armsrc/mifarecmd.c | 11 +++-------- client/cmdhfmfu.c | 26 +++++++++++++++++++++----- 2 files changed, 24 insertions(+), 13 deletions(-) diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 2a21ac48..884da913 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -305,7 +305,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) } for (int i = 0; i < blocks; i++){ - if ((i*4) + 4 > CARD_MEMORY_SIZE) { + if ((i*4) + 4 >= CARD_MEMORY_SIZE) { Dbprintf("Data exceeds buffer!!"); break; } @@ -337,16 +337,11 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks); countblocks *= 4; -/* - LED_B_ON(); - for(size_t i=0; i < countblocks; i += USB_CMD_DATA_SIZE) { - size_t len = MIN((countblocks - i),USB_CMD_DATA_SIZE); - cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K,i,len,countblocks,dataout+i,len); - } -*/ + cmd_send(CMD_ACK, 1, countblocks, BigBuf_max_traceLen(), 0, 0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); + BigBuf_free(); } //----------------------------------------------------------------------------- diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 057708ca..5d211558 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -102,17 +102,20 @@ char *getUlev1CardSizeStr( uint8_t fsize ){ static void ul_switch_on_field(void) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_DISCONNECT, 0, 0}}; + clearCommandBuffer(); SendCommand(&c); } void ul_switch_off_field(void) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; + clearCommandBuffer(); SendCommand(&c); } static int ul_send_cmd_raw( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, uint16_t responseLength ) { UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_APPEND_CRC, cmdlen, 0}}; memcpy(c.d.asBytes, cmd, cmdlen); + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; @@ -129,6 +132,7 @@ static int ul_send_cmd_raw_crc( uint8_t *cmd, uint8_t cmdlen, uint8_t *response, c.arg[0] |= ISO14A_APPEND_CRC; memcpy(c.d.asBytes, cmd, cmdlen); + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return -1; @@ -193,6 +197,7 @@ static int ulc_authentication( uint8_t *key, bool switch_off_field ){ UsbCommand c = {CMD_MIFAREUC_AUTH, {switch_off_field}}; memcpy(c.d.asBytes, key, 16); + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if ( !WaitForResponseTimeout(CMD_ACK, &resp, 1500) ) return 0; @@ -955,6 +960,7 @@ int CmdHF14AMfUWrBl(const char *Cmd){ memcpy(c.d.asBytes+4,authKeyPtr,4); } + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { @@ -1065,13 +1071,16 @@ int CmdHF14AMfURdBl(const char *Cmd){ memcpy(c.d.asBytes,authKeyPtr,4); } + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { uint8_t isOK = resp.arg[0] & 0xff; if (isOK) { uint8_t *data = resp.d.asBytes; - PrintAndLog("Block: %0d (0x%02X) [ %s]", blockNo, blockNo, sprint_hex(data, 4)); + PrintAndLog("\nBlock# | Data | Ascii"); + PrintAndLog("-----------------------------"); + PrintAndLog("%02d/0x%02X | %s| %.4s\n", blockNo, blockNo, sprint_hex(data, 4), data); } else { PrintAndLog("Failed reading block: (%02x)", isOK); @@ -1256,6 +1265,8 @@ int CmdHF14AMfUDump(const char *Cmd){ memcpy(c.d.asBytes, authKeyPtr, dataLen); } + + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; if (!WaitForResponseTimeout(CMD_ACK, &resp,1500)) { @@ -1314,11 +1325,11 @@ int CmdHF14AMfUDump(const char *Cmd){ } } - PrintAndLog("Block# | Data |lck| Ascii"); + PrintAndLog("\nBlock# | Data |lck| Ascii"); PrintAndLog("---------------------------------"); for (i = 0; i < Pages; ++i) { if ( i < 3 ) { - PrintAndLog("%02d/0x%02X | %s | | ", i, i, sprint_hex(data + i * 4, 4)); + PrintAndLog("%02d/0x%02X | %s| | ", i+startPage, i+startPage, sprint_hex(data + i * 4, 4)); continue; } switch(i){ @@ -1365,10 +1376,10 @@ int CmdHF14AMfUDump(const char *Cmd){ case 43: tmplockbit = bit2[9]; break; //auth1 default: break; } - PrintAndLog("%02d/0x%02X | %s | %d | %.4s", i, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); + PrintAndLog("%02d/0x%02X | %s| %d | %.4s", i+startPage, i+startPage, sprint_hex(data + i * 4, 4), tmplockbit, data+i*4); } PrintAndLog("---------------------------------"); - + // user supplied filename? if (fileNlen < 1) { // UID = data 0-1-2 4-5-6-7 (skips a beat) @@ -1558,6 +1569,7 @@ int CmdHF14AMfucSetPwd(const char *Cmd){ UsbCommand c = {CMD_MIFAREUC_SETPWD}; memcpy( c.d.asBytes, pwd, 16); + clearCommandBuffer(); SendCommand(&c); UsbCommand resp; @@ -1606,6 +1618,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ // read block2. c.cmd = CMD_MIFAREU_READBL; c.arg[0] = 2; + clearCommandBuffer(); SendCommand(&c); if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { PrintAndLog("Command execute timeout"); @@ -1623,6 +1636,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ c.d.asBytes[1] = uid[1]; c.d.asBytes[2] = uid[2]; c.d.asBytes[3] = 0x88 ^ uid[0] ^ uid[1] ^ uid[2]; + clearCommandBuffer(); SendCommand(&c); if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) { PrintAndLog("Command execute timeout"); @@ -1635,6 +1649,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ c.d.asBytes[1] = uid[4]; c.d.asBytes[2] = uid[5]; c.d.asBytes[3] = uid[6]; + clearCommandBuffer(); SendCommand(&c); if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { PrintAndLog("Command execute timeout"); @@ -1647,6 +1662,7 @@ int CmdHF14AMfucSetUid(const char *Cmd){ c.d.asBytes[1] = oldblock2[1]; c.d.asBytes[2] = oldblock2[2]; c.d.asBytes[3] = oldblock2[3]; + clearCommandBuffer(); SendCommand(&c); if (!WaitForResponseTimeout(CMD_ACK,&resp,1500) ) { PrintAndLog("Command execute timeout"); From 8e074056acc2ee8edd5222f9937e8c40bfeff013 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Tue, 26 May 2015 07:37:50 +0200 Subject: [PATCH 081/132] also delete *.bin and fpga_compressor when "make clean". Add target to make fpga_compressor when client is not yet compiled. Get version information and cache it when client starts (avoids clearing BigBuf when calling hw version). Add some comments and remove debugging printouts. Add version info and ChangeLog in modified zlib. --- armsrc/Makefile | 6 +- armsrc/appmain.c | 16 +- armsrc/fpgaloader.c | 45 +- armsrc/util.c | 7 +- client/Makefile | 5 +- client/cmdhw.c | 25 +- client/fpga_compress.c | 61 +- client/proxmark3.c | 4 +- zlib/ChangeLog | 1481 ++++++++++++++++++++++++++++++++++++++++ zlib/FAQ | 368 ++++++++++ zlib/README | 124 ++++ zlib/deflate.c | 44 +- zlib/inflate.c | 9 + zlib/inftrees.c | 2 +- zlib/trees.c | 16 +- zlib/zlib.h | 18 + 16 files changed, 2132 insertions(+), 99 deletions(-) create mode 100644 zlib/ChangeLog create mode 100644 zlib/FAQ create mode 100644 zlib/README diff --git a/armsrc/Makefile b/armsrc/Makefile index 8cd927d8..78d67934 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -75,7 +75,10 @@ $(OBJDIR)/fpga_all.o: $(OBJDIR)/fpga_all.bit.z $(OBJDIR)/fpga_all.bit.z: $(FPGA_BITSTREAMS) $(FPGA_COMPRESSOR) $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ - + +$(FPGA_COMPRESSOR): + make -C ../client $(notdir $(FPGA_COMPRESSOR)) + $(OBJDIR)/fullimage.stage1.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_all.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) @@ -107,6 +110,7 @@ clean: $(DELETE) $(OBJDIR)$(PATHSEP)*.map $(DELETE) $(OBJDIR)$(PATHSEP)*.d $(DELETE) $(OBJDIR)$(PATHSEP)*.z + $(DELETE) $(OBJDIR)$(PATHSEP)*.bin $(DELETE) version.c .PHONY: all clean help diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 737873ad..26399046 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -313,8 +313,8 @@ extern struct version_information version_information; extern char *_bootphase1_version_pointer, _flash_start, _flash_end, _bootrom_start, _bootrom_end, __data_src_start__; void SendVersion(void) { - char temp[512]; /* Limited data payload in USB packets */ - DbpString("Prox/RFID mark3 RFID instrument"); + char temp[USB_CMD_DATA_SIZE]; /* Limited data payload in USB packets */ + char VersionString[USB_CMD_DATA_SIZE] = { '\0' }; /* Try to find the bootrom version information. Expect to find a pointer at * symbol _bootphase1_version_pointer, perform slight sanity checks on the @@ -322,24 +322,24 @@ void SendVersion(void) */ char *bootrom_version = *(char**)&_bootphase1_version_pointer; if( bootrom_version < &_flash_start || bootrom_version >= &_flash_end ) { - DbpString("bootrom version information appears invalid"); + strcat(VersionString, "bootrom version information appears invalid\n"); } else { FormatVersionInformation(temp, sizeof(temp), "bootrom: ", bootrom_version); - DbpString(temp); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); } FormatVersionInformation(temp, sizeof(temp), "os: ", &version_information); - DbpString(temp); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); FpgaGatherVersion(FPGA_BITSTREAM_LF, temp, sizeof(temp)); - DbpString(temp); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp)); - DbpString(temp); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); // Send Chip ID and used flash memory uint32_t text_and_rodata_section_size = (uint32_t)&__data_src_start__ - (uint32_t)&_flash_start; uint32_t compressed_data_section_size = common_area.arg1; - cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), text_and_rodata_section_size + compressed_data_section_size, 0, NULL, 0); + cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), text_and_rodata_section_size + compressed_data_section_size, 0, VersionString, strlen(VersionString)); } #ifdef WITH_LF diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c index a2c9d1e4..16fed7c5 100644 --- a/armsrc/fpgaloader.c +++ b/armsrc/fpgaloader.c @@ -173,6 +173,10 @@ bool FpgaSetupSscDma(uint8_t *buf, int len) } +//---------------------------------------------------------------------------- +// Uncompress (inflate) the FPGA data. Returns one decompressed byte with +// each call. +//---------------------------------------------------------------------------- static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) { if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data @@ -193,7 +197,11 @@ static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8 return *fpga_image_ptr++; } - +//---------------------------------------------------------------------------- +// Undo the interleaving of several FPGA config files. FPGA config files +// are combined into one big file: +// 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc. +//---------------------------------------------------------------------------- static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { while((uncompressed_bytes_cnt / FPGA_INTERLEAVE_SIZE) % FPGA_BITSTREAM_MAX != (bitstream_version - 1)) { @@ -208,18 +216,19 @@ static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size) { - Dbprintf("zlib requested %d bytes", items*size); return BigBuf_malloc(items*size); } static void fpga_inflate_free(voidpf opaque, voidpf address) { - Dbprintf("zlib frees memory"); - BigBuf_free_keep_EM(); + BigBuf_free(); } +//---------------------------------------------------------------------------- +// Initialize decompression of the respective (HF or LF) FPGA stream +//---------------------------------------------------------------------------- static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; @@ -234,7 +243,7 @@ static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_s compressed_fpga_stream->zalloc = &fpga_inflate_malloc; compressed_fpga_stream->zfree = &fpga_inflate_free; - inflateInit2(compressed_fpga_stream, 15); + inflateInit2(compressed_fpga_stream, 0); fpga_image_ptr = output_buffer; @@ -330,8 +339,6 @@ static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp comp DownloadFPGA_byte(b); } - Dbprintf("%d bytes loaded into FPGA", i); - // continue to clock FPGA until ready signal goes high i=100000; while ( (i--) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_DONE ) ) ) { @@ -402,10 +409,10 @@ static int bitparse_find_section(int bitstream_version, char section_name, unsig } -//----------------------------------------------------------------------------- -// Find out which FPGA image format is stored in flash, then call DownloadFPGA -// with the right parameters to download the image -//----------------------------------------------------------------------------- +//---------------------------------------------------------------------------- +// Check which FPGA image is currently loaded (if any). If necessary +// decompress and load the correct (HF or LF) image to the FPGA +//---------------------------------------------------------------------------- void FpgaDownloadAndGo(int bitstream_version) { z_stream compressed_fpga_stream; @@ -415,6 +422,9 @@ void FpgaDownloadAndGo(int bitstream_version) if (downloaded_bitstream == bitstream_version) return; + // make sure that we have enough memory to decompress + BigBuf_free(); + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; } @@ -426,10 +436,15 @@ void FpgaDownloadAndGo(int bitstream_version) } inflateEnd(&compressed_fpga_stream); - } +//----------------------------------------------------------------------------- +// Gather version information from FPGA image. Needs to decompress the begin +// of the respective (HF or LF) image. +// Note: decompression makes use of (i.e. overwrites) BigBuf[]. It is therefore +// advisable to call this only once and store the results for later use. +//----------------------------------------------------------------------------- void FpgaGatherVersion(int bitstream_version, char *dst, int len) { unsigned int fpga_info_len; @@ -439,6 +454,9 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) dst[0] = '\0'; + // ensure that we can allocate enough memory for decompression: + BigBuf_free(); + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; } @@ -487,8 +505,9 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len) strncat(dst, tempstr, len-1); } - inflateEnd(&compressed_fpga_stream); + strncat(dst, "\n", len-1); + inflateEnd(&compressed_fpga_stream); } diff --git a/armsrc/util.c b/armsrc/util.c index 74fba94b..8576ddce 100644 --- a/armsrc/util.c +++ b/armsrc/util.c @@ -268,15 +268,15 @@ void FormatVersionInformation(char *dst, int len, const char *prefix, void *vers dst[0] = 0; strncat(dst, prefix, len-1); if(v->magic != VERSION_INFORMATION_MAGIC) { - strncat(dst, "Missing/Invalid version information", len - strlen(dst) - 1); + strncat(dst, "Missing/Invalid version information\n", len - strlen(dst) - 1); return; } if(v->versionversion != 1) { - strncat(dst, "Version information not understood", len - strlen(dst) - 1); + strncat(dst, "Version information not understood\n", len - strlen(dst) - 1); return; } if(!v->present) { - strncat(dst, "Version information not available", len - strlen(dst) - 1); + strncat(dst, "Version information not available\n", len - strlen(dst) - 1); return; } @@ -289,6 +289,7 @@ void FormatVersionInformation(char *dst, int len, const char *prefix, void *vers strncat(dst, " ", len - strlen(dst) - 1); strncat(dst, v->buildtime, len - strlen(dst) - 1); + strncat(dst, "\n", len - strlen(dst) - 1); } // ------------------------------------------------------------------------- diff --git a/client/Makefile b/client/Makefile index bc43408a..7d03b101 100644 --- a/client/Makefile +++ b/client/Makefile @@ -104,7 +104,8 @@ CMDSRCS = nonce2key/crapto1.c\ protocols.c\ ZLIBSRCS = deflate.c adler32.c trees.c zutil.c inflate.c inffast.c inftrees.c -ZLIB_FLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED -DDEBUG -Dverbose=1 +ZLIB_FLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED +#-DDEBUG -Dverbose=1 COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) @@ -113,7 +114,7 @@ ZLIBOBJS = $(ZLIBSRCS:%.c=$(OBJDIR)/%.o) RM = rm -f BINS = proxmark3 flasher fpga_compress #snooper cli -CLEAN = cli cli.exe flasher flasher.exe proxmark3 proxmark3.exe snooper snooper.exe $(CMDOBJS) $(OBJDIR)/*.o *.o *.moc.cpp +CLEAN = cli cli.exe flasher flasher.exe proxmark3 proxmark3.exe fpga_compress fpga_compress.exe snooper snooper.exe $(CMDOBJS) $(OBJDIR)/*.o *.o *.moc.cpp all: lua_build $(BINS) diff --git a/client/cmdhw.c b/client/cmdhw.c index 78695346..05ad0c9f 100644 --- a/client/cmdhw.c +++ b/client/cmdhw.c @@ -404,13 +404,24 @@ int CmdTune(const char *Cmd) int CmdVersion(const char *Cmd) { - UsbCommand c = {CMD_VERSION}; - UsbCommand resp; - SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { - lookupChipID(resp.arg[0], resp.arg[1]); - } - return 0; + + UsbCommand c = {CMD_VERSION}; + static UsbCommand resp = {0, {0, 0, 0}}; + + if (resp.arg[0] == 0 && resp.arg[1] == 0) { // no cached information available + SendCommand(&c); + if (WaitForResponseTimeout(CMD_ACK,&resp,1000) && Cmd != NULL) { + PrintAndLog("Prox/RFID mark3 RFID instrument"); + PrintAndLog((char*)resp.d.asBytes); + lookupChipID(resp.arg[0], resp.arg[1]); + } + } else if (Cmd != NULL) { + PrintAndLog("Prox/RFID mark3 RFID instrument"); + PrintAndLog((char*)resp.d.asBytes); + lookupChipID(resp.arg[0], resp.arg[1]); + } + + return 0; } static command_t CommandTable[] = diff --git a/client/fpga_compress.c b/client/fpga_compress.c index 68e9103c..5f4d23d4 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -3,7 +3,10 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// Flasher frontend tool +// Compression tool for FPGA config files. Compress several *.bit files at +// compile time. Decompression is done at run time (see fpgaloader.c). +// This uses the zlib library tuned to this specific case. The small file sizes +// allow to use "insane" parameters for optimum compression ratio. //----------------------------------------------------------------------------- #include @@ -17,8 +20,8 @@ // zlib configuration #define COMPRESS_LEVEL 9 // use best possible compression -#define COMPRESS_WINDOW_BITS 15 // default = 15 for a window of 2^15 = 32KBytes -#define COMPRESS_MEM_LEVEL 9 // determines the amount of memory allocated during compression. Default = 8. Must be < 9 +#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), Z_FILTERED (more huffmann, less string matching), @@ -36,10 +39,12 @@ #define FPGA_INTERLEAVE_SIZE 288 // (the FPGA's internal config frame size is 288 bits. Interleaving with 288 bytes should give best compression) #define FPGA_CONFIG_SIZE 42336 // our current fpga_[lh]f.bit files are 42175 bytes. Rounded up to next multiple of FPGA_INTERLEAVE_SIZE -static void usage(char *argv0) +static void usage(void) { - fprintf(stderr, "Usage: %s ... \n\n", argv0); - fprintf(stderr, "Combines n FPGA bitstream files and compresses them into one.\n\n"); + fprintf(stderr, "Usage: fpga_compress ... \n"); + fprintf(stderr, " Combine n FPGA bitstream files and compress them into one.\n\n"); + fprintf(stderr, " fpga_compress -d "); + fprintf(stderr, " Decompress . Write result to "); } @@ -77,7 +82,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) fpga_config = malloc(num_infiles * FPGA_CONFIG_SIZE); - // read the input files interleaving into fpga_config[] + // read the input files. Interleave them into fpga_config[] i = 0; do { for(uint16_t j = 0; j < num_infiles; j++) { @@ -100,8 +105,6 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) } } while (!all_feof(infile, num_infiles)); - fprintf(stderr, "Read a total of %ld bytes from %d files\n", i, num_infiles); - // initialize zlib structures compressed_fpga_stream.next_in = fpga_config; compressed_fpga_stream.avail_in = i; @@ -120,7 +123,6 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) uint8_t *outbuf = malloc(outsize_max); compressed_fpga_stream.next_out = outbuf; compressed_fpga_stream.avail_out = outsize_max; - if (ret == Z_OK) { ret = deflateTune(&compressed_fpga_stream, @@ -134,7 +136,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) ret = deflate(&compressed_fpga_stream, Z_FINISH); } - fprintf(stderr, "\ncompressed %d input bytes to %d output bytes\n", i, compressed_fpga_stream.total_out); + fprintf(stderr, "compressed %d input bytes to %d output bytes\n", i, compressed_fpga_stream.total_out); if (ret != Z_STREAM_END) { fprintf(stderr, "Error in deflate(): %d %s\n", ret, compressed_fpga_stream.msg); @@ -175,6 +177,7 @@ int zlib_decompress(FILE *infile, FILE *outfile) int ret; z_stream compressed_fpga_stream; + // initialize zlib structures compressed_fpga_stream.next_in = inbuf; compressed_fpga_stream.avail_in = 0; @@ -240,14 +243,14 @@ int main(int argc, char **argv) FILE *outfile; if (argc == 1 || argc == 2) { - usage(argv[0]); + usage(); return -1; } - if (!strcmp(argv[1], "-d")) { + if (!strcmp(argv[1], "-d")) { // Decompress infiles = calloc(1, sizeof(FILE*)); if (argc != 4) { - usage(argv[0]); + usage(); return -1; } infiles[0] = fopen(argv[2], "rb"); @@ -261,24 +264,22 @@ int main(int argc, char **argv) return -1; } return zlib_decompress(infiles[0], outfile); - } - - infiles = calloc(argc-2, sizeof(FILE*)); - - for (uint16_t i = 0; i < argc-2; i++) { - infiles[i] = fopen(argv[i+1], "rb"); - if (infiles[i] == NULL) { - fprintf(stderr, "Error. Cannot open input file %s", argv[i+1]); + } else { // Compress + + infiles = calloc(argc-2, sizeof(FILE*)); + for (uint16_t i = 0; i < argc-2; i++) { + infiles[i] = fopen(argv[i+1], "rb"); + if (infiles[i] == NULL) { + fprintf(stderr, "Error. Cannot open input file %s", argv[i+1]); + return -1; + } + } + outfile = fopen(argv[argc-1], "wb"); + if (outfile == NULL) { + fprintf(stderr, "Error. Cannot open output file %s", argv[argc-1]); return -1; } + return zlib_compress(infiles, argc-2, outfile); } - - outfile = fopen(argv[argc-1], "wb"); - if (outfile == NULL) { - fprintf(stderr, "Error. Cannot open output file %s", argv[argc-1]); - return -1; - } - - return zlib_compress(infiles, argc-2, outfile); } diff --git a/client/proxmark3.c b/client/proxmark3.c index 0e2a698c..2f370308 100644 --- a/client/proxmark3.c +++ b/client/proxmark3.c @@ -24,7 +24,7 @@ #include "ui.h" #include "sleep.h" #include "cmdparser.h" -#include "cmdmain.h" +#include "cmdhw.h" // a global mutex to prevent interlaced printing from different threads pthread_mutex_t print_lock; @@ -105,6 +105,8 @@ static void *main_loop(void *targ) { if (arg->usb_present == 1) { rarg.run = 1; pthread_create(&reader_thread, NULL, &uart_receiver, &rarg); + // cache Version information now: + CmdVersion(NULL); } FILE *script_file = NULL; diff --git a/zlib/ChangeLog b/zlib/ChangeLog new file mode 100644 index 00000000..b9965157 --- /dev/null +++ b/zlib/ChangeLog @@ -0,0 +1,1481 @@ + + ChangeLog file for zlib + +Changes in 1.2.8.f-Proxmark3 (for Proxmark3 project only) (26 May 2015) +- disable decoding of fixed code blocks in deflate (eliminates the need + to store the fixed tree in RAM or ROM) +- disable generating fixed code blocks in inflate +- look harder for local optimum of consecutive matches and single literals + in inflate. +- stripped down version - unnecessary files from original distribution + are not included + +Changes in 1.2.8 (28 Apr 2013) +- Update contrib/minizip/iowin32.c for Windows RT [Vollant] +- Do not force Z_CONST for C++ +- Clean up contrib/vstudio [Ro§] +- Correct spelling error in zlib.h +- Fix mixed line endings in contrib/vstudio + +Changes in 1.2.7.3 (13 Apr 2013) +- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc + +Changes in 1.2.7.2 (13 Apr 2013) +- Change check for a four-byte type back to hexadecimal +- Fix typo in win32/Makefile.msc +- Add casts in gzwrite.c for pointer differences + +Changes in 1.2.7.1 (24 Mar 2013) +- Replace use of unsafe string functions with snprintf if available +- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink] +- Fix gzgetc undefine when Z_PREFIX set [Turk] +- Eliminate use of mktemp in Makefile (not always available) +- Fix bug in 'F' mode for gzopen() +- Add inflateGetDictionary() function +- Correct comment in deflate.h +- Use _snprintf for snprintf in Microsoft C +- On Darwin, only use /usr/bin/libtool if libtool is not Apple +- Delete "--version" file if created by "ar --version" [Richard G.] +- Fix configure check for veracity of compiler error return codes +- Fix CMake compilation of static lib for MSVC2010 x64 +- Remove unused variable in infback9.c +- Fix argument checks in gzlog_compress() and gzlog_write() +- Clean up the usage of z_const and respect const usage within zlib +- Clean up examples/gzlog.[ch] comparisons of different types +- Avoid shift equal to bits in type (caused endless loop) +- Fix unintialized value bug in gzputc() introduced by const patches +- Fix memory allocation error in examples/zran.c [Nor] +- Fix bug where gzopen(), gzclose() would write an empty file +- Fix bug in gzclose() when gzwrite() runs out of memory +- Check for input buffer malloc failure in examples/gzappend.c +- Add note to contrib/blast to use binary mode in stdio +- Fix comparisons of differently signed integers in contrib/blast +- Check for invalid code length codes in contrib/puff +- Fix serious but very rare decompression bug in inftrees.c +- Update inflateBack() comments, since inflate() can be faster +- Use underscored I/O function names for WINAPI_FAMILY +- Add _tr_flush_bits to the external symbols prefixed by --zprefix +- Add contrib/vstudio/vc10 pre-build step for static only +- Quote --version-script argument in CMakeLists.txt +- Don't specify --version-script on Apple platforms in CMakeLists.txt +- Fix casting error in contrib/testzlib/testzlib.c +- Fix types in contrib/minizip to match result of get_crc_table() +- Simplify contrib/vstudio/vc10 with 'd' suffix +- Add TOP support to win32/Makefile.msc +- Suport i686 and amd64 assembler builds in CMakeLists.txt +- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h +- Add vc11 and vc12 build files to contrib/vstudio +- Add gzvprintf() as an undocumented function in zlib +- Fix configure for Sun shell +- Remove runtime check in configure for four-byte integer type +- Add casts and consts to ease user conversion to C++ +- Add man pages for minizip and miniunzip +- In Makefile uninstall, don't rm if preceding cd fails +- Do not return Z_BUF_ERROR if deflateParam() has nothing to write + +Changes in 1.2.7 (2 May 2012) +- Replace use of memmove() with a simple copy for portability +- Test for existence of strerror +- Restore gzgetc_ for backward compatibility with 1.2.6 +- Fix build with non-GNU make on Solaris +- Require gcc 4.0 or later on Mac OS X to use the hidden attribute +- Include unistd.h for Watcom C +- Use __WATCOMC__ instead of __WATCOM__ +- Do not use the visibility attribute if NO_VIZ defined +- Improve the detection of no hidden visibility attribute +- Avoid using __int64 for gcc or solo compilation +- Cast to char * in gzprintf to avoid warnings [Zinser] +- Fix make_vms.com for VAX [Zinser] +- Don't use library or built-in byte swaps +- Simplify test and use of gcc hidden attribute +- Fix bug in gzclose_w() when gzwrite() fails to allocate memory +- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen() +- Fix bug in test/minigzip.c for configure --solo +- Fix contrib/vstudio project link errors [Mohanathas] +- Add ability to choose the builder in make_vms.com [Schweda] +- Add DESTDIR support to mingw32 win32/Makefile.gcc +- Fix comments in win32/Makefile.gcc for proper usage +- Allow overriding the default install locations for cmake +- Generate and install the pkg-config file with cmake +- Build both a static and a shared version of zlib with cmake +- Include version symbols for cmake builds +- If using cmake with MSVC, add the source directory to the includes +- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta] +- Move obsolete emx makefile to old [Truta] +- Allow the use of -Wundef when compiling or using zlib +- Avoid the use of the -u option with mktemp +- Improve inflate() documentation on the use of Z_FINISH +- Recognize clang as gcc +- Add gzopen_w() in Windows for wide character path names +- Rename zconf.h in CMakeLists.txt to move it out of the way +- Add source directory in CMakeLists.txt for building examples +- Look in build directory for zlib.pc in CMakeLists.txt +- Remove gzflags from zlibvc.def in vc9 and vc10 +- Fix contrib/minizip compilation in the MinGW environment +- Update ./configure for Solaris, support --64 [Mooney] +- Remove -R. from Solaris shared build (possible security issue) +- Avoid race condition for parallel make (-j) running example +- Fix type mismatch between get_crc_table() and crc_table +- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler] +- Fix the path to zlib.map in CMakeLists.txt +- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe] +- Add instructions to win32/Makefile.gcc for shared install [Torri] + +Changes in 1.2.6.1 (12 Feb 2012) +- Avoid the use of the Objective-C reserved name "id" +- Include io.h in gzguts.h for Microsoft compilers +- Fix problem with ./configure --prefix and gzgetc macro +- Include gz_header definition when compiling zlib solo +- Put gzflags() functionality back in zutil.c +- Avoid library header include in crc32.c for Z_SOLO +- Use name in GCC_CLASSIC as C compiler for coverage testing, if set +- Minor cleanup in contrib/minizip/zip.c [Vollant] +- Update make_vms.com [Zinser] +- Remove unnecessary gzgetc_ function +- Use optimized byte swap operations for Microsoft and GNU [Snyder] +- Fix minor typo in zlib.h comments [Rzesniowiecki] + +Changes in 1.2.6 (29 Jan 2012) +- Update the Pascal interface in contrib/pascal +- Fix function numbers for gzgetc_ in zlibvc.def files +- Fix configure.ac for contrib/minizip [Schiffer] +- Fix large-entry detection in minizip on 64-bit systems [Schiffer] +- Have ./configure use the compiler return code for error indication +- Fix CMakeLists.txt for cross compilation [McClure] +- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes] +- Fix compilation of contrib/minizip on FreeBSD [Marquez] +- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath] +- Include io.h for Turbo C / Borland C on all platforms [Truta] +- Make version explicit in contrib/minizip/configure.ac [Bosmans] +- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant] +- Minor cleanup up contrib/minizip/unzip.c [Vollant] +- Fix bug when compiling minizip with C++ [Vollant] +- Protect for long name and extra fields in contrib/minizip [Vollant] +- Avoid some warnings in contrib/minizip [Vollant] +- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip +- Add missing libs to minizip linker command +- Add support for VPATH builds in contrib/minizip +- Add an --enable-demos option to contrib/minizip/configure +- Add the generation of configure.log by ./configure +- Exit when required parameters not provided to win32/Makefile.gcc +- Have gzputc return the character written instead of the argument +- Use the -m option on ldconfig for BSD systems [Tobias] +- Correct in zlib.map when deflateResetKeep was added + +Changes in 1.2.5.3 (15 Jan 2012) +- Restore gzgetc function for binary compatibility +- Do not use _lseeki64 under Borland C++ [Truta] +- Update win32/Makefile.msc to build test/*.c [Truta] +- Remove old/visualc6 given CMakefile and other alternatives +- Update AS400 build files and documentation [Monnerat] +- Update win32/Makefile.gcc to build test/*.c [Truta] +- Permit stronger flushes after Z_BLOCK flushes +- Avoid extraneous empty blocks when doing empty flushes +- Permit Z_NULL arguments to deflatePending +- Allow deflatePrime() to insert bits in the middle of a stream +- Remove second empty static block for Z_PARTIAL_FLUSH +- Write out all of the available bits when using Z_BLOCK +- Insert the first two strings in the hash table after a flush + +Changes in 1.2.5.2 (17 Dec 2011) +- fix ld error: unable to find version dependency 'ZLIB_1.2.5' +- use relative symlinks for shared libs +- Avoid searching past window for Z_RLE strategy +- Assure that high-water mark initialization is always applied in deflate +- Add assertions to fill_window() in deflate.c to match comments +- Update python link in README +- Correct spelling error in gzread.c +- Fix bug in gzgets() for a concatenated empty gzip stream +- Correct error in comment for gz_make() +- Change gzread() and related to ignore junk after gzip streams +- Allow gzread() and related to continue after gzclearerr() +- Allow gzrewind() and gzseek() after a premature end-of-file +- Simplify gzseek() now that raw after gzip is ignored +- Change gzgetc() to a macro for speed (~40% speedup in testing) +- Fix gzclose() to return the actual error last encountered +- Always add large file support for windows +- Include zconf.h for windows large file support +- Include zconf.h.cmakein for windows large file support +- Update zconf.h.cmakein on make distclean +- Merge vestigial vsnprintf determination from zutil.h to gzguts.h +- Clarify how gzopen() appends in zlib.h comments +- Correct documentation of gzdirect() since junk at end now ignored +- Add a transparent write mode to gzopen() when 'T' is in the mode +- Update python link in zlib man page +- Get inffixed.h and MAKEFIXED result to match +- Add a ./config --solo option to make zlib subset with no libary use +- Add undocumented inflateResetKeep() function for CAB file decoding +- Add --cover option to ./configure for gcc coverage testing +- Add #define ZLIB_CONST option to use const in the z_stream interface +- Add comment to gzdopen() in zlib.h to use dup() when using fileno() +- Note behavior of uncompress() to provide as much data as it can +- Add files in contrib/minizip to aid in building libminizip +- Split off AR options in Makefile.in and configure +- Change ON macro to Z_ARG to avoid application conflicts +- Facilitate compilation with Borland C++ for pragmas and vsnprintf +- Include io.h for Turbo C / Borland C++ +- Move example.c and minigzip.c to test/ +- Simplify incomplete code table filling in inflate_table() +- Remove code from inflate.c and infback.c that is impossible to execute +- Test the inflate code with full coverage +- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw) +- Add deflateResetKeep and fix inflateResetKeep to retain dictionary +- Fix gzwrite.c to accommodate reduced memory zlib compilation +- Have inflate() with Z_FINISH avoid the allocation of a window +- Do not set strm->adler when doing raw inflate +- Fix gzeof() to behave just like feof() when read is not past end of file +- Fix bug in gzread.c when end-of-file is reached +- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF +- Document gzread() capability to read concurrently written files +- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo] + +Changes in 1.2.5.1 (10 Sep 2011) +- Update FAQ entry on shared builds (#13) +- Avoid symbolic argument to chmod in Makefile.in +- Fix bug and add consts in contrib/puff [Oberhumer] +- Update contrib/puff/zeros.raw test file to have all block types +- Add full coverage test for puff in contrib/puff/Makefile +- Fix static-only-build install in Makefile.in +- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno] +- Add libz.a dependency to shared in Makefile.in for parallel builds +- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out +- Replace $(...) with `...` in configure for non-bash sh [Bowler] +- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen] +- Add solaris* to Linux* in configure to allow gcc use [Groffen] +- Add *bsd* to Linux* case in configure [Bar-Lev] +- Add inffast.obj to dependencies in win32/Makefile.msc +- Correct spelling error in deflate.h [Kohler] +- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc +- Add test to configure for GNU C looking for gcc in output of $cc -v +- Add zlib.pc generation to win32/Makefile.gcc [Weigelt] +- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not +- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense +- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser) +- Make stronger test in zconf.h to include unistd.h for LFS +- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack] +- Fix zlib.h LFS support when Z_PREFIX used +- Add updated as400 support (removed from old) [Monnerat] +- Avoid deflate sensitivity to volatile input data +- Avoid division in adler32_combine for NO_DIVIDE +- Clarify the use of Z_FINISH with deflateBound() amount of space +- Set binary for output file in puff.c +- Use u4 type for crc_table to avoid conversion warnings +- Apply casts in zlib.h to avoid conversion warnings +- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller] +- Improve inflateSync() documentation to note indeterminancy +- Add deflatePending() function to return the amount of pending output +- Correct the spelling of "specification" in FAQ [Randers-Pehrson] +- Add a check in configure for stdarg.h, use for gzprintf() +- Check that pointers fit in ints when gzprint() compiled old style +- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler] +- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt] +- Add debug records in assmebler code [Londer] +- Update RFC references to use http://tools.ietf.org/html/... [Li] +- Add --archs option, use of libtool to configure for Mac OS X [Borstel] + +Changes in 1.2.5 (19 Apr 2010) +- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev] +- Default to libdir as sharedlibdir in configure [Nieder] +- Update copyright dates on modified source files +- Update trees.c to be able to generate modified trees.h +- Exit configure for MinGW, suggesting win32/Makefile.gcc +- Check for NULL path in gz_open [Homurlu] + +Changes in 1.2.4.5 (18 Apr 2010) +- Set sharedlibdir in configure [Torok] +- Set LDFLAGS in Makefile.in [Bar-Lev] +- Avoid mkdir objs race condition in Makefile.in [Bowler] +- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays +- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C +- Don't use hidden attribute when it is a warning generator (e.g. Solaris) + +Changes in 1.2.4.4 (18 Apr 2010) +- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok] +- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty +- Try to use bash or ksh regardless of functionality of /bin/sh +- Fix configure incompatibility with NetBSD sh +- Remove attempt to run under bash or ksh since have better NetBSD fix +- Fix win32/Makefile.gcc for MinGW [Bar-Lev] +- Add diagnostic messages when using CROSS_PREFIX in configure +- Added --sharedlibdir option to configure [Weigelt] +- Use hidden visibility attribute when available [Frysinger] + +Changes in 1.2.4.3 (10 Apr 2010) +- Only use CROSS_PREFIX in configure for ar and ranlib if they exist +- Use CROSS_PREFIX for nm [Bar-Lev] +- Assume _LARGEFILE64_SOURCE defined is equivalent to true +- Avoid use of undefined symbols in #if with && and || +- Make *64 prototypes in gzguts.h consistent with functions +- Add -shared load option for MinGW in configure [Bowler] +- Move z_off64_t to public interface, use instead of off64_t +- Remove ! from shell test in configure (not portable to Solaris) +- Change +0 macro tests to -0 for possibly increased portability + +Changes in 1.2.4.2 (9 Apr 2010) +- Add consistent carriage returns to readme.txt's in masmx86 and masmx64 +- Really provide prototypes for *64 functions when building without LFS +- Only define unlink() in minigzip.c if unistd.h not included +- Update README to point to contrib/vstudio project files +- Move projects/vc6 to old/ and remove projects/ +- Include stdlib.h in minigzip.c for setmode() definition under WinCE +- Clean up assembler builds in win32/Makefile.msc [Rowe] +- Include sys/types.h for Microsoft for off_t definition +- Fix memory leak on error in gz_open() +- Symbolize nm as $NM in configure [Weigelt] +- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt] +- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined +- Fix bug in gzeof() to take into account unused input data +- Avoid initialization of structures with variables in puff.c +- Updated win32/README-WIN32.txt [Rowe] + +Changes in 1.2.4.1 (28 Mar 2010) +- Remove the use of [a-z] constructs for sed in configure [gentoo 310225] +- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech] +- Restore "for debugging" comment on sprintf() in gzlib.c +- Remove fdopen for MVS from gzguts.h +- Put new README-WIN32.txt in win32 [Rowe] +- Add check for shell to configure and invoke another shell if needed +- Fix big fat stinking bug in gzseek() on uncompressed files +- Remove vestigial F_OPEN64 define in zutil.h +- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE +- Avoid errors on non-LFS systems when applications define LFS macros +- Set EXE to ".exe" in configure for MINGW [Kahle] +- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill] +- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev] +- Add DLL install in win32/makefile.gcc [Bar-Lev] +- Allow Linux* or linux* from uname in configure [Bar-Lev] +- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev] +- Add cross-compilation prefixes to configure [Bar-Lev] +- Match type exactly in gz_load() invocation in gzread.c +- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func +- Provide prototypes for *64 functions when building zlib without LFS +- Don't use -lc when linking shared library on MinGW +- Remove errno.h check in configure and vestigial errno code in zutil.h + +Changes in 1.2.4 (14 Mar 2010) +- Fix VER3 extraction in configure for no fourth subversion +- Update zlib.3, add docs to Makefile.in to make .pdf out of it +- Add zlib.3.pdf to distribution +- Don't set error code in gzerror() if passed pointer is NULL +- Apply destination directory fixes to CMakeLists.txt [Lowman] +- Move #cmakedefine's to a new zconf.in.cmakein +- Restore zconf.h for builds that don't use configure or cmake +- Add distclean to dummy Makefile for convenience +- Update and improve INDEX, README, and FAQ +- Update CMakeLists.txt for the return of zconf.h [Lowman] +- Update contrib/vstudio/vc9 and vc10 [Vollant] +- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc +- Apply license and readme changes to contrib/asm686 [Raiter] +- Check file name lengths and add -c option in minigzip.c [Li] +- Update contrib/amd64 and contrib/masmx86/ [Vollant] +- Avoid use of "eof" parameter in trees.c to not shadow library variable +- Update make_vms.com for removal of zlibdefs.h [Zinser] +- Update assembler code and vstudio projects in contrib [Vollant] +- Remove outdated assembler code contrib/masm686 and contrib/asm586 +- Remove old vc7 and vc8 from contrib/vstudio +- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe] +- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open() +- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant] +- Remove *64 functions from win32/zlib.def (they're not 64-bit yet) +- Fix bug in void-returning vsprintf() case in gzwrite.c +- Fix name change from inflate.h in contrib/inflate86/inffas86.c +- Check if temporary file exists before removing in make_vms.com [Zinser] +- Fix make install and uninstall for --static option +- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta] +- Update readme.txt in contrib/masmx64 and masmx86 to assemble + +Changes in 1.2.3.9 (21 Feb 2010) +- Expunge gzio.c +- Move as400 build information to old +- Fix updates in contrib/minizip and contrib/vstudio +- Add const to vsnprintf test in configure to avoid warnings [Weigelt] +- Delete zconf.h (made by configure) [Weigelt] +- Change zconf.in.h to zconf.h.in per convention [Weigelt] +- Check for NULL buf in gzgets() +- Return empty string for gzgets() with len == 1 (like fgets()) +- Fix description of gzgets() in zlib.h for end-of-file, NULL return +- Update minizip to 1.1 [Vollant] +- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c +- Note in zlib.h that gzerror() should be used to distinguish from EOF +- Remove use of snprintf() from gzlib.c +- Fix bug in gzseek() +- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant] +- Fix zconf.h generation in CMakeLists.txt [Lowman] +- Improve comments in zconf.h where modified by configure + +Changes in 1.2.3.8 (13 Feb 2010) +- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer] +- Use z_off64_t in gz_zero() and gz_skip() to match state->skip +- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t) +- Revert to Makefile.in from 1.2.3.6 (live with the clutter) +- Fix missing error return in gzflush(), add zlib.h note +- Add *64 functions to zlib.map [Levin] +- Fix signed/unsigned comparison in gz_comp() +- Use SFLAGS when testing shared linking in configure +- Add --64 option to ./configure to use -m64 with gcc +- Fix ./configure --help to correctly name options +- Have make fail if a test fails [Levin] +- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson] +- Remove assembler object files from contrib + +Changes in 1.2.3.7 (24 Jan 2010) +- Always gzopen() with O_LARGEFILE if available +- Fix gzdirect() to work immediately after gzopen() or gzdopen() +- Make gzdirect() more precise when the state changes while reading +- Improve zlib.h documentation in many places +- Catch memory allocation failure in gz_open() +- Complete close operation if seek forward in gzclose_w() fails +- Return Z_ERRNO from gzclose_r() if close() fails +- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL +- Return zero for gzwrite() errors to match zlib.h description +- Return -1 on gzputs() error to match zlib.h description +- Add zconf.in.h to allow recovery from configure modification [Weigelt] +- Fix static library permissions in Makefile.in [Weigelt] +- Avoid warnings in configure tests that hide functionality [Weigelt] +- Add *BSD and DragonFly to Linux case in configure [gentoo 123571] +- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212] +- Avoid access of uninitialized data for first inflateReset2 call [Gomes] +- Keep object files in subdirectories to reduce the clutter somewhat +- Remove default Makefile and zlibdefs.h, add dummy Makefile +- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_ +- Remove zlibdefs.h completely -- modify zconf.h instead + +Changes in 1.2.3.6 (17 Jan 2010) +- Avoid void * arithmetic in gzread.c and gzwrite.c +- Make compilers happier with const char * for gz_error message +- Avoid unused parameter warning in inflate.c +- Avoid signed-unsigned comparison warning in inflate.c +- Indent #pragma's for traditional C +- Fix usage of strwinerror() in glib.c, change to gz_strwinerror() +- Correct email address in configure for system options +- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser] +- Update zlib.map [Brown] +- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok] +- Apply various fixes to CMakeLists.txt [Lowman] +- Add checks on len in gzread() and gzwrite() +- Add error message for no more room for gzungetc() +- Remove zlib version check in gzwrite() +- Defer compression of gzprintf() result until need to +- Use snprintf() in gzdopen() if available +- Remove USE_MMAP configuration determination (only used by minigzip) +- Remove examples/pigz.c (available separately) +- Update examples/gun.c to 1.6 + +Changes in 1.2.3.5 (8 Jan 2010) +- Add space after #if in zutil.h for some compilers +- Fix relatively harmless bug in deflate_fast() [Exarevsky] +- Fix same problem in deflate_slow() +- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown] +- Add deflate_rle() for faster Z_RLE strategy run-length encoding +- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding +- Change name of "write" variable in inffast.c to avoid library collisions +- Fix premature EOF from gzread() in gzio.c [Brown] +- Use zlib header window size if windowBits is 0 in inflateInit2() +- Remove compressBound() call in deflate.c to avoid linking compress.o +- Replace use of errno in gz* with functions, support WinCE [Alves] +- Provide alternative to perror() in minigzip.c for WinCE [Alves] +- Don't use _vsnprintf on later versions of MSVC [Lowman] +- Add CMake build script and input file [Lowman] +- Update contrib/minizip to 1.1 [Svensson, Vollant] +- Moved nintendods directory from contrib to . +- Replace gzio.c with a new set of routines with the same functionality +- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above +- Update contrib/minizip to 1.1b +- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h + +Changes in 1.2.3.4 (21 Dec 2009) +- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility +- Update comments in configure and Makefile.in for default --shared +- Fix test -z's in configure [Marquess] +- Build examplesh and minigzipsh when not testing +- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h +- Import LDFLAGS from the environment in configure +- Fix configure to populate SFLAGS with discovered CFLAGS options +- Adapt make_vms.com to the new Makefile.in [Zinser] +- Add zlib2ansi script for C++ compilation [Marquess] +- Add _FILE_OFFSET_BITS=64 test to make test (when applicable) +- Add AMD64 assembler code for longest match to contrib [Teterin] +- Include options from $SFLAGS when doing $LDSHARED +- Simplify 64-bit file support by introducing z_off64_t type +- Make shared object files in objs directory to work around old Sun cc +- Use only three-part version number for Darwin shared compiles +- Add rc option to ar in Makefile.in for when ./configure not run +- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4* +- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile +- Protect against _FILE_OFFSET_BITS being defined when compiling zlib +- Rename Makefile.in targets allstatic to static and allshared to shared +- Fix static and shared Makefile.in targets to be independent +- Correct error return bug in gz_open() by setting state [Brown] +- Put spaces before ;;'s in configure for better sh compatibility +- Add pigz.c (parallel implementation of gzip) to examples/ +- Correct constant in crc32.c to UL [Leventhal] +- Reject negative lengths in crc32_combine() +- Add inflateReset2() function to work like inflateEnd()/inflateInit2() +- Include sys/types.h for _LARGEFILE64_SOURCE [Brown] +- Correct typo in doc/algorithm.txt [Janik] +- Fix bug in adler32_combine() [Zhu] +- Catch missing-end-of-block-code error in all inflates and in puff + Assures that random input to inflate eventually results in an error +- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/ +- Update ENOUGH and its usage to reflect discovered bounds +- Fix gzerror() error report on empty input file [Brown] +- Add ush casts in trees.c to avoid pedantic runtime errors +- Fix typo in zlib.h uncompress() description [Reiss] +- Correct inflate() comments with regard to automatic header detection +- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays) +- Put new version of gzlog (2.0) in examples with interruption recovery +- Add puff compile option to permit invalid distance-too-far streams +- Add puff TEST command options, ability to read piped input +- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but + _LARGEFILE64_SOURCE not defined +- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart +- Fix deflateSetDictionary() to use all 32K for output consistency +- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h) +- Clear bytes after deflate lookahead to avoid use of uninitialized data +- Change a limit in inftrees.c to be more transparent to Coverity Prevent +- Update win32/zlib.def with exported symbols from zlib.h +- Correct spelling errors in zlib.h [Willem, Sobrado] +- Allow Z_BLOCK for deflate() to force a new block +- Allow negative bits in inflatePrime() to delete existing bit buffer +- Add Z_TREES flush option to inflate() to return at end of trees +- Add inflateMark() to return current state information for random access +- Add Makefile for NintendoDS to contrib [Costa] +- Add -w in configure compile tests to avoid spurious warnings [Beucler] +- Fix typos in zlib.h comments for deflateSetDictionary() +- Fix EOF detection in transparent gzread() [Maier] + +Changes in 1.2.3.3 (2 October 2006) +- Make --shared the default for configure, add a --static option +- Add compile option to permit invalid distance-too-far streams +- Add inflateUndermine() function which is required to enable above +- Remove use of "this" variable name for C++ compatibility [Marquess] +- Add testing of shared library in make test, if shared library built +- Use ftello() and fseeko() if available instead of ftell() and fseek() +- Provide two versions of all functions that use the z_off_t type for + binary compatibility -- a normal version and a 64-bit offset version, + per the Large File Support Extension when _LARGEFILE64_SOURCE is + defined; use the 64-bit versions by default when _FILE_OFFSET_BITS + is defined to be 64 +- Add a --uname= option to configure to perhaps help with cross-compiling + +Changes in 1.2.3.2 (3 September 2006) +- Turn off silly Borland warnings [Hay] +- Use off64_t and define _LARGEFILE64_SOURCE when present +- Fix missing dependency on inffixed.h in Makefile.in +- Rig configure --shared to build both shared and static [Teredesai, Truta] +- Remove zconf.in.h and instead create a new zlibdefs.h file +- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant] +- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt] + +Changes in 1.2.3.1 (16 August 2006) +- Add watcom directory with OpenWatcom make files [Daniel] +- Remove #undef of FAR in zconf.in.h for MVS [Fedtke] +- Update make_vms.com [Zinser] +- Use -fPIC for shared build in configure [Teredesai, Nicholson] +- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen] +- Use fdopen() (not _fdopen()) for Interix in zutil.h [BŠck] +- Add some FAQ entries about the contrib directory +- Update the MVS question in the FAQ +- Avoid extraneous reads after EOF in gzio.c [Brown] +- Correct spelling of "successfully" in gzio.c [Randers-Pehrson] +- Add comments to zlib.h about gzerror() usage [Brown] +- Set extra flags in gzip header in gzopen() like deflate() does +- Make configure options more compatible with double-dash conventions + [Weigelt] +- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen] +- Fix uninstall target in Makefile.in [Truta] +- Add pkgconfig support [Weigelt] +- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt] +- Replace set_data_type() with a more accurate detect_data_type() in + trees.c, according to the txtvsbin.txt document [Truta] +- Swap the order of #include and #include "zlib.h" in + gzio.c, example.c and minigzip.c [Truta] +- Shut up annoying VS2005 warnings about standard C deprecation [Rowe, + Truta] (where?) +- Fix target "clean" from win32/Makefile.bor [Truta] +- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe] +- Update zlib www home address in win32/DLL_FAQ.txt [Truta] +- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove] +- Enable browse info in the "Debug" and "ASM Debug" configurations in + the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta] +- Add pkgconfig support [Weigelt] +- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h, + for use in win32/zlib1.rc [Polushin, Rowe, Truta] +- Add a document that explains the new text detection scheme to + doc/txtvsbin.txt [Truta] +- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta] +- Move algorithm.txt into doc/ [Truta] +- Synchronize FAQ with website +- Fix compressBound(), was low for some pathological cases [Fearnley] +- Take into account wrapper variations in deflateBound() +- Set examples/zpipe.c input and output to binary mode for Windows +- Update examples/zlib_how.html with new zpipe.c (also web site) +- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems + that gcc became pickier in 4.0) +- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain + un-versioned, the patch adds versioning only for symbols introduced in + zlib-1.2.0 or later. It also declares as local those symbols which are + not designed to be exported." [Levin] +- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure +- Do not initialize global static by default in trees.c, add a response + NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess] +- Don't use strerror() in gzio.c under WinCE [Yakimov] +- Don't use errno.h in zutil.h under WinCE [Yakimov] +- Move arguments for AR to its usage to allow replacing ar [Marot] +- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson] +- Improve inflateInit() and inflateInit2() documentation +- Fix structure size comment in inflate.h +- Change configure help option from --h* to --help [Santos] + +Changes in 1.2.3 (18 July 2005) +- Apply security vulnerability fixes to contrib/infback9 as well +- Clean up some text files (carriage returns, trailing space) +- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant] + +Changes in 1.2.2.4 (11 July 2005) +- Add inflatePrime() function for starting inflation at bit boundary +- Avoid some Visual C warnings in deflate.c +- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit + compile +- Fix some spelling errors in comments [Betts] +- Correct inflateInit2() error return documentation in zlib.h +- Add zran.c example of compressed data random access to examples + directory, shows use of inflatePrime() +- Fix cast for assignments to strm->state in inflate.c and infback.c +- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer] +- Move declarations of gf2 functions to right place in crc32.c [Oberhumer] +- Add cast in trees.c t avoid a warning [Oberhumer] +- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer] +- Update make_vms.com [Zinser] +- Initialize state->write in inflateReset() since copied in inflate_fast() +- Be more strict on incomplete code sets in inflate_table() and increase + ENOUGH and MAXD -- this repairs a possible security vulnerability for + invalid inflate input. Thanks to Tavis Ormandy and Markus Oberhumer for + discovering the vulnerability and providing test cases. +- Add ia64 support to configure for HP-UX [Smith] +- Add error return to gzread() for format or i/o error [Levin] +- Use malloc.h for OS/2 [Necasek] + +Changes in 1.2.2.3 (27 May 2005) +- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile +- Typecast fread() return values in gzio.c [Vollant] +- Remove trailing space in minigzip.c outmode (VC++ can't deal with it) +- Fix crc check bug in gzread() after gzungetc() [Heiner] +- Add the deflateTune() function to adjust internal compression parameters +- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack) +- Remove an incorrect assertion in examples/zpipe.c +- Add C++ wrapper in infback9.h [Donais] +- Fix bug in inflateCopy() when decoding fixed codes +- Note in zlib.h how much deflateSetDictionary() actually uses +- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used) +- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer] +- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer] +- Add gzdirect() function to indicate transparent reads +- Update contrib/minizip [Vollant] +- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer] +- Add casts in crc32.c to avoid warnings [Oberhumer] +- Add contrib/masmx64 [Vollant] +- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant] + +Changes in 1.2.2.2 (30 December 2004) +- Replace structure assignments in deflate.c and inflate.c with zmemcpy to + avoid implicit memcpy calls (portability for no-library compilation) +- Increase sprintf() buffer size in gzdopen() to allow for large numbers +- Add INFLATE_STRICT to check distances against zlib header +- Improve WinCE errno handling and comments [Chang] +- Remove comment about no gzip header processing in FAQ +- Add Z_FIXED strategy option to deflateInit2() to force fixed trees +- Add updated make_vms.com [Coghlan], update README +- Create a new "examples" directory, move gzappend.c there, add zpipe.c, + fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html. +- Add FAQ entry and comments in deflate.c on uninitialized memory access +- Add Solaris 9 make options in configure [Gilbert] +- Allow strerror() usage in gzio.c for STDC +- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer] +- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant] +- Use z_off_t for adler32_combine() and crc32_combine() lengths +- Make adler32() much faster for small len +- Use OS_CODE in deflate() default gzip header + +Changes in 1.2.2.1 (31 October 2004) +- Allow inflateSetDictionary() call for raw inflate +- Fix inflate header crc check bug for file names and comments +- Add deflateSetHeader() and gz_header structure for custom gzip headers +- Add inflateGetheader() to retrieve gzip headers +- Add crc32_combine() and adler32_combine() functions +- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list +- Use zstreamp consistently in zlib.h (inflate_back functions) +- Remove GUNZIP condition from definition of inflate_mode in inflate.h + and in contrib/inflate86/inffast.S [Truta, Anderson] +- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson] +- Update projects/README.projects and projects/visualc6 [Truta] +- Update win32/DLL_FAQ.txt [Truta] +- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta] +- Deprecate Z_ASCII; use Z_TEXT instead [Truta] +- Use a new algorithm for setting strm->data_type in trees.c [Truta] +- Do not define an exit() prototype in zutil.c unless DEBUG defined +- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta] +- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate() +- Fix Darwin build version identification [Peterson] + +Changes in 1.2.2 (3 October 2004) +- Update zlib.h comments on gzip in-memory processing +- Set adler to 1 in inflateReset() to support Java test suite [Walles] +- Add contrib/dotzlib [Ravn] +- Update win32/DLL_FAQ.txt [Truta] +- Update contrib/minizip [Vollant] +- Move contrib/visual-basic.txt to old/ [Truta] +- Fix assembler builds in projects/visualc6/ [Truta] + +Changes in 1.2.1.2 (9 September 2004) +- Update INDEX file +- Fix trees.c to update strm->data_type (no one ever noticed!) +- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown] +- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE) +- Add limited multitasking protection to DYNAMIC_CRC_TABLE +- Add NO_vsnprintf for VMS in zutil.h [Mozilla] +- Don't declare strerror() under VMS [Mozilla] +- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize +- Update contrib/ada [Anisimkov] +- Update contrib/minizip [Vollant] +- Fix configure to not hardcode directories for Darwin [Peterson] +- Fix gzio.c to not return error on empty files [Brown] +- Fix indentation; update version in contrib/delphi/ZLib.pas and + contrib/pascal/zlibpas.pas [Truta] +- Update mkasm.bat in contrib/masmx86 [Truta] +- Update contrib/untgz [Truta] +- Add projects/README.projects [Truta] +- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta] +- Update win32/DLL_FAQ.txt [Truta] +- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta] +- Remove an unnecessary assignment to curr in inftrees.c [Truta] +- Add OS/2 to exe builds in configure [Poltorak] +- Remove err dummy parameter in zlib.h [Kientzle] + +Changes in 1.2.1.1 (9 January 2004) +- Update email address in README +- Several FAQ updates +- Fix a big fat bug in inftrees.c that prevented decoding valid + dynamic blocks with only literals and no distance codes -- + Thanks to "Hot Emu" for the bug report and sample file +- Add a note to puff.c on no distance codes case. + +Changes in 1.2.1 (17 November 2003) +- Remove a tab in contrib/gzappend/gzappend.c +- Update some interfaces in contrib for new zlib functions +- Update zlib version number in some contrib entries +- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta] +- Support shared libraries on Hurd and KFreeBSD [Brown] +- Fix error in NO_DIVIDE option of adler32.c + +Changes in 1.2.0.8 (4 November 2003) +- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas +- Add experimental NO_DIVIDE #define in adler32.c + - Possibly faster on some processors (let me know if it is) +- Correct Z_BLOCK to not return on first inflate call if no wrap +- Fix strm->data_type on inflate() return to correctly indicate EOB +- Add deflatePrime() function for appending in the middle of a byte +- Add contrib/gzappend for an example of appending to a stream +- Update win32/DLL_FAQ.txt [Truta] +- Delete Turbo C comment in README [Truta] +- Improve some indentation in zconf.h [Truta] +- Fix infinite loop on bad input in configure script [Church] +- Fix gzeof() for concatenated gzip files [Johnson] +- Add example to contrib/visual-basic.txt [Michael B.] +- Add -p to mkdir's in Makefile.in [vda] +- Fix configure to properly detect presence or lack of printf functions +- Add AS400 support [Monnerat] +- Add a little Cygwin support [Wilson] + +Changes in 1.2.0.7 (21 September 2003) +- Correct some debug formats in contrib/infback9 +- Cast a type in a debug statement in trees.c +- Change search and replace delimiter in configure from % to # [Beebe] +- Update contrib/untgz to 0.2 with various fixes [Truta] +- Add build support for Amiga [Nikl] +- Remove some directories in old that have been updated to 1.2 +- Add dylib building for Mac OS X in configure and Makefile.in +- Remove old distribution stuff from Makefile +- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X +- Update links in README + +Changes in 1.2.0.6 (13 September 2003) +- Minor FAQ updates +- Update contrib/minizip to 1.00 [Vollant] +- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta] +- Update POSTINC comment for 68060 [Nikl] +- Add contrib/infback9 with deflate64 decoding (unsupported) +- For MVS define NO_vsnprintf and undefine FAR [van Burik] +- Add pragma for fdopen on MVS [van Burik] + +Changes in 1.2.0.5 (8 September 2003) +- Add OF to inflateBackEnd() declaration in zlib.h +- Remember start when using gzdopen in the middle of a file +- Use internal off_t counters in gz* functions to properly handle seeks +- Perform more rigorous check for distance-too-far in inffast.c +- Add Z_BLOCK flush option to return from inflate at block boundary +- Set strm->data_type on return from inflate + - Indicate bits unused, if at block boundary, and if in last block +- Replace size_t with ptrdiff_t in crc32.c, and check for correct size +- Add condition so old NO_DEFLATE define still works for compatibility +- FAQ update regarding the Windows DLL [Truta] +- INDEX update: add qnx entry, remove aix entry [Truta] +- Install zlib.3 into mandir [Wilson] +- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta] +- Adapt the zlib interface to the new DLL convention guidelines [Truta] +- Introduce ZLIB_WINAPI macro to allow the export of functions using + the WINAPI calling convention, for Visual Basic [Vollant, Truta] +- Update msdos and win32 scripts and makefiles [Truta] +- Export symbols by name, not by ordinal, in win32/zlib.def [Truta] +- Add contrib/ada [Anisimkov] +- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta] +- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant] +- Add contrib/masm686 [Truta] +- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm + [Truta, Vollant] +- Update contrib/delphi; rename to contrib/pascal; add example [Truta] +- Remove contrib/delphi2; add a new contrib/delphi [Truta] +- Avoid inclusion of the nonstandard in contrib/iostream, + and fix some method prototypes [Truta] +- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip + [Truta] +- Avoid the use of backslash (\) in contrib/minizip [Vollant] +- Fix file time handling in contrib/untgz; update makefiles [Truta] +- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines + [Vollant] +- Remove contrib/vstudio/vc15_16 [Vollant] +- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta] +- Update README.contrib [Truta] +- Invert the assignment order of match_head and s->prev[...] in + INSERT_STRING [Truta] +- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings + [Truta] +- Compare function pointers with 0, not with NULL or Z_NULL [Truta] +- Fix prototype of syncsearch in inflate.c [Truta] +- Introduce ASMINF macro to be enabled when using an ASM implementation + of inflate_fast [Truta] +- Change NO_DEFLATE to NO_GZCOMPRESS [Truta] +- Modify test_gzio in example.c to take a single file name as a + parameter [Truta] +- Exit the example.c program if gzopen fails [Truta] +- Add type casts around strlen in example.c [Truta] +- Remove casting to sizeof in minigzip.c; give a proper type + to the variable compared with SUFFIX_LEN [Truta] +- Update definitions of STDC and STDC99 in zconf.h [Truta] +- Synchronize zconf.h with the new Windows DLL interface [Truta] +- Use SYS16BIT instead of __32BIT__ to distinguish between + 16- and 32-bit platforms [Truta] +- Use far memory allocators in small 16-bit memory models for + Turbo C [Truta] +- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in + zlibCompileFlags [Truta] +- Cygwin has vsnprintf [Wilson] +- In Windows16, OS_CODE is 0, as in MSDOS [Truta] +- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson] + +Changes in 1.2.0.4 (10 August 2003) +- Minor FAQ updates +- Be more strict when checking inflateInit2's windowBits parameter +- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well +- Add gzip wrapper option to deflateInit2 using windowBits +- Add updated QNX rule in configure and qnx directory [Bonnefoy] +- Make inflate distance-too-far checks more rigorous +- Clean up FAR usage in inflate +- Add casting to sizeof() in gzio.c and minigzip.c + +Changes in 1.2.0.3 (19 July 2003) +- Fix silly error in gzungetc() implementation [Vollant] +- Update contrib/minizip and contrib/vstudio [Vollant] +- Fix printf format in example.c +- Correct cdecl support in zconf.in.h [Anisimkov] +- Minor FAQ updates + +Changes in 1.2.0.2 (13 July 2003) +- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons +- Attempt to avoid warnings in crc32.c for pointer-int conversion +- Add AIX to configure, remove aix directory [Bakker] +- Add some casts to minigzip.c +- Improve checking after insecure sprintf() or vsprintf() calls +- Remove #elif's from crc32.c +- Change leave label to inf_leave in inflate.c and infback.c to avoid + library conflicts +- Remove inflate gzip decoding by default--only enable gzip decoding by + special request for stricter backward compatibility +- Add zlibCompileFlags() function to return compilation information +- More typecasting in deflate.c to avoid warnings +- Remove leading underscore from _Capital #defines [Truta] +- Fix configure to link shared library when testing +- Add some Windows CE target adjustments [Mai] +- Remove #define ZLIB_DLL in zconf.h [Vollant] +- Add zlib.3 [Rodgers] +- Update RFC URL in deflate.c and algorithm.txt [Mai] +- Add zlib_dll_FAQ.txt to contrib [Truta] +- Add UL to some constants [Truta] +- Update minizip and vstudio [Vollant] +- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h +- Expand use of NO_DUMMY_DECL to avoid all dummy structures +- Added iostream3 to contrib [Schwardt] +- Replace rewind() with fseek() for WinCE [Truta] +- Improve setting of zlib format compression level flags + - Report 0 for huffman and rle strategies and for level == 0 or 1 + - Report 2 only for level == 6 +- Only deal with 64K limit when necessary at compile time [Truta] +- Allow TOO_FAR check to be turned off at compile time [Truta] +- Add gzclearerr() function [Souza] +- Add gzungetc() function + +Changes in 1.2.0.1 (17 March 2003) +- Add Z_RLE strategy for run-length encoding [Truta] + - When Z_RLE requested, restrict matches to distance one + - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE +- Correct FASTEST compilation to allow level == 0 +- Clean up what gets compiled for FASTEST +- Incorporate changes to zconf.in.h [Vollant] + - Refine detection of Turbo C need for dummy returns + - Refine ZLIB_DLL compilation + - Include additional header file on VMS for off_t typedef +- Try to use _vsnprintf where it supplants vsprintf [Vollant] +- Add some casts in inffast.c +- Enchance comments in zlib.h on what happens if gzprintf() tries to + write more than 4095 bytes before compression +- Remove unused state from inflateBackEnd() +- Remove exit(0) from minigzip.c, example.c +- Get rid of all those darn tabs +- Add "check" target to Makefile.in that does the same thing as "test" +- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in +- Update contrib/inflate86 [Anderson] +- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant] +- Add msdos and win32 directories with makefiles [Truta] +- More additions and improvements to the FAQ + +Changes in 1.2.0 (9 March 2003) +- New and improved inflate code + - About 20% faster + - Does not allocate 32K window unless and until needed + - Automatically detects and decompresses gzip streams + - Raw inflate no longer needs an extra dummy byte at end + - Added inflateBack functions using a callback interface--even faster + than inflate, useful for file utilities (gzip, zip) + - Added inflateCopy() function to record state for random access on + externally generated deflate streams (e.g. in gzip files) + - More readable code (I hope) +- New and improved crc32() + - About 50% faster, thanks to suggestions from Rodney Brown +- Add deflateBound() and compressBound() functions +- Fix memory leak in deflateInit2() +- Permit setting dictionary for raw deflate (for parallel deflate) +- Fix const declaration for gzwrite() +- Check for some malloc() failures in gzio.c +- Fix bug in gzopen() on single-byte file 0x1f +- Fix bug in gzread() on concatenated file with 0x1f at end of buffer + and next buffer doesn't start with 0x8b +- Fix uncompress() to return Z_DATA_ERROR on truncated input +- Free memory at end of example.c +- Remove MAX #define in trees.c (conflicted with some libraries) +- Fix static const's in deflate.c, gzio.c, and zutil.[ch] +- Declare malloc() and free() in gzio.c if STDC not defined +- Use malloc() instead of calloc() in zutil.c if int big enough +- Define STDC for AIX +- Add aix/ with approach for compiling shared library on AIX +- Add HP-UX support for shared libraries in configure +- Add OpenUNIX support for shared libraries in configure +- Use $cc instead of gcc to build shared library +- Make prefix directory if needed when installing +- Correct Macintosh avoidance of typedef Byte in zconf.h +- Correct Turbo C memory allocation when under Linux +- Use libz.a instead of -lz in Makefile (assure use of compiled library) +- Update configure to check for snprintf or vsnprintf functions and their + return value, warn during make if using an insecure function +- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that + is lost when library is used--resolution is to build new zconf.h +- Documentation improvements (in zlib.h): + - Document raw deflate and inflate + - Update RFCs URL + - Point out that zlib and gzip formats are different + - Note that Z_BUF_ERROR is not fatal + - Document string limit for gzprintf() and possible buffer overflow + - Note requirement on avail_out when flushing + - Note permitted values of flush parameter of inflate() +- Add some FAQs (and even answers) to the FAQ +- Add contrib/inflate86/ for x86 faster inflate +- Add contrib/blast/ for PKWare Data Compression Library decompression +- Add contrib/puff/ simple inflate for deflate format description + +Changes in 1.1.4 (11 March 2002) +- ZFREE was repeated on same allocation on some error conditions. + This creates a security problem described in + http://www.zlib.org/advisory-2002-03-11.txt +- Returned incorrect error (Z_MEM_ERROR) on some invalid data +- Avoid accesses before window for invalid distances with inflate window + less than 32K. +- force windowBits > 8 to avoid a bug in the encoder for a window size + of 256 bytes. (A complete fix will be available in 1.1.5). + +Changes in 1.1.3 (9 July 1998) +- fix "an inflate input buffer bug that shows up on rare but persistent + occasions" (Mark) +- fix gzread and gztell for concatenated .gz files (Didier Le Botlan) +- fix gzseek(..., SEEK_SET) in write mode +- fix crc check after a gzeek (Frank Faubert) +- fix miniunzip when the last entry in a zip file is itself a zip file + (J Lillge) +- add contrib/asm586 and contrib/asm686 (Brian Raiter) + See http://www.muppetlabs.com/~breadbox/software/assembly.html +- add support for Delphi 3 in contrib/delphi (Bob Dellaca) +- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti) +- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren) +- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks) +- added a FAQ file + +- Support gzdopen on Mac with Metrowerks (Jason Linhart) +- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart) +- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young) +- avoid some warnings with Borland C (Tom Tanner) +- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant) +- emulate utime() for WIN32 in contrib/untgz (Gilles Vollant) +- allow several arguments to configure (Tim Mooney, Frodo Looijaard) +- use libdir and includedir in Makefile.in (Tim Mooney) +- support shared libraries on OSF1 V4 (Tim Mooney) +- remove so_locations in "make clean" (Tim Mooney) +- fix maketree.c compilation error (Glenn, Mark) +- Python interface to zlib now in Python 1.5 (Jeremy Hylton) +- new Makefile.riscos (Rich Walker) +- initialize static descriptors in trees.c for embedded targets (Nick Smith) +- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith) +- add the OS/2 files in Makefile.in too (Andrew Zabolotny) +- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane) +- fix maketree.c to allow clean compilation of inffixed.h (Mark) +- fix parameter check in deflateCopy (Gunther Nikl) +- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler) +- Many portability patches by Christian Spieler: + . zutil.c, zutil.h: added "const" for zmem* + . Make_vms.com: fixed some typos + . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists + . msdos/Makefile.msc: remove "default rtl link library" info from obj files + . msdos/Makefile.*: use model-dependent name for the built zlib library + . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc: + new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT) +- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane) +- replace __far with _far for better portability (Christian Spieler, Tom Lane) +- fix test for errno.h in configure (Tim Newsham) + +Changes in 1.1.2 (19 March 98) +- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant) + See http://www.winimage.com/zLibDll/unzip.html +- preinitialize the inflate tables for fixed codes, to make the code + completely thread safe (Mark) +- some simplifications and slight speed-up to the inflate code (Mark) +- fix gzeof on non-compressed files (Allan Schrum) +- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs) +- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn) +- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny) +- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori) +- do not wrap extern "C" around system includes (Tom Lane) +- mention zlib binding for TCL in README (Andreas Kupries) +- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert) +- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson) +- allow "configure --prefix $HOME" (Tim Mooney) +- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson) +- move Makefile.sas to amiga/Makefile.sas + +Changes in 1.1.1 (27 Feb 98) +- fix macros _tr_tally_* in deflate.h for debug mode (Glenn Randers-Pehrson) +- remove block truncation heuristic which had very marginal effect for zlib + (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the + compression ratio on some files. This also allows inlining _tr_tally for + matches in deflate_slow. +- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier) + +Changes in 1.1.0 (24 Feb 98) +- do not return STREAM_END prematurely in inflate (John Bowler) +- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler) +- compile with -DFASTEST to get compression code optimized for speed only +- in minigzip, try mmap'ing the input file first (Miguel Albrecht) +- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain + on Sun but significant on HP) + +- add a pointer to experimental unzip library in README (Gilles Vollant) +- initialize variable gcc in configure (Chris Herborth) + +Changes in 1.0.9 (17 Feb 1998) +- added gzputs and gzgets functions +- do not clear eof flag in gzseek (Mark Diekhans) +- fix gzseek for files in transparent mode (Mark Diekhans) +- do not assume that vsprintf returns the number of bytes written (Jens Krinke) +- replace EXPORT with ZEXPORT to avoid conflict with other programs +- added compress2 in zconf.h, zlib.def, zlib.dnt +- new asm code from Gilles Vollant in contrib/asm386 +- simplify the inflate code (Mark): + . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new() + . ZALLOC the length list in inflate_trees_fixed() instead of using stack + . ZALLOC the value area for huft_build() instead of using stack + . Simplify Z_FINISH check in inflate() + +- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8 +- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi) +- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with + the declaration of FAR (Gilles VOllant) +- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann) +- read_buf buf parameter of type Bytef* instead of charf* +- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout) +- do not redeclare unlink in minigzip.c for WIN32 (John Bowler) +- fix check for presence of directories in "make install" (Ian Willis) + +Changes in 1.0.8 (27 Jan 1998) +- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant) +- fix gzgetc and gzputc for big endian systems (Markus Oberhumer) +- added compress2() to allow setting the compression level +- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong) +- use constant arrays for the static trees in trees.c instead of computing + them at run time (thanks to Ken Raeburn for this suggestion). To create + trees.h, compile with GEN_TREES_H and run "make test". +- check return code of example in "make test" and display result +- pass minigzip command line options to file_compress +- simplifying code of inflateSync to avoid gcc 2.8 bug + +- support CC="gcc -Wall" in configure -s (QingLong) +- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn) +- fix test for shared library support to avoid compiler warnings +- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant) +- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit) +- do not use fdopen for Metrowerks on Mac (Brad Pettit)) +- add checks for gzputc and gzputc in example.c +- avoid warnings in gzio.c and deflate.c (Andreas Kleinert) +- use const for the CRC table (Ken Raeburn) +- fixed "make uninstall" for shared libraries +- use Tracev instead of Trace in infblock.c +- in example.c use correct compressed length for test_sync +- suppress +vnocompatwarnings in configure for HPUX (not always supported) + +Changes in 1.0.7 (20 Jan 1998) +- fix gzseek which was broken in write mode +- return error for gzseek to negative absolute position +- fix configure for Linux (Chun-Chung Chen) +- increase stack space for MSC (Tim Wegner) +- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant) +- define EXPORTVA for gzprintf (Gilles Vollant) +- added man page zlib.3 (Rick Rodgers) +- for contrib/untgz, fix makedir() and improve Makefile + +- check gzseek in write mode in example.c +- allocate extra buffer for seeks only if gzseek is actually called +- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant) +- add inflateSyncPoint in zconf.h +- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def + +Changes in 1.0.6 (19 Jan 1998) +- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and + gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code) +- Fix a deflate bug occurring only with compression level 0 (thanks to + Andy Buckler for finding this one). +- In minigzip, pass transparently also the first byte for .Z files. +- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress() +- check Z_FINISH in inflate (thanks to Marc Schluper) +- Implement deflateCopy (thanks to Adam Costello) +- make static libraries by default in configure, add --shared option. +- move MSDOS or Windows specific files to directory msdos +- suppress the notion of partial flush to simplify the interface + (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4) +- suppress history buffer provided by application to simplify the interface + (this feature was not implemented anyway in 1.0.4) +- next_in and avail_in must be initialized before calling inflateInit or + inflateInit2 +- add EXPORT in all exported functions (for Windows DLL) +- added Makefile.nt (thanks to Stephen Williams) +- added the unsupported "contrib" directory: + contrib/asm386/ by Gilles Vollant + 386 asm code replacing longest_match(). + contrib/iostream/ by Kevin Ruland + A C++ I/O streams interface to the zlib gz* functions + contrib/iostream2/ by Tyge Løvset + Another C++ I/O streams interface + contrib/untgz/ by "Pedro A. Aranda Guti\irrez" + A very simple tar.gz file extractor using zlib + contrib/visual-basic.txt by Carlos Rios + How to use compress(), uncompress() and the gz* functions from VB. +- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression + level) in minigzip (thanks to Tom Lane) + +- use const for rommable constants in deflate +- added test for gzseek and gztell in example.c +- add undocumented function inflateSyncPoint() (hack for Paul Mackerras) +- add undocumented function zError to convert error code to string + (for Tim Smithers) +- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code. +- Use default memcpy for Symantec MSDOS compiler. +- Add EXPORT keyword for check_func (needed for Windows DLL) +- add current directory to LD_LIBRARY_PATH for "make test" +- create also a link for libz.so.1 +- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura) +- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX) +- added -soname for Linux in configure (Chun-Chung Chen, +- assign numbers to the exported functions in zlib.def (for Windows DLL) +- add advice in zlib.h for best usage of deflateSetDictionary +- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn) +- allow compilation with ANSI keywords only enabled for TurboC in large model +- avoid "versionString"[0] (Borland bug) +- add NEED_DUMMY_RETURN for Borland +- use variable z_verbose for tracing in debug mode (L. Peter Deutsch). +- allow compilation with CC +- defined STDC for OS/2 (David Charlap) +- limit external names to 8 chars for MVS (Thomas Lund) +- in minigzip.c, use static buffers only for 16-bit systems +- fix suffix check for "minigzip -d foo.gz" +- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee) +- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau) +- added makelcc.bat for lcc-win32 (Tom St Denis) +- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe) +- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion. +- check for unistd.h in configure (for off_t) +- remove useless check parameter in inflate_blocks_free +- avoid useless assignment of s->check to itself in inflate_blocks_new +- do not flush twice in gzclose (thanks to Ken Raeburn) +- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h +- use NO_ERRNO_H instead of enumeration of operating systems with errno.h +- work around buggy fclose on pipes for HP/UX +- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson) +- fix configure if CC is already equal to gcc + +Changes in 1.0.5 (3 Jan 98) +- Fix inflate to terminate gracefully when fed corrupted or invalid data +- Use const for rommable constants in inflate +- Eliminate memory leaks on error conditions in inflate +- Removed some vestigial code in inflate +- Update web address in README + +Changes in 1.0.4 (24 Jul 96) +- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF + bit, so the decompressor could decompress all the correct data but went + on to attempt decompressing extra garbage data. This affected minigzip too. +- zlibVersion and gzerror return const char* (needed for DLL) +- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno) +- use z_error only for DEBUG (avoid problem with DLLs) + +Changes in 1.0.3 (2 Jul 96) +- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS + small and medium models; this makes the library incompatible with previous + versions for these models. (No effect in large model or on other systems.) +- return OK instead of BUF_ERROR if previous deflate call returned with + avail_out as zero but there is nothing to do +- added memcmp for non STDC compilers +- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly) +- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO) +- better check for 16-bit mode MSC (avoids problem with Symantec) + +Changes in 1.0.2 (23 May 96) +- added Windows DLL support +- added a function zlibVersion (for the DLL support) +- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model) +- Bytef is define's instead of typedef'd only for Borland C +- avoid reading uninitialized memory in example.c +- mention in README that the zlib format is now RFC1950 +- updated Makefile.dj2 +- added algorithm.doc + +Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion] +- fix array overlay in deflate.c which sometimes caused bad compressed data +- fix inflate bug with empty stored block +- fix MSDOS medium model which was broken in 0.99 +- fix deflateParams() which could generated bad compressed data. +- Bytef is define'd instead of typedef'ed (work around Borland bug) +- added an INDEX file +- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32), + Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas) +- speed up adler32 for modern machines without auto-increment +- added -ansi for IRIX in configure +- static_init_done in trees.c is an int +- define unlink as delete for VMS +- fix configure for QNX +- add configure branch for SCO and HPUX +- avoid many warnings (unused variables, dead assignments, etc...) +- no fdopen for BeOS +- fix the Watcom fix for 32 bit mode (define FAR as empty) +- removed redefinition of Byte for MKWERKS +- work around an MWKERKS bug (incorrect merge of all .h files) + +Changes in 0.99 (27 Jan 96) +- allow preset dictionary shared between compressor and decompressor +- allow compression level 0 (no compression) +- add deflateParams in zlib.h: allow dynamic change of compression level + and compression strategy. +- test large buffers and deflateParams in example.c +- add optional "configure" to build zlib as a shared library +- suppress Makefile.qnx, use configure instead +- fixed deflate for 64-bit systems (detected on Cray) +- fixed inflate_blocks for 64-bit systems (detected on Alpha) +- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2) +- always return Z_BUF_ERROR when deflate() has nothing to do +- deflateInit and inflateInit are now macros to allow version checking +- prefix all global functions and types with z_ with -DZ_PREFIX +- make falloc completely reentrant (inftrees.c) +- fixed very unlikely race condition in ct_static_init +- free in reverse order of allocation to help memory manager +- use zlib-1.0/* instead of zlib/* inside the tar.gz +- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith + -Wconversion -Wstrict-prototypes -Wmissing-prototypes" +- allow gzread on concatenated .gz files +- deflateEnd now returns Z_DATA_ERROR if it was premature +- deflate is finally (?) fully deterministic (no matches beyond end of input) +- Document Z_SYNC_FLUSH +- add uninstall in Makefile +- Check for __cpluplus in zlib.h +- Better test in ct_align for partial flush +- avoid harmless warnings for Borland C++ +- initialize hash_head in deflate.c +- avoid warning on fdopen (gzio.c) for HP cc -Aa +- include stdlib.h for STDC compilers +- include errno.h for Cray +- ignore error if ranlib doesn't exist +- call ranlib twice for NeXTSTEP +- use exec_prefix instead of prefix for libz.a +- renamed ct_* as _tr_* to avoid conflict with applications +- clear z->msg in inflateInit2 before any error return +- initialize opaque in example.c, gzio.c, deflate.c and inflate.c +- fixed typo in zconf.h (_GNUC__ => __GNUC__) +- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode) +- fix typo in Make_vms.com (f$trnlnm -> f$getsyi) +- in fcalloc, normalize pointer if size > 65520 bytes +- don't use special fcalloc for 32 bit Borland C++ +- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc... +- use Z_BINARY instead of BINARY +- document that gzclose after gzdopen will close the file +- allow "a" as mode in gzopen. +- fix error checking in gzread +- allow skipping .gz extra-field on pipes +- added reference to Perl interface in README +- put the crc table in FAR data (I dislike more and more the medium model :) +- added get_crc_table +- added a dimension to all arrays (Borland C can't count). +- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast +- guard against multiple inclusion of *.h (for precompiled header on Mac) +- Watcom C pretends to be Microsoft C small model even in 32 bit mode. +- don't use unsized arrays to avoid silly warnings by Visual C++: + warning C4746: 'inflate_mask' : unsized array treated as '__far' + (what's wrong with far data in far model?). +- define enum out of inflate_blocks_state to allow compilation with C++ + +Changes in 0.95 (16 Aug 95) +- fix MSDOS small and medium model (now easier to adapt to any compiler) +- inlined send_bits +- fix the final (:-) bug for deflate with flush (output was correct but + not completely flushed in rare occasions). +- default window size is same for compression and decompression + (it's now sufficient to set MAX_WBITS in zconf.h). +- voidp -> voidpf and voidnp -> voidp (for consistency with other + typedefs and because voidnp was not near in large model). + +Changes in 0.94 (13 Aug 95) +- support MSDOS medium model +- fix deflate with flush (could sometimes generate bad output) +- fix deflateReset (zlib header was incorrectly suppressed) +- added support for VMS +- allow a compression level in gzopen() +- gzflush now calls fflush +- For deflate with flush, flush even if no more input is provided. +- rename libgz.a as libz.a +- avoid complex expression in infcodes.c triggering Turbo C bug +- work around a problem with gcc on Alpha (in INSERT_STRING) +- don't use inline functions (problem with some gcc versions) +- allow renaming of Byte, uInt, etc... with #define. +- avoid warning about (unused) pointer before start of array in deflate.c +- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c +- avoid reserved word 'new' in trees.c + +Changes in 0.93 (25 June 95) +- temporarily disable inline functions +- make deflate deterministic +- give enough lookahead for PARTIAL_FLUSH +- Set binary mode for stdin/stdout in minigzip.c for OS/2 +- don't even use signed char in inflate (not portable enough) +- fix inflate memory leak for segmented architectures + +Changes in 0.92 (3 May 95) +- don't assume that char is signed (problem on SGI) +- Clear bit buffer when starting a stored block +- no memcpy on Pyramid +- suppressed inftest.c +- optimized fill_window, put longest_match inline for gcc +- optimized inflate on stored blocks. +- untabify all sources to simplify patches + +Changes in 0.91 (2 May 95) +- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h +- Document the memory requirements in zconf.h +- added "make install" +- fix sync search logic in inflateSync +- deflate(Z_FULL_FLUSH) now works even if output buffer too short +- after inflateSync, don't scare people with just "lo world" +- added support for DJGPP + +Changes in 0.9 (1 May 95) +- don't assume that zalloc clears the allocated memory (the TurboC bug + was Mark's bug after all :) +- let again gzread copy uncompressed data unchanged (was working in 0.71) +- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented +- added a test of inflateSync in example.c +- moved MAX_WBITS to zconf.h because users might want to change that. +- document explicitly that zalloc(64K) on MSDOS must return a normalized + pointer (zero offset) +- added Makefiles for Microsoft C, Turbo C, Borland C++ +- faster crc32() + +Changes in 0.8 (29 April 95) +- added fast inflate (inffast.c) +- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this + is incompatible with previous versions of zlib which returned Z_OK. +- work around a TurboC compiler bug (bad code for b << 0, see infutil.h) + (actually that was not a compiler bug, see 0.81 above) +- gzread no longer reads one extra byte in certain cases +- In gzio destroy(), don't reference a freed structure +- avoid many warnings for MSDOS +- avoid the ERROR symbol which is used by MS Windows + +Changes in 0.71 (14 April 95) +- Fixed more MSDOS compilation problems :( There is still a bug with + TurboC large model. + +Changes in 0.7 (14 April 95) +- Added full inflate support. +- Simplified the crc32() interface. The pre- and post-conditioning + (one's complement) is now done inside crc32(). WARNING: this is + incompatible with previous versions; see zlib.h for the new usage. + +Changes in 0.61 (12 April 95) +- workaround for a bug in TurboC. example and minigzip now work on MSDOS. + +Changes in 0.6 (11 April 95) +- added minigzip.c +- added gzdopen to reopen a file descriptor as gzFile +- added transparent reading of non-gziped files in gzread. +- fixed bug in gzread (don't read crc as data) +- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose). +- don't allocate big arrays in the stack (for MSDOS) +- fix some MSDOS compilation problems + +Changes in 0.5: +- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but + not yet Z_FULL_FLUSH. +- support decompression but only in a single step (forced Z_FINISH) +- added opaque object for zalloc and zfree. +- added deflateReset and inflateReset +- added a variable zlib_version for consistency checking. +- renamed the 'filter' parameter of deflateInit2 as 'strategy'. + Added Z_FILTERED and Z_HUFFMAN_ONLY constants. + +Changes in 0.4: +- avoid "zip" everywhere, use zlib instead of ziplib. +- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush + if compression method == 8. +- added adler32 and crc32 +- renamed deflateOptions as deflateInit2, call one or the other but not both +- added the method parameter for deflateInit2. +- added inflateInit2 +- simplied considerably deflateInit and inflateInit by not supporting + user-provided history buffer. This is supported only in deflateInit2 + and inflateInit2. + +Changes in 0.3: +- prefix all macro names with Z_ +- use Z_FINISH instead of deflateEnd to finish compression. +- added Z_HUFFMAN_ONLY +- added gzerror() diff --git a/zlib/FAQ b/zlib/FAQ new file mode 100644 index 00000000..99b7cf92 --- /dev/null +++ b/zlib/FAQ @@ -0,0 +1,368 @@ + + Frequently Asked Questions about zlib + + +If your question is not there, please check the zlib home page +http://zlib.net/ which may have more recent information. +The lastest zlib FAQ is at http://zlib.net/zlib_faq.html + + + 1. Is zlib Y2K-compliant? + + Yes. zlib doesn't handle dates. + + 2. Where can I get a Windows DLL version? + + The zlib sources can be compiled without change to produce a DLL. See the + file win32/DLL_FAQ.txt in the zlib distribution. Pointers to the + precompiled DLL are found in the zlib web site at http://zlib.net/ . + + 3. Where can I get a Visual Basic interface to zlib? + + See + * http://marknelson.us/1997/01/01/zlib-engine/ + * win32/DLL_FAQ.txt in the zlib distribution + + 4. compress() returns Z_BUF_ERROR. + + Make sure that before the call of compress(), the length of the compressed + buffer is equal to the available size of the compressed buffer and not + zero. For Visual Basic, check that this parameter is passed by reference + ("as any"), not by value ("as long"). + + 5. deflate() or inflate() returns Z_BUF_ERROR. + + Before making the call, make sure that avail_in and avail_out are not zero. + When setting the parameter flush equal to Z_FINISH, also make sure that + avail_out is big enough to allow processing all pending input. Note that a + Z_BUF_ERROR is not fatal--another call to deflate() or inflate() can be + made with more input or output space. A Z_BUF_ERROR may in fact be + unavoidable depending on how the functions are used, since it is not + possible to tell whether or not there is more output pending when + strm.avail_out returns with zero. See http://zlib.net/zlib_how.html for a + heavily annotated example. + + 6. Where's the zlib documentation (man pages, etc.)? + + It's in zlib.h . Examples of zlib usage are in the files test/example.c + and test/minigzip.c, with more in examples/ . + + 7. Why don't you use GNU autoconf or libtool or ...? + + Because we would like to keep zlib as a very small and simple package. + zlib is rather portable and doesn't need much configuration. + + 8. I found a bug in zlib. + + Most of the time, such problems are due to an incorrect usage of zlib. + Please try to reproduce the problem with a small program and send the + corresponding source to us at zlib@gzip.org . Do not send multi-megabyte + data files without prior agreement. + + 9. Why do I get "undefined reference to gzputc"? + + If "make test" produces something like + + example.o(.text+0x154): undefined reference to `gzputc' + + check that you don't have old files libz.* in /usr/lib, /usr/local/lib or + /usr/X11R6/lib. Remove any old versions, then do "make install". + +10. I need a Delphi interface to zlib. + + See the contrib/delphi directory in the zlib distribution. + +11. Can zlib handle .zip archives? + + Not by itself, no. See the directory contrib/minizip in the zlib + distribution. + +12. Can zlib handle .Z files? + + No, sorry. You have to spawn an uncompress or gunzip subprocess, or adapt + the code of uncompress on your own. + +13. How can I make a Unix shared library? + + By default a shared (and a static) library is built for Unix. So: + + make distclean + ./configure + make + +14. How do I install a shared zlib library on Unix? + + After the above, then: + + make install + + However, many flavors of Unix come with a shared zlib already installed. + Before going to the trouble of compiling a shared version of zlib and + trying to install it, you may want to check if it's already there! If you + can #include , it's there. The -lz option will probably link to + it. You can check the version at the top of zlib.h or with the + ZLIB_VERSION symbol defined in zlib.h . + +15. I have a question about OttoPDF. + + We are not the authors of OttoPDF. The real author is on the OttoPDF web + site: Joel Hainley, jhainley@myndkryme.com. + +16. Can zlib decode Flate data in an Adobe PDF file? + + Yes. See http://www.pdflib.com/ . To modify PDF forms, see + http://sourceforge.net/projects/acroformtool/ . + +17. Why am I getting this "register_frame_info not found" error on Solaris? + + After installing zlib 1.1.4 on Solaris 2.6, running applications using zlib + generates an error such as: + + ld.so.1: rpm: fatal: relocation error: file /usr/local/lib/libz.so: + symbol __register_frame_info: referenced symbol not found + + The symbol __register_frame_info is not part of zlib, it is generated by + the C compiler (cc or gcc). You must recompile applications using zlib + which have this problem. This problem is specific to Solaris. See + http://www.sunfreeware.com for Solaris versions of zlib and applications + using zlib. + +18. Why does gzip give an error on a file I make with compress/deflate? + + The compress and deflate functions produce data in the zlib format, which + is different and incompatible with the gzip format. The gz* functions in + zlib on the other hand use the gzip format. Both the zlib and gzip formats + use the same compressed data format internally, but have different headers + and trailers around the compressed data. + +19. Ok, so why are there two different formats? + + The gzip format was designed to retain the directory information about a + single file, such as the name and last modification date. The zlib format + on the other hand was designed for in-memory and communication channel + applications, and has a much more compact header and trailer and uses a + faster integrity check than gzip. + +20. Well that's nice, but how do I make a gzip file in memory? + + You can request that deflate write the gzip format instead of the zlib + format using deflateInit2(). You can also request that inflate decode the + gzip format using inflateInit2(). Read zlib.h for more details. + +21. Is zlib thread-safe? + + Yes. However any library routines that zlib uses and any application- + provided memory allocation routines must also be thread-safe. zlib's gz* + functions use stdio library routines, and most of zlib's functions use the + library memory allocation routines by default. zlib's *Init* functions + allow for the application to provide custom memory allocation routines. + + Of course, you should only operate on any given zlib or gzip stream from a + single thread at a time. + +22. Can I use zlib in my commercial application? + + Yes. Please read the license in zlib.h. + +23. Is zlib under the GNU license? + + No. Please read the license in zlib.h. + +24. The license says that altered source versions must be "plainly marked". So + what exactly do I need to do to meet that requirement? + + You need to change the ZLIB_VERSION and ZLIB_VERNUM #defines in zlib.h. In + particular, the final version number needs to be changed to "f", and an + identification string should be appended to ZLIB_VERSION. Version numbers + x.x.x.f are reserved for modifications to zlib by others than the zlib + maintainers. For example, if the version of the base zlib you are altering + is "1.2.3.4", then in zlib.h you should change ZLIB_VERNUM to 0x123f, and + ZLIB_VERSION to something like "1.2.3.f-zachary-mods-v3". You can also + update the version strings in deflate.c and inftrees.c. + + For altered source distributions, you should also note the origin and + nature of the changes in zlib.h, as well as in ChangeLog and README, along + with the dates of the alterations. The origin should include at least your + name (or your company's name), and an email address to contact for help or + issues with the library. + + Note that distributing a compiled zlib library along with zlib.h and + zconf.h is also a source distribution, and so you should change + ZLIB_VERSION and ZLIB_VERNUM and note the origin and nature of the changes + in zlib.h as you would for a full source distribution. + +25. Will zlib work on a big-endian or little-endian architecture, and can I + exchange compressed data between them? + + Yes and yes. + +26. Will zlib work on a 64-bit machine? + + Yes. It has been tested on 64-bit machines, and has no dependence on any + data types being limited to 32-bits in length. If you have any + difficulties, please provide a complete problem report to zlib@gzip.org + +27. Will zlib decompress data from the PKWare Data Compression Library? + + No. The PKWare DCL uses a completely different compressed data format than + does PKZIP and zlib. However, you can look in zlib's contrib/blast + directory for a possible solution to your problem. + +28. Can I access data randomly in a compressed stream? + + No, not without some preparation. If when compressing you periodically use + Z_FULL_FLUSH, carefully write all the pending data at those points, and + keep an index of those locations, then you can start decompression at those + points. You have to be careful to not use Z_FULL_FLUSH too often, since it + can significantly degrade compression. Alternatively, you can scan a + deflate stream once to generate an index, and then use that index for + random access. See examples/zran.c . + +29. Does zlib work on MVS, OS/390, CICS, etc.? + + It has in the past, but we have not heard of any recent evidence. There + were working ports of zlib 1.1.4 to MVS, but those links no longer work. + If you know of recent, successful applications of zlib on these operating + systems, please let us know. Thanks. + +30. Is there some simpler, easier to read version of inflate I can look at to + understand the deflate format? + + First off, you should read RFC 1951. Second, yes. Look in zlib's + contrib/puff directory. + +31. Does zlib infringe on any patents? + + As far as we know, no. In fact, that was originally the whole point behind + zlib. Look here for some more information: + + http://www.gzip.org/#faq11 + +32. Can zlib work with greater than 4 GB of data? + + Yes. inflate() and deflate() will process any amount of data correctly. + Each call of inflate() or deflate() is limited to input and output chunks + of the maximum value that can be stored in the compiler's "unsigned int" + type, but there is no limit to the number of chunks. Note however that the + strm.total_in and strm_total_out counters may be limited to 4 GB. These + counters are provided as a convenience and are not used internally by + inflate() or deflate(). The application can easily set up its own counters + updated after each call of inflate() or deflate() to count beyond 4 GB. + compress() and uncompress() may be limited to 4 GB, since they operate in a + single call. gzseek() and gztell() may be limited to 4 GB depending on how + zlib is compiled. See the zlibCompileFlags() function in zlib.h. + + The word "may" appears several times above since there is a 4 GB limit only + if the compiler's "long" type is 32 bits. If the compiler's "long" type is + 64 bits, then the limit is 16 exabytes. + +33. Does zlib have any security vulnerabilities? + + The only one that we are aware of is potentially in gzprintf(). If zlib is + compiled to use sprintf() or vsprintf(), then there is no protection + against a buffer overflow of an 8K string space (or other value as set by + gzbuffer()), other than the caller of gzprintf() assuring that the output + will not exceed 8K. On the other hand, if zlib is compiled to use + snprintf() or vsnprintf(), which should normally be the case, then there is + no vulnerability. The ./configure script will display warnings if an + insecure variation of sprintf() will be used by gzprintf(). Also the + zlibCompileFlags() function will return information on what variant of + sprintf() is used by gzprintf(). + + If you don't have snprintf() or vsnprintf() and would like one, you can + find a portable implementation here: + + http://www.ijs.si/software/snprintf/ + + Note that you should be using the most recent version of zlib. Versions + 1.1.3 and before were subject to a double-free vulnerability, and versions + 1.2.1 and 1.2.2 were subject to an access exception when decompressing + invalid compressed data. + +34. Is there a Java version of zlib? + + Probably what you want is to use zlib in Java. zlib is already included + as part of the Java SDK in the java.util.zip package. If you really want + a version of zlib written in the Java language, look on the zlib home + page for links: http://zlib.net/ . + +35. I get this or that compiler or source-code scanner warning when I crank it + up to maximally-pedantic. Can't you guys write proper code? + + Many years ago, we gave up attempting to avoid warnings on every compiler + in the universe. It just got to be a waste of time, and some compilers + were downright silly as well as contradicted each other. So now, we simply + make sure that the code always works. + +36. Valgrind (or some similar memory access checker) says that deflate is + performing a conditional jump that depends on an uninitialized value. + Isn't that a bug? + + No. That is intentional for performance reasons, and the output of deflate + is not affected. This only started showing up recently since zlib 1.2.x + uses malloc() by default for allocations, whereas earlier versions used + calloc(), which zeros out the allocated memory. Even though the code was + correct, versions 1.2.4 and later was changed to not stimulate these + checkers. + +37. Will zlib read the (insert any ancient or arcane format here) compressed + data format? + + Probably not. Look in the comp.compression FAQ for pointers to various + formats and associated software. + +38. How can I encrypt/decrypt zip files with zlib? + + zlib doesn't support encryption. The original PKZIP encryption is very + weak and can be broken with freely available programs. To get strong + encryption, use GnuPG, http://www.gnupg.org/ , which already includes zlib + compression. For PKZIP compatible "encryption", look at + http://www.info-zip.org/ + +39. What's the difference between the "gzip" and "deflate" HTTP 1.1 encodings? + + "gzip" is the gzip format, and "deflate" is the zlib format. They should + probably have called the second one "zlib" instead to avoid confusion with + the raw deflate compressed data format. While the HTTP 1.1 RFC 2616 + correctly points to the zlib specification in RFC 1950 for the "deflate" + transfer encoding, there have been reports of servers and browsers that + incorrectly produce or expect raw deflate data per the deflate + specification in RFC 1951, most notably Microsoft. So even though the + "deflate" transfer encoding using the zlib format would be the more + efficient approach (and in fact exactly what the zlib format was designed + for), using the "gzip" transfer encoding is probably more reliable due to + an unfortunate choice of name on the part of the HTTP 1.1 authors. + + Bottom line: use the gzip format for HTTP 1.1 encoding. + +40. Does zlib support the new "Deflate64" format introduced by PKWare? + + No. PKWare has apparently decided to keep that format proprietary, since + they have not documented it as they have previous compression formats. In + any case, the compression improvements are so modest compared to other more + modern approaches, that it's not worth the effort to implement. + +41. I'm having a problem with the zip functions in zlib, can you help? + + There are no zip functions in zlib. You are probably using minizip by + Giles Vollant, which is found in the contrib directory of zlib. It is not + part of zlib. In fact none of the stuff in contrib is part of zlib. The + files in there are not supported by the zlib authors. You need to contact + the authors of the respective contribution for help. + +42. The match.asm code in contrib is under the GNU General Public License. + Since it's part of zlib, doesn't that mean that all of zlib falls under the + GNU GPL? + + No. The files in contrib are not part of zlib. They were contributed by + other authors and are provided as a convenience to the user within the zlib + distribution. Each item in contrib has its own license. + +43. Is zlib subject to export controls? What is its ECCN? + + zlib is not subject to export controls, and so is classified as EAR99. + +44. Can you please sign these lengthy legal documents and fax them back to us + so that we can use your software in our product? + + No. Go away. Shoo. diff --git a/zlib/README b/zlib/README new file mode 100644 index 00000000..ace67a51 --- /dev/null +++ b/zlib/README @@ -0,0 +1,124 @@ +//----------------------------------------------------------------------------- +// 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. +// +// The rest of this file consists of the original README content +//----------------------------------------------------------------------------- + +ZLIB DATA COMPRESSION LIBRARY + +zlib 1.2.8 is a general purpose data compression library. All the code is +thread safe. The data format used by the zlib library is described by RFCs +(Request for Comments) 1950 to 1952 in the files +http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and +rfc1952 (gzip format). + +All functions of the compression library are documented in the file zlib.h +(volunteer to write man pages welcome, contact zlib@gzip.org). A usage example +of the library is given in the file test/example.c which also tests that +the library is working correctly. Another example is given in the file +test/minigzip.c. The compression library itself is composed of all source +files in the root directory. + +To compile all files and run the test program, follow the instructions given at +the top of Makefile.in. In short "./configure; make test", and if that goes +well, "make install" should work for most flavors of Unix. For Windows, use +one of the special makefiles in win32/ or contrib/vstudio/ . For VMS, use +make_vms.com. + +Questions about zlib should be sent to , or to Gilles Vollant + for the Windows DLL version. The zlib home page is +http://zlib.net/ . Before reporting a problem, please check this site to +verify that you have the latest version of zlib; otherwise get the latest +version and check whether the problem still exists or not. + +PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help. + +Mark Nelson wrote an article about zlib for the Jan. 1997 +issue of Dr. Dobb's Journal; a copy of the article is available at +http://marknelson.us/1997/01/01/zlib-engine/ . + +The changes made in version 1.2.8 are documented in the file ChangeLog. + +Unsupported third party contributions are provided in directory contrib/ . + +zlib is available in Java using the java.util.zip package, documented at +http://java.sun.com/developer/technicalArticles/Programming/compression/ . + +A Perl interface to zlib written by Paul Marquess is available +at CPAN (Comprehensive Perl Archive Network) sites, including +http://search.cpan.org/~pmqs/IO-Compress-Zlib/ . + +A Python interface to zlib written by A.M. Kuchling is +available in Python 1.5 and later versions, see +http://docs.python.org/library/zlib.html . + +zlib is built into tcl: http://wiki.tcl.tk/4610 . + +An experimental package to read and write files in .zip format, written on top +of zlib by Gilles Vollant , is available in the +contrib/minizip directory of zlib. + + +Notes for some targets: + +- For Windows DLL versions, please see win32/DLL_FAQ.txt + +- For 64-bit Irix, deflate.c must be compiled without any optimization. With + -O, one libpng test fails. The test works in 32 bit mode (with the -n32 + compiler flag). The compiler bug has been reported to SGI. + +- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works + when compiled with cc. + +- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is + necessary to get gzprintf working correctly. This is done by configure. + +- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with + other compilers. Use "make test" to check your compiler. + +- gzdopen is not supported on RISCOS or BEOS. + +- For PalmOs, see http://palmzlib.sourceforge.net/ + + +Acknowledgments: + + The deflate format used by zlib was defined by Phil Katz. The deflate and + zlib specifications were written by L. Peter Deutsch. Thanks to all the + people who reported problems and suggested various improvements in zlib; they + are too numerous to cite here. + +Copyright notice: + + (C) 1995-2013 Jean-loup Gailly and Mark Adler + + This software is provided 'as-is', without any express or implied + warranty. In no event will the authors be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution. + + Jean-loup Gailly Mark Adler + jloup@gzip.org madler@alumni.caltech.edu + +If you use the zlib library in a product, we would appreciate *not* receiving +lengthy legal documents to sign. The sources are provided for free but without +warranty of any kind. The library has been entirely written by Jean-loup +Gailly and Mark Adler; it does not include third-party code. + +If you redistribute modified sources, we would appreciate that you include in +the file ChangeLog history information documenting your changes. Please read +the FAQ for more information on the distribution of modified source versions. diff --git a/zlib/deflate.c b/zlib/deflate.c index 7c22a72b..8e9a3e65 100644 --- a/zlib/deflate.c +++ b/zlib/deflate.c @@ -52,7 +52,7 @@ #include "deflate.h" const char deflate_copyright[] = - " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler "; + " deflate 1.2.8.f-Proxmark3 Copyright 1995-2013 Jean-loup Gailly and Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot @@ -60,6 +60,15 @@ const char deflate_copyright[] = copyright string in the executable of your product. */ +//----------------------------------------------------------------------------- +// 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. */ @@ -1727,12 +1736,11 @@ local block_state deflate_fast(s, flush) #ifdef ZLIB_PM3_TUNED -local uInt try_harder(s, strstart, lookahead, hash_head, level) +local uInt try_harder(s, strstart, lookahead, hash_head) deflate_state *s; uInt strstart; uInt lookahead; IPos hash_head; - uInt level; { uInt strstart_save = s->strstart; s->strstart = strstart; @@ -1768,22 +1776,11 @@ local uInt try_harder(s, strstart, lookahead, hash_head, level) } else { combined_gain = s->strstart - strstart + 1 - MIN_MATCH; // (possibly truncated) previous_length - 3 literals } - if (level > 1 && s->strstart+1 <= s->window_size - MIN_LOOKAHEAD) { // test one level more - s->prev_length = match_length; - uInt save_ins_h = s->ins_h; - UPDATE_HASH(s, s->ins_h, s->window[(s->strstart+1) + (MIN_MATCH-1)]); - combined_gain += try_harder(s, s->strstart+1, s->lookahead-1, s->head[s->ins_h], level-1); - s->ins_h = save_ins_h; + if (match_length < MIN_MATCH) { + combined_gain += 0; // no gain } else { - if (match_length < MIN_MATCH) { - combined_gain += 0; // no gain - } else { - combined_gain += match_length - MIN_MATCH; // match_length bytes coded as approx three literals - } + combined_gain += match_length - MIN_MATCH; // match_length bytes are coded as three literals } - // if (combined_length > s->lookahead - 1) { - // combined_length = s->lookahead; - // } if (combined_gain >= best_combined_gain) { // in case of a tie we prefer the longer prev_length best_combined_gain = combined_gain; best_prev_length = s->strstart - strstart + 1; @@ -1792,12 +1789,6 @@ local uInt try_harder(s, strstart, lookahead, hash_head, level) s->lookahead--; UPDATE_HASH(s, s->ins_h, s->window[(s->strstart) + (MIN_MATCH-1)]); hash_head = s->head[s->ins_h]; - // if (s->strstart - strstart + 1 == MIN_MATCH-1) { // a match with length == 2 is not possible - // s->strstart++; - // s->lookahead--; - // UPDATE_HASH(s, s->ins_h, s->window[(s->strstart) + (MIN_MATCH-1)]); - // 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 @@ -1806,11 +1797,6 @@ local uInt try_harder(s, strstart, lookahead, hash_head, level) s->ins_h = ins_h_save; s->match_length = current_match_length; s->match_start = current_match_start; - if (prev_length >= MIN_MATCH) { - if (best_prev_length != prev_length && best_prev_length >= MIN_MATCH) { - printf("at %d, level %d: Reducing prev_length from %d to %d\n", s->strstart, level, prev_length, best_prev_length); - } - } if (best_prev_length >= MIN_MATCH) { s->prev_length = best_prev_length; s->match_length = MIN_MATCH - 1; @@ -1865,7 +1851,7 @@ local block_state deflate_slow(s, flush) #ifdef ZLIB_PM3_TUNED if (s->prev_length < s->max_lazy_match) { - try_harder(s, s->strstart, s->lookahead, hash_head, 1); + try_harder(s, s->strstart, s->lookahead, hash_head); } #else diff --git a/zlib/inflate.c b/zlib/inflate.c index 417b2c41..091b9a22 100644 --- a/zlib/inflate.c +++ b/zlib/inflate.c @@ -80,6 +80,15 @@ * The history for versions after 1.2.0 are in ChangeLog in zlib distribution. */ +//----------------------------------------------------------------------------- +// 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" diff --git a/zlib/inftrees.c b/zlib/inftrees.c index d8c53250..7fd506dd 100644 --- a/zlib/inftrees.c +++ b/zlib/inftrees.c @@ -9,7 +9,7 @@ #define MAXBITS 15 const char inflate_copyright[] = - " inflate 1.2.8 Copyright 1995-2013 Mark Adler "; + " inflate 1.2.8.f-Proxmark3 Copyright 1995-2013 Mark Adler "; /* If you use the zlib library in a product, an acknowledgment is welcome in the documentation of your product. If for some reason you cannot diff --git a/zlib/trees.c b/zlib/trees.c index 8c521211..dbfa49c9 100644 --- a/zlib/trees.c +++ b/zlib/trees.c @@ -32,8 +32,16 @@ /* @(#) $Id$ */ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- + /* #define GEN_TREES_H */ + #include "deflate.h" #ifdef DEBUG @@ -910,10 +918,10 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) ulg stored_len; /* length of input block */ int last; /* one if this is the last block for a file */ { - ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ int max_blindex = 0; /* index of last bit length code of non zero freq */ - #ifndef ZLIB_PM3_TUNED + ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + /* Build the Huffman trees unless a stored block is forced */ if (s->level > 0) { #endif @@ -938,6 +946,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) */ max_blindex = build_bl_tree(s); +#ifndef ZLIB_PM3_TUNED /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s->opt_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3; @@ -946,7 +955,6 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, s->last_lit)); -#ifndef ZLIB_PM3_TUNED if (static_lenb <= opt_lenb) opt_lenb = static_lenb; } else { @@ -980,7 +988,7 @@ void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last) s->compressed_len += 3 + s->static_len; #endif } else { -#endif /* ZLIB_PM3_TUNED */ +#endif /* !ZLIB_PM3_TUNED */ send_bits(s, (DYN_TREES<<1)+last, 3); send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1, max_blindex+1); diff --git a/zlib/zlib.h b/zlib/zlib.h index 3e0c7672..b2aa5572 100644 --- a/zlib/zlib.h +++ b/zlib/zlib.h @@ -28,6 +28,13 @@ (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format). */ +//----------------------------------------------------------------------------- +// 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. +//----------------------------------------------------------------------------- + #ifndef ZLIB_H #define ZLIB_H @@ -37,12 +44,23 @@ extern "C" { #endif +#ifndef ZLIB_PM3_TUNED #define ZLIB_VERSION "1.2.8" #define ZLIB_VERNUM 0x1280 #define ZLIB_VER_MAJOR 1 #define ZLIB_VER_MINOR 2 #define ZLIB_VER_REVISION 8 #define ZLIB_VER_SUBREVISION 0 +#else +#define ZLIB_VERSION "1.2.8.f-Proxmark3" +#define ZLIB_VERNUM 0x128f +#define ZLIB_VER_MAJOR 1 +#define ZLIB_VER_MINOR 2 +#define ZLIB_VER_REVISION 8 +#define ZLIB_VER_SUBREVISION f +#endif + + /* The 'zlib' compression library provides in-memory compression and From dcbaa2b5822435a9ba6309ffc83d843c8a1ba21c Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 26 May 2015 20:31:07 -0400 Subject: [PATCH 082/132] @iceman1001 s lua script fix --- client/scripts/dumptoemul.lua | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/client/scripts/dumptoemul.lua b/client/scripts/dumptoemul.lua index f9b71509..f8cc11d4 100644 --- a/client/scripts/dumptoemul.lua +++ b/client/scripts/dumptoemul.lua @@ -73,7 +73,8 @@ local function convert_to_emulform(hexdata) for i = 1, string.len(hexdata),32 do ascii = ascii ..string.sub(hexdata,i,i+31).."\n" end - return ascii + + return string.sub(ascii,1,-1) end local function main(args) From be10fe2f11db33a4f96c573dc47c47822e1a8e9d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 27 May 2015 00:32:01 -0400 Subject: [PATCH 083/132] update changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 85e7f915..3c016c3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] ### Changed +- Added ultralight/ntag tag type detection to `hf 14a read` (marshmellow) +- Improved ultralight dump command to auto detect tag type, take authentication, and dump full memory (or subset specified) of known tag types (iceman1001 / marshmellow) +- Combined ultralight read/write commands and added authentication (iceman1001) - Improved LF manchester and biphase demodulation and ask clock detection especially for reads with heavy clipping. (marshmellow) - Iclass read, `hf iclass read` now also reads tag config and prints configuration. (holiman) - *bootrom* needs to be flashed, due to new address boundaries between os and fpga, after a size optimization (piwi) @@ -13,6 +16,9 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac - Fixed issue #19, problems with LF T55xx commands (iceman1001, marshmellow) ### Added +- Added `hf search` - currently tests for 14443a tags, iclass tags, and 15693 tags (marshmellow) +- Added `hf mfu info` Ultralight/NTAG info command - reads tag configuration and info, allows authentication if needed (iceman1001, marshmellow) +- Added Mifare Ultralight C and Ultralight EV1/NTAG authentication. (iceman1001) - Added changelog ## [2.0.0] - 2015-03-25 From 799b2e2e9da62c96a30e9a04da911ff3cbe8cbd9 Mon Sep 17 00:00:00 2001 From: Pavel Zhovner Date: Wed, 27 May 2015 11:30:50 +0300 Subject: [PATCH 084/132] Compiling manual for MAC OS X --- COMPILING.txt | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/COMPILING.txt b/COMPILING.txt index c894f0ff..1cc34a0f 100644 --- a/COMPILING.txt +++ b/COMPILING.txt @@ -81,7 +81,31 @@ Download the ProxSpace environment archive and extract it to C:\ = Mac OS X = ============ -macport stuff should do ;) +Tested on OSX 10.10 Yosemite + +1 - Install Xcode and Xcode Command Line Tools + +2 - Install Homebrew and dependencies + brew install readline + brew instal libusb + +3 - Download DevKitARM for OSX + http://sourceforge.net/projects/devkitpro/files/devkitARM/devkitARM_r44/ + Unpack devkitARM_r44-osx.tar.bz2 to proxmark3 directory. + +4 - Edit proxmark3/client/Makefile adding path to readline + + LDLIBS = -L/usr/local/Cellar/readline/6.3.8/lib/ -L/opt/local/lib -L/usr/local/lib ../liblua/liblua.a -lreadline -lpthread -lm + CFLAGS = -std=c99 -I/usr/local/Cellar/readline/6.3.8/include/ -I. -I../include -I../common -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -g -O4 + + Replace path /usr/local/Cellar/readline/6.3.8 with your actuall readline path. See homebrew manuals. + +5 - Set Environment + + export DEVKITPRO=$HOME/proxmark3/ + export DEVKITARM=$DEVKITPRO/devkitARM + export PATH=${PATH}:${DEVKITARM}/bin + ============ = Linux = From 4973f23d3c2d2086ec694a13602b21a19726ab49 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 27 May 2015 12:24:13 -0400 Subject: [PATCH 085/132] clean up mfu device side code + add xor calc to util (prep for desfire) commented out MifareUWriteBlockCompat as it isn't used in client currently (it is a command we could support.. but why?) relabeled a few device side mfu functions to be clearer. --- armsrc/appmain.c | 8 ++--- armsrc/apps.h | 4 +-- armsrc/mifarecmd.c | 27 +++++++-------- armsrc/mifareutil.c | 84 ++++++++++++++++++++++++--------------------- armsrc/mifareutil.h | 16 +++++---- client/util.c | 13 +++++-- client/util.h | 2 ++ 7 files changed, 85 insertions(+), 69 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index f8594fcc..c226c726 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -841,11 +841,11 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_MIFARE_WRITEBL: MifareWriteBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; - case CMD_MIFAREU_WRITEBL_COMPAT: - MifareUWriteBlock(c->arg[0], c->d.asBytes); - break; + //case CMD_MIFAREU_WRITEBL_COMPAT: + //MifareUWriteBlockCompat(c->arg[0], c->d.asBytes); + //break; case CMD_MIFAREU_WRITEBL: - MifareUWriteBlock_Special(c->arg[0], c->arg[1], c->d.asBytes); + MifareUWriteBlock(c->arg[0], c->arg[1], c->d.asBytes); break; case CMD_MIFARE_NESTED: MifareNested(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); diff --git a/armsrc/apps.h b/armsrc/apps.h index dfd1fe52..6360b664 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -170,8 +170,8 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *datain); void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain); void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); -void MifareUWriteBlock(uint8_t arg0,uint8_t *datain); -void MifareUWriteBlock_Special(uint8_t arg0, uint8_t arg1, uint8_t *datain); +//void MifareUWriteBlockCompat(uint8_t arg0,uint8_t *datain); +void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 884da913..bf6c404a 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -254,7 +254,6 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { // free eventually allocated BigBuf memory BigBuf_free(); - // clear trace clear_trace(); // params @@ -416,7 +415,8 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } -void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) +/* // Command not needed but left for future testing +void MifareUWriteBlockCompat(uint8_t arg0, uint8_t *datain) { uint8_t blockNo = arg0; byte_t blockdata[16] = {0x00}; @@ -436,7 +436,7 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) return; }; - if(mifare_ultra_writeblock(blockNo, blockdata)) { + if(mifare_ultra_writeblock_compat(blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(0); return; }; @@ -453,6 +453,7 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } +*/ // Arg0 : Block to write to. // Arg1 : 0 = use no authentication. @@ -460,7 +461,7 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) // 2 = use 0x1B authentication. // datain : 4 first bytes is data to be written. // : 4/16 next bytes is authentication key. -void MifareUWriteBlock_Special(uint8_t arg0, uint8_t arg1, uint8_t *datain) +void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; bool useKey = (arg1 == 1); //UL_C @@ -502,7 +503,7 @@ void MifareUWriteBlock_Special(uint8_t arg0, uint8_t arg1, uint8_t *datain) } } - if(mifare_ultra_special_writeblock(blockNo, blockdata)) { + if(mifare_ultra_writeblock(blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(0); return; @@ -542,7 +543,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[6]; blockdata[2] = pwd[5]; blockdata[3] = pwd[4]; - if(mifare_ultra_special_writeblock( 44, blockdata)) { + if(mifare_ultra_writeblock( 44, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(44); return; @@ -552,7 +553,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[2]; blockdata[2] = pwd[1]; blockdata[3] = pwd[0]; - if(mifare_ultra_special_writeblock( 45, blockdata)) { + if(mifare_ultra_writeblock( 45, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(45); return; @@ -562,7 +563,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[14]; blockdata[2] = pwd[13]; blockdata[3] = pwd[12]; - if(mifare_ultra_special_writeblock( 46, blockdata)) { + if(mifare_ultra_writeblock( 46, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(46); return; @@ -572,7 +573,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[10]; blockdata[2] = pwd[9]; blockdata[3] = pwd[8]; - if(mifare_ultra_special_writeblock( 47, blockdata)) { + if(mifare_ultra_writeblock( 47, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(47); return; @@ -1265,14 +1266,12 @@ void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain){ isOK = mifare_desfire_des_auth2(cuid, key, dataout); if( isOK) { - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) - Dbprintf("Authentication part2: Failed"); - //OnError(4); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Authentication part2: Failed"); + OnError(4); return; } - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) - DbpString("AUTH 2 FINISHED"); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 2 FINISHED"); cmd_send(CMD_ACK, isOK, 0, 0, dataout, sizeof(dataout)); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index 2f84797b..c706e78a 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -65,73 +65,74 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) { return bt; } -// send commands +// send 2 byte commands int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) { return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing); } -int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) +// send X byte basic commands +int mifare_sendcmd(uint8_t cmd, uint8_t* data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) { - uint8_t dcmd[8]; - dcmd[0] = cmd; - dcmd[1] = data[0]; - dcmd[2] = data[1]; - dcmd[3] = data[2]; - dcmd[4] = data[3]; - dcmd[5] = data[4]; - AppendCrc14443a(dcmd, 6); - ReaderTransmit(dcmd, sizeof(dcmd), NULL); + uint8_t dcmd[data_size+3]; + dcmd[0] = cmd; + memcpy(dcmd+1,data,data_size); + AppendCrc14443a(dcmd, data_size+1); + ReaderTransmit(dcmd, sizeof(dcmd), timing); int len = ReaderReceive(answer, answer_parity); if(!len) { - if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout."); - return 2; - } + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("%02X Cmd failed. Card timeout.", cmd); + len = ReaderReceive(answer,answer_parity); + //return 0; + } return len; } +/* int mifare_sendcmd_short_mfucauth(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[19]; + uint8_t dcmd[19]; int len; - dcmd[0] = cmd; - memcpy(dcmd+1,data,16); + dcmd[0] = cmd; + memcpy(dcmd+1,data,16); AppendCrc14443a(dcmd, 17); ReaderTransmit(dcmd, sizeof(dcmd), timing); len = ReaderReceive(answer, answer_parity); if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); - len = ReaderReceive(answer,answer_parity); - } - if(len==1) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); + len = ReaderReceive(answer,answer_parity); + } + if(len==1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); return 1; - } + } return len; } int mifare_sendcmd_short_mfuev1auth(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[7]; + uint8_t dcmd[7]; int len; - dcmd[0] = cmd; - memcpy(dcmd+1,data,4); + dcmd[0] = cmd; + memcpy(dcmd+1,data,4); AppendCrc14443a(dcmd, 5); - + ReaderTransmit(dcmd, sizeof(dcmd), timing); len = ReaderReceive(answer, answer_parity); if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); - len = ReaderReceive(answer,answer_parity); - } - if(len==1) { + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); + len = ReaderReceive(answer,answer_parity); + } + if(len==1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); return 1; - } + } return len; } +*/ +// send 2 byte commands int mifare_sendcmd_shortex(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[4], ecmd[4]; @@ -319,7 +320,8 @@ int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){ memcpy(key, keybytes, 4); Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); - len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); + len = mifare_sendcmd(0x1B, key, sizeof(key), resp, respPar, NULL); + //len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); if (len != 4) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len); return 0; @@ -380,8 +382,8 @@ int mifare_ultra_auth(uint8_t *keybytes){ // encrypt out, in, length, key, iv tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL); + //len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL); + len = mifare_sendcmd(0xAF, rnd_ab, sizeof(rnd_ab), resp, respPar, NULL); if (len != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]); return 0; @@ -425,6 +427,7 @@ int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) uint8_t receivedAnswer[MAX_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; + len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL); if (len == 1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); @@ -493,7 +496,8 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl return 0; } -int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) +/* // command not needed, but left for future testing +int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData) { uint16_t len; uint8_t par[3] = {0}; // enough for 18 parity bits @@ -501,7 +505,6 @@ int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) uint8_t receivedAnswer[MAX_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - // command MIFARE_CLASSIC_WRITEBLOCK len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL); if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK @@ -524,20 +527,21 @@ int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) } return 0; } +*/ -int mifare_ultra_special_writeblock(uint8_t blockNo, uint8_t *blockData) +int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) { uint16_t len; - uint8_t d_block[8] = {0x00}; + uint8_t d_block[5] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; // command MIFARE_CLASSIC_WRITEBLOCK d_block[0]= blockNo; memcpy(d_block+1,blockData,4); - AppendCrc14443a(d_block, 6); + //AppendCrc14443a(d_block, 6); - len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL); + len = mifare_sendcmd(0xA2, d_block, sizeof(d_block), receivedAnswer, receivedAnswerPar, NULL); if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK if (MF_DBGLEVEL >= MF_DBG_ERROR) diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index d4fcd818..ed955cc6 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -54,22 +54,24 @@ extern int MF_DBGLEVEL; //functions int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); - -int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_short_mfuev1auth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); +int mifare_sendcmd(uint8_t cmd, uint8_t *data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); +//int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); +//int mifare_sendcmd_short_mfuev1auth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); +// mifare classic 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_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); + +// Ultralight/NTAG... int mifare_ul_ev1_auth(uint8_t *key, uint8_t *pack); int mifare_ultra_auth(uint8_t *key); int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData); -int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); +//int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData); int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData); -int mifare_ultra_special_writeblock(uint8_t blockNo, uint8_t *blockData); -int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); int mifare_ultra_halt(); // desfire diff --git a/client/util.c b/client/util.c index cea9f7d7..1fc684b6 100644 --- a/client/util.c +++ b/client/util.c @@ -108,12 +108,12 @@ void print_hex(const uint8_t * data, const size_t len) printf("\n"); } -char * sprint_hex(const uint8_t * data, const size_t len) { +char *sprint_hex(const uint8_t *data, const size_t len) { int maxLen = ( len > 1024/3) ? 1024/3 : len; static char buf[1024]; memset(buf, 0x00, 1024); - char * tmp = buf; + char *tmp = buf; size_t i; for (i=0; i < maxLen; ++i, tmp += 3) @@ -444,3 +444,12 @@ void wiegand_add_parity(char *target, char *source, char length) target += length; *(target)= GetParity(source + length / 2, ODD, length / 2); } + +void xor(unsigned char *dst, unsigned char *src, size_t len) { + for( ; len > 0; len--,dst++,src++) + *dst ^= *src; +} + +int32_t le24toh (uint8_t data[3]) { + return (data[2] << 16) | (data[1] << 8) | data[0]; +} diff --git a/client/util.h b/client/util.h index f58f64cb..2d2beaf4 100644 --- a/client/util.h +++ b/client/util.h @@ -63,3 +63,5 @@ void binarraytobinstring(char *target, char *source, int length); uint8_t GetParity( char *string, uint8_t type, int length); void wiegand_add_parity(char *target, char *source, char length); +void xor(unsigned char *dst, unsigned char *src, size_t len); +int32_t le24toh(uint8_t data[3]); From e35031d2b73bb4c834d6675a5df870a2de14690c Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 27 May 2015 17:21:42 -0400 Subject: [PATCH 086/132] MFU code cleanup - final ? fixed bug in debug print in MF 1k sim. --- armsrc/iso14443a.c | 4 ++-- armsrc/mifarecmd.c | 4 ++-- armsrc/mifareutil.c | 55 +++------------------------------------------ armsrc/mifareutil.h | 5 +---- 4 files changed, 8 insertions(+), 60 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 64bbcbf5..cf64da2f 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -2510,13 +2510,13 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * || receivedCmd[0] == 0xB0) { // transfer if (receivedCmd[1] >= 16 * 4) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); - if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking",receivedCmd[0],receivedCmd[1],receivedCmd[1]); + if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking",receivedCmd[0],receivedCmd[1],receivedCmd[1]); break; } if (receivedCmd[1] / 4 != cardAUTHSC) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); - if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd[0],receivedCmd[1],cardAUTHSC); + if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02x) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd[0],receivedCmd[1],cardAUTHSC); break; } } diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index bf6c404a..939c9002 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -717,7 +717,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat LED_B_OFF(); } -// ------------------------------------------------------------------------------------------------- + // ------------------------------------------------------------------------------------------------- LED_C_ON(); @@ -746,7 +746,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // nested authentication auth2_time = auth1_time + delta_time; - len = mifare_sendcmd_shortex(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time); + len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time); if (len != 4) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Auth2 error len=%d", len); continue; diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index c706e78a..8ef364c2 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -65,12 +65,6 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) { return bt; } -// send 2 byte commands -int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) -{ - return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing); -} - // send X byte basic commands int mifare_sendcmd(uint8_t cmd, uint8_t* data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) { @@ -88,52 +82,8 @@ int mifare_sendcmd(uint8_t cmd, uint8_t* data, uint8_t data_size, uint8_t* answe return len; } -/* -int mifare_sendcmd_short_mfucauth(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[19]; - int len; - dcmd[0] = cmd; - memcpy(dcmd+1,data,16); - AppendCrc14443a(dcmd, 17); - - ReaderTransmit(dcmd, sizeof(dcmd), timing); - len = ReaderReceive(answer, answer_parity); - if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); - len = ReaderReceive(answer,answer_parity); - } - if(len==1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); - return 1; - } - return len; -} - -int mifare_sendcmd_short_mfuev1auth(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[7]; - int len; - dcmd[0] = cmd; - memcpy(dcmd+1,data,4); - AppendCrc14443a(dcmd, 5); - - ReaderTransmit(dcmd, sizeof(dcmd), timing); - len = ReaderReceive(answer, answer_parity); - if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); - len = ReaderReceive(answer,answer_parity); - } - if(len==1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); - return 1; - } - return len; -} -*/ - // send 2 byte commands -int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) +int mifare_sendcmd_short(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[4], ecmd[4]; uint16_t pos, res; @@ -319,7 +269,8 @@ int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){ uint8_t key[4] = {0x00}; memcpy(key, keybytes, 4); - Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) + Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); len = mifare_sendcmd(0x1B, key, sizeof(key), resp, respPar, NULL); //len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); if (len != 4) { diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index ed955cc6..85a34ef6 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -53,11 +53,8 @@ extern int MF_DBGLEVEL; #define cardSTATE_TO_IDLE() cardSTATE = MFEMUL_IDLE; LED_B_OFF(); LED_C_OFF(); //functions -int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); int mifare_sendcmd(uint8_t cmd, uint8_t *data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); -//int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); -//int mifare_sendcmd_short_mfuev1auth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); +int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); // mifare classic int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested); From fbd0526b349c148b1ef7792978769cc9cdf21d90 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 28 May 2015 02:55:57 +0200 Subject: [PATCH 087/132] delete (yet) unnecessary file client/cmdhftopaz.c --- client/cmdhftopaz.c | 408 -------------------------------------------- 1 file changed, 408 deletions(-) delete mode 100644 client/cmdhftopaz.c diff --git a/client/cmdhftopaz.c b/client/cmdhftopaz.c deleted file mode 100644 index e76b3fb5..00000000 --- a/client/cmdhftopaz.c +++ /dev/null @@ -1,408 +0,0 @@ -//----------------------------------------------------------------------------- -// Copyright (C) 2015 Piwi -// -// 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. -//----------------------------------------------------------------------------- -// High frequency Topaz (NFC Type 1) commands -//----------------------------------------------------------------------------- - -#include -#include -#include -#include -#include "cmdmain.h" -#include "cmdparser.h" -#include "cmdhftopaz.h" -#include "cmdhf14a.h" -#include "ui.h" -#include "mifare.h" -#include "proxmark3.h" -#include "iso14443crc.h" -#include "protocols.h" - -#define TOPAZ_MAX_MEMORY 2048 - -static struct { - uint8_t HR01[2]; - uint8_t uid[7]; - uint8_t size; - uint8_t data_blocks[TOPAZ_MAX_MEMORY/8][8]; - uint8_t *dynamic_lock_areas; - uint8_t *dynamic_reserved_areas; -} topaz_tag; - - -static void topaz_switch_on_field(void) -{ - UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_CONNECT | ISO14A_NO_SELECT | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, 0, 0}}; - SendCommand(&c); -} - - -static void topaz_switch_off_field(void) -{ - UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; - SendCommand(&c); -} - - -static int topaz_send_cmd_raw(uint8_t *cmd, uint8_t len, uint8_t *response) -{ - UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT | ISO14A_TOPAZMODE, len, 0}}; - memcpy(c.d.asBytes, cmd, len); - SendCommand(&c); - - UsbCommand resp; - WaitForResponse(CMD_ACK, &resp); - - if (resp.arg[0] > 0) { - memcpy(response, resp.d.asBytes, resp.arg[0]); - } - - return resp.arg[0]; -} - - -static int topaz_send_cmd(uint8_t *cmd, uint8_t len, uint8_t *response) -{ - if (len > 1) { - uint8_t first, second; - ComputeCrc14443(CRC_14443_B, cmd, len-2, &first, &second); - cmd[len-2] = first; - cmd[len-1] = second; - } - - return topaz_send_cmd_raw(cmd, len, response); -} - - -static int topaz_select(uint8_t *atqa, uint8_t *rid_response) -{ - // ToDo: implement anticollision - - uint8_t wupa_cmd[] = {TOPAZ_WUPA}; - uint8_t rid_cmd[] = {TOPAZ_RID, 0, 0, 0, 0, 0, 0, 0, 0}; - - topaz_switch_on_field(); - - if (!topaz_send_cmd(wupa_cmd, sizeof(wupa_cmd), atqa)) { - topaz_switch_off_field(); - return -1; // WUPA failed - } - - if (!topaz_send_cmd(rid_cmd, sizeof(rid_cmd), rid_response)) { - topaz_switch_off_field(); - return -2; // RID failed - } - - return 0; // OK -} - - -static int topaz_rall(uint8_t *uid, uint8_t *response) -{ - uint8_t rall_cmd[] = {TOPAZ_RALL, 0, 0, 0, 0, 0, 0, 0, 0}; - - memcpy(&rall_cmd[3], uid, 4); - if (!topaz_send_cmd(rall_cmd, sizeof(rall_cmd), response)) { - topaz_switch_off_field(); - return -1; // RALL failed - } - - return 0; -} - - -static bool topaz_block_is_locked(uint8_t blockno, uint8_t *lockbits) -{ - if(lockbits[blockno/8] >> (blockno % 8) & 0x01) { - return true; - } else { - return false; - } -} - - -static int topaz_print_CC(uint8_t *data) -{ - if(data[0] != 0xe1) { - return -1; // no NDEF message - } - - PrintAndLog("Capability Container: %02x %02x %02x %02x", data[0], data[1], data[2], data[3]); - PrintAndLog(" %02x: NDEF Magic Number", data[0]); - PrintAndLog(" %02x: version %d.%d supported by tag", data[1], (data[1] & 0xF0) >> 4, data[1] & 0x0f); - PrintAndLog(" %02x: Physical Memory Size of this tag: %d bytes", data[2], (data[2] + 1) * 8); - PrintAndLog(" %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; -} - - -static void get_TLV(uint8_t **TLV_ptr, uint8_t *tag, uint16_t *length, uint8_t **value) -{ - *length = 0; - *value = NULL; - - *tag = **TLV_ptr; - *TLV_ptr += 1; - switch (*tag) { - case 0x00: // NULL TLV. - case 0xFE: // Terminator TLV. - break; - case 0x01: // Lock Control TLV - case 0x02: // Reserved Memory TLV - case 0x03: // NDEF message TLV - case 0xFD: // proprietary TLV - *length = **TLV_ptr; - *TLV_ptr += 1; - if (*length == 0xff) { - *length = **TLV_ptr << 8; - *TLV_ptr += 1; - *length |= **TLV_ptr; - *TLV_ptr += 1; - } - *value = *TLV_ptr; - *TLV_ptr += *length; - break; - default: // RFU - break; - } -} - - -static bool topaz_print_lock_control_TLVs(uint8_t *memory) -{ - uint8_t *TLV_ptr = memory; - uint8_t tag = 0; - uint16_t length; - uint8_t *value; - bool lock_TLV_present = false; - - 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, &tag, &length, &value); - if (tag == 0x01) { // the Lock Control TLV - uint8_t pages_addr = value[0] >> 4; - uint8_t byte_offset = value[0] & 0x0f; - uint8_t size_in_bits = value[1] ? value[1] : 256; - uint8_t bytes_per_page = 1 << (value[2] & 0x0f); - uint8_t bytes_locked_per_bit = 1 << (value[2] >> 4); - PrintAndLog("Lock Area of %d bits at byte offset 0x%02x. Each Lock Bit locks %d bytes.", - size_in_bits, - pages_addr * bytes_per_page + byte_offset, - bytes_locked_per_bit); - lock_TLV_present = true; - } - } - - if (!lock_TLV_present) { - PrintAndLog("(No Lock Control TLV present)"); - return -1; - } else { - return 0; - } -} - - -static int topaz_print_reserved_memory_control_TLVs(uint8_t *memory) -{ - uint8_t *TLV_ptr = memory; - uint8_t tag = 0; - uint16_t length; - uint8_t *value; - bool reserved_memory_control_TLV_present = false; - - while(*TLV_ptr != 0x03 && *TLV_ptr != 0xFD && *TLV_ptr != 0xFE) { - // all Reserved Memory Control TLVs shall be present before the NDEF message TLV, the proprietary TLV (and the Terminator TLV) - get_TLV(&TLV_ptr, &tag, &length, &value); - if (tag == 0x02) { // the Reserved Memory Control TLV - uint8_t pages_addr = value[0] >> 4; - uint8_t byte_offset = value[0] & 0x0f; - uint8_t size_in_bytes = value[1] ? value[1] : 256; - uint8_t bytes_per_page = 1 << (value[2] & 0x0f); - PrintAndLog("Reserved Memory of %d bytes at byte offset 0x%02x.", - size_in_bytes, - pages_addr * bytes_per_page + byte_offset); - reserved_memory_control_TLV_present = true; - } - } - - if (!reserved_memory_control_TLV_present) { - PrintAndLog("(No Reserved Memory Control TLV present)"); - return -1; - } else { - return 0; - } -} - - -static void topaz_print_lifecycle_state(uint8_t *data) -{ - -} - - -static void topaz_print_NDEF(uint8_t *data) -{ - -} - - -int CmdHFTopazReader(const char *Cmd) -{ - int status; - uint8_t atqa[2]; - uint8_t rid_response[8]; - uint8_t *uid_echo = &rid_response[2]; - uint8_t rall_response[124]; - - status = topaz_select(atqa, rid_response); - - if (status == -1) { - PrintAndLog("Error: couldn't receive ATQA"); - return -1; - } - - PrintAndLog("ATQA : %02x %02x", atqa[1], atqa[0]); - if (atqa[1] != 0x0c && atqa[0] != 0x00) { - PrintAndLog("Tag doesn't support the Topaz protocol."); - topaz_switch_off_field(); - return -1; - } - - if (status == -2) { - PrintAndLog("Error: tag didn't answer to RID"); - topaz_switch_off_field(); - return -1; - } - - topaz_tag.HR01[0] = rid_response[0]; - topaz_tag.HR01[1] = rid_response[1]; - - // ToDo: CRC check - PrintAndLog("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) == 0x10 ? "static" : "dynamic"); - PrintAndLog("HR1 : %02x", rid_response[1]); - - status = topaz_rall(uid_echo, rall_response); - - if(status == -1) { - PrintAndLog("Error: tag didn't answer to RALL"); - topaz_switch_off_field(); - return -1; - } - - memcpy(topaz_tag.uid, rall_response+2, 7); - PrintAndLog("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]); - PrintAndLog(" UID[6] (Manufacturer Byte) = %02x, Manufacturer: %s", - topaz_tag.uid[6], - getTagInfo(topaz_tag.uid[6])); - - memcpy(topaz_tag.data_blocks, rall_response+2, 0x10*8); - PrintAndLog(""); - PrintAndLog("Static Data blocks 00 to 0c:"); - PrintAndLog("block# | offset | Data | Locked?"); - char line[80]; - for (uint16_t i = 0; i <= 0x0c; i++) { - for (uint16_t j = 0; j < 8; j++) { - sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[i][j] /*rall_response[2 + 8*i + j]*/); - } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", i, i*8, line, topaz_block_is_locked(i, &topaz_tag.data_blocks[0x0d][0]) ? "yes" : "no"); - } - - PrintAndLog(""); - PrintAndLog("Static Reserved block 0d:"); - for (uint16_t j = 0; j < 8; j++) { - sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0d][j]); - } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0d, 0x0d*8, line, "n/a"); - - PrintAndLog(""); - PrintAndLog("Static Lockbits and OTP Bytes:"); - for (uint16_t j = 0; j < 8; j++) { - sprintf(&line[3*j], "%02x ", topaz_tag.data_blocks[0x0e][j]); - } - PrintAndLog(" 0x%02x | 0x%02x | %s| %-3s", 0x0e, 0x0e*8, line, "n/a"); - - PrintAndLog(""); - - status = topaz_print_CC(&topaz_tag.data_blocks[1][0]); - - if (status == -1) { - PrintAndLog("No NDEF message present"); - topaz_switch_off_field(); - return 0; - } - - PrintAndLog(""); - bool lock_TLV_present = topaz_print_lock_control_TLVs(&topaz_tag.data_blocks[1][4]); - - PrintAndLog(""); - bool reserved_mem_present = topaz_print_reserved_memory_control_TLVs(&topaz_tag.data_blocks[1][4]); - - 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; -} - - -int CmdHFTopazSim(const char *Cmd) -{ - PrintAndLog("not yet implemented"); - return 0; -} - - -int CmdHFTopazCmdRaw(const char *Cmd) -{ - PrintAndLog("not yet implemented"); - return 0; -} - - -static int CmdHelp(const char *Cmd); - - -static command_t CommandTable[] = -{ - {"help", CmdHelp, 1, "This help"}, - {"reader", CmdHFTopazReader, 0, "Act like a Topaz reader"}, - {"sim", CmdHFTopazSim, 0, " -- Simulate Topaz tag"}, - {"snoop", CmdHF14ASnoop, 0, "Eavesdrop a Topaz reader-tag communication"}, - {"raw", CmdHFTopazCmdRaw, 0, "Send raw hex data to tag"}, - {NULL, NULL, 0, NULL} -}; - - -int CmdHFTopaz(const char *Cmd) { - // flush - WaitForResponseTimeout(CMD_ACK,NULL,100); - - // parse - CmdsParse(CommandTable, Cmd); - return 0; -} - -static int CmdHelp(const char *Cmd) -{ - CmdsHelp(CommandTable); - return 0; -} - - From 979bba376dc9d6430b00b853a99b9dfadca4f38c Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 28 May 2015 13:23:31 -0400 Subject: [PATCH 088/132] add offset option to data printdemodbuffer easily see demod buffer's hex values at different bit offsets by using: data printdemodbuffer x o --- client/cmddata.c | 66 +++++++++++++++++++++++++++++++++++++----------- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index b9069bc1..e23b6d59 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -55,6 +55,15 @@ int CmdSetDebugMode(const char *Cmd) return 1; } +int usage_data_printdemodbuf(){ + PrintAndLog("Usage: data printdemodbuffer x o "); + PrintAndLog("Options: "); + PrintAndLog(" h This help"); + PrintAndLog(" x output in hex (omit for binary output)"); + PrintAndLog(" o enter offset in # of bits"); + return 0; +} + //by marshmellow void printDemodBuff(void) { @@ -73,23 +82,50 @@ void printDemodBuff(void) int CmdPrintDemodBuff(const char *Cmd) { - char hex; - char printBuff[512]={0x00}; - uint8_t numBits = DemodBufferLen & 0xFFFC; - sscanf(Cmd, "%c", &hex); - if (hex == 'h'){ - PrintAndLog("Usage: data printdemodbuffer [x]"); - PrintAndLog("Options: "); - PrintAndLog(" h This help"); - PrintAndLog(" x output in hex (omit for binary output)"); - return 0; + char hex[512]={0x00}; + bool hexMode = false; + bool errors = false; + uint8_t offset = 0; + char cmdp = 0; + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_data_printdemodbuf(); + case 'x': + case 'X': + hexMode = true; + cmdp++; + break; + case 'o': + case 'O': + offset = param_get8(Cmd, cmdp+1); + if (!offset) errors = true; + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) break; } - if (hex == 'x'){ - numBits = binarraytohex(printBuff, (char *)DemodBuffer, numBits); + //Validations + if(errors) return usage_data_printdemodbuf(); + + int numBits = (DemodBufferLen-offset) & 0x7FC; //make sure we don't exceed our string + + if (hexMode){ + char *buf = DemodBuffer + offset; + numBits = binarraytohex(hex, buf, numBits); if (numBits==0) return 0; - PrintAndLog("DemodBuffer: %s",printBuff); + PrintAndLog("DemodBuffer: %s",hex); } else { - printDemodBuff(); + //setDemodBuf(DemodBuffer, DemodBufferLen-offset, offset); + char *bin = sprint_bin_break(DemodBuffer+offset,numBits,16); + PrintAndLog("DemodBuffer:\n%s",bin); } return 1; } @@ -2182,7 +2218,7 @@ static command_t CommandTable[] = {"manrawdecode", Cmdmandecoderaw, 1, "[invert] [maxErr] -- Manchester decode binary stream in DemodBuffer"}, {"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] -- print the data in the DemodBuffer - 'x' for hex output"}, + {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] [o] -- print the data in the DemodBuffer - 'x' for hex output"}, {"pskindalademod", CmdIndalaDecode, 1, "[clock] [invert<0|1>] -- Demodulate an indala tag (PSK1) from GraphBuffer (args optional)"}, {"psknexwatchdemod",CmdPSKNexWatch, 1, "Demodulate a NexWatch tag (nexkey, quadrakey) (PSK1) from GraphBuffer"}, {"rawdemod", CmdRawDemod, 1, "[modulation] ... -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"}, From 5b37e87a24f01af65c2d414a9393e8846a4beafe Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 28 May 2015 22:52:41 -0400 Subject: [PATCH 089/132] fix help typo --- client/cmdlft55xx.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index d4b72b32..1814d4ab 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -66,8 +66,8 @@ int usage_t55xx_write(){ PrintAndLog(" [password], OPTIONAL password 4bytes (8 hex characters)"); PrintAndLog(""); PrintAndLog("Examples:"); - PrintAndLog(" lf t55xx wd 3 11223344 - write 11223344 to block 3"); - PrintAndLog(" lf t55xx wd 3 11223344 feedbeef - write 11223344 to block 3 password feedbeef"); + PrintAndLog(" lf t55xx wr 3 11223344 - write 11223344 to block 3"); + PrintAndLog(" lf t55xx wr 3 11223344 feedbeef - write 11223344 to block 3 password feedbeef"); PrintAndLog(""); return 0; } From 185e038c7de4468e098dadf6303f72efccecaa10 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 28 May 2015 23:14:06 -0400 Subject: [PATCH 090/132] fixed further typo in lf t5 wr help also fixed offset option char to uint8_t warning in the new offset option in data printdemodbuffer --- client/cmddata.c | 2 +- client/cmdlft55xx.c | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index e23b6d59..76552351 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -118,7 +118,7 @@ int CmdPrintDemodBuff(const char *Cmd) int numBits = (DemodBufferLen-offset) & 0x7FC; //make sure we don't exceed our string if (hexMode){ - char *buf = DemodBuffer + offset; + char *buf = (char *) (DemodBuffer + offset); numBits = binarraytohex(hex, buf, numBits); if (numBits==0) return 0; PrintAndLog("DemodBuffer: %s",hex); diff --git a/client/cmdlft55xx.c b/client/cmdlft55xx.c index 1814d4ab..b357e71c 100644 --- a/client/cmdlft55xx.c +++ b/client/cmdlft55xx.c @@ -50,23 +50,23 @@ int usage_t55xx_config(){ } int usage_t55xx_read(){ PrintAndLog("Usage: lf t55xx read "); - PrintAndLog(" , block number to read. Between 0-7"); - PrintAndLog(" , OPTIONAL password (8 hex characters)"); - PrintAndLog(""); + PrintAndLog(" , block number to read. Between 0-7"); + PrintAndLog(" , OPTIONAL password (8 hex characters)"); + PrintAndLog(""); PrintAndLog("Examples:"); - PrintAndLog(" lf t55xx read 0 - read data from block 0"); + PrintAndLog(" lf t55xx read 0 - read data from block 0"); PrintAndLog(" lf t55xx read 0 feedbeef - read data from block 0 password feedbeef"); PrintAndLog(""); return 0; } int usage_t55xx_write(){ PrintAndLog("Usage: lf t55xx wr [password]"); - PrintAndLog(" , block number to read. Between 0-7"); + PrintAndLog(" , block number to write. Between 0-7"); PrintAndLog(" , 4 bytes of data to write (8 hex characters)"); - PrintAndLog(" [password], OPTIONAL password 4bytes (8 hex characters)"); - PrintAndLog(""); + PrintAndLog(" [password], OPTIONAL password 4bytes (8 hex characters)"); + PrintAndLog(""); PrintAndLog("Examples:"); - PrintAndLog(" lf t55xx wr 3 11223344 - write 11223344 to block 3"); + PrintAndLog(" lf t55xx wr 3 11223344 - write 11223344 to block 3"); PrintAndLog(" lf t55xx wr 3 11223344 feedbeef - write 11223344 to block 3 password feedbeef"); PrintAndLog(""); return 0; From dc20a1f63970e2ddca978fe98311dcc09180ca56 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Fri, 29 May 2015 18:14:36 +0200 Subject: [PATCH 091/132] Fix linking under linux. liblua requires libld on linux. --- client/Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/Makefile b/client/Makefile index 7d03b101..f9645194 100644 --- a/client/Makefile +++ b/client/Makefile @@ -36,8 +36,8 @@ else ifeq ($(platform),Darwin) else CXXFLAGS = $(shell pkg-config --cflags QtCore QtGui 2>/dev/null) -Wall -O4 QTLDLIBS = $(shell pkg-config --libs QtCore QtGui 2>/dev/null) + LUALIB += -ldl MOC = $(shell pkg-config --variable=moc_location QtCore) - LDLIBS += -ldl # Below is a variant you can use if you have problems compiling with QT5 on ubuntu. see http://www.proxmark.org/forum/viewtopic.php?id=1661 for more info. #MOC = /usr/lib/x86_64-linux-gnu/qt4/bin/moc LUAPLATFORM = linux @@ -121,7 +121,7 @@ all: lua_build $(BINS) all-static: LDLIBS:=-static $(LDLIBS) all-static: snooper cli flasher fpga_compress -proxmark3: LDLIBS+=$(QTLDLIBS) $(LUALIB) +proxmark3: LDLIBS+=$(LUALIB) $(QTLDLIBS) proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(QTGUI) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ From 1c4c0b068131edc4bc382b767e26dae494e0d4c3 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 30 May 2015 21:51:15 -0400 Subject: [PATCH 092/132] add @Iceman1001 s sha1 scripting changes. --- client/Makefile | 1 + client/lualibs/utils.lua | 28 +- client/scripting.c | 78 ++++- client/util.c | 2 +- common/sha1.c | 665 +++++++++++++++++++++++++++++++++++++++ common/sha1.h | 213 +++++++++++++ 6 files changed, 981 insertions(+), 6 deletions(-) create mode 100644 common/sha1.c create mode 100644 common/sha1.h diff --git a/client/Makefile b/client/Makefile index 7954d1ea..d7126da6 100644 --- a/client/Makefile +++ b/client/Makefile @@ -102,6 +102,7 @@ CMDSRCS = nonce2key/crapto1.c\ pm3_bitlib.c\ aes.c\ protocols.c\ + sha1.c\ COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) diff --git a/client/lualibs/utils.lua b/client/lualibs/utils.lua index a968fde2..592d0477 100644 --- a/client/lualibs/utils.lua +++ b/client/lualibs/utils.lua @@ -99,6 +99,32 @@ local Utils = end return nil end, + + ------------ SHA1 hash + -- Takes a string and calculates a SHA1 hash + Sha1 = function(s) + if s == nil then return nil end + if #s == 0 then return nil end + if type(s) == 'string' then + local utils = require('utils') + --local asc = utils.ConvertHexToAscii(s) + local hash = core.sha1(s) + return hash + end + return nil + end, + -- Takes a hex string and calculates a SHA1 hash + Sha1Hex = function(s) + if s == nil then return nil end + if #s == 0 then return nil end + if type(s) == 'string' then + local utils = require('utils') + local asc = utils.ConvertHexToAscii(s) + local hash = core.sha1(asc) + return hash + end + return nil + end, -- input parameter is a string @@ -288,4 +314,4 @@ local Utils = -- end } -return Utils \ No newline at end of file +return Utils diff --git a/client/scripting.c b/client/scripting.c index 152fd9d4..6b26ec59 100644 --- a/client/scripting.c +++ b/client/scripting.c @@ -20,6 +20,7 @@ #include "../common/iso15693tools.h" #include "../common/crc16.h" #include "../common/crc64.h" +#include "../common/sha1.h" #include "aes.h" /** * The following params expected: @@ -231,7 +232,7 @@ static int l_iso15693_crc(lua_State *L) Simple AES 128 cbc hook up to OpenSSL. params: key, input */ -static int l_aes128decrypt(lua_State *L) +static int l_aes128decrypt_cbc(lua_State *L) { //Check number of arguments int i; @@ -260,7 +261,36 @@ static int l_aes128decrypt(lua_State *L) lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); return 1;// return 1 to signal one return value } -static int l_aes128encrypt(lua_State *L) +static int l_aes128decrypt_ecb(lua_State *L) +{ + //Check number of arguments + int i; + size_t size; + const char *p_key = luaL_checklstring(L, 1, &size); + if(size != 32) return returnToLuaWithError(L,"Wrong size of key, got %d bytes, expected 32", (int) size); + + const char *p_encTxt = luaL_checklstring(L, 2, &size); + + unsigned char indata[16] = {0x00}; + unsigned char outdata[16] = {0x00}; + unsigned char aes_key[16] = {0x00}; + + // convert key to bytearray and convert input to bytearray + for (i = 0; i < 32; i += 2) { + sscanf(&p_encTxt[i], "%02x", (unsigned int *)&indata[i / 2]); + sscanf(&p_key[i], "%02x", (unsigned int *)&aes_key[i / 2]); + } + aes_context ctx; + aes_init(&ctx); + aes_setkey_dec(&ctx, aes_key, 128); + aes_crypt_ecb(&ctx, AES_DECRYPT, indata, outdata ); + + //Push decrypted array as a string + lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); + return 1;// return 1 to signal one return value +} + +static int l_aes128encrypt_cbc(lua_State *L) { //Check number of arguments int i; @@ -289,6 +319,33 @@ static int l_aes128encrypt(lua_State *L) return 1;// return 1 to signal one return value } +static int l_aes128encrypt_ecb(lua_State *L) +{ + //Check number of arguments + int i; + size_t size; + const char *p_key = luaL_checklstring(L, 1, &size); + 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", (unsigned int *)&indata[i / 2]); + sscanf(&p_key[i], "%02x", (unsigned int *)&aes_key[i / 2]); + } + aes_context ctx; + aes_init(&ctx); + aes_setkey_enc(&ctx, aes_key, 128); + aes_crypt_ecb(&ctx, AES_ENCRYPT, indata, outdata ); + //Push encrypted array as a string + lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); + return 1;// return 1 to signal one return value +} + static int l_crc16(lua_State *L) { size_t size; @@ -321,6 +378,16 @@ static int l_crc64(lua_State *L) return 1; } +static int l_sha1(lua_State *L) +{ + size_t size; + const char *p_str = luaL_checklstring(L, 1, &size); + unsigned char outdata[20] = {0x00}; + sha1( (uint8_t*) p_str, size, outdata); + lua_pushlstring(L,(const char *)&outdata, sizeof(outdata)); + return 1; +} + /** * @brief Sets the lua path to include "./lualibs/?.lua", in order for a script to be * able to do "require('foobar')" if foobar.lua is within lualibs folder. @@ -359,10 +426,13 @@ int set_pm3_libraries(lua_State *L) {"clearCommandBuffer", l_clearCommandBuffer}, {"console", l_CmdConsole}, {"iso15693_crc", l_iso15693_crc}, - {"aes128_decrypt", l_aes128decrypt}, - {"aes128_encrypt", l_aes128encrypt}, + {"aes128_decrypt", l_aes128decrypt_cbc}, + {"aes128_decrypt_ecb", l_aes128decrypt_ecb}, + {"aes128_encrypt", l_aes128encrypt_cbc}, + {"aes128_encrypt_ecb", l_aes128encrypt_ecb}, {"crc16", l_crc16}, {"crc64", l_crc64}, + {"sha1", l_sha1}, {NULL, NULL} }; diff --git a/client/util.c b/client/util.c index 1fc684b6..9f2142c6 100644 --- a/client/util.c +++ b/client/util.c @@ -394,7 +394,7 @@ int hextobinstring(char *target, char *source) // convert binary array of 0x00/0x01 values to hex (safe to do in place as target will always be shorter than source) // return number of bits converted -int binarraytohex(char *target, char *source, int length) +int binarraytohex(char *target,char *source, int length) { unsigned char i, x; int j = length; diff --git a/common/sha1.c b/common/sha1.c new file mode 100644 index 00000000..d20c54a4 --- /dev/null +++ b/common/sha1.c @@ -0,0 +1,665 @@ +/* + * FIPS-180-1 compliant SHA-1 implementation + * + * Copyright (C) 2006-2014, ARM Limited, All Rights Reserved + * This file is part of mbed TLS (https://tls.mbed.org) + * + * 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 + * (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 more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +/* + * The SHA-1 standard was published by NIST in 1993. + * + * http://www.itl.nist.gov/fipspubs/fip180-1.htm + */ + +#if !defined(POLARSSL_CONFIG_FILE) +//#include "polarssl/config.h" +#define POLARSSL_SHA1_C + +#else +#include POLARSSL_CONFIG_FILE +#endif + +#if defined(POLARSSL_SHA1_C) + +#include "sha1.h" + +#include + +#if defined(POLARSSL_FS_IO) +#include +#endif + +#if defined(POLARSSL_SELF_TEST) +#if defined(POLARSSL_PLATFORM_C) +#include "polarssl/platform.h" +#else +#include +#define polarssl_printf printf +#endif /* POLARSSL_PLATFORM_C */ +#endif /* POLARSSL_SELF_TEST */ + +/* Implementation that should never be optimized out by the compiler */ +static void polarssl_zeroize( void *v, size_t n ) { + volatile unsigned char *p = v; while( n-- ) *p++ = 0; +} + +#if !defined(POLARSSL_SHA1_ALT) + +/* + * 32-bit integer manipulation macros (big endian) + */ +#ifndef GET_UINT32_BE +#define GET_UINT32_BE(n,b,i) \ +{ \ + (n) = ( (uint32_t) (b)[(i) ] << 24 ) \ + | ( (uint32_t) (b)[(i) + 1] << 16 ) \ + | ( (uint32_t) (b)[(i) + 2] << 8 ) \ + | ( (uint32_t) (b)[(i) + 3] ); \ +} +#endif + +#ifndef PUT_UINT32_BE +#define PUT_UINT32_BE(n,b,i) \ +{ \ + (b)[(i) ] = (unsigned char) ( (n) >> 24 ); \ + (b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \ + (b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \ + (b)[(i) + 3] = (unsigned char) ( (n) ); \ +} +#endif + +void sha1_init( sha1_context *ctx ) +{ + memset( ctx, 0, sizeof( sha1_context ) ); +} + +void sha1_free( sha1_context *ctx ) +{ + if( ctx == NULL ) + return; + + polarssl_zeroize( ctx, sizeof( sha1_context ) ); +} + +/* + * SHA-1 context setup + */ +void sha1_starts( sha1_context *ctx ) +{ + ctx->total[0] = 0; + ctx->total[1] = 0; + + ctx->state[0] = 0x67452301; + ctx->state[1] = 0xEFCDAB89; + ctx->state[2] = 0x98BADCFE; + ctx->state[3] = 0x10325476; + ctx->state[4] = 0xC3D2E1F0; +} + +void sha1_process( sha1_context *ctx, const unsigned char data[64] ) +{ + uint32_t temp, W[16], A, B, C, D, E; + + GET_UINT32_BE( W[ 0], data, 0 ); + GET_UINT32_BE( W[ 1], data, 4 ); + GET_UINT32_BE( W[ 2], data, 8 ); + GET_UINT32_BE( W[ 3], data, 12 ); + GET_UINT32_BE( W[ 4], data, 16 ); + GET_UINT32_BE( W[ 5], data, 20 ); + GET_UINT32_BE( W[ 6], data, 24 ); + GET_UINT32_BE( W[ 7], data, 28 ); + GET_UINT32_BE( W[ 8], data, 32 ); + GET_UINT32_BE( W[ 9], data, 36 ); + GET_UINT32_BE( W[10], data, 40 ); + GET_UINT32_BE( W[11], data, 44 ); + GET_UINT32_BE( W[12], data, 48 ); + GET_UINT32_BE( W[13], data, 52 ); + GET_UINT32_BE( W[14], data, 56 ); + GET_UINT32_BE( W[15], data, 60 ); + +#define S(x,n) ((x << n) | ((x & 0xFFFFFFFF) >> (32 - n))) + +#define R(t) \ +( \ + temp = W[( t - 3 ) & 0x0F] ^ W[( t - 8 ) & 0x0F] ^ \ + W[( t - 14 ) & 0x0F] ^ W[ t & 0x0F], \ + ( W[t & 0x0F] = S(temp,1) ) \ +) + +#define P(a,b,c,d,e,x) \ +{ \ + e += S(a,5) + F(b,c,d) + K + x; b = S(b,30); \ +} + + A = ctx->state[0]; + B = ctx->state[1]; + C = ctx->state[2]; + D = ctx->state[3]; + E = ctx->state[4]; + +#define F(x,y,z) (z ^ (x & (y ^ z))) +#define K 0x5A827999 + + P( A, B, C, D, E, W[0] ); + P( E, A, B, C, D, W[1] ); + P( D, E, A, B, C, W[2] ); + P( C, D, E, A, B, W[3] ); + P( B, C, D, E, A, W[4] ); + P( A, B, C, D, E, W[5] ); + P( E, A, B, C, D, W[6] ); + P( D, E, A, B, C, W[7] ); + P( C, D, E, A, B, W[8] ); + P( B, C, D, E, A, W[9] ); + P( A, B, C, D, E, W[10] ); + P( E, A, B, C, D, W[11] ); + P( D, E, A, B, C, W[12] ); + P( C, D, E, A, B, W[13] ); + P( B, C, D, E, A, W[14] ); + P( A, B, C, D, E, W[15] ); + P( E, A, B, C, D, R(16) ); + P( D, E, A, B, C, R(17) ); + P( C, D, E, A, B, R(18) ); + P( B, C, D, E, A, R(19) ); + +#undef K +#undef F + +#define F(x,y,z) (x ^ y ^ z) +#define K 0x6ED9EBA1 + + P( A, B, C, D, E, R(20) ); + P( E, A, B, C, D, R(21) ); + P( D, E, A, B, C, R(22) ); + P( C, D, E, A, B, R(23) ); + P( B, C, D, E, A, R(24) ); + P( A, B, C, D, E, R(25) ); + P( E, A, B, C, D, R(26) ); + P( D, E, A, B, C, R(27) ); + P( C, D, E, A, B, R(28) ); + P( B, C, D, E, A, R(29) ); + P( A, B, C, D, E, R(30) ); + P( E, A, B, C, D, R(31) ); + P( D, E, A, B, C, R(32) ); + P( C, D, E, A, B, R(33) ); + P( B, C, D, E, A, R(34) ); + P( A, B, C, D, E, R(35) ); + P( E, A, B, C, D, R(36) ); + P( D, E, A, B, C, R(37) ); + P( C, D, E, A, B, R(38) ); + P( B, C, D, E, A, R(39) ); + +#undef K +#undef F + +#define F(x,y,z) ((x & y) | (z & (x | y))) +#define K 0x8F1BBCDC + + P( A, B, C, D, E, R(40) ); + P( E, A, B, C, D, R(41) ); + P( D, E, A, B, C, R(42) ); + P( C, D, E, A, B, R(43) ); + P( B, C, D, E, A, R(44) ); + P( A, B, C, D, E, R(45) ); + P( E, A, B, C, D, R(46) ); + P( D, E, A, B, C, R(47) ); + P( C, D, E, A, B, R(48) ); + P( B, C, D, E, A, R(49) ); + P( A, B, C, D, E, R(50) ); + P( E, A, B, C, D, R(51) ); + P( D, E, A, B, C, R(52) ); + P( C, D, E, A, B, R(53) ); + P( B, C, D, E, A, R(54) ); + P( A, B, C, D, E, R(55) ); + P( E, A, B, C, D, R(56) ); + P( D, E, A, B, C, R(57) ); + P( C, D, E, A, B, R(58) ); + P( B, C, D, E, A, R(59) ); + +#undef K +#undef F + +#define F(x,y,z) (x ^ y ^ z) +#define K 0xCA62C1D6 + + P( A, B, C, D, E, R(60) ); + P( E, A, B, C, D, R(61) ); + P( D, E, A, B, C, R(62) ); + P( C, D, E, A, B, R(63) ); + P( B, C, D, E, A, R(64) ); + P( A, B, C, D, E, R(65) ); + P( E, A, B, C, D, R(66) ); + P( D, E, A, B, C, R(67) ); + P( C, D, E, A, B, R(68) ); + P( B, C, D, E, A, R(69) ); + P( A, B, C, D, E, R(70) ); + P( E, A, B, C, D, R(71) ); + P( D, E, A, B, C, R(72) ); + P( C, D, E, A, B, R(73) ); + P( B, C, D, E, A, R(74) ); + P( A, B, C, D, E, R(75) ); + P( E, A, B, C, D, R(76) ); + P( D, E, A, B, C, R(77) ); + P( C, D, E, A, B, R(78) ); + P( B, C, D, E, A, R(79) ); + +#undef K +#undef F + + ctx->state[0] += A; + ctx->state[1] += B; + ctx->state[2] += C; + ctx->state[3] += D; + ctx->state[4] += E; +} + +/* + * SHA-1 process buffer + */ +void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen ) +{ + size_t fill; + uint32_t left; + + if( ilen == 0 ) + return; + + left = ctx->total[0] & 0x3F; + fill = 64 - left; + + ctx->total[0] += (uint32_t) ilen; + ctx->total[0] &= 0xFFFFFFFF; + + if( ctx->total[0] < (uint32_t) ilen ) + ctx->total[1]++; + + if( left && ilen >= fill ) + { + memcpy( (void *) (ctx->buffer + left), input, fill ); + sha1_process( ctx, ctx->buffer ); + input += fill; + ilen -= fill; + left = 0; + } + + while( ilen >= 64 ) + { + sha1_process( ctx, input ); + input += 64; + ilen -= 64; + } + + if( ilen > 0 ) + memcpy( (void *) (ctx->buffer + left), input, ilen ); +} + +static const unsigned char sha1_padding[64] = +{ + 0x80, 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, 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, 0, 0, 0, 0, 0 +}; + +/* + * SHA-1 final digest + */ +void sha1_finish( sha1_context *ctx, unsigned char output[20] ) +{ + uint32_t last, padn; + uint32_t high, low; + unsigned char msglen[8]; + + high = ( ctx->total[0] >> 29 ) + | ( ctx->total[1] << 3 ); + low = ( ctx->total[0] << 3 ); + + PUT_UINT32_BE( high, msglen, 0 ); + PUT_UINT32_BE( low, msglen, 4 ); + + last = ctx->total[0] & 0x3F; + padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last ); + + sha1_update( ctx, sha1_padding, padn ); + sha1_update( ctx, msglen, 8 ); + + PUT_UINT32_BE( ctx->state[0], output, 0 ); + PUT_UINT32_BE( ctx->state[1], output, 4 ); + PUT_UINT32_BE( ctx->state[2], output, 8 ); + PUT_UINT32_BE( ctx->state[3], output, 12 ); + PUT_UINT32_BE( ctx->state[4], output, 16 ); +} + +#endif /* !POLARSSL_SHA1_ALT */ + +/* + * output = SHA-1( input buffer ) + */ +void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ) +{ + sha1_context ctx; + + sha1_init( &ctx ); + sha1_starts( &ctx ); + sha1_update( &ctx, input, ilen ); + sha1_finish( &ctx, output ); + sha1_free( &ctx ); +} + +#if defined(POLARSSL_FS_IO) +/* + * output = SHA-1( file contents ) + */ +int sha1_file( const char *path, unsigned char output[20] ) +{ + FILE *f; + size_t n; + sha1_context ctx; + unsigned char buf[1024]; + + if( ( f = fopen( path, "rb" ) ) == NULL ) + return( POLARSSL_ERR_SHA1_FILE_IO_ERROR ); + + sha1_init( &ctx ); + sha1_starts( &ctx ); + + while( ( n = fread( buf, 1, sizeof( buf ), f ) ) > 0 ) + sha1_update( &ctx, buf, n ); + + sha1_finish( &ctx, output ); + sha1_free( &ctx ); + + if( ferror( f ) != 0 ) + { + fclose( f ); + return( POLARSSL_ERR_SHA1_FILE_IO_ERROR ); + } + + fclose( f ); + return( 0 ); +} +#endif /* POLARSSL_FS_IO */ + +/* + * SHA-1 HMAC context setup + */ +void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, + size_t keylen ) +{ + size_t i; + unsigned char sum[20]; + + if( keylen > 64 ) + { + sha1( key, keylen, sum ); + keylen = 20; + key = sum; + } + + memset( ctx->ipad, 0x36, 64 ); + memset( ctx->opad, 0x5C, 64 ); + + for( i = 0; i < keylen; i++ ) + { + ctx->ipad[i] = (unsigned char)( ctx->ipad[i] ^ key[i] ); + ctx->opad[i] = (unsigned char)( ctx->opad[i] ^ key[i] ); + } + + sha1_starts( ctx ); + sha1_update( ctx, ctx->ipad, 64 ); + + polarssl_zeroize( sum, sizeof( sum ) ); +} + +/* + * SHA-1 HMAC process buffer + */ +void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, + size_t ilen ) +{ + sha1_update( ctx, input, ilen ); +} + +/* + * SHA-1 HMAC final digest + */ +void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] ) +{ + unsigned char tmpbuf[20]; + + sha1_finish( ctx, tmpbuf ); + sha1_starts( ctx ); + sha1_update( ctx, ctx->opad, 64 ); + sha1_update( ctx, tmpbuf, 20 ); + sha1_finish( ctx, output ); + + polarssl_zeroize( tmpbuf, sizeof( tmpbuf ) ); +} + +/* + * SHA1 HMAC context reset + */ +void sha1_hmac_reset( sha1_context *ctx ) +{ + sha1_starts( ctx ); + sha1_update( ctx, ctx->ipad, 64 ); +} + +/* + * output = HMAC-SHA-1( hmac key, input buffer ) + */ +void sha1_hmac( const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char output[20] ) +{ + sha1_context ctx; + + sha1_init( &ctx ); + sha1_hmac_starts( &ctx, key, keylen ); + sha1_hmac_update( &ctx, input, ilen ); + sha1_hmac_finish( &ctx, output ); + sha1_free( &ctx ); +} + +#if defined(POLARSSL_SELF_TEST) +/* + * FIPS-180-1 test vectors + */ +static const unsigned char sha1_test_buf[3][57] = +{ + { "abc" }, + { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" }, + { "" } +}; + +static const int sha1_test_buflen[3] = +{ + 3, 56, 1000 +}; + +static const unsigned char sha1_test_sum[3][20] = +{ + { 0xA9, 0x99, 0x3E, 0x36, 0x47, 0x06, 0x81, 0x6A, 0xBA, 0x3E, + 0x25, 0x71, 0x78, 0x50, 0xC2, 0x6C, 0x9C, 0xD0, 0xD8, 0x9D }, + { 0x84, 0x98, 0x3E, 0x44, 0x1C, 0x3B, 0xD2, 0x6E, 0xBA, 0xAE, + 0x4A, 0xA1, 0xF9, 0x51, 0x29, 0xE5, 0xE5, 0x46, 0x70, 0xF1 }, + { 0x34, 0xAA, 0x97, 0x3C, 0xD4, 0xC4, 0xDA, 0xA4, 0xF6, 0x1E, + 0xEB, 0x2B, 0xDB, 0xAD, 0x27, 0x31, 0x65, 0x34, 0x01, 0x6F } +}; + +/* + * RFC 2202 test vectors + */ +static const unsigned char sha1_hmac_test_key[7][26] = +{ + { "\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B\x0B" + "\x0B\x0B\x0B\x0B" }, + { "Jefe" }, + { "\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA\xAA" + "\xAA\xAA\xAA\xAA" }, + { "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10" + "\x11\x12\x13\x14\x15\x16\x17\x18\x19" }, + { "\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C\x0C" + "\x0C\x0C\x0C\x0C" }, + { "" }, /* 0xAA 80 times */ + { "" } +}; + +static const int sha1_hmac_test_keylen[7] = +{ + 20, 4, 20, 25, 20, 80, 80 +}; + +static const unsigned char sha1_hmac_test_buf[7][74] = +{ + { "Hi There" }, + { "what do ya want for nothing?" }, + { "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" + "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" + "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" + "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" + "\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD\xDD" }, + { "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" + "\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD\xCD" }, + { "Test With Truncation" }, + { "Test Using Larger Than Block-Size Key - Hash Key First" }, + { "Test Using Larger Than Block-Size Key and Larger" + " Than One Block-Size Data" } +}; + +static const int sha1_hmac_test_buflen[7] = +{ + 8, 28, 50, 50, 20, 54, 73 +}; + +static const unsigned char sha1_hmac_test_sum[7][20] = +{ + { 0xB6, 0x17, 0x31, 0x86, 0x55, 0x05, 0x72, 0x64, 0xE2, 0x8B, + 0xC0, 0xB6, 0xFB, 0x37, 0x8C, 0x8E, 0xF1, 0x46, 0xBE, 0x00 }, + { 0xEF, 0xFC, 0xDF, 0x6A, 0xE5, 0xEB, 0x2F, 0xA2, 0xD2, 0x74, + 0x16, 0xD5, 0xF1, 0x84, 0xDF, 0x9C, 0x25, 0x9A, 0x7C, 0x79 }, + { 0x12, 0x5D, 0x73, 0x42, 0xB9, 0xAC, 0x11, 0xCD, 0x91, 0xA3, + 0x9A, 0xF4, 0x8A, 0xA1, 0x7B, 0x4F, 0x63, 0xF1, 0x75, 0xD3 }, + { 0x4C, 0x90, 0x07, 0xF4, 0x02, 0x62, 0x50, 0xC6, 0xBC, 0x84, + 0x14, 0xF9, 0xBF, 0x50, 0xC8, 0x6C, 0x2D, 0x72, 0x35, 0xDA }, + { 0x4C, 0x1A, 0x03, 0x42, 0x4B, 0x55, 0xE0, 0x7F, 0xE7, 0xF2, + 0x7B, 0xE1 }, + { 0xAA, 0x4A, 0xE5, 0xE1, 0x52, 0x72, 0xD0, 0x0E, 0x95, 0x70, + 0x56, 0x37, 0xCE, 0x8A, 0x3B, 0x55, 0xED, 0x40, 0x21, 0x12 }, + { 0xE8, 0xE9, 0x9D, 0x0F, 0x45, 0x23, 0x7D, 0x78, 0x6D, 0x6B, + 0xBA, 0xA7, 0x96, 0x5C, 0x78, 0x08, 0xBB, 0xFF, 0x1A, 0x91 } +}; + +/* + * Checkup routine + */ +int sha1_self_test( int verbose ) +{ + int i, j, buflen, ret = 0; + unsigned char buf[1024]; + unsigned char sha1sum[20]; + sha1_context ctx; + + sha1_init( &ctx ); + + /* + * SHA-1 + */ + for( i = 0; i < 3; i++ ) + { + if( verbose != 0 ) + polarssl_printf( " SHA-1 test #%d: ", i + 1 ); + + sha1_starts( &ctx ); + + if( i == 2 ) + { + memset( buf, 'a', buflen = 1000 ); + + for( j = 0; j < 1000; j++ ) + sha1_update( &ctx, buf, buflen ); + } + else + sha1_update( &ctx, sha1_test_buf[i], + sha1_test_buflen[i] ); + + sha1_finish( &ctx, sha1sum ); + + if( memcmp( sha1sum, sha1_test_sum[i], 20 ) != 0 ) + { + if( verbose != 0 ) + polarssl_printf( "failed\n" ); + + ret = 1; + goto exit; + } + + if( verbose != 0 ) + polarssl_printf( "passed\n" ); + } + + if( verbose != 0 ) + polarssl_printf( "\n" ); + + for( i = 0; i < 7; i++ ) + { + if( verbose != 0 ) + polarssl_printf( " HMAC-SHA-1 test #%d: ", i + 1 ); + + if( i == 5 || i == 6 ) + { + memset( buf, 0xAA, buflen = 80 ); + sha1_hmac_starts( &ctx, buf, buflen ); + } + else + sha1_hmac_starts( &ctx, sha1_hmac_test_key[i], + sha1_hmac_test_keylen[i] ); + + sha1_hmac_update( &ctx, sha1_hmac_test_buf[i], + sha1_hmac_test_buflen[i] ); + + sha1_hmac_finish( &ctx, sha1sum ); + + buflen = ( i == 4 ) ? 12 : 20; + + if( memcmp( sha1sum, sha1_hmac_test_sum[i], buflen ) != 0 ) + { + if( verbose != 0 ) + polarssl_printf( "failed\n" ); + + ret = 1; + goto exit; + } + + if( verbose != 0 ) + polarssl_printf( "passed\n" ); + } + + if( verbose != 0 ) + polarssl_printf( "\n" ); + +exit: + sha1_free( &ctx ); + + return( ret ); +} + +#endif /* POLARSSL_SELF_TEST */ + +#endif /* POLARSSL_SHA1_C */ + diff --git a/common/sha1.h b/common/sha1.h new file mode 100644 index 00000000..056bba7e --- /dev/null +++ b/common/sha1.h @@ -0,0 +1,213 @@ +/** + * \file sha1.h + * + * \brief SHA-1 cryptographic hash function + * + * Copyright (C) 2006-2014, ARM Limited, All Rights Reserved + * + * This file is part of mbed TLS (https://tls.mbed.org) + * + * 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 + * (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 more details. + * + * You should have received a copy of the GNU General Public License along + * with this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + */ +#ifndef POLARSSL_SHA1_H +#define POLARSSL_SHA1_H + +#if !defined(POLARSSL_CONFIG_FILE) +//#include "config.h" +/** + * \def POLARSSL_SHA1_C + * + * Enable the SHA1 cryptographic hash algorithm. + * + * Module: library/sha1.c + * Caller: library/md.c + * library/ssl_cli.c + * library/ssl_srv.c + * library/ssl_tls.c + * library/x509write_crt.c + * + * This module is required for SSL/TLS and SHA1-signed certificates. + */ +#define POLARSSL_SHA1_C + +#else +#include POLARSSL_CONFIG_FILE +#endif + +#include + +#if defined(_MSC_VER) && !defined(EFIX64) && !defined(EFI32) +#include +typedef UINT32 uint32_t; +#else +#include +#endif + +#define POLARSSL_ERR_SHA1_FILE_IO_ERROR -0x0076 /**< Read/write error in file. */ + +#if !defined(POLARSSL_SHA1_ALT) +// Regular implementation +// + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief SHA-1 context structure + */ +typedef struct +{ + uint32_t total[2]; /*!< number of bytes processed */ + uint32_t state[5]; /*!< intermediate digest state */ + unsigned char buffer[64]; /*!< data block being processed */ + + unsigned char ipad[64]; /*!< HMAC: inner padding */ + unsigned char opad[64]; /*!< HMAC: outer padding */ +} +sha1_context; + +/** + * \brief Initialize SHA-1 context + * + * \param ctx SHA-1 context to be initialized + */ +void sha1_init( sha1_context *ctx ); + +/** + * \brief Clear SHA-1 context + * + * \param ctx SHA-1 context to be cleared + */ +void sha1_free( sha1_context *ctx ); + +/** + * \brief SHA-1 context setup + * + * \param ctx context to be initialized + */ +void sha1_starts( sha1_context *ctx ); + +/** + * \brief SHA-1 process buffer + * + * \param ctx SHA-1 context + * \param input buffer holding the data + * \param ilen length of the input data + */ +void sha1_update( sha1_context *ctx, const unsigned char *input, size_t ilen ); + +/** + * \brief SHA-1 final digest + * + * \param ctx SHA-1 context + * \param output SHA-1 checksum result + */ +void sha1_finish( sha1_context *ctx, unsigned char output[20] ); + +/* Internal use */ +void sha1_process( sha1_context *ctx, const unsigned char data[64] ); + +#ifdef __cplusplus +} +#endif + +#else /* POLARSSL_SHA1_ALT */ +#include "sha1_alt.h" +#endif /* POLARSSL_SHA1_ALT */ + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * \brief Output = SHA-1( input buffer ) + * + * \param input buffer holding the data + * \param ilen length of the input data + * \param output SHA-1 checksum result + */ +void sha1( const unsigned char *input, size_t ilen, unsigned char output[20] ); + +/** + * \brief Output = SHA-1( file contents ) + * + * \param path input file name + * \param output SHA-1 checksum result + * + * \return 0 if successful, or POLARSSL_ERR_SHA1_FILE_IO_ERROR + */ +int sha1_file( const char *path, unsigned char output[20] ); + +/** + * \brief SHA-1 HMAC context setup + * + * \param ctx HMAC context to be initialized + * \param key HMAC secret key + * \param keylen length of the HMAC key + */ +void sha1_hmac_starts( sha1_context *ctx, const unsigned char *key, + size_t keylen ); + +/** + * \brief SHA-1 HMAC process buffer + * + * \param ctx HMAC context + * \param input buffer holding the data + * \param ilen length of the input data + */ +void sha1_hmac_update( sha1_context *ctx, const unsigned char *input, + size_t ilen ); + +/** + * \brief SHA-1 HMAC final digest + * + * \param ctx HMAC context + * \param output SHA-1 HMAC checksum result + */ +void sha1_hmac_finish( sha1_context *ctx, unsigned char output[20] ); + +/** + * \brief SHA-1 HMAC context reset + * + * \param ctx HMAC context to be reset + */ +void sha1_hmac_reset( sha1_context *ctx ); + +/** + * \brief Output = HMAC-SHA-1( hmac key, input buffer ) + * + * \param key HMAC secret key + * \param keylen length of the HMAC key + * \param input buffer holding the data + * \param ilen length of the input data + * \param output HMAC-SHA-1 result + */ +void sha1_hmac( const unsigned char *key, size_t keylen, + const unsigned char *input, size_t ilen, + unsigned char output[20] ); + +/** + * \brief Checkup routine + * + * \return 0 if successful, or 1 if the test failed + */ +int sha1_self_test( int verbose ); + +#ifdef __cplusplus +} +#endif + +#endif /* sha1.h */ From 97a0f5f4aa89ddd940f9fc15779534ebb9ac630a Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Sun, 31 May 2015 19:51:44 +0200 Subject: [PATCH 093/132] fix format strings for nit picking compilers --- client/fpga_compress.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/client/fpga_compress.c b/client/fpga_compress.c index 5f4d23d4..f7333b36 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -96,8 +96,8 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) } } - if (i > num_infiles * FPGA_CONFIG_SIZE) { - fprintf(stderr, "Input files too big (total of %ld > %d bytes). These are probably not PM3 FPGA config files.", i, num_infiles*FPGA_CONFIG_SIZE); + if (i >= num_infiles * FPGA_CONFIG_SIZE) { + fprintf(stderr, "Input files too big (total > %lu bytes). These are probably not PM3 FPGA config files.", num_infiles*FPGA_CONFIG_SIZE); for(uint16_t j = 0; j < num_infiles; j++) { fclose(infile[j]); } @@ -136,7 +136,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) ret = deflate(&compressed_fpga_stream, Z_FINISH); } - fprintf(stderr, "compressed %d input bytes to %d output bytes\n", i, compressed_fpga_stream.total_out); + fprintf(stderr, "compressed %lu input bytes to %lu output bytes\n", i, compressed_fpga_stream.total_out); if (ret != Z_STREAM_END) { fprintf(stderr, "Error in deflate(): %d %s\n", ret, compressed_fpga_stream.msg); From be290d68bdc8601efaff25f86dc02e317b509536 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 31 May 2015 16:08:58 -0400 Subject: [PATCH 094/132] new lua script from @iceman1001 + bug fix in hf mfu --- client/cmdhfmfu.c | 1 + client/scripts/didump.lua | 473 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 474 insertions(+) create mode 100644 client/scripts/didump.lua diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 5d211558..731ab72f 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -617,6 +617,7 @@ uint32_t GetHF14AMfU_Type(void){ } } } else { + ul_switch_off_field(); // Infinition MY-D tests Exam high nibble uint8_t nib = (card.uid[1] & 0xf0) >> 4; switch ( nib ){ diff --git a/client/scripts/didump.lua b/client/scripts/didump.lua new file mode 100644 index 00000000..2386d42d --- /dev/null +++ b/client/scripts/didump.lua @@ -0,0 +1,473 @@ +local cmds = require('commands') +local getopt = require('getopt') +local utils = require('utils') +local lib14a = require('read14a') + +example =[[ + script run didump + script run didump -k aabbccddeeff +]] +author = "Iceman" +usage = "script run didump -k " +desc = [[ +This is a script to dump and decrypt the data of a specific type of Mifare Mini token. + +Arguments: + -h : this help + -k : Mifare Key A. +]] + +local band=bit32.band +local bor=bit32.bor +local bnot=bit32.bnot +local bxor=bit32.bxor +local lshift=bit32.lshift +local rshift=bit32.rshift + +local FOO = 'AF62D2EC0491968CC52A1A7165F865FE' +local BAR = '286329204469736E65792032303133' +local RANDOM = FOO..BAR +local outputTemplate = os.date("toydump_%Y-%m-%d_%H%M%S"); +local TIMEOUT = 2000 +local DEBUG = false +local numBlocks = 20 +local numSectors = 5 +local CHECKSUM_OFFSET = 12; -- +1??? +--- +-- A debug printout-function +function dbg(args) + if DEBUG then + print("###", args) + end +end +--- +-- This is only meant to be used when errors occur +function oops(err) + print("ERROR: ",err) + core.clearCommandBuffer() +end +--- +-- Usage help +function help() + print(desc) + print("Example usage") + print(example) +end +--- +-- Get checksum, +-- called: data is string (32 hex digits) +-- returns: number +local function getChecksum(data) + local chksum = data:sub(25,32) + return tonumber(chksum,16) +end +--- +-- calculate checksum +-- called: data is bytes (24 hex digits) +-- returns: number +local function calculateChecksum(data) + + -- Generate table + local _tbl = {} +_tbl[0] = { 0x0 } +_tbl[1] = { 0x77073096 } +_tbl[2] = { 0xEE0E612C } +_tbl[3] = { 0x990951BA } +_tbl[4] = { 0x76DC419 } +_tbl[5] = { 0x706AF48F } +_tbl[6] = { 0xE963A535 } +_tbl[7] = { 0x9E6495A3 } +_tbl[8] = { 0xEDB8832 } +_tbl[9] = { 0x79DCB8A4 } +_tbl[10] = { 0xE0D5E91E } +_tbl[11] = { 0x97D2D988 } +_tbl[12] = { 0x9B64C2B } +_tbl[13] = { 0x7EB17CBD } +_tbl[14] = { 0xE7B82D07 } +_tbl[15] = { 0x90BF1D91 } +_tbl[16] = { 0x1DB71064 } +_tbl[17] = { 0x6AB020F2 } +_tbl[18] = { 0xF3B97148 } +_tbl[19] = { 0x84BE41DE } +_tbl[20] = { 0x1ADAD47D } +_tbl[21] = { 0x6DDDE4EB } +_tbl[22] = { 0xF4D4B551 } +_tbl[23] = { 0x83D385C7 } +_tbl[24] = { 0x136C9856 } +_tbl[25] = { 0x646BA8C0 } +_tbl[26] = { 0xFD62F97A } +_tbl[27] = { 0x8A65C9EC } +_tbl[28] = { 0x14015C4F } +_tbl[29] = { 0x63066CD9 } +_tbl[30] = { 0xFA0F3D63 } +_tbl[31] = { 0x8D080DF5 } +_tbl[32] = { 0x3B6E20C8 } +_tbl[33] = { 0x4C69105E } +_tbl[34] = { 0xD56041E4 } +_tbl[35] = { 0xA2677172 } +_tbl[36] = { 0x3C03E4D1 } +_tbl[37] = { 0x4B04D447 } +_tbl[38] = { 0xD20D85FD } +_tbl[39] = { 0xA50AB56B } +_tbl[40] = { 0x35B5A8FA } +_tbl[41] = { 0x42B2986C } +_tbl[42] = { 0xDBBBC9D6 } +_tbl[43] = { 0xACBCF940 } +_tbl[44] = { 0x32D86CE3 } +_tbl[45] = { 0x45DF5C75 } +_tbl[46] = { 0xDCD60DCF } +_tbl[47] = { 0xABD13D59 } +_tbl[48] = { 0x26D930AC } +_tbl[49] = { 0x51DE003A } +_tbl[50] = { 0xC8D75180 } +_tbl[51] = { 0xBFD06116 } +_tbl[52] = { 0x21B4F4B5 } +_tbl[53] = { 0x56B3C423 } +_tbl[54] = { 0xCFBA9599 } +_tbl[55] = { 0xB8BDA50F } +_tbl[56] = { 0x2802B89E } +_tbl[57] = { 0x5F058808 } +_tbl[58] = { 0xC60CD9B2 } +_tbl[59] = { 0xB10BE924 } +_tbl[60] = { 0x2F6F7C87 } +_tbl[61] = { 0x58684C11 } +_tbl[62] = { 0xC1611DAB } +_tbl[63] = { 0xB6662D3D } +_tbl[64] = { 0x76DC4190 } +_tbl[65] = { 0x1DB7106 } +_tbl[66] = { 0x98D220BC } +_tbl[67] = { 0xEFD5102A } +_tbl[68] = { 0x71B18589 } +_tbl[69] = { 0x6B6B51F } +_tbl[70] = { 0x9FBFE4A5 } +_tbl[71] = { 0xE8B8D433 } +_tbl[72] = { 0x7807C9A2 } +_tbl[73] = { 0xF00F934 } +_tbl[74] = { 0x9609A88E } +_tbl[75] = { 0xE10E9818 } +_tbl[76] = { 0x7F6A0DBB } +_tbl[77] = { 0x86D3D2D } +_tbl[78] = { 0x91646C97 } +_tbl[79] = { 0xE6635C01 } +_tbl[80] = { 0x6B6B51F4 } +_tbl[81] = { 0x1C6C6162 } +_tbl[82] = { 0x856530D8 } +_tbl[83] = { 0xF262004E } +_tbl[84] = { 0x6C0695ED } +_tbl[85] = { 0x1B01A57B } +_tbl[86] = { 0x8208F4C1 } +_tbl[87] = { 0xF50FC457 } +_tbl[88] = { 0x65B0D9C6 } +_tbl[89] = { 0x12B7E950 } +_tbl[90] = { 0x8BBEB8EA } +_tbl[91] = { 0xFCB9887C } +_tbl[92] = { 0x62DD1DDF } +_tbl[93] = { 0x15DA2D49 } +_tbl[94] = { 0x8CD37CF3 } +_tbl[95] = { 0xFBD44C65 } +_tbl[96] = { 0x4DB26158 } +_tbl[97] = { 0x3AB551CE } +_tbl[98] = { 0xA3BC0074 } +_tbl[99] = { 0xD4BB30E2 } +_tbl[100] = { 0x4ADFA541 } +_tbl[101] = { 0x3DD895D7 } +_tbl[102] = { 0xA4D1C46D } +_tbl[103] = { 0xD3D6F4FB } +_tbl[104] = { 0x4369E96A } +_tbl[105] = { 0x346ED9FC } +_tbl[106] = { 0xAD678846 } +_tbl[107] = { 0xDA60B8D0 } +_tbl[108] = { 0x44042D73 } +_tbl[109] = { 0x33031DE5 } +_tbl[110] = { 0xAA0A4C5F } +_tbl[111] = { 0xDD0D7CC9 } +_tbl[112] = { 0x5005713C } +_tbl[113] = { 0x270241AA } +_tbl[114] = { 0xBE0B1010 } +_tbl[115] = { 0xC90C2086 } +_tbl[116] = { 0x5768B525 } +_tbl[117] = { 0x206F85B3 } +_tbl[118] = { 0xB966D409 } +_tbl[119] = { 0xCE61E49F } +_tbl[120] = { 0x5EDEF90E } +_tbl[121] = { 0x29D9C998 } +_tbl[122] = { 0xB0D09822 } +_tbl[123] = { 0xC7D7A8B4 } +_tbl[124] = { 0x59B33D17 } +_tbl[125] = { 0x2EB40D81 } +_tbl[126] = { 0xB7BD5C3B } +_tbl[127] = { 0xC0BA6CAD } +_tbl[128] = { 0xEDB88320 } +_tbl[129] = { 0x9ABFB3B6 } +_tbl[130] = { 0x3B6E20C } +_tbl[131] = { 0x74B1D29A } +_tbl[132] = { 0xEAD54739 } +_tbl[133] = { 0x9DD277AF } +_tbl[134] = { 0x4DB2615 } +_tbl[135] = { 0x73DC1683 } +_tbl[136] = { 0xE3630B12 } +_tbl[137] = { 0x94643B84 } +_tbl[138] = { 0xD6D6A3E } +_tbl[139] = { 0x7A6A5AA8 } +_tbl[140] = { 0xE40ECF0B } +_tbl[141] = { 0x9309FF9D } +_tbl[142] = { 0xA00AE27 } +_tbl[143] = { 0x7D079EB1 } +_tbl[144] = { 0xF00F9344 } +_tbl[145] = { 0x8708A3D2 } +_tbl[146] = { 0x1E01F268 } +_tbl[147] = { 0x6906C2FE } +_tbl[148] = { 0xF762575D } +_tbl[149] = { 0x806567CB } +_tbl[150] = { 0x196C3671 } +_tbl[151] = { 0x6E6B06E7 } +_tbl[152] = { 0xFED41B76 } +_tbl[153] = { 0x89D32BE0 } +_tbl[154] = { 0x10DA7A5A } +_tbl[155] = { 0x67DD4ACC } +_tbl[156] = { 0xF9B9DF6F } +_tbl[157] = { 0x8EBEEFF9 } +_tbl[158] = { 0x17B7BE43 } +_tbl[159] = { 0x60B08ED5 } +_tbl[160] = { 0xD6D6A3E8 } +_tbl[161] = { 0xA1D1937E } +_tbl[162] = { 0x38D8C2C4 } +_tbl[163] = { 0x4FDFF252 } +_tbl[164] = { 0xD1BB67F1 } +_tbl[165] = { 0xA6BC5767 } +_tbl[166] = { 0x3FB506DD } +_tbl[167] = { 0x48B2364B } +_tbl[168] = { 0xD80D2BDA } +_tbl[169] = { 0xAF0A1B4C } +_tbl[170] = { 0x36034AF6 } +_tbl[171] = { 0x41047A60 } +_tbl[172] = { 0xDF60EFC3 } +_tbl[173] = { 0xA867DF55 } +_tbl[174] = { 0x316E8EEF } +_tbl[175] = { 0x4669BE79 } +_tbl[176] = { 0xCB61B38C } +_tbl[177] = { 0xBC66831A } +_tbl[178] = { 0x256FD2A0 } +_tbl[179] = { 0x5268E236 } +_tbl[180] = { 0xCC0C7795 } +_tbl[181] = { 0xBB0B4703 } +_tbl[182] = { 0x220216B9 } +_tbl[183] = { 0x5505262F } +_tbl[184] = { 0xC5BA3BBE } +_tbl[185] = { 0xB2BD0B28 } +_tbl[186] = { 0x2BB45A92 } +_tbl[187] = { 0x5CB36A04 } +_tbl[188] = { 0xC2D7FFA7 } +_tbl[189] = { 0xB5D0CF31 } +_tbl[190] = { 0x2CD99E8B } +_tbl[191] = { 0x5BDEAE1D } +_tbl[192] = { 0x9B64C2B0 } +_tbl[193] = { 0xEC63F226 } +_tbl[194] = { 0x756AA39C } +_tbl[195] = { 0x26D930A } +_tbl[196] = { 0x9C0906A9 } +_tbl[197] = { 0xEB0E363F } +_tbl[198] = { 0x72076785 } +_tbl[199] = { 0x5005713 } +_tbl[200] = { 0x95BF4A82 } +_tbl[201] = { 0xE2B87A14 } +_tbl[202] = { 0x7BB12BAE } +_tbl[203] = { 0xCB61B38 } +_tbl[204] = { 0x92D28E9B } +_tbl[205] = { 0xE5D5BE0D } +_tbl[206] = { 0x7CDCEFB7 } +_tbl[207] = { 0xBDBDF21 } +_tbl[208] = { 0x86D3D2D4 } +_tbl[209] = { 0xF1D4E242 } +_tbl[210] = { 0x68DDB3F8 } +_tbl[211] = { 0x1FDA836E } +_tbl[212] = { 0x81BE16CD } +_tbl[213] = { 0xF6B9265B } +_tbl[214] = { 0x6FB077E1 } +_tbl[215] = { 0x18B74777 } +_tbl[216] = { 0x88085AE6 } +_tbl[217] = { 0xFF0F6A70 } +_tbl[218] = { 0x66063BCA } +_tbl[219] = { 0x11010B5C } +_tbl[220] = { 0x8F659EFF } +_tbl[221] = { 0xF862AE69 } +_tbl[222] = { 0x616BFFD3 } +_tbl[223] = { 0x166CCF45 } +_tbl[224] = { 0xA00AE278 } +_tbl[225] = { 0xD70DD2EE } +_tbl[226] = { 0x4E048354 } +_tbl[227] = { 0x3903B3C2 } +_tbl[228] = { 0xA7672661 } +_tbl[229] = { 0xD06016F7 } +_tbl[230] = { 0x4969474D } +_tbl[231] = { 0x3E6E77DB } +_tbl[232] = { 0xAED16A4A } +_tbl[233] = { 0xD9D65ADC } +_tbl[234] = { 0x40DF0B66 } +_tbl[235] = { 0x37D83BF0 } +_tbl[236] = { 0xA9BCAE53 } +_tbl[237] = { 0xDEBB9EC5 } +_tbl[238] = { 0x47B2CF7F } +_tbl[239] = { 0x30B5FFE9 } +_tbl[240] = { 0xBDBDF21C } +_tbl[241] = { 0xCABAC28A } +_tbl[242] = { 0x53B39330 } +_tbl[243] = { 0x24B4A3A6 } +_tbl[244] = { 0xBAD03605 } +_tbl[245] = { 0xCDD70693 } +_tbl[246] = { 0x54DE5729 } +_tbl[247] = { 0x23D967BF } +_tbl[248] = { 0xB3667A2E } +_tbl[249] = { 0xC4614AB8 } +_tbl[250] = { 0x5D681B02 } +_tbl[251] = { 0x2A6F2B94 } +_tbl[252] = { 0xB40BBE37 } +_tbl[253] = { 0xC30C8EA1 } +_tbl[254] = { 0x5A05DF1B } +_tbl[255] = { 0x2D02EF8D } + + + -- Calculate it + local ret = 0 + for i,item in pairs(data) do + local tmp = band(ret, 0xFF) + local index = band( bxor(tmp, item), 0xFF) + ret = bxor(rshift(ret,8), _tbl[index][1]) + end + return ret +end +--- +-- update checksum +-- called: data is string, ( >= 24 hex digits ) +-- returns: string, (data concat new checksum) +local function updateChecksum(data) + local part = data:sub(1,24) + local chksum = calculateChecksum( utils.ConvertHexToBytes(part)) + return string.format("%s%X", part, chksum) +end +--- +-- receives the answer from deviceside, used with a readblock command +local function waitCmd() + local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT) + if response then + local count,cmd,arg0 = bin.unpack('LL',response) + if(arg0==1) then + local count,arg1,arg2,data = bin.unpack('LLH511',response,count) + return data:sub(1,32) + else + return nil, "Couldn't read block.." + end + end + return nil, "No response from device" +end + +local function selftest() + local testdata = '000F42430D0A14000001D11F'..'5D738517' + local chksum = getChecksum(testdata) + local calc = calculateChecksum( utils.ConvertHexToBytes(testdata:sub(1,24))) + print ('TESTDATA :: '..testdata) + print ('DATA :: '..testdata:sub(1,24)) + print (('CHKSUM :: %X'):format(chksum)) + print (('CHKSUM CALC :: %X'):format(calc)) + print ('UPDATE CHKSUM :: '..updateChecksum(testdata)) + + +end +--- +-- The main entry point +-- -d decrypt +-- -e encrypt +-- -v validate +function main(args) + + local cmd, result, err, blockNo, keyA + local blocks = {} + local decryptkey = '' + + -- Read the parameters + for o, a in getopt.getopt(args, 'hk:') do + if o == "h" then help() return end + if o == "k" then keyA = a end + end + + selftest() + + local tst2 = '00100100030209094312356432324E34B79A349B' + + -- validate input args. + keyA = keyA or '6dd747e86975' + if #(keyA) ~= 12 then + return oops( string.format('Wrong length of write key (was %d) expected 12', #keyA)) + end + + -- Turn off Debug + local cmdSetDbgOff = "hf mf dbg 0" + core.console( cmdSetDbgOff) + + -- GET TAG UID + + result, err = lib14a.read1443a(false) + if not result then + return oops(err) + end + + core.clearCommandBuffer() + + print(result.uid, keyA) + + local my = result.uid + if 1 == 1 then + return + end + + -- Show tag info + print((' Found tag %s'):format(result.name)) + + local longrandom = RANDOM..result.uid + local res = utils.Sha1Hex(longrandom) + res = utils.ConvertBytesToHex(utils.ConvertAsciiToBytes(res:sub(1,16))) + decryptkey = utils.SwapEndiannessStr(res:sub(1,8) , 32) + decryptkey = decryptkey..utils.SwapEndiannessStr( res:sub(9,16),32) + decryptkey = decryptkey..utils.SwapEndiannessStr( res:sub(17,24),32) + decryptkey = decryptkey..utils.SwapEndiannessStr( res:sub(25,32),32) + print('Decrypt key::',decryptkey) + print('Reading card data') + print('Raw','Decrypted') + for blockNo = 0, numBlocks-1, 1 do + + if core.ukbhit() then + print("aborted by user") + break + end + + cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = blockNo ,arg2 = 0,arg3 = 0, data = keyA} + local err = core.SendCommand(cmd:getBytes()) + if err then return oops(err) end + local blockdata, err = waitCmd() + if err then return oops(err) end + + if blockNo%4 ~= 3 then + + -- blocks with zero not encrypted. + if string.find(blockdata, '^0+$') then + print(blockdata, blockdata) + else + local aes = core.aes128_decrypt_ecb(decryptkey, blockdata) + local bytes = utils.ConvertAsciiToBytes(aes) + local hex = utils.ConvertBytesToHex(bytes) + print(blockdata , hex) + end + elseif blockNo == 0 then + print(blockdata,blockdata) + else + -- Sectorblocks, not encrypted + local sectortrailer = keyA..blockdata:sub(13,20)..keyA + print(sectortrailer, sectortrailer, blockdata:sub(13,20)) + end + end + -- checksum fyra sista bytes i varje rad. (kanske inte för s0) + -- s0b1,s1b0,s2b0,s3b0 + -- +end + +main(args) From 4a74e2be72b133ceea811d6f559b5b1a0da52377 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 1 Jun 2015 00:18:03 -0400 Subject: [PATCH 095/132] add my_d move lean identification. --- client/cmdhfmfu.c | 56 +++++++++++++++++++++++++++-------------------- client/cmdhfmfu.h | 7 +++--- 2 files changed, 36 insertions(+), 27 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 731ab72f..48f549ba 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -16,16 +16,19 @@ #include "protocols.h" #include "data.h" -#define MAX_UL_BLOCKS 0x0f -#define MAX_ULC_BLOCKS 0x2b -#define MAX_ULEV1a_BLOCKS 0x13 -#define MAX_ULEV1b_BLOCKS 0x28 -#define MAX_NTAG_203 0x29 -#define MAX_NTAG_210 0x13 -#define MAX_NTAG_212 0x28 -#define MAX_NTAG_213 0x2c -#define MAX_NTAG_215 0x86 -#define MAX_NTAG_216 0xe6 +#define MAX_UL_BLOCKS 0x0f +#define MAX_ULC_BLOCKS 0x2b +#define MAX_ULEV1a_BLOCKS 0x13 +#define MAX_ULEV1b_BLOCKS 0x28 +#define MAX_NTAG_203 0x29 +#define MAX_NTAG_210 0x13 +#define MAX_NTAG_212 0x28 +#define MAX_NTAG_213 0x2c +#define MAX_NTAG_215 0x86 +#define MAX_NTAG_216 0xe6 +#define MAX_MY_D_NFC 0xff +#define MAX_MY_D_MOVE 0x25 +#define MAX_MY_D_MOVE_LEAN 0x0f #define KEYS_3DES_COUNT 7 uint8_t default_3des_keys[KEYS_3DES_COUNT][16] = { @@ -54,17 +57,18 @@ uint8_t default_pwd_pack[KEYS_PWD_COUNT][4] = { {0x32,0x0C,0x16,0x17}, // PACK 0x80,0x80 -- AMiiboo (sniffed) }; -#define MAX_UL_TYPES 16 +#define MAX_UL_TYPES 17 uint16_t UL_TYPES_ARRAY[MAX_UL_TYPES] = {UNKNOWN, UL, UL_C, UL_EV1_48, UL_EV1_128, NTAG, NTAG_203, - NTAG_210, NTAG_212, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC}; + NTAG_210, NTAG_212, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC, MY_D_MOVE_LEAN}; 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_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS, MAX_UL_BLOCKS}; + 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}; static int CmdHelp(const char *Cmd); +// get version nxp product type char *getProductTypeStr( uint8_t id){ static char buf[20]; @@ -285,12 +289,12 @@ static int ul_print_default( uint8_t *data){ PrintAndLog(" UID : %s ", sprint_hex(uid, 7)); PrintAndLog(" UID[0] : %02X, %s", uid[0], getTagInfo(uid[0]) ); - if ( uid[0] == 0x05 ) { + if ( uid[0] == 0x05 && ((uid[1] & 0xf0) >> 4) == 2 ) { // is infineon and 66RxxP uint8_t chip = (data[8] & 0xC7); // 11000111 mask, bit 3,4,5 RFU switch (chip){ - case 0xc2: PrintAndLog(" IC type : SLE 66R04P"); break; - case 0xc4: PrintAndLog(" IC type : SLE 66R16P"); break; - case 0xc6: PrintAndLog(" IC type : SLE 66R32P"); break; + case 0xc2: PrintAndLog(" IC type : SLE 66R04P 770 Bytes"); break; //77 pages + case 0xc4: PrintAndLog(" IC type : SLE 66R16P 2560 Bytes"); break; //256 pages + case 0xc6: PrintAndLog(" IC type : SLE 66R32P 5120 Bytes"); break; //512 pages /2 sectors } } // CT (cascade tag byte) 0x88 xor SN0 xor SN1 xor SN2 @@ -376,13 +380,15 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ else if ( tagtype & NTAG_I2C_2K ) PrintAndLog("%sTYPE : NTAG I%sC 1904bytes (NT3H1201FHK)", spacer, "\xFD"); else if ( tagtype & MY_D ) - PrintAndLog("%sTYPE : INFINEON my-d\x99", spacer); + PrintAndLog("%sTYPE : INFINEON my-d\x99 (SLE 66RxxS)", spacer); else if ( tagtype & MY_D_NFC ) - PrintAndLog("%sTYPE : INFINEON my-d\x99 NFC", spacer); + PrintAndLog("%sTYPE : INFINEON my-d\x99 NFC (SLE 66RxxP)", spacer); else if ( tagtype & MY_D_MOVE ) - PrintAndLog("%sTYPE : INFINEON my-d\x99 move", spacer); + PrintAndLog("%sTYPE : INFINEON my-d\x99 move (SLE 66R01P)", spacer); else if ( tagtype & MY_D_MOVE_NFC ) - PrintAndLog("%sTYPE : INFINEON my-d\x99 move NFC", spacer); + PrintAndLog("%sTYPE : INFINEON my-d\x99 move NFC (SLE 66R01P)", spacer); + else if ( tagtype & MY_D_MOVE_LEAN ) + PrintAndLog("%sTYPE : INFINEON my-d\x99 move lean (SLE 66R01L)", spacer); else PrintAndLog("%sTYPE : Unknown %06x", spacer, tagtype); return 0; @@ -621,9 +627,11 @@ uint32_t GetHF14AMfU_Type(void){ // Infinition MY-D tests Exam high nibble uint8_t nib = (card.uid[1] & 0xf0) >> 4; switch ( nib ){ - case 1: tagtype = MY_D; break; - case 2: tagtype = (MY_D | MY_D_NFC); break; //notice: we can not currently distinguish between these two - case 3: tagtype = (MY_D_MOVE | MY_D_MOVE_NFC); break; //notice: we can not currently distinguish between these two + // case 0: tagtype = SLE66R35E7; break; //or SLE 66R35E7 - mifare compat... should have different sak/atqa for mf 1k + case 1: tagtype = MY_D; break; //or SLE 66RxxS ... up to 512 pages of 8 user bytes... + case 2: tagtype = (MY_D_NFC); break; //or SLE 66RxxP ... up to 512 pages of 8 user bytes... (or in nfc mode FF pages of 4 bytes) + case 3: tagtype = (MY_D_MOVE | MY_D_MOVE_NFC); break; //or SLE 66R01P // 38 pages of 4 bytes //notice: we can not currently distinguish between these two + case 7: tagtype = MY_D_MOVE_LEAN; break; //or SLE 66R01L // 16 pages of 4 bytes } } diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 4ec48ff9..132e4f90 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -42,9 +42,10 @@ typedef enum TAGTYPE_UL { MY_D_NFC = 0x001000, MY_D_MOVE = 0x002000, MY_D_MOVE_NFC = 0x004000, - NTAG_I2C_1K = 0x008000, - NTAG_I2C_2K = 0x010000, - MAGIC = 0x020000, + MY_D_MOVE_LEAN= 0x008000, + NTAG_I2C_1K = 0x010000, + NTAG_I2C_2K = 0x020000, + MAGIC = 0x040000, UL_MAGIC = UL | MAGIC, UL_C_MAGIC = UL_C | MAGIC, UL_ERROR = 0xFFFFFF, From 0d9a86c72441fd0510748bcd2d70ee1fb6f2ff57 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Mon, 1 Jun 2015 19:42:50 +0200 Subject: [PATCH 096/132] Fix issue #103 (hopefully). Quite an old bug which was previously masked by a big DMA_BUFFER_SIZE. --- armsrc/iso14443.c | 37 ++++++++++++++++--------------------- 1 file changed, 16 insertions(+), 21 deletions(-) diff --git a/armsrc/iso14443.c b/armsrc/iso14443.c index c7f49f14..c202e312 100644 --- a/armsrc/iso14443.c +++ b/armsrc/iso14443.c @@ -24,6 +24,9 @@ #define TAG_READER_BUFFER_SIZE 2048 #define DEMOD_DMA_BUFFER_SIZE 1024 */ + +#define RECEIVE_SAMPLES_TIMEOUT 2000 + //============================================================================= // An ISO 14443 Type B tag. We listen for commands from the reader, using // a UART kind of thing that's implemented in software. When we get a @@ -658,9 +661,6 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) // free all previous allocations first BigBuf_free(); - // The command (reader -> tag) that we're receiving. - uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - // The response (tag -> reader) that we're receiving. uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); @@ -669,8 +669,6 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse); - // Set up the demodulator for the reader -> tag commands - UartInit(receivedCmd); // Setup and start DMA. FpgaSetupSscDma(dmaBuf, DMA_BUFFER_SIZE); @@ -695,8 +693,8 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) ci = upTo[0]; cq = upTo[1]; upTo += 2; - if(upTo - dmaBuf > DMA_BUFFER_SIZE) { - upTo -= DMA_BUFFER_SIZE; + if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { + upTo = dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; } @@ -707,15 +705,12 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) samples += 2; - Handle14443UartBit(1); - Handle14443UartBit(1); - if(Handle14443SamplesDemod(ci, cq)) { gotFrame = 1; } } - if(samples > 2000) { + if(samples > n) { break; } } @@ -724,8 +719,8 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) //Tracing if (tracing && Demod.len > 0) { uint8_t parity[MAX_PARITY_SIZE]; - GetParity(Demod.output , Demod.len, parity); - LogTrace(Demod.output,Demod.len, 0, 0, parity, FALSE); + GetParity(Demod.output, Demod.len, parity); + LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE); } } @@ -934,7 +929,7 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); + GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len == 0) { @@ -952,7 +947,7 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); + GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len != 3) { Dbprintf("Expected 3 bytes from tag, got %d", Demod.len); @@ -976,7 +971,7 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); + GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len != 10) { Dbprintf("Expected 10 bytes from tag, got %d", Demod.len); @@ -1008,7 +1003,7 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); + GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len != 6) { // Check if we got an answer from the tag DbpString("Expected 6 bytes from tag, got less..."); @@ -1118,10 +1113,10 @@ void RAMFUNC SnoopIso14443(void) cq = upTo[1]; upTo += 2; lastRxCounter -= 2; - if(upTo - dmaBuf > DMA_BUFFER_SIZE) { - upTo -= DMA_BUFFER_SIZE; + if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { + upTo = dmaBuf; lastRxCounter += DMA_BUFFER_SIZE; - AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; + AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; } @@ -1237,8 +1232,8 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv,uint8_t powerfield, ui if(recv) { + GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); uint16_t iLen = MIN(Demod.len,USB_CMD_DATA_SIZE); - GetSamplesFor14443Demod(TRUE, 2000, TRUE); cmd_send(CMD_ACK,iLen,0,0,Demod.output,iLen); } if(!powerfield) From 67ac4bf75c6953cae546159acd3e887d757bd0c3 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Tue, 2 Jun 2015 07:22:23 +0200 Subject: [PATCH 097/132] fix issue #103: revert type change. Samples from FPGA are signed. Renamed iso14443.c to iso14443b.c --- armsrc/Makefile | 2 +- armsrc/{iso14443.c => iso14443b.c} | 34 +++++++++++++++++++++--------- 2 files changed, 25 insertions(+), 11 deletions(-) rename armsrc/{iso14443.c => iso14443b.c} (98%) diff --git a/armsrc/Makefile b/armsrc/Makefile index 899b0307..502ab958 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -17,7 +17,7 @@ APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ SRC_LF = lfops.c hitag2.c lfsampling.c SRC_ISO15693 = iso15693.c iso15693tools.c SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c -SRC_ISO14443b = iso14443.c +SRC_ISO14443b = iso14443b.c SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c diff --git a/armsrc/iso14443.c b/armsrc/iso14443b.c similarity index 98% rename from armsrc/iso14443.c rename to armsrc/iso14443b.c index c202e312..8add8f9c 100644 --- a/armsrc/iso14443.c +++ b/armsrc/iso14443b.c @@ -619,6 +619,8 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) if (Demod.state == DEMOD_UNSYNCD) LED_C_OFF(); // Not synchronized... return FALSE; } + + static void DemodReset() { // Clear out the state of the "UART" that receives from the tag. @@ -626,12 +628,15 @@ static void DemodReset() Demod.state = DEMOD_UNSYNCD; memset(Demod.output, 0x00, MAX_FRAME_SIZE); } + + static void DemodInit(uint8_t *data) { Demod.output = data; DemodReset(); } + static void UartReset() { Uart.byteCntMax = MAX_FRAME_SIZE; @@ -639,12 +644,15 @@ static void UartReset() Uart.byteCnt = 0; Uart.bitCnt = 0; } + + static void UartInit(uint8_t *data) { Uart.output = data; UartReset(); } + /* * Demodulate the samples we received from the tag, also log to tracebuffer * weTx: set to 'TRUE' if we behave like a reader @@ -665,15 +673,15 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); // The DMA buffer, used to stream samples from the FPGA - uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse); // Setup and start DMA. - FpgaSetupSscDma(dmaBuf, DMA_BUFFER_SIZE); + FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); - uint8_t *upTo= dmaBuf; + int8_t *upTo = dmaBuf; lastRxCounter = DMA_BUFFER_SIZE; // Signal field is ON with the appropriate LED: @@ -724,6 +732,7 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) } } + //----------------------------------------------------------------------------- // Read the tag's response. We just receive a stream of slightly-processed // samples from the FPGA, which we will later do some signal processing on, @@ -756,6 +765,7 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) } }*/ + //----------------------------------------------------------------------------- // Transmit the command (to the tag) that was placed in ToSend[]. //----------------------------------------------------------------------------- @@ -806,6 +816,7 @@ static void TransmitFor14443(void) LED_B_OFF(); // Finished sending } + //----------------------------------------------------------------------------- // Code a layer 2 command (string of octets, including CRC) into ToSend[], // so that it is ready to transmit to the tag using TransmitFor14443(). @@ -862,6 +873,7 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) ToSendMax++; } + //----------------------------------------------------------------------------- // Read an ISO 14443 tag. We send it some set of commands, and record the // responses. @@ -877,6 +889,7 @@ void AcquireRawAdcSamplesIso14443(uint32_t parameter) SendRawCommand14443B(sizeof(cmd1),1,1,cmd1); } + /** Convenience function to encode, transmit and trace iso 14443b comms **/ @@ -891,6 +904,7 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) } } + //----------------------------------------------------------------------------- // Read a SRI512 ISO 14443 tag. // @@ -1059,9 +1073,9 @@ void RAMFUNC SnoopIso14443(void) set_tracing(TRUE); // The DMA buffer, used to stream samples from the FPGA - uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); int lastRxCounter; - uint8_t *upTo; + int8_t *upTo; int ci, cq; int maxBehindBy = 0; @@ -1092,7 +1106,7 @@ void RAMFUNC SnoopIso14443(void) FpgaSetupSsc(); upTo = dmaBuf; lastRxCounter = DMA_BUFFER_SIZE; - FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); + FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); uint8_t parity[MAX_PARITY_SIZE]; LED_A_ON(); @@ -1138,7 +1152,7 @@ void RAMFUNC SnoopIso14443(void) if(Handle14443UartBit(cq & 1)) { if(triggered && tracing) { GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE); + LogTrace(Uart.output,Uart.byteCnt,samples, samples, parity, TRUE); } if(Uart.byteCnt==0) Dbprintf("[2] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); @@ -1156,7 +1170,7 @@ void RAMFUNC SnoopIso14443(void) { uint8_t parity[MAX_PARITY_SIZE]; GetParity(Demod.output, Demod.len, parity); - LogTrace(Demod.output,Demod.len,samples, samples,parity,FALSE); + LogTrace(Demod.output, Demod.len,samples, samples, parity, FALSE); } triggered = TRUE; LED_A_OFF(); @@ -1190,6 +1204,7 @@ void RAMFUNC SnoopIso14443(void) Dbprintf(" Trace length: %i", BigBuf_get_traceLen()); } + /* * Send raw command to tag ISO14443B * @Input @@ -1202,8 +1217,7 @@ void RAMFUNC SnoopIso14443(void) * none * */ - -void SendRawCommand14443B(uint32_t datalen, uint32_t recv,uint8_t powerfield, uint8_t data[]) +void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, uint8_t data[]) { FpgaDownloadAndGo(FPGA_BITSTREAM_HF); if(!powerfield) From 5b95953d4227d9af4b5a5f20156b668bba55aac8 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Tue, 2 Jun 2015 22:27:14 +0200 Subject: [PATCH 098/132] fixing iso14443b (issue #103): - most significant bit of tag data (which happens to be the sign bit) had been dropped when snooping (FPGA change) - avoid trying to decode both tag and reader data when snooping (we don't have the time to do so). --- armsrc/iso14443b.c | 96 ++++++++++++++++++++++------------------ fpga/fpga_hf.bit | Bin 42175 -> 42175 bytes fpga/hi_read_rx_xcorr.v | 13 +++--- 3 files changed, 60 insertions(+), 49 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 8add8f9c..d6595586 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -158,7 +158,6 @@ static int Handle14443UartBit(int bit) { switch(Uart.state) { case STATE_UNSYNCD: - LED_A_OFF(); if(!bit) { // we went low, so this could be the beginning // of an SOF @@ -272,8 +271,7 @@ static int Handle14443UartBit(int bit) break; } - // This row make the error blew circular buffer in hf 14b snoop - //if (Uart.state == STATE_ERROR_WAIT) LED_A_OFF(); // Error + if (Uart.state == STATE_UNSYNCD) LED_A_OFF(); return FALSE; } @@ -1054,17 +1052,17 @@ void ReadSTMemoryIso14443(uint32_t dwLast) //----------------------------------------------------------------------------- /* * Memory usage for this function, (within BigBuf) - * 0-4095 : Demodulated samples receive (4096 bytes) - DEMOD_TRACE_SIZE - * 4096-6143 : Last Received command, 2048 bytes (reader->tag) - READER_TAG_BUFFER_SIZE - * 6144-8191 : Last Received command, 2048 bytes(tag->reader) - TAG_READER_BUFFER_SIZE - * 8192-9215 : DMA Buffer, 1024 bytes (samples) - DEMOD_DMA_BUFFER_SIZE + * Last Received command (reader->tag) - MAX_FRAME_SIZE + * Last Received command (tag->reader) - MAX_FRAME_SIZE + * DMA Buffer, 1024 bytes (samples) - DMA_BUFFER_SIZE + * Demodulated samples received - all the rest */ void RAMFUNC SnoopIso14443(void) { // 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. - int triggered = TRUE; + int triggered = TRUE; // TODO: set and evaluate trigger condition FpgaDownloadAndGo(FPGA_BITSTREAM_HF); BigBuf_free(); @@ -1109,7 +1107,10 @@ void RAMFUNC SnoopIso14443(void) FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); uint8_t parity[MAX_PARITY_SIZE]; LED_A_ON(); - + + bool TagIsActive = FALSE; + bool ReaderIsActive = FALSE; + // And now we loop, receiving samples. for(;;) { int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & @@ -1136,49 +1137,56 @@ void RAMFUNC SnoopIso14443(void) samples += 2; - if(Handle14443UartBit(ci & 1)) { - if(triggered && tracing) { - GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE); - } - if(Uart.byteCnt==0) Dbprintf("[1] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); + if (!TagIsActive) { // no need to try decoding reader data if the tag is sending + if(Handle14443UartBit(ci & 0x01)) { + if(triggered && tracing) { + GetParity(Uart.output, Uart.byteCnt, parity); + LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE); + } + if(Uart.byteCnt==0) Dbprintf("[1] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); - /* And ready to receive another command. */ - UartReset(); - /* And also reset the demod code, which might have been */ - /* false-triggered by the commands from the reader. */ - DemodReset(); - } - if(Handle14443UartBit(cq & 1)) { - if(triggered && tracing) { - GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples, parity, TRUE); + /* And ready to receive another command. */ + UartReset(); + /* And also reset the demod code, which might have been */ + /* false-triggered by the commands from the reader. */ + DemodReset(); } - if(Uart.byteCnt==0) Dbprintf("[2] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); + if(Handle14443UartBit(cq & 0x01)) { + if(triggered && tracing) { + GetParity(Uart.output, Uart.byteCnt, parity); + LogTrace(Uart.output,Uart.byteCnt,samples, samples, parity, TRUE); + } + if(Uart.byteCnt==0) Dbprintf("[2] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); - /* And ready to receive another command. */ - UartReset(); - /* And also reset the demod code, which might have been */ - /* false-triggered by the commands from the reader. */ - DemodReset(); + /* And ready to receive another command. */ + UartReset(); + /* And also reset the demod code, which might have been */ + /* false-triggered by the commands from the reader. */ + DemodReset(); + } + ReaderIsActive = (Uart.state != STATE_UNSYNCD); } - if(Handle14443SamplesDemod(ci, cq)) { + if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time + if(Handle14443SamplesDemod(ci, cq)) { - //Use samples as a time measurement - if(tracing) - { - uint8_t parity[MAX_PARITY_SIZE]; - GetParity(Demod.output, Demod.len, parity); - LogTrace(Demod.output, Demod.len,samples, samples, parity, FALSE); + //Use samples as a time measurement + if(tracing) + { + uint8_t parity[MAX_PARITY_SIZE]; + GetParity(Demod.output, Demod.len, parity); + LogTrace(Demod.output, Demod.len,samples, samples, parity, FALSE); + } + triggered = TRUE; + LED_A_OFF(); + LED_B_ON(); + + // And ready to receive another response. + DemodReset(); } - triggered = TRUE; - LED_A_OFF(); - LED_B_ON(); - - // And ready to receive another response. - DemodReset(); + TagIsActive = (Demod.state != DEMOD_UNSYNCD); } + WDT_HIT(); if(!tracing) { diff --git a/fpga/fpga_hf.bit b/fpga/fpga_hf.bit index 20fb2bd4401254d899d6273451bfccbd827f562b..53078a782422c09596f006d95c85ae45da20072d 100644 GIT binary patch literal 42175 zcmeIb4Rl=PbvC-s&&bD`k>^O3QiUILG!kTR#`0JK;}{{mmIaw4PEZq)xLvuq197RF zy7@$!uh&U)(^n$_@(=Mq+{8`Xtg&$tg}Ckbry#(EV8 zAME?=_nbL1vPo9f`qo|du2s~v%Ffa2bKbwbpZ)B;-&Zs{TJ-*pNV}Ql-rD!)H~*ij zZ(Y#0=H}1+*{aqrd~OxpLe*`5-JblL+ZH90^f?N*B^O=2Fu8bPvW-^J?6$V0ZHt#) z-9~>#w4?7Fe(w8+Pu`j&sS(kvq?YFYT1m~(NOmnqlFR>_{NK+`5}ud;x0WP9z0~qK zsG_%pVNmXVy-o! z$8!Tt%nj%3Can#GCpq0QliX$~G_G%_7S~GZJmy3w3r zn+~@b3w4<53#}>Z&CC>CE6^XQM`#1Jy5Svq8#WMr3ZakE-7?`=9lD@B0^>^RCJpEb zH@sb6f-Qz0N1G=G<${8>w(6(i0ohbA*6NGt&i)03@RV+O?@3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_r&$zLlv~p38(aV^z-C5Fr<@l@ zKfJhRw%`=Um7E0u0Vufsi-_U4u87MsgcZdm|F7cmOgJtA^#2}w)@(Q~KDijQnSsjz zKr10=Bl=KtplZGYVN)VE!cT%WR89qnW`I!8h)>eMX|t$LG*G`2#rY#&2%22wJ=Y{O z?}f!i%H8Wn_$v^U7udfDyUqLgtvir6XV512^Vx#`CiA!Ml}@7sRwHQce%`~(x_3&rzj{6_x>Eo5E z+QTV?vNe@gQD%Py{r8j{nBt55e-}~MHS8-M{?`9&Z~v{oB8o(Q$1nd^{i^fw<;yO= ze6|pLhh+9r-S}y(bYy}D2o`_I!xtkUG6Jtw?ENW z(`BTZy`T4V`D&)%|66_cm*#i;lOS8;ZIYm_KlmNZ-uu;iGw|LFyf*{y&A@vz@ZJo( zHv|7|XF&N&aG2mPIsa`Z;k|*sHv{j@z@?Y}*0J}#whyVZp diff --git a/fpga/hi_read_rx_xcorr.v b/fpga/hi_read_rx_xcorr.v index dece2db3..ec6583b2 100644 --- a/fpga/hi_read_rx_xcorr.v +++ b/fpga/hi_read_rx_xcorr.v @@ -99,8 +99,10 @@ end reg [5:0] corr_i_cnt; reg [5:0] corr_q_cnt; // And a couple of registers in which to accumulate the correlations. -reg signed [15:0] corr_i_accum; -reg signed [15:0] corr_q_accum; +// we would add at most 32 times adc_d, the result can be held in 13 bits. +// Need one additional bit because it can be negative as well +reg signed [13:0] corr_i_accum; +reg signed [13:0] corr_q_accum; reg signed [7:0] corr_i_out; reg signed [7:0] corr_q_out; @@ -114,12 +116,13 @@ begin begin if(snoop) begin - corr_i_out <= {corr_i_accum[12:6], after_hysteresis_prev}; - corr_q_out <= {corr_q_accum[12:6], after_hysteresis}; + // highest 7 significant bits of tag signal (signed), 1 bit reader signal: + corr_i_out <= {corr_i_accum[13:7], after_hysteresis_prev}; + corr_q_out <= {corr_q_accum[13:7], after_hysteresis}; end else begin - // Only correlations need to be delivered. + // highest 8 significant bits of tag signal corr_i_out <= corr_i_accum[13:6]; corr_q_out <= corr_q_accum[13:6]; end From 09c66f1f09776989fda2d1005a2c9feb1db6b3ac Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 3 Jun 2015 13:28:28 +0200 Subject: [PATCH 099/132] fixing iso14443b (issue #103): fix timing issue (speeding up the decoders) --- armsrc/iso14443b.c | 22 +++++++++++----------- fpga/hi_read_rx_xcorr.v | 4 +++- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index d6595586..4e40bb68 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -210,7 +210,6 @@ static int Handle14443UartBit(int bit) Uart.bitCnt = 0; Uart.shiftReg = 0; Uart.state = STATE_RECEIVING_DATA; - LED_A_ON(); // Indicate we're receiving } break; @@ -263,6 +262,7 @@ static int Handle14443UartBit(int bit) Uart.posCnt++; if(Uart.posCnt > 10) { Uart.state = STATE_UNSYNCD; + LED_A_OFF(); } break; @@ -271,8 +271,6 @@ static int Handle14443UartBit(int bit) break; } - if (Uart.state == STATE_UNSYNCD) LED_A_OFF(); - return FALSE; } @@ -548,6 +546,7 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) } else { if(Demod.posCount > 100) { Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); } } Demod.posCount++; @@ -558,6 +557,7 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) if(v > 0) { if(Demod.posCount > 10) { Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); } } else { Demod.bitCount = 0; @@ -596,13 +596,13 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) Demod.output[Demod.len] = b; Demod.len++; Demod.state = DEMOD_AWAITING_START_BIT; - } else if(s == 0x000) { - // This is EOF - LED_C_OFF(); - Demod.state = DEMOD_UNSYNCD; - return TRUE; } else { Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); + if(s == 0x000) { + // This is EOF + return TRUE; + } } } Demod.posCount = 0; @@ -611,10 +611,10 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) default: Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); break; } - if (Demod.state == DEMOD_UNSYNCD) LED_C_OFF(); // Not synchronized... return FALSE; } @@ -1168,14 +1168,14 @@ void RAMFUNC SnoopIso14443(void) } if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time - if(Handle14443SamplesDemod(ci, cq)) { + if(Handle14443SamplesDemod(ci & 0xFE, cq & 0xFE)) { //Use samples as a time measurement if(tracing) { uint8_t parity[MAX_PARITY_SIZE]; GetParity(Demod.output, Demod.len, parity); - LogTrace(Demod.output, Demod.len,samples, samples, parity, FALSE); + LogTrace(Demod.output, Demod.len, samples, samples, parity, FALSE); } triggered = TRUE; LED_A_OFF(); diff --git a/fpga/hi_read_rx_xcorr.v b/fpga/hi_read_rx_xcorr.v index ec6583b2..06142637 100644 --- a/fpga/hi_read_rx_xcorr.v +++ b/fpga/hi_read_rx_xcorr.v @@ -171,7 +171,9 @@ begin end end - if(corr_i_cnt[5:2] == 4'b000 || corr_i_cnt[5:2] == 4'b1000) + // set ssp_frame signal for corr_i_cnt = 0..3 and corr_i_cnt = 32..35 + // (two frames with 8 Bits each) + if(corr_i_cnt[5:2] == 4'b0000 || corr_i_cnt[5:2] == 4'b1000) ssp_frame = 1'b1; else ssp_frame = 1'b0; From 04bb05670dfaac4ba29bbd614c3530036fdb6433 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 3 Jun 2015 16:52:20 -0400 Subject: [PATCH 100/132] Testing animal tags --- client/cmddata.c | 81 ++++++++++++++++++++++++++++++++++++++++++++++-- common/lfdemod.c | 27 ++++++++++++++++ common/lfdemod.h | 1 + 3 files changed, 107 insertions(+), 2 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 76552351..089e7d5f 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -40,7 +40,7 @@ void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx) size = MAX_DEMOD_BUF_LEN; size_t i = 0; - for (; i < size; i++){ +for (; i < size; i++){ DemodBuffer[i]=buff[startIdx++]; } DemodBufferLen=size; @@ -500,7 +500,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) int offset=0, clk=0, invert=0, maxErr=0, ans=0; ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); if (ans>0) - ans = ASKDemod(Cmd+1, FALSE, FALSE, 0); + ans = ASKDemod(Cmd+2, FALSE, FALSE, 0); else ans = ASKDemod(Cmd, FALSE, FALSE, 0); if (!ans) { @@ -1457,6 +1457,83 @@ int CmdFSKdemodPyramid(const char *Cmd) return 1; } +// ISO11784/85 demod (aka animal tag) BIPHASE, inverted, rf/32, with preamble of 00000000001 (128bits) +// 8 databits + 1 parity (1) +// CIITT 16 chksum +// NATIONAL CODE, ICAR database +// COUNTRY CODE (ISO3166) +// FLAG (animal/non-animal) +int CmdIso11784demodBI(const char *Cmd){ + + int invert = 1; + int clk = 32; + int errCnt = 0; + int maxErr = 0; + uint8_t BitStream[MAX_DEMOD_BUF_LEN]; + size_t size = getFromGraphBuf(BitStream); + + errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0); + if ( errCnt < 0 || errCnt > maxErr ) { + if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: 32", errCnt); + return 0; + } + + errCnt = BiphaseRawDecode(BitStream, &size, maxErr, 1); + if (errCnt < 0 || errCnt > maxErr ) { + if (g_debugMode) PrintAndLog("Error BiphaseRawDecode: %d", errCnt); + return 0; + } + + int preambleIndex = ISO11784demodBI(BitStream, &size); + if (preambleIndex < 0){ + if (g_debugMode) PrintAndLog("Error ISO11784Demod , no startmarker found :: %d",preambleIndex); + return 0; + } + + setDemodBuf(BitStream, 128, preambleIndex); + //printDemodBuff(); + + size = removeParity(BitStream, preambleIndex + 11, 9, 1, 117); + if ( size <= 0 ) { + if (g_debugMode) PrintAndLog("Error removeParity:: %d", size); + return 0; + } + PrintAndLog("startmarker %d; Size %d", preambleIndex, size); + + //return 1; + //got a good demod + uint32_t NationalCodeA = bytebits_to_byteLSBF(BitStream,32); + uint32_t NationalCodeB = bytebits_to_byteLSBF(BitStream+32,6); + uint32_t countryCode = bytebits_to_byteLSBF(BitStream+38,10); + uint8_t dataBlockBit = BitStream[48]; + uint32_t reservedCode = bytebits_to_byteLSBF(BitStream+49,14); + uint8_t animalBit = BitStream[63]; + uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16); + uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24); + + PrintAndLog("NationalCode: %x%08x",NationalCodeB,NationalCodeA); + //add rest of print code here... + /* + uint8_t ByteStream[16] = {0x00}; + uint8_t bitCnt = 0; + uint8_t ByteCnt = 0; + size_t startIdx = preambleIndex + 11; //start after preamble + for (size_t idx = 0; idx < size-11; idx++){ + + //lsb first + ByteStream[ByteCnt] = ByteStream[ByteCnt] | (BitStream[startIdx+idx] << bitCnt); + bitCnt++; + if (bitCnt % 8 == 0){ + if (g_debugMode) PrintAndLog("byte %d: %02x", ByteCnt, ByteStream[ByteCnt]); + bitCnt = 0; + ByteCnt++; + } + } + */ + return 1; +} + + //by marshmellow //attempt to psk1 demod graph buffer int PSKDemod(const char *Cmd, bool verbose) diff --git a/common/lfdemod.c b/common/lfdemod.c index 7d40d22e..c0f2bb71 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -537,6 +537,18 @@ uint32_t bytebits_to_byte(uint8_t* src, size_t numbits) return num; } +//least significant bit first +uint32_t bytebits_to_byteLSBF(uint8_t* src, size_t numbits) +{ + uint32_t num = 0; + for(int i = 0 ; i < numbits ; i++) + { + num = (num << 1) | (*src); + src++; + } + return num; +} + int IOdemodFSK(uint8_t *dest, size_t size) { if (justNoise(dest, size)) return -1; @@ -590,6 +602,21 @@ size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t p return bitCnt; } +// Ask/Biphase Demod then try to locate an ISO 11784/85 ID +// BitStream must contain previously askrawdemod and biphasedemoded data +int ISO11784demodBI(uint8_t *dest, size_t *size) +{ + //make sure buffer has enough data + if (*size < 128) return -1; + + size_t startIdx = 0; + uint8_t preamble[] = {0,0,0,0,0,0,0,0,0,0,1}; + + uint8_t errChk = preambleSearch(dest, preamble, sizeof(preamble), size, &startIdx); + if (errChk == 0) return -2; //preamble not found + return (int)startIdx; +} + // by marshmellow // FSK Demod then try to locate an AWID ID int AWIDdemodFSK(uint8_t *dest, size_t *size) diff --git a/common/lfdemod.h b/common/lfdemod.h index ab81c34c..81157d19 100644 --- a/common/lfdemod.h +++ b/common/lfdemod.h @@ -19,6 +19,7 @@ int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr, uint8_t amp, uint8_t askType); int BiphaseRawDecode(uint8_t * BitStream, size_t *size, int offset, int invert); uint32_t bytebits_to_byte(uint8_t* src, size_t numbits); +uint32_t bytebits_to_byteLSBF(uint8_t* src, size_t numbits); uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj); int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr); uint8_t DetectCleanAskWave(uint8_t dest[], size_t size, uint8_t high, uint8_t low); From fd1d30cb76a384adc8176df1f0f35658c091d96c Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 3 Jun 2015 18:28:56 -0400 Subject: [PATCH 101/132] addition animal tags demod info --- client/cmddata.c | 35 ++++++++++++++--------------------- common/lfdemod.c | 13 +++++++------ common/lfdemod.h | 1 + 3 files changed, 22 insertions(+), 27 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 089e7d5f..fd08b6dd 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1493,11 +1493,14 @@ int CmdIso11784demodBI(const char *Cmd){ setDemodBuf(BitStream, 128, preambleIndex); //printDemodBuff(); - size = removeParity(BitStream, preambleIndex + 11, 9, 1, 117); - if ( size <= 0 ) { + size = removeParity(BitStream, preambleIndex + 11, 9, 2, 117); + if ( size <= 103 ) { if (g_debugMode) PrintAndLog("Error removeParity:: %d", size); return 0; } + //char *bin = sprint_bin_break(BitStream,size,16); + //PrintAndLog("DEBUG BinStream:\n%s",bin); + PrintAndLog("startmarker %d; Size %d", preambleIndex, size); //return 1; @@ -1511,25 +1514,14 @@ int CmdIso11784demodBI(const char *Cmd){ uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16); uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24); - PrintAndLog("NationalCode: %x%08x",NationalCodeB,NationalCodeA); - //add rest of print code here... - /* - uint8_t ByteStream[16] = {0x00}; - uint8_t bitCnt = 0; - uint8_t ByteCnt = 0; - size_t startIdx = preambleIndex + 11; //start after preamble - for (size_t idx = 0; idx < size-11; idx++){ - - //lsb first - ByteStream[ByteCnt] = ByteStream[ByteCnt] | (BitStream[startIdx+idx] << bitCnt); - bitCnt++; - if (bitCnt % 8 == 0){ - if (g_debugMode) PrintAndLog("byte %d: %02x", ByteCnt, ByteStream[ByteCnt]); - bitCnt = 0; - ByteCnt++; - } - } - */ + PrintAndLog("NationalCode: %X%08X",NationalCodeB,NationalCodeA); + PrintAndLog("CountryCode: %d",countryCode); + PrintAndLog("dataBlockBit: %d",dataBlockBit); + PrintAndLog("reservedCode: %X",reservedCode); + PrintAndLog("animalBit: %d", animalBit); + PrintAndLog("CRC: %02X", crc16); + PrintAndLog("Extended: %x", extended); + return 1; } @@ -2289,6 +2281,7 @@ static command_t CommandTable[] = {"hexsamples", CmdHexsamples, 0, " [] -- Dump big buffer as hex bytes"}, {"hide", CmdHide, 1, "Hide graph window"}, {"hpf", CmdHpf, 1, "Remove DC offset from trace"}, + {"iso11784demod", CmdIso11784demodBI, 1, "Demodulate a ISO11784/85 Biphase tag from GraphBuffer"}, {"load", CmdLoad, 1, " -- Load trace (to graph window"}, {"ltrim", CmdLtrim, 1, " -- Trim samples from left of trace"}, {"rtrim", CmdRtrim, 1, " -- Trim samples from right of trace"}, diff --git a/common/lfdemod.c b/common/lfdemod.c index c0f2bb71..aa37bb9e 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -526,7 +526,7 @@ int ParadoxdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, ui return (int)startIdx; } -uint32_t bytebits_to_byte(uint8_t* src, size_t numbits) +uint32_t bytebits_to_byte(uint8_t *src, size_t numbits) { uint32_t num = 0; for(int i = 0 ; i < numbits ; i++) @@ -538,13 +538,12 @@ uint32_t bytebits_to_byte(uint8_t* src, size_t numbits) } //least significant bit first -uint32_t bytebits_to_byteLSBF(uint8_t* src, size_t numbits) +uint32_t bytebits_to_byteLSBF(uint8_t *src, size_t numbits) { uint32_t num = 0; for(int i = 0 ; i < numbits ; i++) { - num = (num << 1) | (*src); - src++; + num = (num << 1) | *(src + (numbits-(i+1))); } return num; } @@ -581,7 +580,7 @@ int IOdemodFSK(uint8_t *dest, size_t size) // 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), and binary Length (length to run) +// Parity Type (1 for odd; 0 for even; 2 for just drop it), 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; @@ -593,7 +592,9 @@ size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t p } j--; // if parity fails then return 0 - if (parityTest(parityWd, pLen, pType) == 0) return -1; + if (pType != 2) { + if (parityTest(parityWd, pLen, pType) == 0) return -1; + } bitCnt+=(pLen-1); parityWd = 0; } diff --git a/common/lfdemod.h b/common/lfdemod.h index 81157d19..e21bfe11 100644 --- a/common/lfdemod.h +++ b/common/lfdemod.h @@ -41,6 +41,7 @@ void psk1TOpsk2(uint8_t *BitStream, size_t size); size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen); //tag specific +int ISO11784demodBI(uint8_t *dest, size_t *size); int AWIDdemodFSK(uint8_t *dest, size_t *size); int gProxII_Demod(uint8_t BitStream[], size_t *size); int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo); From b2c330b36778471de73683ca779d4850556db895 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Wed, 3 Jun 2015 23:59:22 -0400 Subject: [PATCH 102/132] bug fix - biphase invert + fdx-b adjustments --- client/cmddata.c | 44 +++++++++++++++++++++++--------------------- common/lfdemod.c | 2 +- common/lfdemod.h | 2 +- 3 files changed, 25 insertions(+), 23 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index fd08b6dd..dad0a711 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -498,7 +498,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) { //ask raw demod GraphBuffer first int offset=0, clk=0, invert=0, maxErr=0, ans=0; - ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); + ans = sscanf(Cmd, "%i %i 0 %i", &offset, &clk, &maxErr); if (ans>0) ans = ASKDemod(Cmd+2, FALSE, FALSE, 0); else @@ -512,7 +512,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) size_t size = DemodBufferLen; uint8_t BitStream[MAX_DEMOD_BUF_LEN]; memcpy(BitStream, DemodBuffer, DemodBufferLen); - int errCnt = BiphaseRawDecode(BitStream, &size, offset, 0); + int errCnt = BiphaseRawDecode(BitStream, &size, offset, invert); if (errCnt < 0){ if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode: %d", errCnt); return 0; @@ -1457,13 +1457,13 @@ int CmdFSKdemodPyramid(const char *Cmd) return 1; } -// ISO11784/85 demod (aka animal tag) BIPHASE, inverted, rf/32, with preamble of 00000000001 (128bits) +// FDX-B ISO11784/85 demod (aka animal tag) BIPHASE, inverted, rf/32, with preamble of 00000000001 (128bits) // 8 databits + 1 parity (1) // CIITT 16 chksum // NATIONAL CODE, ICAR database -// COUNTRY CODE (ISO3166) +// COUNTRY CODE (ISO3166) or http://cms.abvma.ca/uploads/ManufacturersISOsandCountryCodes.pdf // FLAG (animal/non-animal) -int CmdIso11784demodBI(const char *Cmd){ +int CmdFDXBdemodBI(const char *Cmd){ int invert = 1; int clk = 32; @@ -1484,9 +1484,9 @@ int CmdIso11784demodBI(const char *Cmd){ return 0; } - int preambleIndex = ISO11784demodBI(BitStream, &size); + int preambleIndex = FDXBdemodBI(BitStream, &size); if (preambleIndex < 0){ - if (g_debugMode) PrintAndLog("Error ISO11784Demod , no startmarker found :: %d",preambleIndex); + if (g_debugMode) PrintAndLog("Error FDXBDemod , no startmarker found :: %d",preambleIndex); return 0; } @@ -1498,15 +1498,16 @@ int CmdIso11784demodBI(const char *Cmd){ if (g_debugMode) PrintAndLog("Error removeParity:: %d", size); return 0; } - //char *bin = sprint_bin_break(BitStream,size,16); - //PrintAndLog("DEBUG BinStream:\n%s",bin); - - PrintAndLog("startmarker %d; Size %d", preambleIndex, size); + if (g_debugMode) { + char *bin = sprint_bin_break(BitStream,size,16); + PrintAndLog("DEBUG BinStream:\n%s",bin); + } + PrintAndLog("\nFDX-B / ISO 11784/5 Animal Tag ID Found:"); + if (g_debugMode) PrintAndLog("startmarker %d; Size %d", preambleIndex, size); //return 1; //got a good demod - uint32_t NationalCodeA = bytebits_to_byteLSBF(BitStream,32); - uint32_t NationalCodeB = bytebits_to_byteLSBF(BitStream+32,6); + uint64_t NationalCode = ((uint64_t)(bytebits_to_byteLSBF(BitStream+32,6)) << 32) | bytebits_to_byteLSBF(BitStream,32); uint32_t countryCode = bytebits_to_byteLSBF(BitStream+38,10); uint8_t dataBlockBit = BitStream[48]; uint32_t reservedCode = bytebits_to_byteLSBF(BitStream+49,14); @@ -1514,13 +1515,14 @@ int CmdIso11784demodBI(const char *Cmd){ uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16); uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24); - PrintAndLog("NationalCode: %X%08X",NationalCodeB,NationalCodeA); - PrintAndLog("CountryCode: %d",countryCode); - PrintAndLog("dataBlockBit: %d",dataBlockBit); - PrintAndLog("reservedCode: %X",reservedCode); - PrintAndLog("animalBit: %d", animalBit); - PrintAndLog("CRC: %02X", crc16); - PrintAndLog("Extended: %x", extended); + PrintAndLog("Animal ID: %u-%012llu", countryCode, NationalCode); + PrintAndLog("National Code: %012llu", NationalCode); + PrintAndLog("CountryCode: %u", countryCode); + PrintAndLog("Extended Data: %s", dataBlockBit ? "True" : "False"); + PrintAndLog("reserved Code: %u", reservedCode); + PrintAndLog("Animal Tag: %s", animalBit ? "True" : "False"); + PrintAndLog("CRC: 0x%02X", crc16); + PrintAndLog("Extended: 0x%X", extended); return 1; } @@ -2270,6 +2272,7 @@ static command_t CommandTable[] = {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"}, {"dec", CmdDec, 1, "Decimate samples"}, {"detectclock", CmdDetectClockRate, 1, "[modulation] Detect clock rate of wave in GraphBuffer (options: 'a','f','n','p' for ask, fsk, nrz, psk respectively)"}, + {"fdxbdemod", CmdFDXBdemodBI , 1, "Demodulate a FDX-B ISO11784/85 Biphase tag from GraphBuffer"}, {"fskawiddemod", CmdFSKdemodAWID, 1, "Demodulate an AWID FSK tag from GraphBuffer"}, //{"fskfcdetect", CmdFSKfcDetect, 1, "Try to detect the Field Clock of an FSK wave"}, {"fskhiddemod", CmdFSKdemodHID, 1, "Demodulate a HID FSK tag from GraphBuffer"}, @@ -2281,7 +2284,6 @@ static command_t CommandTable[] = {"hexsamples", CmdHexsamples, 0, " [] -- Dump big buffer as hex bytes"}, {"hide", CmdHide, 1, "Hide graph window"}, {"hpf", CmdHpf, 1, "Remove DC offset from trace"}, - {"iso11784demod", CmdIso11784demodBI, 1, "Demodulate a ISO11784/85 Biphase tag from GraphBuffer"}, {"load", CmdLoad, 1, " -- Load trace (to graph window"}, {"ltrim", CmdLtrim, 1, " -- Trim samples from left of trace"}, {"rtrim", CmdRtrim, 1, " -- Trim samples from right of trace"}, diff --git a/common/lfdemod.c b/common/lfdemod.c index aa37bb9e..f13a567c 100644 --- a/common/lfdemod.c +++ b/common/lfdemod.c @@ -605,7 +605,7 @@ size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t p // Ask/Biphase Demod then try to locate an ISO 11784/85 ID // BitStream must contain previously askrawdemod and biphasedemoded data -int ISO11784demodBI(uint8_t *dest, size_t *size) +int FDXBdemodBI(uint8_t *dest, size_t *size) { //make sure buffer has enough data if (*size < 128) return -1; diff --git a/common/lfdemod.h b/common/lfdemod.h index e21bfe11..d16aab9e 100644 --- a/common/lfdemod.h +++ b/common/lfdemod.h @@ -41,7 +41,7 @@ void psk1TOpsk2(uint8_t *BitStream, size_t size); size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen); //tag specific -int ISO11784demodBI(uint8_t *dest, size_t *size); +int FDXBdemodBI(uint8_t *dest, size_t *size); int AWIDdemodFSK(uint8_t *dest, size_t *size); int gProxII_Demod(uint8_t BitStream[], size_t *size); int HIDdemodFSK(uint8_t *dest, size_t *size, uint32_t *hi2, uint32_t *hi, uint32_t *lo); From ecfcb34cc5615d8546534ccdcba5cf9c091e98a3 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 4 Jun 2015 00:04:49 -0400 Subject: [PATCH 103/132] add fdx-b to lf search --- client/cmdlf.c | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/client/cmdlf.c b/client/cmdlf.c index dfbbe992..edf02932 100644 --- a/client/cmdlf.c +++ b/client/cmdlf.c @@ -1072,6 +1072,12 @@ int CmdLFfind(const char *Cmd) return 1; } + ans=CmdFDXBdemodBI(""); + if (ans>0) { + PrintAndLog("\nValid FDX-B ID Found!"); + return 1; + } + ans=EM4x50Read("", false); if (ans>0) { PrintAndLog("\nValid EM4x50 ID Found!"); From cf4d3e21b01bcaa56addc04c0d5a5db4571158e7 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 4 Jun 2015 00:05:37 -0400 Subject: [PATCH 104/132] add fdx-b to cmddata.h --- client/cmddata.h | 1 + 1 file changed, 1 insertion(+) diff --git a/client/cmddata.h b/client/cmddata.h index c6230736..fcc51a6b 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -27,6 +27,7 @@ int CmdBitsamples(const char *Cmd); int CmdBuffClear(const char *Cmd); int CmdDec(const char *Cmd); int CmdDetectClockRate(const char *Cmd); +int CmdFDXBdemodBI(const char *Cmd); int CmdFSKdemodAWID(const char *Cmd); int CmdFSKdemodHID(const char *Cmd); int CmdFSKdemodIO(const char *Cmd); From 6eaa8da9dcc7543194435f706c72272783331df7 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 4 Jun 2015 12:53:19 -0400 Subject: [PATCH 105/132] Add CCITT Kermit CRC check for FDX-B demod --- client/cmddata.c | 16 ++++++++++--- common/crc16.c | 60 +++++++++++++++++++++++++++++------------------- common/crc16.h | 1 + 3 files changed, 51 insertions(+), 26 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index dad0a711..00caefd9 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -23,6 +23,7 @@ #include "lfdemod.h" #include "usb_cmd.h" #include "crc.h" +#include "crc16.h" uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; uint8_t g_debugMode; @@ -1501,9 +1502,10 @@ int CmdFDXBdemodBI(const char *Cmd){ if (g_debugMode) { char *bin = sprint_bin_break(BitStream,size,16); PrintAndLog("DEBUG BinStream:\n%s",bin); + PrintAndLog("0x%s", sprint_hex(BitStream,16)); } PrintAndLog("\nFDX-B / ISO 11784/5 Animal Tag ID Found:"); - if (g_debugMode) PrintAndLog("startmarker %d; Size %d", preambleIndex, size); + if (g_debugMode) PrintAndLog("Start marker %d; Size %d", preambleIndex, size); //return 1; //got a good demod @@ -1515,14 +1517,22 @@ int CmdFDXBdemodBI(const char *Cmd){ uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16); uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24); + uint64_t rawid = ((uint64_t)bytebits_to_byteLSBF(BitStream,32)<<32) | bytebits_to_byteLSBF(BitStream+32,32); + uint8_t raw[8]; + num_to_bytes(rawid, 8, raw); + uint8_t *ID = SwapEndian64(raw, 8, 4); + + if (g_debugMode) PrintAndLog("Raw ID Hex: %s", sprint_hex(ID,8)); + + uint16_t calcCrc = crc16_ccitt_kermit(ID, 8); PrintAndLog("Animal ID: %u-%012llu", countryCode, NationalCode); PrintAndLog("National Code: %012llu", NationalCode); PrintAndLog("CountryCode: %u", countryCode); PrintAndLog("Extended Data: %s", dataBlockBit ? "True" : "False"); PrintAndLog("reserved Code: %u", reservedCode); PrintAndLog("Animal Tag: %s", animalBit ? "True" : "False"); - PrintAndLog("CRC: 0x%02X", crc16); - PrintAndLog("Extended: 0x%X", extended); + PrintAndLog("CRC: 0x%04X - [%04X] - %s", crc16, calcCrc, (calcCrc == crc16) ? "Passed" : "Failed"); + PrintAndLog("Extended: 0x%X\n", extended); return 1; } diff --git a/common/crc16.c b/common/crc16.c index 973cd103..d48df3b2 100644 --- a/common/crc16.c +++ b/common/crc16.c @@ -11,35 +11,49 @@ unsigned short update_crc16( unsigned short crc, unsigned char c ) { - unsigned short i, v, tcrc = 0; + unsigned short i, v, tcrc = 0; - v = (crc ^ c) & 0xff; - for (i = 0; i < 8; i++) { - tcrc = ( (tcrc ^ v) & 1 ) ? ( tcrc >> 1 ) ^ 0x8408 : tcrc >> 1; - v >>= 1; - } + v = (crc ^ c) & 0xff; + for (i = 0; i < 8; i++) { + tcrc = ( (tcrc ^ v) & 1 ) ? ( tcrc >> 1 ) ^ 0x8408 : tcrc >> 1; + v >>= 1; + } - return ((crc >> 8) ^ tcrc)&0xffff; + return ((crc >> 8) ^ tcrc)&0xffff; } uint16_t crc16(uint8_t const *message, int length, uint16_t remainder, uint16_t polynomial) { - - if (length == 0) - return (~remainder); - - for (int byte = 0; byte < length; ++byte) { - remainder ^= (message[byte] << 8); - for (uint8_t bit = 8; bit > 0; --bit) { - if (remainder & 0x8000) { - remainder = (remainder << 1) ^ polynomial; - } else { - remainder = (remainder << 1); - } - } - } - return remainder; + + if (length == 0) return (~remainder); + + for (int byte = 0; byte < length; ++byte) { + remainder ^= (message[byte] << 8); + for (uint8_t bit = 8; bit > 0; --bit) { + if (remainder & 0x8000) { + remainder = (remainder << 1) ^ polynomial; + } else { + remainder = (remainder << 1); + } + } + } + return remainder; } uint16_t crc16_ccitt(uint8_t const *message, int length) { - return crc16(message, length, 0xffff, 0x1021); + return crc16(message, length, 0xffff, 0x1021); +} + +uint16_t crc16_ccitt_kermit(uint8_t const *message, int length) { + if (length == 0) return 0; + uint32_t crc = 0, q = 0; + uint8_t c; + + for (int i = 0; i < length; i++){ + c = message[i]; + q = (crc ^ c ) & 0xF; + crc = (crc >> 4) ^ (q * 0x1081); + q = (crc ^ (c >> 4)) & 0xF; + crc = (crc >> 4) ^ (q * 0x1081); + } + return crc; } diff --git a/common/crc16.h b/common/crc16.h index d16d83b5..3656ce27 100644 --- a/common/crc16.h +++ b/common/crc16.h @@ -12,4 +12,5 @@ unsigned short update_crc16(unsigned short crc, unsigned char c); uint16_t crc16(uint8_t const *message, int length, uint16_t remainder, uint16_t polynomial); uint16_t crc16_ccitt(uint8_t const *message, int length); +uint16_t crc16_ccitt_kermit(uint8_t const *message, int length); #endif From c2c7f6c271b33c6d95aa47f339fe6d47c433d8d5 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 4 Jun 2015 13:10:33 -0400 Subject: [PATCH 106/132] fdx-b clean up --- client/cmddata.c | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 00caefd9..e85b3a6c 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1475,7 +1475,7 @@ int CmdFDXBdemodBI(const char *Cmd){ errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0); if ( errCnt < 0 || errCnt > maxErr ) { - if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: 32", errCnt); + if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: %d", errCnt, clk); return 0; } @@ -1492,8 +1492,8 @@ int CmdFDXBdemodBI(const char *Cmd){ } setDemodBuf(BitStream, 128, preambleIndex); - //printDemodBuff(); + // remove but don't verify parity. (pType = 2) size = removeParity(BitStream, preambleIndex + 11, 9, 2, 117); if ( size <= 103 ) { if (g_debugMode) PrintAndLog("Error removeParity:: %d", size); @@ -1502,12 +1502,10 @@ int CmdFDXBdemodBI(const char *Cmd){ if (g_debugMode) { char *bin = sprint_bin_break(BitStream,size,16); PrintAndLog("DEBUG BinStream:\n%s",bin); - PrintAndLog("0x%s", sprint_hex(BitStream,16)); } PrintAndLog("\nFDX-B / ISO 11784/5 Animal Tag ID Found:"); if (g_debugMode) PrintAndLog("Start marker %d; Size %d", preambleIndex, size); - //return 1; //got a good demod uint64_t NationalCode = ((uint64_t)(bytebits_to_byteLSBF(BitStream+32,6)) << 32) | bytebits_to_byteLSBF(BitStream,32); uint32_t countryCode = bytebits_to_byteLSBF(BitStream+38,10); @@ -1520,14 +1518,14 @@ int CmdFDXBdemodBI(const char *Cmd){ uint64_t rawid = ((uint64_t)bytebits_to_byteLSBF(BitStream,32)<<32) | bytebits_to_byteLSBF(BitStream+32,32); uint8_t raw[8]; num_to_bytes(rawid, 8, raw); - uint8_t *ID = SwapEndian64(raw, 8, 4); + uint8_t *raw_ptr = SwapEndian64(raw, 8, 4); - if (g_debugMode) PrintAndLog("Raw ID Hex: %s", sprint_hex(ID,8)); + if (g_debugMode) PrintAndLog("Raw ID Hex: %s", sprint_hex(raw_ptr,8)); - uint16_t calcCrc = crc16_ccitt_kermit(ID, 8); - PrintAndLog("Animal ID: %u-%012llu", countryCode, NationalCode); + uint16_t calcCrc = crc16_ccitt_kermit(raw_ptr, 8); + PrintAndLog("Animal ID: %04u-%012llu", countryCode, NationalCode); PrintAndLog("National Code: %012llu", NationalCode); - PrintAndLog("CountryCode: %u", countryCode); + PrintAndLog("CountryCode: %04u", countryCode); PrintAndLog("Extended Data: %s", dataBlockBit ? "True" : "False"); PrintAndLog("reserved Code: %u", reservedCode); PrintAndLog("Animal Tag: %s", animalBit ? "True" : "False"); From 07b5a3c3ba774ec93007827cf1233b4edb699bad Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Fri, 5 Jun 2015 22:39:56 -0400 Subject: [PATCH 107/132] Modified kermit crc to use existing crc calc code --- client/cmddata.c | 7 +++---- common/crc16.c | 28 +++++++++++++++------------- common/crc16.h | 1 + 3 files changed, 19 insertions(+), 17 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index e85b3a6c..cf105f88 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1515,14 +1515,13 @@ int CmdFDXBdemodBI(const char *Cmd){ uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16); uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24); - uint64_t rawid = ((uint64_t)bytebits_to_byteLSBF(BitStream,32)<<32) | bytebits_to_byteLSBF(BitStream+32,32); + uint64_t rawid = ((uint64_t)bytebits_to_byte(BitStream,32)<<32) | bytebits_to_byte(BitStream+32,32); uint8_t raw[8]; num_to_bytes(rawid, 8, raw); - uint8_t *raw_ptr = SwapEndian64(raw, 8, 4); - if (g_debugMode) PrintAndLog("Raw ID Hex: %s", sprint_hex(raw_ptr,8)); + if (g_debugMode) PrintAndLog("Raw ID Hex: %s", sprint_hex(raw,8)); - uint16_t calcCrc = crc16_ccitt_kermit(raw_ptr, 8); + uint16_t calcCrc = crc16_ccitt_kermit(raw, 8); PrintAndLog("Animal ID: %04u-%012llu", countryCode, NationalCode); PrintAndLog("National Code: %012llu", NationalCode); PrintAndLog("CountryCode: %04u", countryCode); diff --git a/common/crc16.c b/common/crc16.c index d48df3b2..a37f1d7e 100644 --- a/common/crc16.c +++ b/common/crc16.c @@ -8,7 +8,6 @@ #include "crc16.h" - unsigned short update_crc16( unsigned short crc, unsigned char c ) { unsigned short i, v, tcrc = 0; @@ -44,16 +43,19 @@ uint16_t crc16_ccitt(uint8_t const *message, int length) { } uint16_t crc16_ccitt_kermit(uint8_t const *message, int length) { - if (length == 0) return 0; - uint32_t crc = 0, q = 0; - uint8_t c; - - for (int i = 0; i < length; i++){ - c = message[i]; - q = (crc ^ c ) & 0xF; - crc = (crc >> 4) ^ (q * 0x1081); - q = (crc ^ (c >> 4)) & 0xF; - crc = (crc >> 4) ^ (q * 0x1081); - } - return crc; + return bit_reverse_uint16(crc16(message, length, 0x0000, 0x1021)); +} + +uint16_t bit_reverse_uint16 (uint16_t value) { + const uint16_t mask0 = 0x5555; + const uint16_t mask1 = 0x3333; + const uint16_t mask2 = 0x0F0F; + const uint16_t mask3 = 0x00FF; + + value = (((~mask0) & value) >> 1) | ((mask0 & value) << 1); + value = (((~mask1) & value) >> 2) | ((mask1 & value) << 2); + value = (((~mask2) & value) >> 4) | ((mask2 & value) << 4); + value = (((~mask3) & value) >> 8) | ((mask3 & value) << 8); + + return value; } diff --git a/common/crc16.h b/common/crc16.h index 3656ce27..8eb4befb 100644 --- a/common/crc16.h +++ b/common/crc16.h @@ -13,4 +13,5 @@ unsigned short update_crc16(unsigned short crc, unsigned char c); uint16_t crc16(uint8_t const *message, int length, uint16_t remainder, uint16_t polynomial); uint16_t crc16_ccitt(uint8_t const *message, int length); uint16_t crc16_ccitt_kermit(uint8_t const *message, int length); +uint16_t bit_reverse_uint16 (uint16_t value); #endif From 8e2e6c8eb0b762bba6e7cad2d257a219a51390ae Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 7 Jun 2015 00:42:57 -0400 Subject: [PATCH 108/132] add clock to ask rawdemod outputs fix biphase invert bug (correctly) --- client/cmddata.c | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index cf105f88..976dc084 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -41,7 +41,7 @@ void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx) size = MAX_DEMOD_BUF_LEN; size_t i = 0; -for (; i < size; i++){ + for (; i < size; i++){ DemodBuffer[i]=buff[startIdx++]; } DemodBufferLen=size; @@ -344,8 +344,8 @@ int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) setDemodBuf(BitStream,BitLen,0); if (verbose || g_debugMode){ if (errCnt>0) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); - if (askType) PrintAndLog("ASK/Manchester decoded bitstream:"); - else PrintAndLog("ASK/Raw decoded bitstream:"); + if (askType) PrintAndLog("ASK/Manchester - Clock: %d - Decoded bitstream:",clk); + else PrintAndLog("ASK/Raw - Clock: %d - Decoded bitstream:",clk); // Now output the bitstream to the scrollback by line of 16 bits printDemodBuff(); @@ -499,21 +499,19 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) { //ask raw demod GraphBuffer first int offset=0, clk=0, invert=0, maxErr=0, ans=0; - ans = sscanf(Cmd, "%i %i 0 %i", &offset, &clk, &maxErr); - if (ans>0) - ans = ASKDemod(Cmd+2, FALSE, FALSE, 0); - else - ans = ASKDemod(Cmd, FALSE, FALSE, 0); - if (!ans) { - if (g_debugMode || verbose) PrintAndLog("Error AskDemod: %d", ans); - return 0; - } + ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); - //attempt to Biphase decode DemodBuffer - size_t size = DemodBufferLen; - uint8_t BitStream[MAX_DEMOD_BUF_LEN]; - memcpy(BitStream, DemodBuffer, DemodBufferLen); - int errCnt = BiphaseRawDecode(BitStream, &size, offset, invert); + uint8_t BitStream[MAX_DEMOD_BUF_LEN]; + size_t size = getFromGraphBuf(BitStream); + + int errCnt = askdemod(BitStream, &size, &clk, 0, maxErr, 0, 0); + if ( errCnt < 0 || errCnt > maxErr ) { + if (g_debugMode) PrintAndLog("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) PrintAndLog("Error BiphaseRawDecode: %d", errCnt); return 0; @@ -525,7 +523,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) //success set DemodBuffer and return setDemodBuf(BitStream, size, 0); if (g_debugMode || verbose){ - PrintAndLog("Biphase Decoded using offset: %d - # errors:%d - data:",offset,errCnt); + PrintAndLog("Biphase Decoded using offset: %d - clock: %d - # errors:%d - data:",offset,clk,errCnt); printDemodBuff(); } return 1; From 4a3f1a379314368330fab879a616cf7b9e5e25c4 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 11 Jun 2015 23:52:40 -0400 Subject: [PATCH 109/132] revert t55xx start gap and write timing changes also noted specs in comments --- armsrc/lfops.c | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/armsrc/lfops.c b/armsrc/lfops.c index c3fa8a0e..7e53d4a5 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -1024,10 +1024,10 @@ void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol) * To compensate antenna falling times shorten the write times * and enlarge the gap ones. */ -#define START_GAP 50*8 // 10 - 50fc 250 -#define WRITE_GAP 20*8 // - 30fc 160 -#define WRITE_0 24*8 // 16 - 63fc 54fc 144 -#define WRITE_1 54*8 // 48 - 63fc 54fc 432 for T55x7; 448 for E5550 //400 +#define START_GAP 31*8 // was 250 // SPEC: 1*8 to 50*8 - typ 15*8 (or 15fc) +#define WRITE_GAP 20*8 // was 160 // SPEC: 1*8 to 20*8 - typ 10*8 (or 10fc) +#define WRITE_0 18*8 // was 144 // SPEC: 16*8 to 32*8 - typ 24*8 (or 24fc) +#define WRITE_1 50*8 // was 400 // SPEC: 48*8 to 64*8 - typ 56*8 (or 56fc) 432 for T55x7; 448 for E5550 #define T55xx_SAMPLES_SIZE 12000 // 32 x 32 x 10 (32 bit times numofblock (7), times clock skip..) From c7d672129049e1dd274a8c24174c6035bcdb5964 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 14 Jun 2015 10:54:55 -0400 Subject: [PATCH 110/132] bug fix. askdemod edits invert pointer, cannot be 0 --- client/cmddata.c | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index 976dc084..77959cf3 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -498,13 +498,12 @@ int CmdBiphaseDecodeRaw(const char *Cmd) int ASKbiphaseDemod(const char *Cmd, bool verbose) { //ask raw demod GraphBuffer first - int offset=0, clk=0, invert=0, maxErr=0, ans=0; - ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); + 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); - - int errCnt = askdemod(BitStream, &size, &clk, 0, maxErr, 0, 0); + int errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0); if ( errCnt < 0 || errCnt > maxErr ) { if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: %d", errCnt, clk); return 0; From fd227f4e7d7967ce06a2ef90828aa13159a80d98 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sun, 14 Jun 2015 11:11:00 -0400 Subject: [PATCH 111/132] add comment --- client/cmddata.c | 1 + 1 file changed, 1 insertion(+) diff --git a/client/cmddata.c b/client/cmddata.c index 77959cf3..309044e1 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -503,6 +503,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) uint8_t BitStream[MAX_DEMOD_BUF_LEN]; size_t size = getFromGraphBuf(BitStream); + //invert here inverts the ask raw demoded bits which has no effect on the demod, but we need the pointer int errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0); if ( errCnt < 0 || errCnt > maxErr ) { if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: %d", errCnt, clk); From 6ac4cb270a202d6f723b82753d57ee48c9a6980e Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Mon, 15 Jun 2015 00:44:57 -0400 Subject: [PATCH 112/132] minor fixes see @icemant1001 - https://github.com/iceman1001/proxmark3/commit/0ad1a1d492ab62eb42c1eb7b4ce6fff05d90e0a3 for more details --- client/cmddata.c | 2 +- client/cmdlfem4x.c | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/client/cmddata.c b/client/cmddata.c index 309044e1..aa1170fc 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -392,7 +392,7 @@ int Cmdmandecoderaw(const char *Cmd) int errCnt=0; size_t size=0; int invert=0; - size_t maxErr = 20; + int maxErr = 20; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 5 || cmdp == 'h' || cmdp == 'H') { PrintAndLog("Usage: data manrawdecode [invert] [maxErr]"); diff --git a/client/cmdlfem4x.c b/client/cmdlfem4x.c index c492a64d..eddeec56 100644 --- a/client/cmdlfem4x.c +++ b/client/cmdlfem4x.c @@ -20,6 +20,9 @@ #include "cmdlf.h" #include "cmdlfem4x.h" #include "lfdemod.h" + +#define llx PRIx64 + char *global_em410xId; static int CmdHelp(const char *Cmd); From 51d4f6f1146b083f12381419bbfb6addd550e6a3 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Fri, 12 Jun 2015 07:43:00 +0200 Subject: [PATCH 113/132] fixing iso14443b (issue #103): - fix: IQ demodulator (FPGA) - fix: approximately align reader signal delay to tag response delay (FPGA) - fix: remove deprecated RSSI calculation to improve decoder speed (iso14443b.c) - fix: better approximation of signal amplitude to avoid false carrier detection (iso14443b.c) - fix: remove initial power off in iso14443b raw command (iso14443b.c) - add: enable tracing for iso14443b raw command (iso14443b.c) - fix: client crashed when checking CRC for incomplete responses (iso14433b.c) - speeding up snoop to avoid circular buffer overflow - added some comments for better documentation - rename functions (iso14443 -> iso14443b) - remove unused code in hi_read_rx_xcorr.v --- armsrc/appmain.c | 12 +- armsrc/apps.h | 8 +- armsrc/iso14443b.c | 476 ++++++++++++++++++++-------------------- client/cmdhf14b.c | 14 +- fpga/fpga_hf.bit | Bin 42175 -> 42175 bytes fpga/fpga_hf.v | 11 +- fpga/hi_read_rx_xcorr.v | 78 ++----- 7 files changed, 279 insertions(+), 320 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index c226c726..9bfa5ea7 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -263,7 +263,7 @@ void SimulateTagHfListen(void) // We're using this mode just so that I can test it out; the simulated // tag mode would work just as well and be simpler. FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_SNOOP); // We need to listen to the high-frequency, peak-detected path. SetAdcMuxFor(GPIO_MUXSEL_HIPKD); @@ -783,19 +783,19 @@ void UsbPacketReceived(uint8_t *packet, int len) #ifdef WITH_ISO14443b case CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443: - AcquireRawAdcSamplesIso14443(c->arg[0]); + AcquireRawAdcSamplesIso14443b(c->arg[0]); break; case CMD_READ_SRI512_TAG: - ReadSTMemoryIso14443(0x0F); + ReadSTMemoryIso14443b(0x0F); break; case CMD_READ_SRIX4K_TAG: - ReadSTMemoryIso14443(0x7F); + ReadSTMemoryIso14443b(0x7F); break; case CMD_SNOOP_ISO_14443: - SnoopIso14443(); + SnoopIso14443b(); break; case CMD_SIMULATE_TAG_ISO_14443: - SimulateIso14443Tag(); + SimulateIso14443bTag(); break; case CMD_ISO_14443B_COMMAND: SendRawCommand14443B(c->arg[0],c->arg[1],c->arg[2],c->d.asBytes); diff --git a/armsrc/apps.h b/armsrc/apps.h index 6360b664..542f3a65 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -141,10 +141,10 @@ void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode); void EM4xWriteWord(uint32_t Data, uint8_t Address, uint32_t Pwd, uint8_t PwdMode); /// iso14443.h -void SimulateIso14443Tag(void); -void AcquireRawAdcSamplesIso14443(uint32_t parameter); -void ReadSTMemoryIso14443(uint32_t); -void RAMFUNC SnoopIso14443(void); +void SimulateIso14443bTag(void); +void AcquireRawAdcSamplesIso14443b(uint32_t parameter); +void ReadSTMemoryIso14443b(uint32_t); +void RAMFUNC SnoopIso14443b(void); void SendRawCommand14443B(uint32_t, uint32_t, uint8_t, uint8_t[]); /// iso14443a.h diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 4e40bb68..f598df3c 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -5,9 +5,8 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// Routines to support ISO 14443. This includes both the reader software and -// the `fake tag' modes. At the moment only the Type B modulation is -// supported. +// Routines to support ISO 14443B. This includes both the reader software and +// the `fake tag' modes. //----------------------------------------------------------------------------- #include "proxmark3.h" @@ -17,15 +16,8 @@ #include "iso14443crc.h" -//static void GetSamplesFor14443(int weTx, int n); - -/*#define DEMOD_TRACE_SIZE 4096 -#define READER_TAG_BUFFER_SIZE 2048 -#define TAG_READER_BUFFER_SIZE 2048 -#define DEMOD_DMA_BUFFER_SIZE 1024 -*/ - #define RECEIVE_SAMPLES_TIMEOUT 2000 +#define ISO14443B_DMA_BUFFER_SIZE 512 //============================================================================= // An ISO 14443 Type B tag. We listen for commands from the reader, using @@ -104,14 +96,14 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) ToSendStuffBit(1); } - // Send SOF. + // Send EOF. for(i = 0; i < 10; i++) { ToSendStuffBit(0); ToSendStuffBit(0); ToSendStuffBit(0); ToSendStuffBit(0); } - for(i = 0; i < 10; i++) { + for(i = 0; i < 2; i++) { ToSendStuffBit(1); ToSendStuffBit(1); ToSendStuffBit(1); @@ -120,9 +112,6 @@ static void CodeIso14443bAsTag(const uint8_t *cmd, int len) // Convert from last byte pos to length ToSendMax++; - - // Add a few more for slop - ToSendMax += 2; } //----------------------------------------------------------------------------- @@ -146,6 +135,9 @@ static struct { } Uart; /* Receive & handle a bit coming from the reader. + * + * This function is called 4 times per bit (every 2 subcarrier cycles). + * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us * * LED handling: * LED A -> ON once we have received the SOF and are expecting the rest. @@ -154,7 +146,7 @@ static struct { * Returns: true if we received a EOF * false if we are still waiting for some more */ -static int Handle14443UartBit(int bit) +static int Handle14443bUartBit(int bit) { switch(Uart.state) { case STATE_UNSYNCD: @@ -169,9 +161,9 @@ static int Handle14443UartBit(int bit) case STATE_GOT_FALLING_EDGE_OF_SOF: Uart.posCnt++; - if(Uart.posCnt == 2) { + if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit if(bit) { - if(Uart.bitCnt >= 10) { + if(Uart.bitCnt > 9) { // we've seen enough consecutive // zeros that it's a valid SOF Uart.posCnt = 0; @@ -189,7 +181,7 @@ static int Handle14443UartBit(int bit) Uart.bitCnt++; } if(Uart.posCnt >= 4) Uart.posCnt = 0; - if(Uart.bitCnt > 14) { + if(Uart.bitCnt > 12) { // Give up if we see too many zeros without // a one, too. Uart.state = STATE_ERROR_WAIT; @@ -199,7 +191,7 @@ static int Handle14443UartBit(int bit) case STATE_AWAITING_START_BIT: Uart.posCnt++; if(bit) { - if(Uart.posCnt > 25) { + if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs // stayed high for too long between // characters, error Uart.state = STATE_ERROR_WAIT; @@ -283,12 +275,12 @@ static int Handle14443UartBit(int bit) // Assume that we're called with the SSC (to the FPGA) and ADC path set // correctly. //----------------------------------------------------------------------------- -static int GetIso14443CommandFromReader(uint8_t *received, int *len, int maxLen) +static int GetIso14443bCommandFromReader(uint8_t *received, int *len, int maxLen) { uint8_t mask; int i, bit; - // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen + // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen // only, since we are receiving, not transmitting). // Signal field is off with the appropriate LED LED_D_OFF(); @@ -314,7 +306,7 @@ static int GetIso14443CommandFromReader(uint8_t *received, int *len, int maxLen) mask = 0x80; for(i = 0; i < 8; i++, mask >>= 1) { bit = (b & mask); - if(Handle14443UartBit(bit)) { + if(Handle14443bUartBit(bit)) { *len = Uart.byteCnt; return TRUE; } @@ -327,9 +319,13 @@ static int GetIso14443CommandFromReader(uint8_t *received, int *len, int maxLen) // Main loop of simulated tag: receive commands from reader, decide what // response to send, and send it. //----------------------------------------------------------------------------- -void SimulateIso14443Tag(void) +void SimulateIso14443bTag(void) { + // the only command we understand is REQB, AFI=0, Select All, N=0: static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; + // ... and we 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: static const uint8_t response1[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 @@ -338,10 +334,9 @@ void SimulateIso14443Tag(void) uint8_t *resp; int respLen; - uint8_t *resp1 = BigBuf_get_addr() + 800; - int resp1Len; - - uint8_t *receivedCmd = BigBuf_get_addr(); + // allocate command receive buffer + BigBuf_free(); + uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); int len; int i; @@ -349,10 +344,12 @@ void SimulateIso14443Tag(void) int cmdsRecvd = 0; FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - memset(receivedCmd, 0x44, 400); + // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); - memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax; + uint8_t *resp1 = BigBuf_malloc(ToSendMax); + memcpy(resp1, ToSend, ToSendMax); + uint16_t resp1Len = ToSendMax; // We need to listen to the high-frequency, peak-detected path. SetAdcMuxFor(GPIO_MUXSEL_HIPKD); @@ -363,14 +360,14 @@ void SimulateIso14443Tag(void) for(;;) { uint8_t b1, b2; - if(!GetIso14443CommandFromReader(receivedCmd, &len, 100)) { - Dbprintf("button pressed, received %d commands", cmdsRecvd); - break; - } + if(!GetIso14443bCommandFromReader(receivedCmd, &len, 100)) { + Dbprintf("button pressed, received %d commands", cmdsRecvd); + break; + } // Good, look at the command now. - if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len)==0) { + if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) { resp = resp1; respLen = resp1Len; } else { Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); @@ -385,8 +382,6 @@ void SimulateIso14443Tag(void) break; } - memset(receivedCmd, 0x44, 32); - cmdsRecvd++; if(cmdsRecvd > 0x30) { @@ -444,8 +439,10 @@ static struct { int bitCount; int posCount; int thisBit; +/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented. int metric; int metricN; +*/ uint16_t shiftReg; uint8_t *output; int len; @@ -456,6 +453,9 @@ static struct { /* * Handles reception of a bit from the tag * + * This function is called 2 times per bit (every 4 subcarrier cycles). + * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us + * * LED handling: * LED C -> ON once we have received the SOF and are expecting the rest. * LED C -> OFF once we have received EOF or are unsynced @@ -464,12 +464,12 @@ static struct { * false if we are still waiting for some more * */ -static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) +static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) { int v; - // The soft decision on the bit uses an estimate of just the - // quadrant of the reference angle, not the exact angle. +// The soft decision on the bit uses an estimate of just the +// quadrant of the reference angle, not the exact angle. #define MAKE_SOFT_DECISION() { \ if(Demod.sumI > 0) { \ v = ci; \ @@ -483,47 +483,87 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) } \ } +#define SUBCARRIER_DETECT_THRESHOLD 8 + +// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq) +/* #define CHECK_FOR_SUBCARRIER() { \ + v = ci; \ + if(v < 0) v = -v; \ + if(cq > 0) { \ + v += cq; \ + } else { \ + v -= cq; \ + } \ + } + */ +// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq))) +#define CHECK_FOR_SUBCARRIER() { \ + if(ci < 0) { \ + if(cq < 0) { /* ci < 0, cq < 0 */ \ + if (cq < ci) { \ + v = -cq - (ci >> 1); \ + } else { \ + v = -ci - (cq >> 1); \ + } \ + } else { /* ci < 0, cq >= 0 */ \ + if (cq < -ci) { \ + v = -ci + (cq >> 1); \ + } else { \ + v = cq - (ci >> 1); \ + } \ + } \ + } else { \ + if(cq < 0) { /* ci >= 0, cq < 0 */ \ + if (-cq < ci) { \ + v = ci - (cq >> 1); \ + } else { \ + v = -cq + (ci >> 1); \ + } \ + } else { /* ci >= 0, cq >= 0 */ \ + if (cq < ci) { \ + v = ci + (cq >> 1); \ + } else { \ + v = cq + (ci >> 1); \ + } \ + } \ + } \ + } + switch(Demod.state) { case DEMOD_UNSYNCD: - v = ci; - if(v < 0) v = -v; - if(cq > 0) { - v += cq; - } else { - v -= cq; - } - if(v > 40) { - Demod.posCount = 0; + CHECK_FOR_SUBCARRIER(); + if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected Demod.state = DEMOD_PHASE_REF_TRAINING; - Demod.sumI = 0; - Demod.sumQ = 0; - } + Demod.sumI = ci; + Demod.sumQ = cq; + Demod.posCount = 1; + } break; case DEMOD_PHASE_REF_TRAINING: if(Demod.posCount < 8) { - Demod.sumI += ci; - Demod.sumQ += cq; - } else if(Demod.posCount > 100) { - // error, waited too long - Demod.state = DEMOD_UNSYNCD; - } else { - MAKE_SOFT_DECISION(); - if(v < 0) { - Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF; - Demod.posCount = 0; + 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 { // subcarrier lost + Demod.state = DEMOD_UNSYNCD; } + } else { + Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF; } - Demod.posCount++; break; case DEMOD_AWAITING_FALLING_EDGE_OF_SOF: MAKE_SOFT_DECISION(); - if(v < 0) { + if(v < 0) { // logic '0' detected Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF; - Demod.posCount = 0; + Demod.posCount = 0; // start of SOF sequence } else { - if(Demod.posCount > 100) { + if(Demod.posCount > 200/4) { // maximum length of TR1 = 200 1/fs Demod.state = DEMOD_UNSYNCD; } } @@ -531,37 +571,40 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) break; case DEMOD_GOT_FALLING_EDGE_OF_SOF: + Demod.posCount++; MAKE_SOFT_DECISION(); if(v > 0) { - if(Demod.posCount < 12) { + if(Demod.posCount < 9*2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges Demod.state = DEMOD_UNSYNCD; } else { LED_C_ON(); // Got SOF Demod.state = DEMOD_AWAITING_START_BIT; Demod.posCount = 0; Demod.len = 0; +/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented. Demod.metricN = 0; Demod.metric = 0; +*/ } } else { - if(Demod.posCount > 100) { + if(Demod.posCount > 12*2) { // low phase of SOF too long (> 12 etu) Demod.state = DEMOD_UNSYNCD; LED_C_OFF(); } } - Demod.posCount++; break; case DEMOD_AWAITING_START_BIT: + Demod.posCount++; MAKE_SOFT_DECISION(); if(v > 0) { - if(Demod.posCount > 10) { + if(Demod.posCount > 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs Demod.state = DEMOD_UNSYNCD; LED_C_OFF(); } - } else { + } else { // start bit detected Demod.bitCount = 0; - Demod.posCount = 1; + Demod.posCount = 1; // this was the first half Demod.thisBit = v; Demod.shiftReg = 0; Demod.state = DEMOD_RECEIVING_DATA; @@ -570,28 +613,30 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) 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; - } else { + } else { // second half of bit Demod.thisBit += v; +/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented. if(Demod.thisBit > 0) { Demod.metric += Demod.thisBit; } else { Demod.metric -= Demod.thisBit; } (Demod.metricN)++; +*/ Demod.shiftReg >>= 1; - if(Demod.thisBit > 0) { + if(Demod.thisBit > 0) { // logic '1' Demod.shiftReg |= 0x200; } Demod.bitCount++; if(Demod.bitCount == 10) { uint16_t s = Demod.shiftReg; - if((s & 0x200) && !(s & 0x001)) { + if((s & 0x200) && !(s & 0x001)) { // stop bit == '1', start bit == '0' uint8_t b = (s >> 1); Demod.output[Demod.len] = b; Demod.len++; @@ -600,7 +645,7 @@ static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) Demod.state = DEMOD_UNSYNCD; LED_C_OFF(); if(s == 0x000) { - // This is EOF + // This is EOF (start, stop and all data bits == '0' return TRUE; } } @@ -624,6 +669,7 @@ static void DemodReset() // Clear out the state of the "UART" that receives from the tag. Demod.len = 0; Demod.state = DEMOD_UNSYNCD; + Demod.posCount = 0; memset(Demod.output, 0x00, MAX_FRAME_SIZE); } @@ -653,14 +699,12 @@ static void UartInit(uint8_t *data) /* * Demodulate the samples we received from the tag, also log to tracebuffer - * weTx: set to 'TRUE' if we behave like a reader - * set to 'FALSE' if we behave like a snooper * quiet: set to 'TRUE' to disable debug output */ -static void GetSamplesFor14443Demod(int weTx, int n, int quiet) +static void GetSamplesFor14443bDemod(int n, bool quiet) { int max = 0; - int gotFrame = FALSE; + bool gotFrame = FALSE; int lastRxCounter, ci, cq, samples = 0; // Allocate memory from BigBuf for some buffers @@ -671,57 +715,56 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); // The DMA buffer, used to stream samples from the FPGA - int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse); // Setup and start DMA. - FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); + FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); int8_t *upTo = dmaBuf; - lastRxCounter = DMA_BUFFER_SIZE; + lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; // Signal field is ON with the appropriate LED: - if (weTx) LED_D_ON(); else LED_D_OFF(); + LED_D_ON(); // And put the FPGA in the appropriate mode - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | - (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP)); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); for(;;) { int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; if(behindBy > max) max = behindBy; - while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1)) - > 2) - { + while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (ISO14443B_DMA_BUFFER_SIZE-1)) > 2) { ci = upTo[0]; cq = upTo[1]; upTo += 2; - if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { + if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { upTo = dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; - AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; } lastRxCounter -= 2; if(lastRxCounter <= 0) { - lastRxCounter += DMA_BUFFER_SIZE; + lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; } samples += 2; - if(Handle14443SamplesDemod(ci, cq)) { - gotFrame = 1; + if(Handle14443bSamplesDemod(ci, cq)) { + gotFrame = TRUE; + break; } } - if(samples > n) { + if(samples > n || gotFrame) { break; } } + AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; - if (!quiet) Dbprintf("%x %x %x", max, gotFrame, Demod.len); + + if (!quiet) Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", max, samples, gotFrame, Demod.len, Demod.sumI, Demod.sumQ); //Tracing if (tracing && Demod.len > 0) { uint8_t parity[MAX_PARITY_SIZE]; @@ -731,43 +774,10 @@ static void GetSamplesFor14443Demod(int weTx, int n, int quiet) } -//----------------------------------------------------------------------------- -// Read the tag's response. We just receive a stream of slightly-processed -// samples from the FPGA, which we will later do some signal processing on, -// to get the bits. -//----------------------------------------------------------------------------- -/*static void GetSamplesFor14443(int weTx, int n) -{ - uint8_t *dest = (uint8_t *)BigBuf; - int c; - - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | - (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP)); - - c = 0; - for(;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0x43; - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - int8_t b; - b = (int8_t)AT91C_BASE_SSC->SSC_RHR; - - dest[c++] = (uint8_t)b; - - if(c >= n) { - break; - } - } - } -}*/ - - //----------------------------------------------------------------------------- // Transmit the command (to the tag) that was placed in ToSend[]. //----------------------------------------------------------------------------- -static void TransmitFor14443(void) +static void TransmitFor14443b(void) { int c; @@ -781,8 +791,7 @@ static void TransmitFor14443(void) LED_D_ON(); // Signal we are transmitting with the Green LED LED_B_ON(); - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); for(c = 0; c < 10;) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { @@ -817,7 +826,7 @@ static void TransmitFor14443(void) //----------------------------------------------------------------------------- // Code a layer 2 command (string of octets, including CRC) into ToSend[], -// so that it is ready to transmit to the tag using TransmitFor14443(). +// so that it is ready to transmit to the tag using TransmitFor14443b(). //----------------------------------------------------------------------------- static void CodeIso14443bAsReader(const uint8_t *cmd, int len) { @@ -873,16 +882,16 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) //----------------------------------------------------------------------------- -// Read an ISO 14443 tag. We send it some set of commands, and record the +// Read an ISO 14443B tag. We send it some set of commands, and record the // responses. // The command name is misleading, it actually decodes the reponse in HEX // into the output buffer (read the result using hexsamples, not hisamples) // // obsolete function only for test //----------------------------------------------------------------------------- -void AcquireRawAdcSamplesIso14443(uint32_t parameter) +void AcquireRawAdcSamplesIso14443b(uint32_t parameter) { - uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; + uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // REQB with AFI=0, Request All, N=0 SendRawCommand14443B(sizeof(cmd1),1,1,cmd1); } @@ -894,7 +903,7 @@ void AcquireRawAdcSamplesIso14443(uint32_t parameter) static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) { CodeIso14443bAsReader(cmd, len); - TransmitFor14443(); + TransmitFor14443b(); if (tracing) { uint8_t parity[MAX_PARITY_SIZE]; GetParity(cmd, len, parity); @@ -904,7 +913,7 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) //----------------------------------------------------------------------------- -// Read a SRI512 ISO 14443 tag. +// Read a SRI512 ISO 14443B tag. // // SRI512 tags are just simple memory tags, here we're looking at making a dump // of the contents of the memory. No anticollision algorithm is done, we assume @@ -912,7 +921,7 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) // // I tried to be systematic and check every answer of the tag, every CRC, etc... //----------------------------------------------------------------------------- -void ReadSTMemoryIso14443(uint32_t dwLast) +void ReadSTMemoryIso14443b(uint32_t dwLast) { clear_trace(); set_tracing(TRUE); @@ -933,15 +942,15 @@ void ReadSTMemoryIso14443(uint32_t dwLast) // Signal field is on with the appropriate LED LED_D_ON(); FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); + FPGA_MAJOR_MODE_HF_READER_RX_XCORR); SpinDelay(200); // First command: wake up the tag using the INITIATE command - uint8_t cmd1[] = { 0x06, 0x00, 0x97, 0x5b}; + uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len == 0) { @@ -949,7 +958,7 @@ void ReadSTMemoryIso14443(uint32_t dwLast) return; } else { Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %x %x %x", - Demod.output[0], Demod.output[1],Demod.output[2]); + Demod.output[0], Demod.output[1], Demod.output[2]); } // There is a response, SELECT the uid DbpString("Now SELECT tag:"); @@ -959,22 +968,22 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len != 3) { - Dbprintf("Expected 3 bytes from tag, got %d", Demod.len); - return; + Dbprintf("Expected 3 bytes from tag, got %d", Demod.len); + return; } // Check the CRC of the answer: ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]); if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) { - DbpString("CRC Error reading select response."); - return; + DbpString("CRC Error reading select response."); + return; } // Check response from the tag: should be the same UID as the command we just sent: if (cmd1[1] != Demod.output[0]) { - Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1[1], Demod.output[0]); - return; + Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1[1], Demod.output[0]); + return; } // Tag is now selected, // First get the tag's UID: @@ -983,22 +992,22 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len != 10) { - Dbprintf("Expected 10 bytes from tag, got %d", Demod.len); - return; + Dbprintf("Expected 10 bytes from tag, got %d", Demod.len); + return; } // The check the CRC of the answer (use cmd1 as temporary variable): ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]); - if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) { - Dbprintf("CRC Error reading block! - Below: expected, got %x %x", - (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); - // Do not return;, let's go on... (we should retry, maybe ?) + if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) { + Dbprintf("CRC Error reading block! - Below: expected, got %x %x", + (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); + // Do not return;, let's go on... (we should retry, maybe ?) } Dbprintf("Tag UID (64 bits): %08x %08x", - (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], - (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); + (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], + (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); // Now loop to read all 16 blocks, address from 0 to last block Dbprintf("Tag memory dump, block 0 to %d",dwLast); @@ -1006,7 +1015,7 @@ void ReadSTMemoryIso14443(uint32_t dwLast) i = 0x00; dwLast++; for (;;) { - if (i == dwLast) { + if (i == dwLast) { DbpString("System area block (0xff):"); i = 0xff; } @@ -1015,25 +1024,25 @@ void ReadSTMemoryIso14443(uint32_t dwLast) CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); // LED_A_ON(); - GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); // LED_A_OFF(); if (Demod.len != 6) { // Check if we got an answer from the tag - DbpString("Expected 6 bytes from tag, got less..."); - return; + DbpString("Expected 6 bytes from tag, got less..."); + return; } // The check the CRC of the answer (use cmd1 as temporary variable): ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]); - if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) { - Dbprintf("CRC Error reading block! - Below: expected, got %x %x", - (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); - // Do not return;, let's go on... (we should retry, maybe ?) + if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) { + Dbprintf("CRC Error reading block! - Below: expected, got %x %x", + (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); + // Do not return;, let's go on... (we should retry, maybe ?) } // Now print out the memory location: Dbprintf("Address=%x, Contents=%x, CRC=%x", i, - (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], - (Demod.output[4]<<8)+Demod.output[5]); + (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], + (Demod.output[4]<<8)+Demod.output[5]); if (i == 0xff) { - break; + break; } i++; } @@ -1054,10 +1063,10 @@ void ReadSTMemoryIso14443(uint32_t dwLast) * Memory usage for this function, (within BigBuf) * Last Received command (reader->tag) - MAX_FRAME_SIZE * Last Received command (tag->reader) - MAX_FRAME_SIZE - * DMA Buffer, 1024 bytes (samples) - DMA_BUFFER_SIZE + * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE * Demodulated samples received - all the rest */ -void RAMFUNC SnoopIso14443(void) +void RAMFUNC SnoopIso14443b(void) { // 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 @@ -1071,7 +1080,7 @@ void RAMFUNC SnoopIso14443(void) set_tracing(TRUE); // The DMA buffer, used to stream samples from the FPGA - int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); int lastRxCounter; int8_t *upTo; int ci, cq; @@ -1089,24 +1098,21 @@ void RAMFUNC SnoopIso14443(void) Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen()); Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE); Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE); - Dbprintf(" DMA: %i bytes", DMA_BUFFER_SIZE); + Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE); - // Signal field is off with the appropriate LED - LED_D_OFF(); + // Signal field is off, no reader signal, no tag signal + LEDsoff(); // And put the 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); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_SNOOP); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Setup for the DMA. FpgaSetupSsc(); upTo = dmaBuf; - lastRxCounter = DMA_BUFFER_SIZE; - FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); + lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; + FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); uint8_t parity[MAX_PARITY_SIZE]; - LED_A_ON(); bool TagIsActive = FALSE; bool ReaderIsActive = FALSE; @@ -1114,50 +1120,56 @@ void RAMFUNC SnoopIso14443(void) // And now we loop, receiving samples. for(;;) { int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & - (DMA_BUFFER_SIZE-1); + (ISO14443B_DMA_BUFFER_SIZE-1); if(behindBy > maxBehindBy) { maxBehindBy = behindBy; - if(behindBy > (9*DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? - Dbprintf("blew circular buffer! behindBy=0x%x", behindBy); - break; - } } + if(behindBy < 2) continue; ci = upTo[0]; cq = upTo[1]; upTo += 2; lastRxCounter -= 2; - if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { + if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { upTo = dmaBuf; - lastRxCounter += DMA_BUFFER_SIZE; + lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; - AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; + WDT_HIT(); + if(behindBy > (9*ISO14443B_DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? + Dbprintf("blew circular buffer! behindBy=0x%x", behindBy); + break; + } + if(!tracing) { + DbpString("Reached trace limit"); + break; + } + if(BUTTON_PRESS()) { + DbpString("cancelled"); + break; + } } samples += 2; if (!TagIsActive) { // no need to try decoding reader data if the tag is sending - if(Handle14443UartBit(ci & 0x01)) { + if(Handle14443bUartBit(ci & 0x01)) { if(triggered && tracing) { GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE); + LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); } - if(Uart.byteCnt==0) Dbprintf("[1] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); - /* And ready to receive another command. */ UartReset(); /* And also reset the demod code, which might have been */ /* false-triggered by the commands from the reader. */ DemodReset(); } - if(Handle14443UartBit(cq & 0x01)) { + if(Handle14443bUartBit(cq & 0x01)) { if(triggered && tracing) { GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples, parity, TRUE); + LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); } - if(Uart.byteCnt==0) Dbprintf("[2] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); - /* And ready to receive another command. */ UartReset(); /* And also reset the demod code, which might have been */ @@ -1168,7 +1180,7 @@ void RAMFUNC SnoopIso14443(void) } if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time - if(Handle14443SamplesDemod(ci & 0xFE, cq & 0xFE)) { + if(Handle14443bSamplesDemod(ci & 0xFE, cq & 0xFE)) { //Use samples as a time measurement if(tracing) @@ -1178,31 +1190,17 @@ void RAMFUNC SnoopIso14443(void) LogTrace(Demod.output, Demod.len, samples, samples, parity, FALSE); } triggered = TRUE; - LED_A_OFF(); - LED_B_ON(); // And ready to receive another response. DemodReset(); } - TagIsActive = (Demod.state != DEMOD_UNSYNCD); + TagIsActive = (Demod.state > DEMOD_PHASE_REF_TRAINING); } - WDT_HIT(); - - if(!tracing) { - DbpString("Reached trace limit"); - break; - } - - if(BUTTON_PRESS()) { - DbpString("cancelled"); - break; - } } + FpgaDisableSscDma(); - LED_A_OFF(); - LED_B_OFF(); - LED_C_OFF(); + LEDsoff(); AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; DbpString("Snoop statistics:"); Dbprintf(" Max behind by: %i", maxBehindBy); @@ -1228,38 +1226,36 @@ void RAMFUNC SnoopIso14443(void) void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, uint8_t data[]) { FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - if(!powerfield) - { + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + FpgaSetupSsc(); + + set_tracing(TRUE); + +/* if(!powerfield) { // Make sure that we start from off, since the tags are stateful; // confusing things will happen if we don't reset them between reads. FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LED_D_OFF(); SpinDelay(200); } + */ - if(!GETBIT(GPIO_LED_D)) - { - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); - - // Now give it time to spin up. - // Signal field is on with the appropriate LED - LED_D_ON(); - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); - SpinDelay(200); - } + // if(!GETBIT(GPIO_LED_D)) { // if field is off + // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); + // // Signal field is on with the appropriate LED + // LED_D_ON(); + // SpinDelay(200); + // } CodeAndTransmit14443bAsReader(data, datalen); - if(recv) - { - GetSamplesFor14443Demod(TRUE, RECEIVE_SAMPLES_TIMEOUT, TRUE); - uint16_t iLen = MIN(Demod.len,USB_CMD_DATA_SIZE); - cmd_send(CMD_ACK,iLen,0,0,Demod.output,iLen); + if(recv) { + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE); + cmd_send(CMD_ACK, iLen, 0, 0, Demod.output, iLen); } - if(!powerfield) - { + + if(!powerfield) { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LED_D_OFF(); } diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 525ffcc6..21a4e179 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -288,7 +288,7 @@ int CmdHF14BCmdRaw (const char *cmd) { if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { recv = resp.d.asBytes; PrintAndLog("received %i octets",resp.arg[0]); - if(!resp.arg[0]) + if(resp.arg[0] == 0) return 0; hexout = (char *)malloc(resp.arg[0] * 3 + 1); if (hexout != NULL) { @@ -298,11 +298,13 @@ int CmdHF14BCmdRaw (const char *cmd) { } PrintAndLog("%s", hexout); free(hexout); - ComputeCrc14443(CRC_14443_B, recv, resp.arg[0]-2, &first, &second); - if(recv[resp.arg[0]-2]==first && recv[resp.arg[0]-1]==second) { - PrintAndLog("CRC OK"); - } else { - PrintAndLog("CRC failed"); + if (resp.arg[0] > 2) { + ComputeCrc14443(CRC_14443_B, recv, resp.arg[0]-2, &first, &second); + if(recv[resp.arg[0]-2]==first && recv[resp.arg[0]-1]==second) { + PrintAndLog("CRC OK"); + } else { + PrintAndLog("CRC failed"); + } } } else { PrintAndLog("malloc failed your client has low memory?"); diff --git a/fpga/fpga_hf.bit b/fpga/fpga_hf.bit index 53078a782422c09596f006d95c85ae45da20072d..717dad13eb67e5ef2cfeb39da3c4a0f6e9e04fd3 100644 GIT binary patch literal 42175 zcmeIb4|rVFbuYSRpCkErW~4cm?Ns59b2Jjp;EbfPn<<+g@UGWaS)5JQBa zARF0!zqQYqGeK0Jv2Wt?fs7^asw^=a{uq& z@PBOha&!O28@}{=H?{oHmu{jPDcbfY?U_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3_l?o<6G~{W6oNL_e(htw{Kf;5ubgDzo@*xWI(hBd)SX7K**?1k+}W>Tn+%* z_U*ht(*TYy6x53ZI+&CZ$FS(Y1%j)ZsBc|}r~VV^*gjr_y-?`(zLlaXS|;tZ*{EG8c(0)pFs_8l7YKeE0X%&NT=tM!_?V*IVBXe$N&170 zwTCVcT))rS4f<_zYx;eSvk&RF^_K+iiQlI8op8AX&p-p$t z&HW|8dm_F5(Di9^tu~K7C~FJmS{!Ef1n)^{Z(zM<;Bo-ajLY78u%;Eb49E@unsM20 zgMBFaZKnr^g-jt!g7<_<<1(n%txtv`+VTqo;lIbj<^B>b2LR22*M#@s3|wY7Rsdar z%R&H9>&mvN@S)VAP9*rf`{2SmE*vL6*M7 za9nR*uhqVT;D5`Uxzw48T~JyJdM8}2^^uxL@YlrkA2mK9o|(A%su~tzEFCPO|z2PIQ=!~k1t%}LLfZ3LWXWoAgz0;`p zAW+5p;AK3@nG>LTSQ}cf6p)f-}+V8xpU`S ze))w$@W~5*6+HR>ZJP^KICv8D`47>-ci3aW?hRh_2iS!3by+WKrT?0l8}Py{$<6+E zbXo24l77()6&|0V)Ipoyqsu{?-!ng@HZxV2m0Ibt5`Ld9m*&}j&pYaJNq2*#cn4h$ zrqXZpPP!cY`*(HuolL?1xB4C|&hHdZ*01q4NmBQRerKb1fAQ`NygLK$&cM4f@a_z} zI|J{|z<=WzQ2r7eCiqL@zwtD@JM?#F;N2N`cLv^_fp=%%-5L0AIs?e^Bd@UOACn~U fUqV!0%>F~B!fzi+QjY%}R~_KL`^#x5|0VwqAA(}7 diff --git a/fpga/fpga_hf.v b/fpga/fpga_hf.v index a2100df6..e84081b3 100644 --- a/fpga/fpga_hf.v +++ b/fpga/fpga_hf.v @@ -67,15 +67,10 @@ assign major_mode = conf_word[7:5]; // some fraction of the buffers) wire hi_read_tx_shallow_modulation = conf_word[0]; -// For the high-frequency receive correlator: frequency against which to -// correlate. -wire hi_read_rx_xcorr_848 = conf_word[0]; -// and whether to drive the coil (reader) or just short it (snooper) +// For the high-frequency receive correlator: +// whether to drive the coil (reader) or just short it (snooper) wire hi_read_rx_xcorr_snoop = conf_word[1]; -// Divide the expected subcarrier frequency for hi_read_rx_xcorr by 4 -wire hi_read_rx_xcorr_quarter = conf_word[2]; - // For the high-frequency simulated tag: what kind of modulation to use. wire [2:0] hi_simulate_mod_type = conf_word[2:0]; @@ -102,7 +97,7 @@ hi_read_rx_xcorr hrxc( hrxc_ssp_frame, hrxc_ssp_din, ssp_dout, hrxc_ssp_clk, cross_hi, cross_lo, hrxc_dbg, - hi_read_rx_xcorr_848, hi_read_rx_xcorr_snoop, hi_read_rx_xcorr_quarter + hi_read_rx_xcorr_snoop ); hi_simulate hs( diff --git a/fpga/hi_read_rx_xcorr.v b/fpga/hi_read_rx_xcorr.v index 06142637..a6a99cd5 100644 --- a/fpga/hi_read_rx_xcorr.v +++ b/fpga/hi_read_rx_xcorr.v @@ -10,7 +10,7 @@ module hi_read_rx_xcorr( ssp_frame, ssp_din, ssp_dout, ssp_clk, cross_hi, cross_lo, dbg, - xcorr_is_848, snoop, xcorr_quarter_freq + snoop ); input pck0, ck_1356meg, ck_1356megb; output pwr_lo, pwr_hi, pwr_oe1, pwr_oe2, pwr_oe3, pwr_oe4; @@ -20,58 +20,20 @@ module hi_read_rx_xcorr( output ssp_frame, ssp_din, ssp_clk; input cross_hi, cross_lo; output dbg; - input xcorr_is_848, snoop, xcorr_quarter_freq; + input snoop; // Carrier is steady on through this, unless we're snooping. assign pwr_hi = ck_1356megb & (~snoop); assign pwr_oe1 = 1'b0; -assign pwr_oe2 = 1'b0; assign pwr_oe3 = 1'b0; assign pwr_oe4 = 1'b0; -reg ssp_clk; -reg ssp_frame; - -reg fc_div_2; -always @(posedge ck_1356meg) - fc_div_2 = ~fc_div_2; - -reg fc_div_4; -always @(posedge fc_div_2) - fc_div_4 = ~fc_div_4; - -reg fc_div_8; -always @(posedge fc_div_4) - fc_div_8 = ~fc_div_8; - -reg adc_clk; - -always @(xcorr_is_848 or xcorr_quarter_freq or ck_1356meg) - if(~xcorr_quarter_freq) - begin - if(xcorr_is_848) - // The subcarrier frequency is fc/16; we will sample at fc, so that - // means the subcarrier is 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 ... - adc_clk <= ck_1356meg; - else - // The subcarrier frequency is fc/32; we will sample at fc/2, and - // the subcarrier will look identical. - adc_clk <= fc_div_2; - end - else - begin - if(xcorr_is_848) - // The subcarrier frequency is fc/64 - adc_clk <= fc_div_4; - else - // The subcarrier frequency is fc/128 - adc_clk <= fc_div_8; - end +wire adc_clk = ck_1356megb; // When we're a reader, we just need to do the BPSK demod; but when we're an // eavesdropper, we also need to pick out the commands sent by the reader, // using AM. Do this the same way that we do it for the simulated tag. -reg after_hysteresis, after_hysteresis_prev; +reg after_hysteresis, after_hysteresis_prev, after_hysteresis_prev_prev; reg [11:0] has_been_low_for; always @(negedge adc_clk) begin @@ -97,7 +59,6 @@ end // Let us report a correlation every 4 subcarrier cycles, or 4*16 samples, // so we need a 6-bit counter. reg [5:0] corr_i_cnt; -reg [5:0] corr_q_cnt; // And a couple of registers in which to accumulate the correlations. // we would add at most 32 times adc_d, the result can be held in 13 bits. // Need one additional bit because it can be negative as well @@ -105,32 +66,38 @@ reg signed [13:0] corr_i_accum; reg signed [13:0] corr_q_accum; reg signed [7:0] corr_i_out; reg signed [7:0] corr_q_out; +// clock and frame signal for communication to ARM +reg ssp_clk; +reg ssp_frame; + + // ADC data appears on the rising edge, so sample it on the falling edge always @(negedge adc_clk) begin + corr_i_cnt <= corr_i_cnt + 1; + // These are the correlators: we correlate against in-phase and quadrature // versions of our reference signal, and keep the (signed) result to // send out later over the SSP. - if(corr_i_cnt == 7'd63) + if(corr_i_cnt == 7'd0) begin if(snoop) begin - // highest 7 significant bits of tag signal (signed), 1 bit reader signal: - corr_i_out <= {corr_i_accum[13:7], after_hysteresis_prev}; - corr_q_out <= {corr_q_accum[13:7], after_hysteresis}; + // 7 most significant bits of tag signal (signed), 1 bit reader signal: + corr_i_out <= {corr_i_accum[13:7], after_hysteresis_prev_prev}; + corr_q_out <= {corr_q_accum[13:7], after_hysteresis_prev}; + after_hysteresis_prev_prev <= after_hysteresis; end else begin - // highest 8 significant bits of tag signal + // 8 most significant bits of tag signal corr_i_out <= corr_i_accum[13:6]; corr_q_out <= corr_q_accum[13:6]; end corr_i_accum <= adc_d; corr_q_accum <= adc_d; - corr_q_cnt <= 4; - corr_i_cnt <= 0; end else begin @@ -139,13 +106,11 @@ begin else corr_i_accum <= corr_i_accum + adc_d; - if(corr_q_cnt[3]) - corr_q_accum <= corr_q_accum - adc_d; - else + if(corr_i_cnt[3] == corr_i_cnt[2]) // phase shifted by pi/2 corr_q_accum <= corr_q_accum + adc_d; + else + corr_q_accum <= corr_q_accum - adc_d; - corr_i_cnt <= corr_i_cnt + 1; - corr_q_cnt <= corr_q_cnt + 1; end // The logic in hi_simulate.v reports 4 samples per bit. We report two @@ -172,7 +137,7 @@ begin end // set ssp_frame signal for corr_i_cnt = 0..3 and corr_i_cnt = 32..35 - // (two frames with 8 Bits each) + // (send two frames with 8 Bits each) if(corr_i_cnt[5:2] == 4'b0000 || corr_i_cnt[5:2] == 4'b1000) ssp_frame = 1'b1; else @@ -186,5 +151,6 @@ assign dbg = corr_i_cnt[3]; // Unused. assign pwr_lo = 1'b0; +assign pwr_oe2 = 1'b0; endmodule From d5875804a3555b9d6305a4c9dcdbfeac380d9f00 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 18 Jun 2015 07:56:08 +0200 Subject: [PATCH 114/132] fixing iso14443b (issue #103): fix: don't waste time to calculate parity bits. Instead add void parity bits to trace and ignore them on client side --- armsrc/iso14443b.c | 11 +++++------ client/cmdhf.c | 2 +- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index f598df3c..989b477c 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -17,7 +17,6 @@ #include "iso14443crc.h" #define RECEIVE_SAMPLES_TIMEOUT 2000 -#define ISO14443B_DMA_BUFFER_SIZE 512 //============================================================================= // An ISO 14443 Type B tag. We listen for commands from the reader, using @@ -768,7 +767,7 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) //Tracing if (tracing && Demod.len > 0) { uint8_t parity[MAX_PARITY_SIZE]; - GetParity(Demod.output, Demod.len, parity); + //GetParity(Demod.output, Demod.len, parity); LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE); } } @@ -1156,7 +1155,7 @@ void RAMFUNC SnoopIso14443b(void) if (!TagIsActive) { // no need to try decoding reader data if the tag is sending if(Handle14443bUartBit(ci & 0x01)) { if(triggered && tracing) { - GetParity(Uart.output, Uart.byteCnt, parity); + //GetParity(Uart.output, Uart.byteCnt, parity); LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); } /* And ready to receive another command. */ @@ -1167,7 +1166,7 @@ void RAMFUNC SnoopIso14443b(void) } if(Handle14443bUartBit(cq & 0x01)) { if(triggered && tracing) { - GetParity(Uart.output, Uart.byteCnt, parity); + //GetParity(Uart.output, Uart.byteCnt, parity); LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); } /* And ready to receive another command. */ @@ -1186,7 +1185,7 @@ void RAMFUNC SnoopIso14443b(void) if(tracing) { uint8_t parity[MAX_PARITY_SIZE]; - GetParity(Demod.output, Demod.len, parity); + //GetParity(Demod.output, Demod.len, parity); LogTrace(Demod.output, Demod.len, samples, samples, parity, FALSE); } triggered = TRUE; @@ -1194,7 +1193,7 @@ void RAMFUNC SnoopIso14443b(void) // And ready to receive another response. DemodReset(); } - TagIsActive = (Demod.state > DEMOD_PHASE_REF_TRAINING); + TagIsActive = (Demod.state > DEMOD_GOT_FALLING_EDGE_OF_SOF); } } diff --git a/client/cmdhf.c b/client/cmdhf.c index 16f7bb0f..fc6127c2 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -378,7 +378,7 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui oddparity ^= (((frame[j] & 0xFF) >> k) & 0x01); } uint8_t parityBits = parityBytes[j>>3]; - if (isResponse && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { + if (protocol != ISO_14443B && isResponse && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { snprintf(line[j/16]+(( j % 16) * 4),110, "%02x! ", frame[j]); } else { From 132a02179cfad11fbf484b191544fb3c8475eda8 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 18 Jun 2015 09:49:22 +0200 Subject: [PATCH 115/132] fixing iso 14443b (issue #103): - fix: treat empty commands as error - deleting dead code - rename USB-Commands (ISO14443 -> iso14443B) --- armsrc/appmain.c | 60 +-------------- armsrc/iso14443b.c | 70 +++++++---------- client/cmdhf14b.c | 144 ++--------------------------------- client/hid-flasher/usb_cmd.h | 6 +- client/lualibs/commands.lua | 6 +- include/usb_cmd.h | 6 +- 6 files changed, 42 insertions(+), 250 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 9bfa5ea7..fb3c0f18 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -250,55 +250,6 @@ void MeasureAntennaTuningHf(void) } -void SimulateTagHfListen(void) -{ - // ToDo: historically this used the free buffer, which was 2744 Bytes long. - // There might be a better size to be defined: - #define HF_14B_SNOOP_BUFFER_SIZE 2744 - uint8_t *dest = BigBuf_malloc(HF_14B_SNOOP_BUFFER_SIZE); - uint8_t v = 0; - int i; - int p = 0; - - // We're using this mode just so that I can test it out; the simulated - // tag mode would work just as well and be simpler. - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_SNOOP); - - // We need to listen to the high-frequency, peak-detected path. - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - - FpgaSetupSsc(); - - i = 0; - for(;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0xff; - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - uint8_t r = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - - v <<= 1; - if(r & 1) { - v |= 1; - } - p++; - - if(p >= 8) { - dest[i] = v; - v = 0; - p = 0; - i++; - - if(i >= HF_14B_SNOOP_BUFFER_SIZE) { - break; - } - } - } - } - DbpString("simulate tag (now type bitsamples)"); -} - void ReadMem(int addr) { const uint8_t *data = ((uint8_t *)addr); @@ -782,19 +733,16 @@ void UsbPacketReceived(uint8_t *packet, int len) #endif #ifdef WITH_ISO14443b - case CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443: - AcquireRawAdcSamplesIso14443b(c->arg[0]); - break; case CMD_READ_SRI512_TAG: ReadSTMemoryIso14443b(0x0F); break; case CMD_READ_SRIX4K_TAG: ReadSTMemoryIso14443b(0x7F); break; - case CMD_SNOOP_ISO_14443: + case CMD_SNOOP_ISO_14443B: SnoopIso14443b(); break; - case CMD_SIMULATE_TAG_ISO_14443: + case CMD_SIMULATE_TAG_ISO_14443B: SimulateIso14443bTag(); break; case CMD_ISO_14443B_COMMAND: @@ -911,10 +859,6 @@ void UsbPacketReceived(uint8_t *packet, int len) break; #endif - case CMD_SIMULATE_TAG_HF_LISTEN: - SimulateTagHfListen(); - break; - case CMD_BUFF_CLEAR: BigBuf_Clear(); break; diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 989b477c..80f93678 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -237,7 +237,11 @@ static int Handle14443bUartBit(int bit) } else if(Uart.shiftReg == 0x000) { // this is an EOF byte LED_A_OFF(); // Finished receiving - return TRUE; + if (Uart.byteCnt != 0) { + return TRUE; + } + Uart.posCnt = 0; + Uart.state = STATE_ERROR_WAIT; } else { // this is an error Uart.posCnt = 0; @@ -714,16 +718,16 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) uint8_t *receivedResponse = 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 *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse); // Setup and start DMA. - FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); + FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); int8_t *upTo = dmaBuf; - lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; + lastRxCounter = DMA_BUFFER_SIZE; // Signal field is ON with the appropriate LED: LED_D_ON(); @@ -734,18 +738,18 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; if(behindBy > max) max = behindBy; - while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (ISO14443B_DMA_BUFFER_SIZE-1)) > 2) { + while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1)) > 2) { ci = upTo[0]; cq = upTo[1]; upTo += 2; - if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { + if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { upTo = dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; - AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; } lastRxCounter -= 2; if(lastRxCounter <= 0) { - lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; + lastRxCounter += DMA_BUFFER_SIZE; } samples += 2; @@ -880,22 +884,6 @@ static void CodeIso14443bAsReader(const uint8_t *cmd, int len) } -//----------------------------------------------------------------------------- -// Read an ISO 14443B tag. We send it some set of commands, and record the -// responses. -// The command name is misleading, it actually decodes the reponse in HEX -// into the output buffer (read the result using hexsamples, not hisamples) -// -// obsolete function only for test -//----------------------------------------------------------------------------- -void AcquireRawAdcSamplesIso14443b(uint32_t parameter) -{ - uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // REQB with AFI=0, Request All, N=0 - - SendRawCommand14443B(sizeof(cmd1),1,1,cmd1); -} - - /** Convenience function to encode, transmit and trace iso 14443b comms **/ @@ -956,7 +944,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) DbpString("No response from tag"); return; } else { - Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %x %x %x", + Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %02x %02x %02x", Demod.output[0], Demod.output[1], Demod.output[2]); } // There is a response, SELECT the uid @@ -981,7 +969,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) } // Check response from the tag: should be the same UID as the command we just sent: if (cmd1[1] != Demod.output[0]) { - Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1[1], Demod.output[0]); + Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1[1], Demod.output[0]); return; } // Tag is now selected, @@ -1000,7 +988,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) // The check the CRC of the answer (use cmd1 as temporary variable): ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]); if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) { - Dbprintf("CRC Error reading block! - Below: expected, got %x %x", + Dbprintf("CRC Error reading block! Expected: %04x got: %04x", (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); // Do not return;, let's go on... (we should retry, maybe ?) } @@ -1009,7 +997,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); // Now loop to read all 16 blocks, address from 0 to last block - Dbprintf("Tag memory dump, block 0 to %d",dwLast); + Dbprintf("Tag memory dump, block 0 to %d", dwLast); cmd1[0] = 0x08; i = 0x00; dwLast++; @@ -1032,12 +1020,12 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) // The check the CRC of the answer (use cmd1 as temporary variable): ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]); if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) { - Dbprintf("CRC Error reading block! - Below: expected, got %x %x", + Dbprintf("CRC Error reading block! Expected: %04x got: %04x", (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); // Do not return;, let's go on... (we should retry, maybe ?) } // Now print out the memory location: - Dbprintf("Address=%x, Contents=%x, CRC=%x", i, + Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i, (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], (Demod.output[4]<<8)+Demod.output[5]); if (i == 0xff) { @@ -1062,7 +1050,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) * Memory usage for this function, (within BigBuf) * Last Received command (reader->tag) - MAX_FRAME_SIZE * Last Received command (tag->reader) - MAX_FRAME_SIZE - * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE + * DMA Buffer - DMA_BUFFER_SIZE * Demodulated samples received - all the rest */ void RAMFUNC SnoopIso14443b(void) @@ -1079,7 +1067,7 @@ void RAMFUNC SnoopIso14443b(void) set_tracing(TRUE); // The DMA buffer, used to stream samples from the FPGA - int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); int lastRxCounter; int8_t *upTo; int ci, cq; @@ -1097,7 +1085,7 @@ void RAMFUNC SnoopIso14443b(void) Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen()); Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE); Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE); - Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE); + Dbprintf(" DMA: %i bytes", DMA_BUFFER_SIZE); // Signal field is off, no reader signal, no tag signal LEDsoff(); @@ -1109,8 +1097,8 @@ void RAMFUNC SnoopIso14443b(void) // Setup for the DMA. FpgaSetupSsc(); upTo = dmaBuf; - lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; - FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); + lastRxCounter = DMA_BUFFER_SIZE; + FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); uint8_t parity[MAX_PARITY_SIZE]; bool TagIsActive = FALSE; @@ -1119,7 +1107,7 @@ void RAMFUNC SnoopIso14443b(void) // And now we loop, receiving samples. for(;;) { int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & - (ISO14443B_DMA_BUFFER_SIZE-1); + (DMA_BUFFER_SIZE-1); if(behindBy > maxBehindBy) { maxBehindBy = behindBy; } @@ -1130,14 +1118,14 @@ void RAMFUNC SnoopIso14443b(void) cq = upTo[1]; upTo += 2; lastRxCounter -= 2; - if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { + if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { upTo = dmaBuf; - lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; + lastRxCounter += DMA_BUFFER_SIZE; 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 = DMA_BUFFER_SIZE; WDT_HIT(); - if(behindBy > (9*ISO14443B_DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? - Dbprintf("blew circular buffer! behindBy=0x%x", behindBy); + if(behindBy > (9*DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? + Dbprintf("blew circular buffer! behindBy=%d", behindBy); break; } if(!tracing) { diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 21a4e179..496267cd 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -25,154 +25,23 @@ static int CmdHelp(const char *Cmd); -int CmdHF14BDemod(const char *Cmd) -{ - int i, j, iold; - int isum, qsum; - int outOfWeakAt; - bool negateI, negateQ; - - uint8_t data[256]; - int dataLen = 0; - - // As received, the samples are pairs, correlations against I and Q - // square waves. So estimate angle of initial carrier (or just - // quadrant, actually), and then do the demod. - - // First, estimate where the tag starts modulating. - for (i = 0; i < GraphTraceLen; i += 2) { - if (abs(GraphBuffer[i]) + abs(GraphBuffer[i + 1]) > 40) { - break; - } - } - if (i >= GraphTraceLen) { - PrintAndLog("too weak to sync"); - return 0; - } - PrintAndLog("out of weak at %d", i); - outOfWeakAt = i; - - // Now, estimate the phase in the initial modulation of the tag - isum = 0; - qsum = 0; - for (; i < (outOfWeakAt + 16); i += 2) { - isum += GraphBuffer[i + 0]; - qsum += GraphBuffer[i + 1]; - } - negateI = (isum < 0); - negateQ = (qsum < 0); - - // Turn the correlation pairs into soft decisions on the bit. - j = 0; - for (i = 0; i < GraphTraceLen / 2; i++) { - int si = GraphBuffer[j]; - int sq = GraphBuffer[j + 1]; - if (negateI) si = -si; - if (negateQ) sq = -sq; - GraphBuffer[i] = si + sq; - j += 2; - } - GraphTraceLen = i; - - i = outOfWeakAt / 2; - while (GraphBuffer[i] > 0 && i < GraphTraceLen) - i++; - if (i >= GraphTraceLen) goto demodError; - - iold = i; - while (GraphBuffer[i] < 0 && i < GraphTraceLen) - i++; - if (i >= GraphTraceLen) goto demodError; - if ((i - iold) > 23) goto demodError; - - PrintAndLog("make it to demod loop"); - - for (;;) { - iold = i; - while (GraphBuffer[i] >= 0 && i < GraphTraceLen) - i++; - if (i >= GraphTraceLen) goto demodError; - if ((i - iold) > 6) goto demodError; - - uint16_t shiftReg = 0; - if (i + 20 >= GraphTraceLen) goto demodError; - - for (j = 0; j < 10; j++) { - int soft = GraphBuffer[i] + GraphBuffer[i + 1]; - - if (abs(soft) < (abs(isum) + abs(qsum)) / 20) { - PrintAndLog("weak bit"); - } - - shiftReg >>= 1; - if(GraphBuffer[i] + GraphBuffer[i+1] >= 0) { - shiftReg |= 0x200; - } - - i+= 2; - } - - if ((shiftReg & 0x200) && !(shiftReg & 0x001)) - { - // valid data byte, start and stop bits okay - PrintAndLog(" %02x", (shiftReg >> 1) & 0xff); - data[dataLen++] = (shiftReg >> 1) & 0xff; - if (dataLen >= sizeof(data)) { - return 0; - } - } else if (shiftReg == 0x000) { - // this is EOF - break; - } else { - goto demodError; - } - } - - uint8_t first, second; - ComputeCrc14443(CRC_14443_B, data, dataLen-2, &first, &second); - PrintAndLog("CRC: %02x %02x (%s)\n", first, second, - (first == data[dataLen-2] && second == data[dataLen-1]) ? - "ok" : "****FAIL****"); - - RepaintGraphWindow(); - return 0; - -demodError: - PrintAndLog("demod error"); - RepaintGraphWindow(); - return 0; -} - int CmdHF14BList(const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list 14b' instead"); return 0; } -int CmdHF14BRead(const char *Cmd) -{ - UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443, {strtol(Cmd, NULL, 0), 0, 0}}; - SendCommand(&c); - return 0; -} -int CmdHF14Sim(const char *Cmd) +int CmdHF14BSim(const char *Cmd) { - UsbCommand c={CMD_SIMULATE_TAG_ISO_14443}; - SendCommand(&c); - return 0; -} - -int CmdHFSimlisten(const char *Cmd) -{ - UsbCommand c = {CMD_SIMULATE_TAG_HF_LISTEN}; + UsbCommand c={CMD_SIMULATE_TAG_ISO_14443B}; SendCommand(&c); return 0; } int CmdHF14BSnoop(const char *Cmd) { - UsbCommand c = {CMD_SNOOP_ISO_14443}; + UsbCommand c = {CMD_SNOOP_ISO_14443B}; SendCommand(&c); return 0; } @@ -387,12 +256,9 @@ int CmdHF14BWrite( const char *Cmd){ static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdHF14BDemod, 1, "Demodulate ISO14443 Type B from tag"}, {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443b history"}, - {"read", CmdHF14BRead, 0, "Read HF tag (ISO 14443)"}, - {"sim", CmdHF14Sim, 0, "Fake ISO 14443 tag"}, - {"simlisten", CmdHFSimlisten, 0, "Get HF samples as fake tag"}, - {"snoop", CmdHF14BSnoop, 0, "Eavesdrop ISO 14443"}, + {"sim", CmdHF14BSim, 0, "Fake ISO 14443B tag"}, + {"snoop", CmdHF14BSnoop, 0, "Eavesdrop ISO 14443B"}, {"sri512read", CmdSri512Read, 0, "Read contents of a SRI512 tag"}, {"srix4kread", CmdSrix4kRead, 0, "Read contents of a SRIX4K tag"}, {"raw", CmdHF14BCmdRaw, 0, "Send raw hex data to tag"}, diff --git a/client/hid-flasher/usb_cmd.h b/client/hid-flasher/usb_cmd.h index c5b91f99..b3a7f4ec 100644 --- a/client/hid-flasher/usb_cmd.h +++ b/client/hid-flasher/usb_cmd.h @@ -89,7 +89,6 @@ typedef struct { // For the 13.56 MHz tags #define CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693 0x0300 -#define CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443 0x0301 #define CMD_READ_SRI512_TAG 0x0303 #define CMD_READ_SRIX4K_TAG 0x0304 #define CMD_READER_ISO_15693 0x0310 @@ -105,9 +104,8 @@ typedef struct { #define CMD_SIMULATE_HITAG 0x0371 #define CMD_READER_HITAG 0x0372 -#define CMD_SIMULATE_TAG_HF_LISTEN 0x0380 -#define CMD_SIMULATE_TAG_ISO_14443 0x0381 -#define CMD_SNOOP_ISO_14443 0x0382 +#define CMD_SIMULATE_TAG_ISO_14443B 0x0381 +#define CMD_SNOOP_ISO_14443B 0x0382 #define CMD_SNOOP_ISO_14443a 0x0383 #define CMD_SIMULATE_TAG_ISO_14443a 0x0384 #define CMD_READER_ISO_14443a 0x0385 diff --git a/client/lualibs/commands.lua b/client/lualibs/commands.lua index 678c745e..4c7bc638 100644 --- a/client/lualibs/commands.lua +++ b/client/lualibs/commands.lua @@ -59,7 +59,6 @@ local _commands = { --// For the 13.56 MHz tags CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693 = 0x0300, - CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443 = 0x0301, CMD_READ_SRI512_TAG = 0x0303, CMD_READ_SRIX4K_TAG = 0x0304, CMD_READER_ISO_15693 = 0x0310, @@ -76,9 +75,8 @@ local _commands = { CMD_SIMULATE_HITAG = 0x0371, CMD_READER_HITAG = 0x0372, - CMD_SIMULATE_TAG_HF_LISTEN = 0x0380, - CMD_SIMULATE_TAG_ISO_14443 = 0x0381, - CMD_SNOOP_ISO_14443 = 0x0382, + CMD_SIMULATE_TAG_ISO_14443B = 0x0381, + CMD_SNOOP_ISO_14443B = 0x0382, CMD_SNOOP_ISO_14443a = 0x0383, CMD_SIMULATE_TAG_ISO_14443a = 0x0384, CMD_READER_ISO_14443a = 0x0385, diff --git a/include/usb_cmd.h b/include/usb_cmd.h index 357395d4..132e1805 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -100,7 +100,6 @@ typedef struct{ // For the 13.56 MHz tags #define CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693 0x0300 -#define CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443 0x0301 #define CMD_READ_SRI512_TAG 0x0303 #define CMD_READ_SRIX4K_TAG 0x0304 #define CMD_ISO_14443B_COMMAND 0x0305 @@ -118,9 +117,8 @@ typedef struct{ #define CMD_SIMULATE_HITAG 0x0371 #define CMD_READER_HITAG 0x0372 -#define CMD_SIMULATE_TAG_HF_LISTEN 0x0380 -#define CMD_SIMULATE_TAG_ISO_14443 0x0381 -#define CMD_SNOOP_ISO_14443 0x0382 +#define CMD_SIMULATE_TAG_ISO_14443B 0x0381 +#define CMD_SNOOP_ISO_14443B 0x0382 #define CMD_SNOOP_ISO_14443a 0x0383 #define CMD_SIMULATE_TAG_ISO_14443a 0x0384 #define CMD_READER_ISO_14443a 0x0385 From 50365fedcbaf91ce530ca8507d2f377dc76ffd59 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 18 Jun 2015 11:33:53 +0200 Subject: [PATCH 116/132] fix issue #116: remove includes of stdio.h in armsrc --- armsrc/aes.c | 4 +++- armsrc/optimized_cipher.c | 1 - common/protocols.c | 1 - 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/armsrc/aes.c b/armsrc/aes.c index 3df006bb..a199d04b 100644 --- a/armsrc/aes.c +++ b/armsrc/aes.c @@ -1,4 +1,3 @@ -#include "stdio.h" #include "aes.h" static const unsigned int Te0[256] = { @@ -1138,6 +1137,9 @@ int AesDecrypt(AesCtx *pCtx, unsigned char *pCipher, unsigned char *pData, unsig ////////////////////////////////////////////////////////////////////////////// #ifndef EMBEDDED + +#include + int main() { AesCtx ctx; diff --git a/armsrc/optimized_cipher.c b/armsrc/optimized_cipher.c index 444b93d0..23562621 100644 --- a/armsrc/optimized_cipher.c +++ b/armsrc/optimized_cipher.c @@ -61,7 +61,6 @@ **/ #include "optimized_cipher.h" -#include #include #include #include diff --git a/common/protocols.c b/common/protocols.c index 6a4c9a10..aa80491b 100644 --- a/common/protocols.c +++ b/common/protocols.c @@ -1,4 +1,3 @@ -#include #include #include #include From da586b170276fd44963ec4a8934beaf563feb132 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 18 Jun 2015 15:30:56 +0200 Subject: [PATCH 117/132] fixing iso14443b (issue #103): - revert removal of FPGA_HF_READER_RX_XCORR_848_KHZ. Need to be able to switch to 424kHz for ISO15693. --- armsrc/iso14443b.c | 8 ++++---- fpga/fpga_hf.bit | Bin 42175 -> 42175 bytes fpga/fpga_hf.v | 8 +++++--- fpga/hi_read_rx_xcorr.v | 20 +++++++++++++++++--- 4 files changed, 26 insertions(+), 10 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 80f93678..8d1a5cca 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -732,7 +732,7 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) // Signal field is ON with the appropriate LED: LED_D_ON(); // And put the FPGA in the appropriate mode - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); for(;;) { int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; @@ -929,7 +929,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) // Signal field is on with the appropriate LED LED_D_ON(); FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR); + FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); SpinDelay(200); // First command: wake up the tag using the INITIATE command @@ -1091,7 +1091,7 @@ void RAMFUNC SnoopIso14443b(void) LEDsoff(); // And put the FPGA in the appropriate mode - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_SNOOP); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP); SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Setup for the DMA. @@ -1228,7 +1228,7 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u */ // if(!GETBIT(GPIO_LED_D)) { // if field is off - // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); + // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); // // Signal field is on with the appropriate LED // LED_D_ON(); // SpinDelay(200); diff --git a/fpga/fp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k@S5j9dc4=*-wWY5c;fewSAWL%oP2KL<11<|Y)JpJBE1(t zKmZDE`NJ5F>&m!1r?IBo<^NY)o(soifc}f%vo3_=@{=<`pEkAZuou51~&MU zaKm)M|Mjcd9UZ^ow~55B_~rksUv-^3ch2RPU)Tsf^1@#QPyUzfGe?&LrT(9z%fF6I z_!T20oa94`$$l8TfZR z1KMAL!vudx{yUzA4~G81416#HAI!i9Gw{I-d@uw5PGEnA;7jp)4pq`p{!9KJU6^^c diff --git a/fpga/fpga_hf.v b/fpga/fpga_hf.v index e84081b3..8a465e75 100644 --- a/fpga/fpga_hf.v +++ b/fpga/fpga_hf.v @@ -67,8 +67,10 @@ assign major_mode = conf_word[7:5]; // some fraction of the buffers) wire hi_read_tx_shallow_modulation = conf_word[0]; -// For the high-frequency receive correlator: -// whether to drive the coil (reader) or just short it (snooper) +// For the high-frequency receive correlator: frequency against which to +// correlate. +wire hi_read_rx_xcorr_848 = conf_word[0]; +// and whether to drive the coil (reader) or just short it (snooper) wire hi_read_rx_xcorr_snoop = conf_word[1]; // For the high-frequency simulated tag: what kind of modulation to use. @@ -97,7 +99,7 @@ hi_read_rx_xcorr hrxc( hrxc_ssp_frame, hrxc_ssp_din, ssp_dout, hrxc_ssp_clk, cross_hi, cross_lo, hrxc_dbg, - hi_read_rx_xcorr_snoop + hi_read_rx_xcorr_848, hi_read_rx_xcorr_snoop ); hi_simulate hs( diff --git a/fpga/hi_read_rx_xcorr.v b/fpga/hi_read_rx_xcorr.v index a6a99cd5..4a5de553 100644 --- a/fpga/hi_read_rx_xcorr.v +++ b/fpga/hi_read_rx_xcorr.v @@ -10,7 +10,7 @@ module hi_read_rx_xcorr( ssp_frame, ssp_din, ssp_dout, ssp_clk, cross_hi, cross_lo, dbg, - snoop + xcorr_is_848, snoop ); input pck0, ck_1356meg, ck_1356megb; output pwr_lo, pwr_hi, pwr_oe1, pwr_oe2, pwr_oe3, pwr_oe4; @@ -20,7 +20,7 @@ module hi_read_rx_xcorr( output ssp_frame, ssp_din, ssp_clk; input cross_hi, cross_lo; output dbg; - input snoop; + input xcorr_is_848, snoop; // Carrier is steady on through this, unless we're snooping. assign pwr_hi = ck_1356megb & (~snoop); @@ -28,8 +28,22 @@ assign pwr_oe1 = 1'b0; assign pwr_oe3 = 1'b0; assign pwr_oe4 = 1'b0; -wire adc_clk = ck_1356megb; +(* clock_signal = "yes" *) reg fc_div_2; +always @(negedge ck_1356megb) + fc_div_2 <= fc_div_2 + 1; +(* clock_signal = "yes" *) reg adc_clk; +always @(xcorr_is_848, ck_1356megb, fc_div_2) +if (xcorr_is_848) + // The subcarrier frequency is fc/16; we will sample at fc, so that + // means the subcarrier is 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 1 1 ... + adc_clk <= ck_1356megb; +else + // The subcarrier frequency is fc/32; we will sample at fc/2, and + // the subcarrier will look identical. + adc_clk <= fc_div_2; + + // When we're a reader, we just need to do the BPSK demod; but when we're an // eavesdropper, we also need to pick out the commands sent by the reader, // using AM. Do this the same way that we do it for the simulated tag. From f4217d58b68ef3e7828892d8401ea1eb3da4696d Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Thu, 18 Jun 2015 17:19:43 -0400 Subject: [PATCH 118/132] add ultralight compatible test --- client/cmdhfmfu.c | 33 +++++++++++++++++++++++++++++---- client/cmdhfmfu.h | 3 ++- 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 48f549ba..a631b6b1 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -57,13 +57,13 @@ uint8_t default_pwd_pack[KEYS_PWD_COUNT][4] = { {0x32,0x0C,0x16,0x17}, // PACK 0x80,0x80 -- AMiiboo (sniffed) }; -#define MAX_UL_TYPES 17 -uint16_t UL_TYPES_ARRAY[MAX_UL_TYPES] = {UNKNOWN, UL, UL_C, UL_EV1_48, UL_EV1_128, NTAG, NTAG_203, - NTAG_210, NTAG_212, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC, MY_D_MOVE_LEAN}; +#define MAX_UL_TYPES 18 +uint32_t UL_TYPES_ARRAY[MAX_UL_TYPES] = {UNKNOWN, UL, UL_C, UL_EV1_48, UL_EV1_128, NTAG, NTAG_203, + NTAG_210, NTAG_212, NTAG_213, NTAG_215, NTAG_216, MY_D, MY_D_NFC, MY_D_MOVE, MY_D_MOVE_NFC, MY_D_MOVE_LEAN, FUDAN_UL}; 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_UL_BLOCKS, MAX_MY_D_NFC, MAX_MY_D_MOVE, MAX_MY_D_MOVE, MAX_MY_D_MOVE_LEAN}; + 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}; static int CmdHelp(const char *Cmd); @@ -276,6 +276,25 @@ static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ return len; } +//make sure field is off before calling this function +static int ul_fudan_check( void ){ + iso14a_card_select_t card; + if ( !ul_select(&card) ) + return UL_ERROR; + + UsbCommand c = {CMD_READER_ISO_14443a, {ISO14A_RAW | ISO14A_NO_DISCONNECT, 4, 0}}; + + uint8_t cmd[4] = {0x30,0x00,0x02,0xa7}; //wrong crc on purpose should be 0xa8 + memcpy(c.d.asBytes, cmd, 4); + clearCommandBuffer(); + SendCommand(&c); + UsbCommand resp; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) return UL_ERROR; + if (resp.arg[0] != 1) return UL_ERROR; + + return (!resp.d.asBytes[0]) ? FUDAN_UL : UL; //if response == 0x00 then Fudan, else Genuine NXP +} + static int ul_print_default( uint8_t *data){ uint8_t uid[7]; @@ -389,6 +408,8 @@ int ul_print_type(uint32_t tagtype, uint8_t spaces){ PrintAndLog("%sTYPE : INFINEON my-d\x99 move NFC (SLE 66R01P)", spacer); else if ( tagtype & MY_D_MOVE_LEAN ) PrintAndLog("%sTYPE : INFINEON my-d\x99 move lean (SLE 66R01L)", spacer); + else if ( tagtype & FUDAN_UL ) + PrintAndLog("%sTYPE : FUDAN Ultralight Compatible (or other compatible) %s", spacer, (tagtype & MAGIC) ? "" : "" ); else PrintAndLog("%sTYPE : Unknown %06x", spacer, tagtype); return 0; @@ -622,6 +643,10 @@ uint32_t GetHF14AMfU_Type(void){ ul_switch_off_field(); } } + if (tagtype & UL) { + tagtype = ul_fudan_check(); + ul_switch_off_field(); + } } else { ul_switch_off_field(); // Infinition MY-D tests Exam high nibble diff --git a/client/cmdhfmfu.h b/client/cmdhfmfu.h index 132e4f90..6c9e3ea1 100644 --- a/client/cmdhfmfu.h +++ b/client/cmdhfmfu.h @@ -45,7 +45,8 @@ typedef enum TAGTYPE_UL { MY_D_MOVE_LEAN= 0x008000, NTAG_I2C_1K = 0x010000, NTAG_I2C_2K = 0x020000, - MAGIC = 0x040000, + FUDAN_UL = 0x040000, + MAGIC = 0x080000, UL_MAGIC = UL | MAGIC, UL_C_MAGIC = UL_C | MAGIC, UL_ERROR = 0xFFFFFF, From 7c8b5e68110a08a78b6fc5d49175108d9e751345 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Sat, 20 Jun 2015 21:33:42 -0400 Subject: [PATCH 119/132] comment fudan check possibilities --- client/cmdhfmfu.c | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index a631b6b1..3dfee3a6 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -276,7 +276,20 @@ static int ulev1_readSignature( uint8_t *response, uint16_t responseLength ){ return len; } -//make sure field is off before calling this function + +// 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 +// UL responds with 00, fudan doesn't respond +// or +// send a200 + crc +// UL doesn't respond, fudan responds with 00 +// or +// send 300000 + crc (read with extra byte(s)) +// UL responds with read of page 0, fudan doesn't respond. +// +// make sure field is off before calling this function static int ul_fudan_check( void ){ iso14a_card_select_t card; if ( !ul_select(&card) ) From 467340996e7af6563070df2c96c374e6a97b1456 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Sun, 21 Jun 2015 18:00:42 +0200 Subject: [PATCH 120/132] fixing iso14443b (issue #103): - fix hf 14b snoop - fix hf 14b sim --- armsrc/iso14443b.c | 161 ++++++++++++++++++++-------------------- fpga/fpga_hf.bit | Bin 42175 -> 42175 bytes fpga/hi_read_rx_xcorr.v | 26 +++---- 3 files changed, 90 insertions(+), 97 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 8d1a5cca..1ae1692b 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -122,8 +122,7 @@ static struct { STATE_UNSYNCD, STATE_GOT_FALLING_EDGE_OF_SOF, STATE_AWAITING_START_BIT, - STATE_RECEIVING_DATA, - STATE_ERROR_WAIT + STATE_RECEIVING_DATA } state; uint16_t shiftReg; int bitCnt; @@ -145,7 +144,7 @@ static struct { * Returns: true if we received a EOF * false if we are still waiting for some more */ -static int Handle14443bUartBit(int bit) +static RAMFUNC int Handle14443bUartBit(uint8_t bit) { switch(Uart.state) { case STATE_UNSYNCD: @@ -172,7 +171,7 @@ static int Handle14443bUartBit(int bit) } else { // didn't stay down long enough // before going high, error - Uart.state = STATE_ERROR_WAIT; + Uart.state = STATE_UNSYNCD; } } else { // do nothing, keep waiting @@ -183,7 +182,8 @@ static int Handle14443bUartBit(int bit) if(Uart.bitCnt > 12) { // Give up if we see too many zeros without // a one, too. - Uart.state = STATE_ERROR_WAIT; + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; } break; @@ -193,7 +193,7 @@ static int Handle14443bUartBit(int bit) if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs // stayed high for too long between // characters, error - Uart.state = STATE_ERROR_WAIT; + Uart.state = STATE_UNSYNCD; } } else { // falling edge, this starts the data byte @@ -227,41 +227,30 @@ static int Handle14443bUartBit(int bit) if(Uart.byteCnt >= Uart.byteCntMax) { // Buffer overflowed, give up - Uart.posCnt = 0; - Uart.state = STATE_ERROR_WAIT; + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; } else { // so get the next byte now Uart.posCnt = 0; Uart.state = STATE_AWAITING_START_BIT; } - } else if(Uart.shiftReg == 0x000) { + } else if (Uart.shiftReg == 0x000) { // this is an EOF byte LED_A_OFF(); // Finished receiving + Uart.state = STATE_UNSYNCD; if (Uart.byteCnt != 0) { return TRUE; } - Uart.posCnt = 0; - Uart.state = STATE_ERROR_WAIT; } else { // this is an error - Uart.posCnt = 0; - Uart.state = STATE_ERROR_WAIT; + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; } } break; - case STATE_ERROR_WAIT: - // We're all screwed up, so wait a little while - // for whatever went wrong to finish, and then - // start over. - Uart.posCnt++; - if(Uart.posCnt > 10) { - Uart.state = STATE_UNSYNCD; - LED_A_OFF(); - } - break; - default: + LED_A_OFF(); Uart.state = STATE_UNSYNCD; break; } @@ -269,6 +258,23 @@ static int Handle14443bUartBit(int bit) return FALSE; } + +static void UartReset() +{ + Uart.byteCntMax = MAX_FRAME_SIZE; + Uart.state = STATE_UNSYNCD; + Uart.byteCnt = 0; + Uart.bitCnt = 0; +} + + +static void UartInit(uint8_t *data) +{ + Uart.output = data; + UartReset(); +} + + //----------------------------------------------------------------------------- // Receive a command (from the reader to us, where we are the simulated tag), // and store it in the given buffer, up to the given maximum length. Keeps @@ -278,44 +284,34 @@ static int Handle14443bUartBit(int bit) // Assume that we're called with the SSC (to the FPGA) and ADC path set // correctly. //----------------------------------------------------------------------------- -static int GetIso14443bCommandFromReader(uint8_t *received, int *len, int maxLen) +static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) { - uint8_t mask; - int i, bit; - // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen // only, since we are receiving, not transmitting). // Signal field is off with the appropriate LED LED_D_OFF(); FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION); - // Now run a `software UART' on the stream of incoming samples. - Uart.output = received; - Uart.byteCntMax = maxLen; - Uart.state = STATE_UNSYNCD; + UartInit(received); for(;;) { WDT_HIT(); if(BUTTON_PRESS()) return FALSE; - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0x00; - } if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - - mask = 0x80; - for(i = 0; i < 8; i++, mask >>= 1) { - bit = (b & mask); - if(Handle14443bUartBit(bit)) { + for(uint8_t mask = 0x80; mask != 0x00; mask >>= 1) { + if(Handle14443bUartBit(b & mask)) { *len = Uart.byteCnt; return TRUE; } } } } + + return FALSE; } //----------------------------------------------------------------------------- @@ -324,9 +320,12 @@ static int GetIso14443bCommandFromReader(uint8_t *received, int *len, int maxLen //----------------------------------------------------------------------------- void SimulateIso14443bTag(void) { - // the only command we understand is REQB, AFI=0, Select All, N=0: + // the only commands we understand is REQB, AFI=0, Select All, N=0: static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; - // ... and we respond with ATQB, PUPI = 820de174, Application Data = 0x20381922, + // ... and REQB, AFI=0, Normal Request, N=0: + static const uint8_t cmd2[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; + + // ... and 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: static const uint8_t response1[] = { @@ -334,25 +333,27 @@ void SimulateIso14443bTag(void) 0x00, 0x21, 0x85, 0x5e, 0xd7 }; - uint8_t *resp; - int respLen; + clear_trace(); + set_tracing(TRUE); + + const uint8_t *resp; + uint8_t *respCode; + uint16_t respLen, respCodeLen; // allocate command receive buffer BigBuf_free(); uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - int len; - int i; - - int cmdsRecvd = 0; + uint16_t len; + uint16_t cmdsRecvd = 0; FpgaDownloadAndGo(FPGA_BITSTREAM_HF); // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); - uint8_t *resp1 = BigBuf_malloc(ToSendMax); - memcpy(resp1, ToSend, ToSendMax); - uint16_t resp1Len = ToSendMax; + uint8_t *resp1Code = BigBuf_malloc(ToSendMax); + memcpy(resp1Code, ToSend, ToSendMax); + uint16_t resp1CodeLen = ToSendMax; // We need to listen to the high-frequency, peak-detected path. SetAdcMuxFor(GPIO_MUXSEL_HIPKD); @@ -361,20 +362,28 @@ void SimulateIso14443bTag(void) cmdsRecvd = 0; for(;;) { - uint8_t b1, b2; - if(!GetIso14443bCommandFromReader(receivedCmd, &len, 100)) { + if(!GetIso14443bCommandFromReader(receivedCmd, &len)) { Dbprintf("button pressed, received %d commands", cmdsRecvd); break; - } + } + + if (tracing) { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(receivedCmd, len, 0, 0, parity, TRUE); + } // Good, look at the command now. - - if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) { - resp = resp1; respLen = resp1Len; + if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) + || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) { + resp = response1; + respLen = sizeof(response1); + respCode = resp1Code; + respCodeLen = resp1CodeLen; } else { Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); // And print whether the CRC fails, just for good measure + uint8_t b1, b2; ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2); if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) { // Not so good, try again. @@ -392,7 +401,7 @@ void SimulateIso14443bTag(void) break; } - if(respLen <= 0) continue; + if(respCodeLen <= 0) continue; // Modulate BPSK // Signal field is off with the appropriate LED @@ -402,15 +411,15 @@ void SimulateIso14443bTag(void) FpgaSetupSsc(); // Transmit the response. - i = 0; + uint16_t i = 0; for(;;) { if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - uint8_t b = resp[i]; + uint8_t b = respCode[i]; AT91C_BASE_SSC->SSC_THR = b; i++; - if(i > respLen) { + if(i > respCodeLen) { break; } } @@ -419,6 +428,13 @@ void SimulateIso14443bTag(void) (void)b; } } + + // trace the response: + if (tracing) { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(resp, respLen, 0, 0, parity, FALSE); + } + } } @@ -436,8 +452,7 @@ static struct { DEMOD_AWAITING_FALLING_EDGE_OF_SOF, DEMOD_GOT_FALLING_EDGE_OF_SOF, DEMOD_AWAITING_START_BIT, - DEMOD_RECEIVING_DATA, - DEMOD_ERROR_WAIT + DEMOD_RECEIVING_DATA } state; int bitCount; int posCount; @@ -684,22 +699,6 @@ static void DemodInit(uint8_t *data) } -static void UartReset() -{ - Uart.byteCntMax = MAX_FRAME_SIZE; - Uart.state = STATE_UNSYNCD; - Uart.byteCnt = 0; - Uart.bitCnt = 0; -} - - -static void UartInit(uint8_t *data) -{ - Uart.output = data; - UartReset(); -} - - /* * Demodulate the samples we received from the tag, also log to tracebuffer * quiet: set to 'TRUE' to disable debug output @@ -1163,11 +1162,11 @@ void RAMFUNC SnoopIso14443b(void) /* false-triggered by the commands from the reader. */ DemodReset(); } - ReaderIsActive = (Uart.state != STATE_UNSYNCD); + ReaderIsActive = (Uart.state > STATE_GOT_FALLING_EDGE_OF_SOF); } if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time - if(Handle14443bSamplesDemod(ci & 0xFE, cq & 0xFE)) { + if(Handle14443bSamplesDemod(ci | 0x01, cq | 0x01)) { //Use samples as a time measurement if(tracing) diff --git a/fpga/fpga_hf.bit b/fpga/fpga_hf.bit index 49bec2242cb7720524289f3eba1397bbc2a22867..a4d72e373bb59cfa56cc3869b1ccb3c18908250a 100644 GIT binary patch literal 42175 zcmeIbe{@{cbvC@`-jRHz8F{W{n{`A=`8+o`_uFIJ@f^3LU{6n&Z^ovGy?>`1Nb=v+=4sc!kI)v3j6JYBF>lw!~8U35YAlwvdbSLi|kPiFLTXn=pe<1@li5-gxY)Y>q#_TX5&dYoaQ#P_!PY@JMEYm>7ujLZO2CSJ0OhOv4UO< ztNxTikJ6b-dhFP9`Yc_b9*UKf@VE_OhSYn6`4G(*cuzq;MNesX&wdDJX|?kni@$23 zCP_b_-4fq^p0-i@y314ADSDh%a(~_=!EH)4>uE3L?Z~CtGc+`qEMhp5=<|pTVFp_a zKUQcd?awurBDZQUSzEGg`O7zJFVO+{nNno4HsQRd&xq0+W@P6Z@ZQ;m(_98uQTx~;m&Y5SM(C2*fKxA|OdHOrqR*3Ye zK4TP{wK7@!U44tNroyteeF#H-fRa{()Yua|_UFQCO{W)+(0Q>h|7^ZxnqHu;e5|BT z(>pXOV|o1@=ezo-WXxFI6dTq{G))jBgt8+%2NlMTVNTH*S}F9y`Y~}l*KOaM)A>oK zh~@M#=euNhBki4ti<`fty(+g(vF-c_@k}lw~2F` zW6oL_;V{OP7ZFn%4-Ik~2(;I-_{o?uBXqDKO*3*OclDLs6X@!8*;1kz>f|TC)cg6n zc3v?>=j_M1hbPh1Zo8$ZPleB{>gFe})()utgwUqcDWW<3ZTdBa1Hm8HF=xG2nI$?{ z-c1b>qc}**sNNCc6p`99&e)9_^bjLOSD%DnxqXJ9`s{qy;yrZ8jEg#FT9&P=-=XHm z8N0I<`9*u^j7)tznp-$!oT1b}bSK)JA?&D}KJDmNg7(lG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XDmxpgF)nO)kD(4=-1)d1^!Q^W@brCf*+XjSV~TNo(AM^ zUfii30xr*Z{(^=-rt`WYzRxY;dl8`b`)ha}E{F7saasRJ$bPG;$>Ju#doF1BW9YhU zWF6x8A5*gm7c`1z1N&8m%Nn2^52=gq!hV(EvMd5LdYM5NfL;13AV zLq)kv>U8I1D&oef3mVdY&Uv^T05mteA^ff~Tn+%58^w1S@^3R*1Vo#q@ma6w~#@m;GT*?l#c>*KR}FK8%# z4Gl?U=0p_jif-r!Nuz_|m{C~ca#=$a-zD2SXU&ORXUuw^MsdGFzF6Rtd5z*;Pzi+t zI1U=#tFT|6F#lA(GJ5rrstX&kC|Ab?5DpzGXj;o8fT-I1w9PRrMS5Tr>zh^Y(*& z Date: Mon, 22 Jun 2015 14:20:13 +0200 Subject: [PATCH 121/132] Add PACE replay functionality This function allows the user to specify APDUs which are sent to a card supporting the PACE protocol. The response times are measured and printed. The code was pulled from the old Google Code repository (branch "epa") and modified to fit into the new code base. --- armsrc/appmain.c | 3 + armsrc/apps.h | 1 + armsrc/epa.c | 145 +++++++++++++++++++++++++++++++++++----------- armsrc/epa.h | 4 +- client/cmdhfepa.c | 122 ++++++++++++++++++++++++++++++++++++-- include/usb_cmd.h | 1 + 6 files changed, 234 insertions(+), 42 deletions(-) diff --git a/armsrc/appmain.c b/armsrc/appmain.c index c226c726..bd1075c1 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -816,6 +816,9 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_EPA_PACE_COLLECT_NONCE: EPA_PACE_Collect_Nonce(c); break; + case CMD_EPA_PACE_REPLAY: + EPA_PACE_Replay(c); + break; case CMD_READER_MIFARE: ReaderMifare(c->arg[0]); diff --git a/armsrc/apps.h b/armsrc/apps.h index 6360b664..715e7002 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -160,6 +160,7 @@ void RAMFUNC SniffMifare(uint8_t param); /// epa.h void EPA_PACE_Collect_Nonce(UsbCommand * c); +void EPA_PACE_Replay(UsbCommand *c); // mifarecmd.h void ReaderMifare(bool first_try); diff --git a/armsrc/epa.c b/armsrc/epa.c index 0006d59d..6bd8692e 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -5,7 +5,7 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// Routines to support the German eletronic "Personalausweis" (ID card) +// Routines to support the German electronic "Personalausweis" (ID card) // Note that the functions which do not implement USB commands do NOT initialize // the card (with iso14443a_select_card etc.). If You want to use these // functions, You need to do the setup before calling them! @@ -74,6 +74,32 @@ static const uint8_t oid_pace_start[] = { 0x04 // id-PACE }; +// APDUs for replaying: +// MSE: Set AT (initiate PACE) +static uint8_t apdu_replay_mse_set_at_pace[41]; +// General Authenticate (Get Nonce) +static uint8_t apdu_replay_general_authenticate_pace_get_nonce[8]; +// General Authenticate (Map Nonce) +static uint8_t apdu_replay_general_authenticate_pace_map_nonce[75]; +// General Authenticate (Mutual Authenticate) +static uint8_t apdu_replay_general_authenticate_pace_mutual_authenticate[75]; +// General Authenticate (Perform Key Agreement) +static uint8_t apdu_replay_general_authenticate_pace_perform_key_agreement[18]; +// pointers to the APDUs (for iterations) +static struct { + uint8_t len; + uint8_t *data; +} const apdus_replay[] = { + {sizeof(apdu_replay_mse_set_at_pace), apdu_replay_mse_set_at_pace}, + {sizeof(apdu_replay_general_authenticate_pace_get_nonce), apdu_replay_general_authenticate_pace_get_nonce}, + {sizeof(apdu_replay_general_authenticate_pace_map_nonce), apdu_replay_general_authenticate_pace_map_nonce}, + {sizeof(apdu_replay_general_authenticate_pace_mutual_authenticate), apdu_replay_general_authenticate_pace_mutual_authenticate}, + {sizeof(apdu_replay_general_authenticate_pace_perform_key_agreement), apdu_replay_general_authenticate_pace_perform_key_agreement} +}; + +// lengths of the replay APDUs +static uint8_t apdu_lengths_replay[5]; + //----------------------------------------------------------------------------- // Closes the communication channel and turns off the field //----------------------------------------------------------------------------- @@ -101,7 +127,7 @@ size_t EPA_Parse_CardAccess(uint8_t *data, pace_version_info_t *pace_info) { size_t index = 0; - + while (index <= length - 2) { // determine type of element // SET or SEQUENCE @@ -158,7 +184,7 @@ size_t EPA_Parse_CardAccess(uint8_t *data, index += 2 + data[index + 1]; } } - + // TODO: We should check whether we reached the end in error, but for that // we need a better parser (e.g. with states like IN_SET or IN_PACE_INFO) return 0; @@ -176,7 +202,7 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) // we reserve 262 bytes here just to be safe (256-byte APDU + SW + ISO frame) uint8_t response_apdu[262]; int rapdu_length = 0; - + // select the file EF.CardAccess rapdu_length = iso14_apdu((uint8_t *)apdu_select_binary_cardaccess, sizeof(apdu_select_binary_cardaccess), @@ -188,7 +214,7 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) Dbprintf("epa - no select cardaccess"); return -1; } - + // read the file rapdu_length = iso14_apdu((uint8_t *)apdu_read_binary, sizeof(apdu_read_binary), @@ -200,7 +226,7 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) Dbprintf("epa - no read cardaccess"); return -1; } - + // copy the content into the buffer // length of data available: apdu_length - 4 (ISO frame) - 2 (SW) size_t to_copy = rapdu_length - 6; @@ -215,16 +241,11 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) //----------------------------------------------------------------------------- static void EPA_PACE_Collect_Nonce_Abort(uint8_t step, int func_return) { -// // step in which the failure occured -// ack->arg[0] = step; -// // last return code -// ack->arg[1] = func_return; - // power down the field EPA_Finish(); - + // send the USB packet - cmd_send(CMD_ACK,step,func_return,0,0,0); + cmd_send(CMD_ACK,step,func_return,0,0,0); } //----------------------------------------------------------------------------- @@ -246,10 +267,6 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) // return value of a function int func_return = 0; -// // initialize ack with 0s -// memset(ack->arg, 0, 12); -// memset(ack->d.asBytes, 0, 48); - // set up communication func_return = EPA_Setup(); if (func_return != 0) { @@ -277,11 +294,11 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) EPA_PACE_Collect_Nonce_Abort(3, func_return); return; } - + // initiate the PACE protocol // use the CAN for the password since that doesn't change func_return = EPA_PACE_MSE_Set_AT(pace_version_info, 2); - + // now get the nonce uint8_t nonce[256] = {0}; uint8_t requested_size = (uint8_t)c->arg[0]; @@ -292,14 +309,12 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) EPA_PACE_Collect_Nonce_Abort(4, func_return); return; } - - // all done, return + + // all done, return EPA_Finish(); - + // save received information -// ack->arg[1] = func_return; -// memcpy(ack->d.asBytes, nonce, func_return); - cmd_send(CMD_ACK,0,func_return,0,nonce,func_return); + cmd_send(CMD_ACK,0,func_return,0,nonce,func_return); } //----------------------------------------------------------------------------- @@ -320,7 +335,7 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) sizeof(apdu_general_authenticate_pace_get_nonce)); // append Le (requested length + 2 due to tag/length taking 2 bytes) in RAPDU apdu[sizeof(apdu_general_authenticate_pace_get_nonce)] = requested_length + 4; - + // send it uint8_t response_apdu[262]; int send_return = iso14_apdu(apdu, @@ -333,7 +348,7 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) { return -1; } - + // if there is no nonce in the RAPDU, return here if (send_return < 10) { @@ -348,7 +363,7 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) } // copy the nonce memcpy(nonce, response_apdu + 6, nonce_length); - + return nonce_length; } @@ -407,13 +422,79 @@ int EPA_PACE_MSE_Set_AT(pace_version_info_t pace_version_info, uint8_t password) return 0; } +//----------------------------------------------------------------------------- +// Perform the PACE protocol by replaying given APDUs +//----------------------------------------------------------------------------- +void EPA_PACE_Replay(UsbCommand *c) +{ + uint32_t timings[sizeof(apdu_lengths_replay) / sizeof(apdu_lengths_replay[0])] = {0}; + + // if an APDU has been passed, save it + if (c->arg[0] != 0) { + // make sure it's not too big + if(c->arg[2] > apdus_replay[c->arg[0] - 1].len) + { + cmd_send(CMD_ACK, 1, 0, 0, NULL, 0); + } + memcpy(apdus_replay[c->arg[0] - 1].data + c->arg[1], + c->d.asBytes, + c->arg[2]); + // save/update APDU length + if (c->arg[1] == 0) { + apdu_lengths_replay[c->arg[0] - 1] = c->arg[2]; + } else { + apdu_lengths_replay[c->arg[0] - 1] += c->arg[2]; + } + cmd_send(CMD_ACK, 0, 0, 0, NULL, 0); + return; + } + + // return value of a function + int func_return; + + // set up communication + func_return = EPA_Setup(); + if (func_return != 0) { + EPA_Finish(); + cmd_send(CMD_ACK, 2, func_return, 0, NULL, 0); + return; + } + + // increase the timeout (at least some cards really do need this!)///////////// + // iso14a_set_timeout(0x0003FFFF); + + // response APDU + uint8_t response_apdu[300] = {0}; + + // now replay the data and measure the timings + for (int i = 0; i < sizeof(apdu_lengths_replay); i++) { + StartCountUS(); + func_return = iso14_apdu(apdus_replay[i].data, + apdu_lengths_replay[i], + response_apdu); + timings[i] = GetCountUS(); + // every step but the last one should succeed + if (i < sizeof(apdu_lengths_replay) - 1 + && (func_return < 6 + || response_apdu[func_return - 4] != 0x90 + || response_apdu[func_return - 3] != 0x00)) + { + EPA_Finish(); + cmd_send(CMD_ACK, 3 + i, func_return, 0, timings, 20); + return; + } + } + EPA_Finish(); + cmd_send(CMD_ACK,0,0,0,timings,20); + return; +} + //----------------------------------------------------------------------------- // Set up a communication channel (Card Select, PPS) // Returns 0 on success or a non-zero error code on failure //----------------------------------------------------------------------------- int EPA_Setup() { - int return_code = 0; uint8_t uid[10]; uint8_t pps_response[3]; @@ -422,20 +503,16 @@ int EPA_Setup() // power up the field iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - // select the card return_code = iso14443a_select_card(uid, &card_select_info, NULL); if (return_code != 1) { - Dbprintf("Epa: Can't select card"); return 1; } - // send the PPS request ReaderTransmit((uint8_t *)pps, sizeof(pps), NULL); return_code = ReaderReceive(pps_response, pps_response_par); if (return_code != 3 || pps_response[0] != 0xD0) { return return_code == 0 ? 2 : return_code; } - return 0; -} \ No newline at end of file +} diff --git a/armsrc/epa.h b/armsrc/epa.h index 730652b7..0c580205 100644 --- a/armsrc/epa.h +++ b/armsrc/epa.h @@ -19,7 +19,7 @@ typedef struct { uint8_t parameter_id; } pace_version_info_t; -// note: EPA_PACE_GetNonce is declared in apps.h +// note: EPA_PACE_Collect_Nonce is declared in apps.h // general functions void EPA_Finish(); @@ -33,4 +33,4 @@ int EPA_Setup(); int EPA_PACE_MSE_Set_AT(pace_version_info_t pace_version_info, uint8_t password); int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce); -#endif /* __EPA_H */ \ No newline at end of file +#endif /* __EPA_H */ diff --git a/client/cmdhfepa.c b/client/cmdhfepa.c index 3286ceb9..e9c63f20 100644 --- a/client/cmdhfepa.c +++ b/client/cmdhfepa.c @@ -9,7 +9,7 @@ //----------------------------------------------------------------------------- #include "util.h" -//#include "proxusb.h" + #include "proxmark3.h" #include "ui.h" #include "cmdparser.h" @@ -29,9 +29,9 @@ int CmdHFEPACollectPACENonces(const char *Cmd) unsigned int n = 0; // delay between requests unsigned int d = 0; - + sscanf(Cmd, "%u %u %u", &m, &n, &d); - + // values are expected to be > 0 m = m > 0 ? m : 1; n = n > 0 ? n : 1; @@ -44,7 +44,7 @@ int CmdHFEPACollectPACENonces(const char *Cmd) UsbCommand c = {CMD_EPA_PACE_COLLECT_NONCE, {(int)m, 0, 0}}; SendCommand(&c); UsbCommand resp; - + WaitForResponse(CMD_ACK,&resp); // check if command failed @@ -68,13 +68,123 @@ int CmdHFEPACollectPACENonces(const char *Cmd) return 1; } +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////The commands lie below here///////////////////////////////////////////////////////////////////////////////////////// + +// perform the PACE protocol by replaying APDUs +int CmdHFEPAPACEReplay(const char *Cmd) +{ + // the 4 APDUs which are replayed + their lengths + uint8_t msesa_apdu[41], gn_apdu[8], map_apdu[75]; + uint8_t pka_apdu[75], ma_apdu[18], apdu_lengths[5] = {0}; + // pointers to the arrays to be able to iterate + uint8_t *apdus[] = {msesa_apdu, gn_apdu, map_apdu, pka_apdu, ma_apdu}; + + // usage message + static const char const *usage_msg = + "Please specify 5 APDUs separated by spaces. " + "Example:\n preplay 0022C1A4 1068000000 1086000002 1234ABCDEF 1A2B3C4D"; + + // Proxmark response + UsbCommand resp; + + int skip = 0, skip_add = 0, scan_return = 0; + // for each APDU + for (int i = 0; i < sizeof(apdu_lengths); i++) { + // scan to next space or end of string + while (Cmd[skip] != ' ' && Cmd[skip] != '\0') { + // convert + scan_return = sscanf(Cmd + skip, "%2X%n", + (unsigned int *) (apdus[i] + apdu_lengths[i]), + &skip_add); + if (scan_return < 1) { + PrintAndLog((char *)usage_msg); + PrintAndLog("Not enough APDUs! Try again!"); + return 0; + } + skip += skip_add; + apdu_lengths[i]++; + } + + // break on EOF + if (Cmd[skip] == '\0') { + if (i < sizeof(apdu_lengths) - 1) { + + PrintAndLog((char *)usage_msg); + return 0; + } + break; + } + // skip the space + skip++; + } + + // transfer the APDUs to the Proxmark + UsbCommand usb_cmd; + usb_cmd.cmd = CMD_EPA_PACE_REPLAY; + for (int i = 0; i < sizeof(apdu_lengths); i++) { + // APDU number + usb_cmd.arg[0] = i + 1; + // transfer the APDU in several parts if necessary + for (int j = 0; j * sizeof(usb_cmd.d.asBytes) < apdu_lengths[i]; j++) { + // offset into the APDU + usb_cmd.arg[1] = j * sizeof(usb_cmd.d.asBytes); + // amount of data in this packet + int packet_length = apdu_lengths[i] - (j * sizeof(usb_cmd.d.asBytes)); + if (packet_length > sizeof(usb_cmd.d.asBytes)) { + packet_length = sizeof(usb_cmd.d.asBytes); + } + usb_cmd.arg[2] = packet_length; + + memcpy(usb_cmd.d.asBytes, // + (j * sizeof(usb_cmd.d.asBytes)), + apdus[i] + (j * sizeof(usb_cmd.d.asBytes)), + packet_length); + SendCommand(&usb_cmd); + WaitForResponse(CMD_ACK, &resp); + if (resp.arg[0] != 0) { + PrintAndLog("Transfer of APDU #%d Part %d failed!", i, j); + return 0; + } + } + } + + // now perform the replay + usb_cmd.arg[0] = 0; + SendCommand(&usb_cmd); + WaitForResponse(CMD_ACK, &resp); + if (resp.arg[0] != 0) { + PrintAndLog("\nPACE replay failed in step %u!", (uint32_t)resp.arg[0]); + PrintAndLog("Measured times:"); + PrintAndLog("MSE Set AT: %u us", resp.d.asDwords[0]); + PrintAndLog("GA Get Nonce: %u us", resp.d.asDwords[1]); + PrintAndLog("GA Map Nonce: %u us", resp.d.asDwords[2]); + PrintAndLog("GA Perform Key Agreement: %u us", resp.d.asDwords[3]); + PrintAndLog("GA Mutual Authenticate: %u us", resp.d.asDwords[4]); + } else { + PrintAndLog("PACE replay successfull!"); + PrintAndLog("MSE Set AT: %u us", resp.d.asDwords[0]); + PrintAndLog("GA Get Nonce: %u us", resp.d.asDwords[1]); + PrintAndLog("GA Map Nonce: %u us", resp.d.asDwords[2]); + PrintAndLog("GA Perform Key Agreement: %u us", resp.d.asDwords[3]); + PrintAndLog("GA Mutual Authenticate: %u us", resp.d.asDwords[4]); + } + + + return 1; +} + +////////////////////////////////The new commands lie above here///////////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // UI-related stuff -static const command_t CommandTable[] = +static const command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, {"cnonces", CmdHFEPACollectPACENonces, 0, " Acquire n>0 encrypted PACE nonces of size m>0 with d sec pauses"}, + {"preplay", CmdHFEPAPACEReplay, 0, + " Perform PACE protocol by replaying given APDUs"}, {NULL, NULL, 0, NULL} }; @@ -92,4 +202,4 @@ int CmdHFEPA(const char *Cmd) // parse CmdsParse(CommandTable, Cmd); return 0; -} \ No newline at end of file +} diff --git a/include/usb_cmd.h b/include/usb_cmd.h index 357395d4..169f30cf 100644 --- a/include/usb_cmd.h +++ b/include/usb_cmd.h @@ -128,6 +128,7 @@ typedef struct{ #define CMD_READER_LEGIC_RF 0x0388 #define CMD_WRITER_LEGIC_RF 0x0389 #define CMD_EPA_PACE_COLLECT_NONCE 0x038A +#define CMD_EPA_PACE_REPLAY 0x038B #define CMD_SNOOP_ICLASS 0x0392 #define CMD_SIMULATE_TAG_ICLASS 0x0393 From 705bfa1058837ae60f014458b0a01e88cdf5839d Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Mon, 22 Jun 2015 21:45:28 +0200 Subject: [PATCH 122/132] fixing iso14443b (issue #103): - increased DMA_BUFFER_SIZE to avoid occasional circular buffer overflows. - minor code cleanups --- armsrc/iso14443b.c | 93 ++++++++++++++-------------------------- fpga/fpga_hf.bit | Bin 42175 -> 42175 bytes fpga/hi_read_rx_xcorr.v | 4 +- 3 files changed, 33 insertions(+), 64 deletions(-) diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 1ae1692b..416c31f9 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -17,6 +17,7 @@ #include "iso14443crc.h" #define RECEIVE_SAMPLES_TIMEOUT 2000 +#define ISO14443B_DMA_BUFFER_SIZE 256 //============================================================================= // An ISO 14443 Type B tag. We listen for commands from the reader, using @@ -717,16 +718,16 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); // The DMA buffer, used to stream samples from the FPGA - int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse); // Setup and start DMA. - FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); + FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); int8_t *upTo = dmaBuf; - lastRxCounter = DMA_BUFFER_SIZE; + lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; // Signal field is ON with the appropriate LED: LED_D_ON(); @@ -737,18 +738,18 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; if(behindBy > max) max = behindBy; - while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1)) > 2) { + while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (ISO14443B_DMA_BUFFER_SIZE-1)) > 2) { ci = upTo[0]; cq = upTo[1]; upTo += 2; - if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { + if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { upTo = dmaBuf; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; - AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; } lastRxCounter -= 2; if(lastRxCounter <= 0) { - lastRxCounter += DMA_BUFFER_SIZE; + lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; } samples += 2; @@ -770,7 +771,6 @@ static void GetSamplesFor14443bDemod(int n, bool quiet) //Tracing if (tracing && Demod.len > 0) { uint8_t parity[MAX_PARITY_SIZE]; - //GetParity(Demod.output, Demod.len, parity); LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE); } } @@ -892,7 +892,6 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) TransmitFor14443b(); if (tracing) { uint8_t parity[MAX_PARITY_SIZE]; - GetParity(cmd, len, parity); LogTrace(cmd,len, 0, 0, parity, TRUE); } } @@ -927,35 +926,29 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) // Now give it time to spin up. // Signal field is on with the appropriate LED LED_D_ON(); - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); SpinDelay(200); // First command: wake up the tag using the INITIATE command uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; - CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); -// LED_A_ON(); GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); -// LED_A_OFF(); if (Demod.len == 0) { - DbpString("No response from tag"); - return; + DbpString("No response from tag"); + return; } else { - Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %02x %02x %02x", - Demod.output[0], Demod.output[1], Demod.output[2]); + Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x", + Demod.output[0], Demod.output[1], Demod.output[2]); } + // There is a response, SELECT the uid DbpString("Now SELECT tag:"); cmd1[0] = 0x0E; // 0x0E is SELECT cmd1[1] = Demod.output[0]; ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]); CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); - -// LED_A_ON(); GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); -// LED_A_OFF(); if (Demod.len != 3) { Dbprintf("Expected 3 bytes from tag, got %d", Demod.len); return; @@ -971,15 +964,13 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1[1], Demod.output[0]); return; } + // Tag is now selected, // First get the tag's UID: cmd1[0] = 0x0B; ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]); CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one - -// LED_A_ON(); GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); -// LED_A_OFF(); if (Demod.len != 10) { Dbprintf("Expected 10 bytes from tag, got %d", Demod.len); return; @@ -988,12 +979,12 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]); if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) { Dbprintf("CRC Error reading block! Expected: %04x got: %04x", - (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); + (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); // Do not return;, let's go on... (we should retry, maybe ?) } Dbprintf("Tag UID (64 bits): %08x %08x", - (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], - (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); + (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], + (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); // Now loop to read all 16 blocks, address from 0 to last block Dbprintf("Tag memory dump, block 0 to %d", dwLast); @@ -1008,10 +999,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) cmd1[1] = i; ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]); CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); - -// LED_A_ON(); GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); -// LED_A_OFF(); if (Demod.len != 6) { // Check if we got an answer from the tag DbpString("Expected 6 bytes from tag, got less..."); return; @@ -1020,13 +1008,13 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]); if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) { Dbprintf("CRC Error reading block! Expected: %04x got: %04x", - (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); + (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); // Do not return;, let's go on... (we should retry, maybe ?) } // 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], - (Demod.output[4]<<8)+Demod.output[5]); + (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], + (Demod.output[4]<<8)+Demod.output[5]); if (i == 0xff) { break; } @@ -1049,7 +1037,7 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) * Memory usage for this function, (within BigBuf) * Last Received command (reader->tag) - MAX_FRAME_SIZE * Last Received command (tag->reader) - MAX_FRAME_SIZE - * DMA Buffer - DMA_BUFFER_SIZE + * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE * Demodulated samples received - all the rest */ void RAMFUNC SnoopIso14443b(void) @@ -1066,7 +1054,7 @@ void RAMFUNC SnoopIso14443b(void) set_tracing(TRUE); // The DMA buffer, used to stream samples from the FPGA - int8_t *dmaBuf = (int8_t*) BigBuf_malloc(DMA_BUFFER_SIZE); + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); int lastRxCounter; int8_t *upTo; int ci, cq; @@ -1084,7 +1072,7 @@ void RAMFUNC SnoopIso14443b(void) Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen()); Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE); Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE); - Dbprintf(" DMA: %i bytes", DMA_BUFFER_SIZE); + Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE); // Signal field is off, no reader signal, no tag signal LEDsoff(); @@ -1096,8 +1084,8 @@ void RAMFUNC SnoopIso14443b(void) // Setup for the DMA. FpgaSetupSsc(); upTo = dmaBuf; - lastRxCounter = DMA_BUFFER_SIZE; - FpgaSetupSscDma((uint8_t*) dmaBuf, DMA_BUFFER_SIZE); + lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; + FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); uint8_t parity[MAX_PARITY_SIZE]; bool TagIsActive = FALSE; @@ -1106,7 +1094,7 @@ void RAMFUNC SnoopIso14443b(void) // And now we loop, receiving samples. for(;;) { int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & - (DMA_BUFFER_SIZE-1); + (ISO14443B_DMA_BUFFER_SIZE-1); if(behindBy > maxBehindBy) { maxBehindBy = behindBy; } @@ -1117,13 +1105,13 @@ void RAMFUNC SnoopIso14443b(void) cq = upTo[1]; upTo += 2; lastRxCounter -= 2; - if(upTo >= dmaBuf + DMA_BUFFER_SIZE) { + if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { upTo = dmaBuf; - lastRxCounter += DMA_BUFFER_SIZE; + lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; - AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; WDT_HIT(); - if(behindBy > (9*DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? + if(behindBy > (9*ISO14443B_DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? Dbprintf("blew circular buffer! behindBy=%d", behindBy); break; } @@ -1142,7 +1130,6 @@ void RAMFUNC SnoopIso14443b(void) if (!TagIsActive) { // no need to try decoding reader data if the tag is sending if(Handle14443bUartBit(ci & 0x01)) { if(triggered && tracing) { - //GetParity(Uart.output, Uart.byteCnt, parity); LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); } /* And ready to receive another command. */ @@ -1153,7 +1140,6 @@ void RAMFUNC SnoopIso14443b(void) } if(Handle14443bUartBit(cq & 0x01)) { if(triggered && tracing) { - //GetParity(Uart.output, Uart.byteCnt, parity); LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); } /* And ready to receive another command. */ @@ -1172,7 +1158,6 @@ void RAMFUNC SnoopIso14443b(void) if(tracing) { uint8_t parity[MAX_PARITY_SIZE]; - //GetParity(Demod.output, Demod.len, parity); LogTrace(Demod.output, Demod.len, samples, samples, parity, FALSE); } triggered = TRUE; @@ -1217,22 +1202,6 @@ void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, u set_tracing(TRUE); -/* if(!powerfield) { - // Make sure that we start from off, since the tags are stateful; - // confusing things will happen if we don't reset them between reads. - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - LED_D_OFF(); - SpinDelay(200); - } - */ - - // if(!GETBIT(GPIO_LED_D)) { // if field is off - // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); - // // Signal field is on with the appropriate LED - // LED_D_ON(); - // SpinDelay(200); - // } - CodeAndTransmit14443bAsReader(data, datalen); if(recv) { diff --git a/fpga/fpga_hf.bit b/fpga/fpga_hf.bit index a4d72e373bb59cfa56cc3869b1ccb3c18908250a..50c7eef97c8b98461b7d8be9e4e643dd85910241 100644 GIT binary patch literal 42175 zcmeIbe|%ikbuYSRpCfTRGx8kEGEX6f9F2rCxFcySJKz{u+LjGfgA>$*ByKBAS-q+r@H4-5INIapmbyC_lHcqOfv>nUF7(?J#2r>o%x(+YTp)MV$Ac8nl z7>CIC*ZZ!0&YU^2livJs-{-y0r>LJ#Sl!w_Xa8F3yS{6!eMIvTGv5CZMQ*2sU+n+= z+yB>1Uu^B)eES!EZ)4k+zOa$*plHWemS_IAJC|iL^aYA_WR`uTJ#&3~M+a@Bc^%7E zt+-*;M^@195$)~2h@bC$^V46Njgj2o6<$&b$XV%vgwSG7Eh{< zLcC~9n)*5A$YXSox;G|fjEnOxQkP83tUX5;@9Vxd@t847`Z>~m5YOpy@vmAST<^{= z8vNuAg%;a%_*JEvG{)2BrbYz|$s>AT5QZ_q4wBrbT(jPr*UD%Mge5YX5ho-2$thr_ zD{;i|<3z5ZhgJJVYm2xNLQ{5li+I_3LNyh7w+PF7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zF~`%K^PWl6)R?p-)jY{F@4knsMm0z%tRxLlLZ!TJfAEj2D6?8Pw};-y(W2tO@Nc0Q z5dTHEXp;XQg)Q~Z@9>|luK%D>EcPFK_@DJr&xH#YY<~I0g8!8lf8;;;|81K&y6h`8 z1i#P!r*!#ud5^Dg7YlBG{sRqEA91t)L|tBT!c%Hb2a#?2tzMho=08Q3tBvQo>T*D3 z1GWxRH0J~Svj4=L=xSYdAA0}1r_1kV3jV* Date: Tue, 23 Jun 2015 12:16:23 -0400 Subject: [PATCH 123/132] fix bug in pskdemod return value if no samples... ... caused crash in data psknexwatchdemod if no samples were in the graphbuffer. also fixed hf mfu wrbl and rdbl to allow printing of help without a tag being present. --- client/cmddata.c | 4 ++-- client/cmdhfmfu.c | 56 ++++++++++++++++++++++------------------------- 2 files changed, 28 insertions(+), 32 deletions(-) diff --git a/client/cmddata.c b/client/cmddata.c index aa1170fc..bec1b5aa 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -1546,12 +1546,12 @@ int PSKDemod(const char *Cmd, bool verbose) clk=0; } if (invert != 0 && invert != 1) { - if (verbose) PrintAndLog("Invalid argument: %s", Cmd); + if (g_debugMode || verbose) PrintAndLog("Invalid argument: %s", Cmd); return 0; } uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; size_t BitLen = getFromGraphBuf(BitStream); - if (BitLen==0) return -1; + if (BitLen==0) return 0; uint8_t carrier=countFC(BitStream, BitLen, 0); if (carrier!=2 && carrier!=4 && carrier!=8){ //invalid carrier diff --git a/client/cmdhfmfu.c b/client/cmdhfmfu.c index 3dfee3a6..25a073d3 100644 --- a/client/cmdhfmfu.c +++ b/client/cmdhfmfu.c @@ -908,10 +908,6 @@ int CmdHF14AMfUWrBl(const char *Cmd){ uint8_t authenticationkey[16] = {0x00}; uint8_t *authKeyPtr = authenticationkey; - // starting with getting tagtype - TagTypeUL_t tagtype = GetHF14AMfU_Type(); - if (tagtype == UL_ERROR) return -1; - while(param_getchar(Cmd, cmdp) != 0x00) { switch(param_getchar(Cmd, cmdp)) @@ -943,21 +939,10 @@ int CmdHF14AMfUWrBl(const char *Cmd){ case 'b': case 'B': blockNo = param_get8(Cmd, cmdp+1); - - uint8_t maxblockno = 0; - for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++){ - if (tagtype & UL_TYPES_ARRAY[idx]) - maxblockno = UL_MEMORY_ARRAY[idx]; - } - if (blockNo < 0) { PrintAndLog("Wrong block number"); errors = true; } - if (blockNo > maxblockno){ - PrintAndLog("block number too large. Max block is %u/0x%02X \n", maxblockno,maxblockno); - errors = true; - } cmdp += 2; break; case 'l': @@ -984,6 +969,19 @@ int CmdHF14AMfUWrBl(const char *Cmd){ } if ( blockNo == -1 ) return usage_hf_mfu_wrbl(); + // starting with getting tagtype + TagTypeUL_t tagtype = GetHF14AMfU_Type(); + if (tagtype == UL_ERROR) return -1; + + uint8_t maxblockno = 0; + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++){ + if (tagtype & UL_TYPES_ARRAY[idx]) + maxblockno = UL_MEMORY_ARRAY[idx]; + } + if (blockNo > maxblockno){ + PrintAndLog("block number too large. Max block is %u/0x%02X \n", maxblockno,maxblockno); + return usage_hf_mfu_wrbl(); + } // Swap endianness if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, 16, 8); @@ -1035,10 +1033,6 @@ int CmdHF14AMfURdBl(const char *Cmd){ uint8_t authenticationkey[16] = {0x00}; uint8_t *authKeyPtr = authenticationkey; - // starting with getting tagtype - TagTypeUL_t tagtype = GetHF14AMfU_Type(); - if (tagtype == UL_ERROR) return -1; - while(param_getchar(Cmd, cmdp) != 0x00) { switch(param_getchar(Cmd, cmdp)) @@ -1070,21 +1064,10 @@ int CmdHF14AMfURdBl(const char *Cmd){ case 'b': case 'B': blockNo = param_get8(Cmd, cmdp+1); - - uint8_t maxblockno = 0; - for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++){ - if (tagtype & UL_TYPES_ARRAY[idx]) - maxblockno = UL_MEMORY_ARRAY[idx]; - } - if (blockNo < 0) { PrintAndLog("Wrong block number"); errors = true; } - if (blockNo > maxblockno){ - PrintAndLog("block number to large. Max block is %u/0x%02X \n", maxblockno,maxblockno); - errors = true; - } cmdp += 2; break; case 'l': @@ -1102,6 +1085,19 @@ int CmdHF14AMfURdBl(const char *Cmd){ } if ( blockNo == -1 ) return usage_hf_mfu_rdbl(); + // start with getting tagtype + TagTypeUL_t tagtype = GetHF14AMfU_Type(); + if (tagtype == UL_ERROR) return -1; + + uint8_t maxblockno = 0; + for (uint8_t idx = 0; idx < MAX_UL_TYPES; idx++){ + if (tagtype & UL_TYPES_ARRAY[idx]) + maxblockno = UL_MEMORY_ARRAY[idx]; + } + if (blockNo > maxblockno){ + PrintAndLog("block number to large. Max block is %u/0x%02X \n", maxblockno,maxblockno); + return usage_hf_mfu_rdbl(); + } // Swap endianness if (swapEndian && hasAuthKey) authKeyPtr = SwapEndian64(authenticationkey, 16, 8); From 475aefa5958d0eab881b5b140e0d0e59571f397c Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Tue, 23 Jun 2015 22:12:03 +0200 Subject: [PATCH 124/132] Updated changelog --- CHANGELOG.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c016c3d..5a6ac620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,11 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... ## [Unreleased][unreleased] + + + +## [2.1.0][2015-06-23] + ### Changed - Added ultralight/ntag tag type detection to `hf 14a read` (marshmellow) - Improved ultralight dump command to auto detect tag type, take authentication, and dump full memory (or subset specified) of known tag types (iceman1001 / marshmellow) @@ -14,6 +19,7 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ### Fixed - Fixed EM4x50 read/demod of the tags broadcasted memory blocks. 'lf em4x em4x50read' (not page read) (marshmellow) - Fixed issue #19, problems with LF T55xx commands (iceman1001, marshmellow) +- Fixed various problems with iso14443b, issue #103 (piwi, marshmellow) ### Added - Added `hf search` - currently tests for 14443a tags, iclass tags, and 15693 tags (marshmellow) From dd3d1b7012762887ada17fa041100d8e16f540c0 Mon Sep 17 00:00:00 2001 From: Martin Holst Swende Date: Tue, 23 Jun 2015 22:24:55 +0200 Subject: [PATCH 125/132] Changelog --- CHANGELOG.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a6ac620..b416e26a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,11 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] +### Added +- Add PACE replay functionality (frederikmoellers) + +### Fixed +- t55xx write timing (marshmellow) ## [2.1.0][2015-06-23] From ff4fdb321f7c0e736da959581d379dc566704df2 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 23 Jun 2015 17:41:24 -0400 Subject: [PATCH 126/132] add 14b info command add 14b to hf search update change log --- CHANGELOG.md | 2 + client/cmdhf.c | 14 +- client/cmdhf14b.c | 466 ++++++++++++++++++++++++++++++++++------------ client/cmdhf14b.h | 8 +- 4 files changed, 361 insertions(+), 129 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b416e26a..bf318284 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] ### Added +- Add `hf 14b info` to `hf search` (marshmellow) +- Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) - Add PACE replay functionality (frederikmoellers) ### Fixed diff --git a/client/cmdhf.c b/client/cmdhf.c index fc6127c2..4c5db589 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -556,7 +556,12 @@ int CmdHFSearch(const char *Cmd){ if (ans > 0) { PrintAndLog("\nValid ISO14443A Tag Found - Quiting Search\n"); return ans; - } + } + ans = HF14BInfo(false); + if (ans) { + PrintAndLog("\nValid ISO14443B Tag Found - Quiting Search\n"); + return ans; + } ans = HFiClassReader("", false, false); if (ans) { PrintAndLog("\nValid iClass Tag (or PicoPass Tag) Found - Quiting Search\n"); @@ -567,12 +572,7 @@ int CmdHFSearch(const char *Cmd){ PrintAndLog("\nValid ISO15693 Tag Found - Quiting Search\n"); return ans; } - - - //14b has issues currently... - //ans = CmdHF14BRead(Cmd); - //if (ans > 0) return ans; - + PrintAndLog("\nno known/supported 13.56 MHz tags found\n"); return 0; } diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 496267cd..d1d668e9 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -22,6 +22,7 @@ #include "cmdparser.h" #include "cmdhf14b.h" #include "cmdmain.h" +#include "cmdhf14a.h" static int CmdHelp(const char *Cmd); @@ -35,6 +36,7 @@ int CmdHF14BList(const char *Cmd) int CmdHF14BSim(const char *Cmd) { UsbCommand c={CMD_SIMULATE_TAG_ISO_14443B}; + clearCommandBuffer(); SendCommand(&c); return 0; } @@ -42,6 +44,7 @@ int CmdHF14BSim(const char *Cmd) int CmdHF14BSnoop(const char *Cmd) { UsbCommand c = {CMD_SNOOP_ISO_14443B}; + clearCommandBuffer(); SendCommand(&c); return 0; } @@ -53,6 +56,7 @@ int CmdHF14BSnoop(const char *Cmd) int CmdSri512Read(const char *Cmd) { UsbCommand c = {CMD_READ_SRI512_TAG, {strtol(Cmd, NULL, 0), 0, 0}}; + clearCommandBuffer(); SendCommand(&c); return 0; } @@ -64,129 +68,356 @@ int CmdSri512Read(const char *Cmd) int CmdSrix4kRead(const char *Cmd) { UsbCommand c = {CMD_READ_SRIX4K_TAG, {strtol(Cmd, NULL, 0), 0, 0}}; + clearCommandBuffer(); SendCommand(&c); return 0; } -int CmdHF14BCmdRaw (const char *cmd) { - UsbCommand resp; - uint8_t *recv; - UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; // len,recv? - uint8_t reply=1; - uint8_t crc=0; - uint8_t power=0; - char buf[5]=""; - int i=0; - uint8_t data[100] = {0x00}; - unsigned int datalen=0, temp; - char *hexout; - - if (strlen(cmd)<3) { - PrintAndLog("Usage: hf 14b raw [-r] [-c] [-p] <0A 0B 0C ... hex>"); - PrintAndLog(" -r do not read response"); - PrintAndLog(" -c calculate and append CRC"); - PrintAndLog(" -p leave the field on after receive"); - return 0; - } - - // 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': - reply=0; - break; - case 'c': - case 'C': - crc=1; - break; - case 'p': - case 'P': - power=1; - break; - default: - PrintAndLog("Invalid option"); - return 0; - } - i+=2; - continue; - } - if ((cmd[i]>='0' && cmd[i]<='9') || - (cmd[i]>='a' && cmd[i]<='f') || - (cmd[i]>='A' && cmd[i]<='F') ) { - 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); - datalen++; - *buf=0; - } - continue; - } - PrintAndLog("Invalid char on input"); - return 1; - } - if (datalen == 0) - { - PrintAndLog("Missing data input"); - return 0; - } - if(crc) - { - uint8_t first, second; - ComputeCrc14443(CRC_14443_B, data, datalen, &first, &second); - data[datalen++] = first; - data[datalen++] = second; - } - - c.arg[0] = datalen; - c.arg[1] = reply; - c.arg[2] = power; - memcpy(c.d.asBytes,data,datalen); - - SendCommand(&c); - - if (reply) { - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { - recv = resp.d.asBytes; - PrintAndLog("received %i octets",resp.arg[0]); - if(resp.arg[0] == 0) - return 0; - hexout = (char *)malloc(resp.arg[0] * 3 + 1); - if (hexout != NULL) { - uint8_t first, second; - for (int i = 0; i < resp.arg[0]; i++) { // data in hex - sprintf(&hexout[i * 3], "%02X ", recv[i]); - } - PrintAndLog("%s", hexout); - free(hexout); - if (resp.arg[0] > 2) { - ComputeCrc14443(CRC_14443_B, recv, resp.arg[0]-2, &first, &second); - if(recv[resp.arg[0]-2]==first && recv[resp.arg[0]-1]==second) { - PrintAndLog("CRC OK"); - } else { - PrintAndLog("CRC failed"); - } - } - } else { - PrintAndLog("malloc failed your client has low memory?"); - } - } else { - PrintAndLog("timeout while waiting for reply."); - } - } // if reply - return 0; +int rawClose(void){ + UsbCommand resp; + UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; + clearCommandBuffer(); + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + return 0; + } + return 0; } -int CmdHF14BWrite( const char *Cmd){ +int HF14BCmdRaw(bool reply, bool *crc, bool power, uint8_t *data, uint8_t *datalen, bool verbose){ + UsbCommand resp; + UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; // len,recv,power + if(*crc) + { + uint8_t first, second; + ComputeCrc14443(CRC_14443_B, data, *datalen, &first, &second); + data[*datalen] = first; + data[*datalen + 1] = second; + *datalen += 2; + } + + c.arg[0] = *datalen; + c.arg[1] = reply; + c.arg[2] = power; + memcpy(c.d.asBytes,data,*datalen); + clearCommandBuffer(); + SendCommand(&c); + + if (!reply) return 1; + if (!WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (verbose) PrintAndLog("timeout while waiting for reply."); + return 0; + } + *datalen = resp.arg[0]; + if (verbose) PrintAndLog("received %u octets", *datalen); + if(*datalen<2) return 0; + + memcpy(data, resp.d.asBytes, *datalen); + if (verbose) PrintAndLog("%s", sprint_hex(data, *datalen)); + + uint8_t first, second; + ComputeCrc14443(CRC_14443_B, data, *datalen-2, &first, &second); + if(data[*datalen-2] == first && data[*datalen-1] == second) { + if (verbose) PrintAndLog("CRC OK"); + *crc = true; + } else { + if (verbose) PrintAndLog("CRC failed"); + *crc = false; + } + return 1; +} + +int CmdHF14BCmdRaw (const char *Cmd) { + bool reply = true; + bool crc = false; + bool power = false; + char buf[5] = ""; + uint8_t data[100] = {0x00}; + uint8_t datalen = 0; + unsigned int temp; + int i = 0; + if (strlen(Cmd)<3) { + PrintAndLog("Usage: hf 14b raw [-r] [-c] [-p] <0A 0B 0C ... hex>"); + PrintAndLog(" -r do not read response"); + PrintAndLog(" -c calculate and append CRC"); + PrintAndLog(" -p leave the field on after receive"); + return 0; + } + + // 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': + reply = false; + break; + case 'c': + case 'C': + crc = true; + break; + case 'p': + case 'P': + power = true; + break; + default: + PrintAndLog("Invalid option"); + return 0; + } + i+=2; + continue; + } + if ((Cmd[i]>='0' && Cmd[i]<='9') || + (Cmd[i]>='a' && Cmd[i]<='f') || + (Cmd[i]>='A' && Cmd[i]<='F') ) { + 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); + *buf=0; + } + continue; + } + PrintAndLog("Invalid char on input"); + return 1; + } + if (datalen == 0) + { + PrintAndLog("Missing data input"); + return 0; + } + + return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); +} + +static void print_atqb_resp(uint8_t *data){ + PrintAndLog (" UID: %s", sprint_hex(data+1,4)); + PrintAndLog (" App Data: %s", sprint_hex(data+5,4)); + PrintAndLog (" Protocol: %s", sprint_hex(data+9,3)); + uint8_t BitRate = data[9]; + if (!BitRate) + PrintAndLog (" Bit Rate: 106 kbit/s only PICC <-> PCD"); + if (BitRate & 0x10) + PrintAndLog (" Bit Rate: 212 kbit/s PICC -> PCD supported"); + if (BitRate & 0x20) + PrintAndLog (" Bit Rate: 424 kbit/s PICC -> PCD supported"); + if (BitRate & 0x40) + PrintAndLog (" Bit Rate: 847 kbit/s PICC -> PCD supported"); + if (BitRate & 0x01) + PrintAndLog (" Bit Rate: 212 kbit/s PICC <- PCD supported"); + if (BitRate & 0x02) + PrintAndLog (" Bit Rate: 424 kbit/s PICC <- PCD supported"); + if (BitRate & 0x04) + PrintAndLog (" Bit Rate: 847 kbit/s PICC <- PCD supported"); + if (BitRate & 0x80) + PrintAndLog (" Same bit rate <-> required"); + + uint16_t maxFrame = data[10]>>4; + if (maxFrame < 5) + maxFrame = 8*maxFrame + 16; + else if (maxFrame == 5) + maxFrame = 64; + else if (maxFrame == 6) + maxFrame = 96; + else if (maxFrame == 7) + maxFrame = 128; + else if (maxFrame == 8) + maxFrame = 256; + else + maxFrame = 257; + + PrintAndLog ("Max Frame Size: %d%s",maxFrame, (maxFrame == 257) ? "+ RFU" : ""); + + uint8_t protocolT = data[10] & 0xF; + PrintAndLog (" Protocol Type: Protocol is %scompliant with ISO/IEC 14443-4",(protocolT) ? "" : "not " ); + PrintAndLog ("Frame Wait Int: %d", data[11]>>4); + PrintAndLog (" App Data Code: Application is %s",(data[11]&4) ? "Standard" : "Proprietary"); + PrintAndLog (" Frame Options: NAD is %ssupported",(data[11]&2) ? "" : "not "); + PrintAndLog (" Frame Options: CID is %ssupported",(data[11]&1) ? "" : "not "); + + return; +} + +char *get_ST_Chip_Model(uint8_t data){ + static char model[20]; + char *retStr = model; + memset(model,0, sizeof(model)); + + switch (data) { + case 0x0: sprintf(retStr, "SRIX4K (Special)"); break; + case 0x2: sprintf(retStr, "SR176"); break; + case 0x3: sprintf(retStr, "SRIX4K"); break; + case 0x4: sprintf(retStr, "SRIX512"); break; + case 0x6: sprintf(retStr, "SRI512"); break; + case 0x7: sprintf(retStr, "SRI4K"); break; + case 0xC: sprintf(retStr, "SRT512"); break; + default : sprintf(retStr, "Unknown"); break; + } + return retStr; +} + +static void print_st_info(uint8_t *data){ + //uid = first 8 bytes in data + PrintAndLog(" UID: %s", sprint_hex(SwapEndian64(data,8,8),8)); + PrintAndLog(" MFG: %02X, %s", data[6], getTagInfo(data[6])); + PrintAndLog("Chip: %02X, %s", data[5]>>2, get_ST_Chip_Model(data[5]>>2)); + return; +} + +int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ + + //05 00 00 = find one tag in field + //1d xx xx xx xx 20 00 08 01 00 = attrib xx=crc + //a3 = ? (resp 03 e2 c2) + //02 = ? (resp 02 6a d3) + // 022b (resp 02 67 00 [29 5b]) + // 0200a40400 (resp 02 67 00 [29 5b]) + // 0200a4040c07a0000002480300 (resp 02 67 00 [29 5b]) + // 0200a4040c07a0000002480200 (resp 02 67 00 [29 5b]) + // 0200a4040006a0000000010100 (resp 02 6a 82 [4b 4c]) + // 0200a4040c09d27600002545500200 (resp 02 67 00 [29 5b]) + // 0200a404000cd2760001354b414e4d30310000 (resp 02 6a 82 [4b 4c]) + // 0200a404000ca000000063504b43532d313500 (resp 02 6a 82 [4b 4c]) + // 0200a4040010a000000018300301000000000000000000 (resp 02 6a 82 [4b 4c]) + //03 = ? (resp 03 [e3 c2]) + //c2 = ? (resp c2 [66 15]) + //b2 = ? (resp a3 [e9 67]) + bool crc = true; + *datalen = 3; + //std read cmd + data[0] = 0x05; + data[1] = 0x00; + data[2] = 0x00; + + if (HF14BCmdRaw(true, &crc, false, data, datalen, false)==0) return 0; + + if (data[0] != 0x50 || *datalen != 14 || !crc) return 0; + + PrintAndLog ("\n14443-3b tag found:"); + print_atqb_resp(data); + + return 1; +} + +int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ + bool crc = true; + *datalen = 2; + //wake cmd + data[0] = 0x06; + data[1] = 0x00; + + //leave power on + // verbose on for now for testing - turn off when functional + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (*datalen != 3 || !crc) return rawClose(); + + uint8_t chipID = data[0]; + // select + data[0] = 0x0E; + data[1] = chipID; + *datalen = 2; + + //leave power on + // verbose on for now for testing - turn off when functional + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (*datalen != 3 || !crc || data[0] != chipID) return rawClose(); + + // get uid + data[0] = 0x0B; + *datalen = 1; + + //power off + // verbose on for now for testing - turn off when functional + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return 0; + rawClose(); + if (*datalen != 10 || !crc) return 0; + + PrintAndLog("\n14443-3b ST tag found:"); + print_st_info(data); + return 1; +} + +// test for other 14b type tags (mimic another reader - don't have tags to identify) +int HF14B_Other_Info(uint8_t *data, uint8_t *datalen){ + bool crc = true; + *datalen = 4; + //std read cmd + data[0] = 0x00; + data[1] = 0x0b; + data[2] = 0x3f; + data[3] = 0x80; + + if (HF14BCmdRaw(true, &crc, false, data, datalen, false)!=0) { + if (*datalen > 2 || !crc) { + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog ("Unknown tag type answered to a 0x000b3f80 command ans:"); + PrintAndLog ("%s",sprint_hex(data,*datalen)); + return 1; + } + } + + crc = false; + *datalen = 1; + data[0] = 0x0a; + + if (HF14BCmdRaw(true, &crc, false, data, datalen, false)!=0) { + if (*datalen > 0) { + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog ("Unknown tag type answered to a 0x0A command ans:"); + PrintAndLog ("%s",sprint_hex(data,*datalen)); + return 1; + } + } + + crc = false; + *datalen = 1; + data[0] = 0x0c; + + if (HF14BCmdRaw(true, &crc, false, data, datalen, false)!=0) { + if (*datalen > 0) { + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog ("Unknown tag type answered to a 0x0C command ans:"); + PrintAndLog ("%s",sprint_hex(data,*datalen)); + return 1; + } + } + + return 0; + +} + +int HF14BInfo(bool verbose){ + uint8_t data[100]; + uint8_t datalen = 5; + + // try std 14b (atqb) + if (HF14BStdInfo(data, &datalen)) return 1; + + // try st 14b + if (HF14B_ST_Info(data, &datalen)) return 1; + + // try unknown 14b read commands (to be identified later) + // could be read of calypso, CEPAS, moneo, or pico pass. + if (HF14B_Other_Info(data, &datalen)) return 1; + + if (verbose) PrintAndLog("no 14443B tag found"); + return 0; +} + +int CmdHF14Binfo(const char *Cmd){ + return HF14BInfo(true); +} + +int CmdSriWrite( const char *Cmd){ /* * For SRIX4K blocks 00 - 7F * hf 14b raw -c -p 09 $srix4kwblock $srix4kwdata @@ -256,13 +487,14 @@ int CmdHF14BWrite( const char *Cmd){ static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, + {"info", CmdHF14Binfo, 0, "Find and print info about a 14b type tag (HF ISO 14443b)"}, {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443b history"}, {"sim", CmdHF14BSim, 0, "Fake ISO 14443B tag"}, {"snoop", CmdHF14BSnoop, 0, "Eavesdrop ISO 14443B"}, {"sri512read", CmdSri512Read, 0, "Read contents of a SRI512 tag"}, {"srix4kread", CmdSrix4kRead, 0, "Read contents of a SRIX4K tag"}, + {"sriwrite", CmdSriWrite, 0, "Write data to a SRI512 | SRIX4K tag"}, {"raw", CmdHF14BCmdRaw, 0, "Send raw hex data to tag"}, - {"write", CmdHF14BWrite, 0, "Write data to a SRI512 | SRIX4K tag"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdhf14b.h b/client/cmdhf14b.h index cc8b9dbd..a45b7434 100644 --- a/client/cmdhf14b.h +++ b/client/cmdhf14b.h @@ -12,15 +12,13 @@ #define CMDHF14B_H__ int CmdHF14B(const char *Cmd); - -int CmdHF14BDemod(const char *Cmd); int CmdHF14BList(const char *Cmd); -int CmdHF14BRead(const char *Cmd); -int CmdHF14Sim(const char *Cmd); -int CmdHFSimlisten(const char *Cmd); +int CmdHF14BInfo(const char *Cmd); +int CmdHF14BSim(const char *Cmd); int CmdHF14BSnoop(const char *Cmd); int CmdSri512Read(const char *Cmd); int CmdSrix4kRead(const char *Cmd); int CmdHF14BWrite( const char *cmd); +int HF14BInfo(bool verbose); #endif From b7eddc14db9262a51ad3100ade7386d03500ace8 Mon Sep 17 00:00:00 2001 From: marshmellow42 Date: Tue, 23 Jun 2015 17:45:48 -0400 Subject: [PATCH 127/132] update change log for adjusted 14b write cmd --- CHANGELOG.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bf318284..3f9546d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,11 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ## [Unreleased][unreleased] +### Changed +- Changed `hf 14b write` to `hf 14b sriwrite` as it only applied to sri tags (marshmellow) +- Added `hf 14b info` to `hf search` (marshmellow) + ### Added -- Add `hf 14b info` to `hf search` (marshmellow) - Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) - Add PACE replay functionality (frederikmoellers) From 61611f5b85475a94a4d8e10620ed5736034111bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Frederik=20M=C3=B6llers?= Date: Wed, 24 Jun 2015 14:57:08 +0200 Subject: [PATCH 128/132] Fix comparison error in fpga_compress The comparison would check for greater-than-or-equal the maximum amount of bytes to read/write when it should check for greater-than only. --- client/fpga_compress.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/fpga_compress.c b/client/fpga_compress.c index f7333b36..5c168292 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -96,7 +96,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) } } - if (i >= num_infiles * FPGA_CONFIG_SIZE) { + if (i > num_infiles * FPGA_CONFIG_SIZE) { fprintf(stderr, "Input files too big (total > %lu bytes). These are probably not PM3 FPGA config files.", num_infiles*FPGA_CONFIG_SIZE); for(uint16_t j = 0; j < num_infiles; j++) { fclose(infile[j]); From 7b242c1ca24fa8c59512f6c6f5f2a543c7ad3342 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 24 Jun 2015 08:29:59 +0200 Subject: [PATCH 129/132] fix: fpga_compressor file size check - commit 61611f5 fixed the check in case of correct filesizes but fails in case of files which are too big to fit in fpga_config[] - fix exit codes and Makefile to handle errors correctly during make --- armsrc/Makefile | 4 +++- client/fpga_compress.c | 36 +++++++++++++++++++----------------- 2 files changed, 22 insertions(+), 18 deletions(-) diff --git a/armsrc/Makefile b/armsrc/Makefile index f21f106c..1214c949 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -70,11 +70,13 @@ FPGA_COMPRESSOR = ../client/fpga_compress all: $(OBJS) +.DELETE_ON_ERROR: + $(OBJDIR)/fpga_all.o: $(OBJDIR)/fpga_all.bit.z $(OBJCOPY) -O elf32-littlearm -I binary -B arm --prefix-sections=fpga_all_bit $^ $@ $(OBJDIR)/fpga_all.bit.z: $(FPGA_BITSTREAMS) $(FPGA_COMPRESSOR) - $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ + $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ $(FPGA_COMPRESSOR): make -C ../client $(notdir $(FPGA_COMPRESSOR)) diff --git a/client/fpga_compress.c b/client/fpga_compress.c index 5c168292..2779e835 100644 --- a/client/fpga_compress.c +++ b/client/fpga_compress.c @@ -85,6 +85,15 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) // read the input files. Interleave them into fpga_config[] i = 0; do { + + if (i >= num_infiles * FPGA_CONFIG_SIZE) { + fprintf(stderr, "Input files too big (total > %lu bytes). These are probably not PM3 FPGA config files.\n", num_infiles*FPGA_CONFIG_SIZE); + for(uint16_t j = 0; j < num_infiles; j++) { + fclose(infile[j]); + } + return(EXIT_FAILURE); + } + for(uint16_t j = 0; j < num_infiles; j++) { for(uint16_t k = 0; k < FPGA_INTERLEAVE_SIZE; k++) { c = fgetc(infile[j]); @@ -96,13 +105,6 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) } } - if (i > num_infiles * FPGA_CONFIG_SIZE) { - fprintf(stderr, "Input files too big (total > %lu bytes). These are probably not PM3 FPGA config files.", num_infiles*FPGA_CONFIG_SIZE); - for(uint16_t j = 0; j < num_infiles; j++) { - fclose(infile[j]); - } - return -1; - } } while (!all_feof(infile, num_infiles)); // initialize zlib structures @@ -148,7 +150,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) fclose(outfile); free(infile); free(fpga_config); - return -1; + return(EXIT_FAILURE); } for (i = 0; i < compressed_fpga_stream.total_out; i++) { @@ -164,7 +166,7 @@ int zlib_compress(FILE *infile[], uint8_t num_infiles, FILE *outfile) free(infile); free(fpga_config); - return 0; + return(EXIT_SUCCESS); } @@ -226,12 +228,12 @@ int zlib_decompress(FILE *infile, FILE *outfile) } fclose(outfile); fclose(infile); - return 0; + return(EXIT_SUCCESS); } else { fprintf(stderr, "Error. Inflate() returned error %d, %s", ret, compressed_fpga_stream.msg); fclose(outfile); fclose(infile); - return -1; + return(EXIT_FAILURE); } } @@ -244,24 +246,24 @@ int main(int argc, char **argv) if (argc == 1 || argc == 2) { usage(); - return -1; + return(EXIT_FAILURE); } if (!strcmp(argv[1], "-d")) { // Decompress infiles = calloc(1, sizeof(FILE*)); if (argc != 4) { usage(); - return -1; + return(EXIT_FAILURE); } infiles[0] = fopen(argv[2], "rb"); if (infiles[0] == NULL) { fprintf(stderr, "Error. Cannot open input file %s", argv[2]); - return -1; + return(EXIT_FAILURE); } outfile = fopen(argv[3], "wb"); if (outfile == NULL) { fprintf(stderr, "Error. Cannot open output file %s", argv[3]); - return -1; + return(EXIT_FAILURE); } return zlib_decompress(infiles[0], outfile); @@ -272,13 +274,13 @@ int main(int argc, char **argv) infiles[i] = fopen(argv[i+1], "rb"); if (infiles[i] == NULL) { fprintf(stderr, "Error. Cannot open input file %s", argv[i+1]); - return -1; + return(EXIT_FAILURE); } } outfile = fopen(argv[argc-1], "wb"); if (outfile == NULL) { fprintf(stderr, "Error. Cannot open output file %s", argv[argc-1]); - return -1; + return(EXIT_FAILURE); } return zlib_compress(infiles, argc-2, outfile); } From dc8ba239fbc1b8f50f572e84adfcfdf52bd0d0da Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Wed, 24 Jun 2015 07:48:36 +0200 Subject: [PATCH 130/132] (implementing suggestion #94) hf mf mifare: gracefully exit if tag isn't vulnerable to this attack hf mf nested: dito --- armsrc/iso14443a.c | 27 ++++++++++++++++++++------- armsrc/mifarecmd.c | 22 +++++++++++++++++----- client/cmdhfmf.c | 39 ++++++++++++++++++++++++++++----------- client/mifarehost.c | 38 ++++++++++++++++++-------------------- 4 files changed, 83 insertions(+), 43 deletions(-) diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index cf64da2f..2fd568b9 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -1971,7 +1971,7 @@ int32_t dist_nt(uint32_t nt1, uint32_t nt2) { nttmp1 = prng_successor(nttmp1, 1); if (nttmp1 == nt2) return i; nttmp2 = prng_successor(nttmp2, 1); - if (nttmp2 == nt1) return -i; + if (nttmp2 == nt1) return -i; } return(-99999); // either nt1 or nt2 are invalid nonces @@ -2040,18 +2040,21 @@ void ReaderMifare(bool first_try) LED_B_OFF(); LED_C_OFF(); - + + #define DARKSIDE_MAX_TRIES 32 // number of tries to sync on PRNG cycle. Then give up. + uint16_t unsuccessfull_tries = 0; + for(uint16_t i = 0; TRUE; i++) { + LED_C_ON(); WDT_HIT(); // Test if the action was cancelled if(BUTTON_PRESS()) { + isOK = -1; break; } - LED_C_ON(); - if(!iso14443a_select_card(uid, NULL, &cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card"); continue; @@ -2086,8 +2089,14 @@ void ReaderMifare(bool first_try) nt_attacked = nt; } else { - if (nt_distance == -99999) { // invalid nonce received, try again - continue; + if (nt_distance == -99999) { // invalid nonce received + unsuccessfull_tries++; + if (!nt_attacked && unsuccessfull_tries > DARKSIDE_MAX_TRIES) { + isOK = -3; // Card has an unpredictable PRNG. Give up + break; + } else { + continue; // continue trying... + } } sync_cycles = (sync_cycles - nt_distance); if (MF_DBGLEVEL >= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i, nt_distance, sync_cycles); @@ -2149,6 +2158,10 @@ void ReaderMifare(bool first_try) if (nt_diff == 0 && first_try) { par[0]++; + if (par[0] == 0x00) { // tried all 256 possible parities without success. Card doesn't send NACK. + isOK = -2; + break; + } } else { par[0] = ((par[0] & 0x1F) + 1) | par_low; } @@ -2165,7 +2178,7 @@ void ReaderMifare(bool first_try) memcpy(buf + 16, ks_list, 8); memcpy(buf + 24, mf_nr_ar, 4); - cmd_send(CMD_ACK,isOK,0,0,buf,28); + cmd_send(CMD_ACK, isOK, 0, 0, buf, 28); // Thats it... FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 939c9002..14d2b68a 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -645,6 +645,9 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // statistics on nonce distance + int16_t isOK = 0; + #define NESTED_MAX_TRIES 12 + uint16_t unsuccessfull_tries = 0; if (calibrate) { // for first call only. Otherwise reuse previous calibration LED_B_ON(); WDT_HIT(); @@ -655,6 +658,12 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat for (rtr = 0; rtr < 17; rtr++) { + // Test if the action was cancelled + if(BUTTON_PRESS()) { + isOK = -2; + break; + } + // prepare next select. No need to power down the card. if(mifare_classic_halt(pcs, cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Halt error"); @@ -702,14 +711,17 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat delta_time = auth2_time - auth1_time + 32; // allow some slack for proper timing } if (MF_DBGLEVEL >= 3) Dbprintf("Nested: calibrating... ntdist=%d", i); + } else { + unsuccessfull_tries++; + if (unsuccessfull_tries > NESTED_MAX_TRIES) { // card isn't vulnerable to nested attack (random numbers are not predictable) + isOK = -3; + } } } - - if (rtr <= 1) return; davg = (davg + (rtr - 1)/2) / (rtr - 1); - if (MF_DBGLEVEL >= 3) Dbprintf("min=%d max=%d avg=%d, delta_time=%d", dmin, dmax, davg, delta_time); + 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; @@ -722,7 +734,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat LED_C_ON(); // get crypted nonces for target sector - for(i=0; i < 2; i++) { // look for exactly two different nonces + for(i=0; i < 2 && !isOK; i++) { // look for exactly two different nonces target_nt[i] = 0; while(target_nt[i] == 0) { // continue until we have an unambiguous nonce @@ -800,7 +812,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat memcpy(buf+16, &target_ks[1], 4); LED_B_ON(); - cmd_send(CMD_ACK, 0, 2, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); + cmd_send(CMD_ACK, isOK, 0, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); LED_B_OFF(); if (MF_DBGLEVEL >= 3) DbpString("NESTED FINISHED"); diff --git a/client/cmdhfmf.c b/client/cmdhfmf.c index 5abda060..5ef5273a 100644 --- a/client/cmdhfmf.c +++ b/client/cmdhfmf.c @@ -17,7 +17,7 @@ int CmdHF14AMifare(const char *Cmd) uint32_t uid = 0; uint32_t nt = 0, nr = 0; uint64_t par_list = 0, ks_list = 0, r_key = 0; - uint8_t isOK = 0; + int16_t isOK = 0; uint8_t keyBlock[8] = {0}; UsbCommand c = {CMD_READER_MIFARE, {true, 0, 0}}; @@ -25,7 +25,7 @@ int CmdHF14AMifare(const char *Cmd) // message printf("-------------------------------------------------------------------------\n"); printf("Executing command. Expected execution time: 25sec on average :-)\n"); - printf("Press the key on the proxmark3 device to abort both proxmark3 and client.\n"); + printf("Press button on the proxmark3 device to abort both proxmark3 and client.\n"); printf("-------------------------------------------------------------------------\n"); @@ -47,15 +47,20 @@ start: } UsbCommand resp; - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { - isOK = resp.arg[0] & 0xff; + if (WaitForResponseTimeout(CMD_ACK, &resp, 1000)) { + isOK = resp.arg[0]; 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); ks_list = bytes_to_num(resp.d.asBytes + 16, 8); nr = bytes_to_num(resp.d.asBytes + 24, 4); printf("\n\n"); - if (!isOK) PrintAndLog("Proxmark can't get statistic info. Execution aborted.\n"); + switch (isOK) { + case -1 : PrintAndLog("Button pressed. Aborted.\n"); break; + case -2 : PrintAndLog("Card is not vulnerable to Darkside attack (doesn't send NACK on authentication requests).\n"); break; + case -3 : PrintAndLog("Card is not vulnerable to Darkside attack (its random number generator is not predictable).\n"); break; + default: ; + } break; } } @@ -622,8 +627,14 @@ int CmdHF14AMfNested(const char *Cmd) if (cmdp == 'o') { PrintAndLog("--target block no:%3d, target key type:%c ", trgBlockNo, trgKeyType?'B':'A'); - if (mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true)) { - PrintAndLog("Nested error."); + int16_t isOK = mfnested(blockNo, keyType, key, trgBlockNo, trgKeyType, keyBlock, true); + if (isOK) { + switch (isOK) { + case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; + case -2 : PrintAndLog("Button pressed. Aborted.\n"); break; + case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break; + default : PrintAndLog("Unknown Error.\n"); + } return 2; } key64 = bytes_to_num(keyBlock, 6); @@ -696,11 +707,17 @@ int CmdHF14AMfNested(const char *Cmd) for (trgKeyType = 0; trgKeyType < 2; trgKeyType++) { if (e_sector[sectorNo].foundKey[trgKeyType]) continue; PrintAndLog("-----------------------------------------------"); - if(mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate)) { - PrintAndLog("Nested error.\n"); + int16_t isOK = mfnested(blockNo, keyType, key, FirstBlockOfSector(sectorNo), trgKeyType, keyBlock, calibrate); + if(isOK) { + switch (isOK) { + case -1 : PrintAndLog("Error: No response from Proxmark.\n"); break; + case -2 : PrintAndLog("Button pressed. Aborted.\n"); break; + case -3 : PrintAndLog("Tag isn't vulnerable to Nested Attack (random numbers are not predictable).\n"); break; + default : PrintAndLog("Unknown Error.\n"); + } free(e_sector); - return 2; } - else { + return 2; + } else { calibrate = false; } diff --git a/client/mifarehost.c b/client/mifarehost.c index 237979c1..95453ebf 100644 --- a/client/mifarehost.c +++ b/client/mifarehost.c @@ -69,7 +69,7 @@ void* nested_worker_thread(void *arg) int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo, uint8_t trgKeyType, uint8_t * resultKey, bool calibrate) { - uint16_t i, len; + uint16_t i; uint32_t uid; UsbCommand resp; @@ -77,31 +77,29 @@ int mfnested(uint8_t blockNo, uint8_t keyType, uint8_t * key, uint8_t trgBlockNo struct Crypto1State *p1, *p2, *p3, *p4; // flush queue - WaitForResponseTimeout(CMD_ACK,NULL,100); + WaitForResponseTimeout(CMD_ACK, NULL, 100); UsbCommand c = {CMD_MIFARE_NESTED, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, calibrate}}; memcpy(c.d.asBytes, key, 6); SendCommand(&c); - if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { - len = resp.arg[1]; - if (len == 2) { - memcpy(&uid, resp.d.asBytes, 4); - PrintAndLog("uid:%08x len=%d trgbl=%d trgkey=%x", uid, len, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8); - - for (i = 0; i < 2; i++) { - statelists[i].blockNo = resp.arg[2] & 0xff; - statelists[i].keyType = (resp.arg[2] >> 8) & 0xff; - statelists[i].uid = uid; + if (!WaitForResponseTimeout(CMD_ACK, &resp, 1500)) { + return -1; + } - 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); - } - } - else { - PrintAndLog("Got 0 keys from proxmark."); - return 1; - } + if (resp.arg[0]) { + return resp.arg[0]; // error during nested + } + + memcpy(&uid, resp.d.asBytes, 4); + PrintAndLog("uid:%08x trgbl=%d trgkey=%x", uid, (uint16_t)resp.arg[2] & 0xff, (uint16_t)resp.arg[2] >> 8); + + for (i = 0; i < 2; i++) { + statelists[i].blockNo = resp.arg[2] & 0xff; + statelists[i].keyType = (resp.arg[2] >> 8) & 0xff; + statelists[i].uid = uid; + 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 From 377d692be1ee14b2377bc7fe3ad7f2486447c778 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Thu, 25 Jun 2015 16:58:54 +0200 Subject: [PATCH 131/132] fix compile error (issue #116): remove #include in ARM sources --- armsrc/optimized_cipher.c | 1 - 1 file changed, 1 deletion(-) diff --git a/armsrc/optimized_cipher.c b/armsrc/optimized_cipher.c index 23562621..bfaf5088 100644 --- a/armsrc/optimized_cipher.c +++ b/armsrc/optimized_cipher.c @@ -65,7 +65,6 @@ #include #include #include -#include #define opt_T(s) (0x1 & ((s->t >> 15) ^ (s->t >> 14)^ (s->t >> 10)^ (s->t >> 8)^ (s->t >> 5)^ (s->t >> 4)^ (s->t >> 1)^ s->t)) From 09ffd16ee2d0d6d43fc562035487226cf4f58b86 Mon Sep 17 00:00:00 2001 From: pwpiwi Date: Mon, 29 Jun 2015 09:07:54 +0200 Subject: [PATCH 132/132] - fix: ensure that FpgaDownloadAndGo() is always called before requesting any memory from BigBuf[]. This is required because FpgaDownloadAndGo() might allocate, use, and free most of BigBuf[] when decompressing FPGA configs. - cleanup: remove rests of deprecated "end of trace markers" (0x44) --- armsrc/BigBuf.c | 10 ++---- armsrc/hitag2.c | 25 ++++++++------ armsrc/iclass.c | 2 -- armsrc/iso14443a.c | 57 ++++++++++++++++--------------- armsrc/iso14443b.c | 10 +++--- armsrc/iso15693.c | 28 +++++++--------- armsrc/mifarecmd.c | 84 ++++++++++++++++++++++++---------------------- 7 files changed, 105 insertions(+), 111 deletions(-) diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index 703ade65..510f7bef 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -96,9 +96,6 @@ uint16_t BigBuf_max_traceLen(void) } void clear_trace() { - uint8_t *trace = BigBuf_get_addr(); - uint16_t max_traceLen = BigBuf_max_traceLen(); - memset(trace, 0x44, max_traceLen); traceLen = 0; } @@ -176,13 +173,10 @@ bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_ } traceLen += num_paritybytes; - if(traceLen +4 < max_traceLen) - { //If it hadn't been cleared, for whatever reason.. - memset(trace+traceLen,0x44, 4); - } - return TRUE; } + + int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int readerToTag) { /** diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index 4b173d6f..719164d1 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -710,22 +710,24 @@ void SnoopHitag(uint32_t type) { byte_t rx[HITAG_FRAME_LEN]; size_t rxlen=0; - auth_table_len = 0; - auth_table_pos = 0; - BigBuf_free(); - auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); - memset(auth_table, 0x00, AUTH_TABLE_LENGTH); + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); // Clean up trace and prepare it for storing frames set_tracing(TRUE); clear_trace(); + auth_table_len = 0; + auth_table_pos = 0; + + BigBuf_free(); + auth_table = (byte_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. - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); @@ -922,6 +924,12 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { bool bQuitTraceFull = false; bQuiet = false; + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + // Clean up trace and prepare it for storing frames + set_tracing(TRUE); + clear_trace(); + auth_table_len = 0; auth_table_pos = 0; byte_t* auth_table; @@ -929,10 +937,6 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); memset(auth_table, 0x00, AUTH_TABLE_LENGTH); - // Clean up trace and prepare it for storing frames - set_tracing(TRUE); - clear_trace(); - DbpString("Starting Hitag2 simulation"); LED_D_ON(); hitag2_init(); @@ -953,7 +957,6 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { // Set up simulator mode, frequency divisor which will drive the FPGA // and analog mux selection. - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 9139d3bd..97c62bb6 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1125,7 +1125,6 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) int resp_cc_len; uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - memset(receivedCmd, 0x44, MAX_FRAME_SIZE); int len; // Prepare card messages @@ -1336,7 +1335,6 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) } } - memset(receivedCmd, 0x44, MAX_FRAME_SIZE); } //Dbprintf("%x", cmdsRecvd); diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 2fd568b9..5c7367a1 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -551,12 +551,8 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { LEDsoff(); - // 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); - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); @@ -583,8 +579,6 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { bool TagIsActive = FALSE; bool ReaderIsActive = FALSE; - iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse, receivedResponsePar); @@ -594,6 +588,12 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { // Setup and start DMA. FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); + // 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); + // And now we loop, receiving samples. for(uint32_t rsamples = 0; TRUE; ) { @@ -1026,6 +1026,9 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) .modulation_n = 0 }; + // We need to listen to the high-frequency, peak-detected path. + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + BigBuf_free_keep_EM(); // allocate buffers: @@ -1054,9 +1057,6 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) int happened2 = 0; int cmdsRecvd = 0; - // We need to listen to the high-frequency, peak-detected path. - iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - cmdsRecvd = 0; tag_response_info_t* p_response; @@ -1994,6 +1994,10 @@ void ReaderMifare(bool first_try) uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; + if (first_try) { + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + } + // free eventually allocated BigBuf memory. We want all for tracing. BigBuf_free(); @@ -2022,7 +2026,6 @@ void ReaderMifare(bool first_try) if (first_try) { mf_nr_ar3 = 0; - iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); sync_time = GetCountSspClk() & 0xfffffff8; sync_cycles = 65536; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). nt_attacked = 0; @@ -2239,13 +2242,6 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * uint32_t ar_nr_responses[] = {0,0,0,0,0,0,0,0}; uint8_t ar_nr_collected = 0; - // free eventually allocated BigBuf memory but keep Emulator Memory - BigBuf_free_keep_EM(); - - // clear trace - clear_trace(); - set_tracing(TRUE); - // Authenticate response - nonce uint32_t nonce = bytes_to_num(rAUTH_NT, 4); @@ -2287,10 +2283,6 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; } - // We need to listen to the high-frequency, peak-detected path. - iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - - if (MF_DBGLEVEL >= 1) { if (!_7BUID) { Dbprintf("4B UID: %02x%02x%02x%02x", @@ -2302,6 +2294,17 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * } } + // We need to listen to the high-frequency, peak-detected path. + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + + // free eventually allocated BigBuf memory but keep Emulator Memory + BigBuf_free_keep_EM(); + + // clear trace + clear_trace(); + set_tracing(TRUE); + + bool finished = FALSE; while (!BUTTON_PRESS() && !finished) { WDT_HIT(); @@ -2720,10 +2723,8 @@ void RAMFUNC SniffMifare(uint8_t param) { uint8_t receivedResponse[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedResponsePar[MAX_MIFARE_PARITY_SIZE]; - // As we receive stuff, we copy it from receivedCmd or receivedResponse - // into trace, along with its length and other annotations. - //uint8_t *trace = (uint8_t *)BigBuf; - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + // free eventually allocated BigBuf memory BigBuf_free(); // allocate the DMA buffer, used to stream samples from the FPGA @@ -2735,8 +2736,6 @@ void RAMFUNC SniffMifare(uint8_t param) { bool ReaderIsActive = FALSE; bool TagIsActive = FALSE; - iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse, receivedResponsePar); diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c index 416c31f9..33c047d8 100644 --- a/armsrc/iso14443b.c +++ b/armsrc/iso14443b.c @@ -334,6 +334,8 @@ void SimulateIso14443bTag(void) 0x00, 0x21, 0x85, 0x5e, 0xd7 }; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + clear_trace(); set_tracing(TRUE); @@ -348,8 +350,6 @@ void SimulateIso14443bTag(void) uint16_t len; uint16_t cmdsRecvd = 0; - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - // prepare the (only one) tag answer: CodeIso14443bAsTag(response1, sizeof(response1)); uint8_t *resp1Code = BigBuf_malloc(ToSendMax); @@ -908,9 +908,6 @@ static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) //----------------------------------------------------------------------------- void ReadSTMemoryIso14443b(uint32_t dwLast) { - clear_trace(); - set_tracing(TRUE); - uint8_t i = 0x00; FpgaDownloadAndGo(FPGA_BITSTREAM_HF); @@ -929,6 +926,9 @@ void ReadSTMemoryIso14443b(uint32_t dwLast) FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); SpinDelay(200); + clear_trace(); + set_tracing(TRUE); + // First command: wake up the tag using the INITIATE command uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index 94040a85..e7145c5c 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -877,12 +877,12 @@ int SendDataTag(uint8_t *send, int sendlen, int init, int speed, uint8_t **recv) LED_C_OFF(); LED_D_OFF(); + if (init) Iso15693InitReader(); + int answerLen=0; uint8_t *answer = BigBuf_get_addr() + 3660; if (recv != NULL) memset(answer, 0, 100); - if (init) Iso15693InitReader(); - if (!speed) { // low speed (1 out of 256) CodeIso15693AsReader256(send, sendlen); @@ -999,10 +999,6 @@ void ReaderIso15693(uint32_t parameter) LED_C_OFF(); LED_D_OFF(); - uint8_t *answer1 = BigBuf_get_addr() + 3660; - uint8_t *answer2 = BigBuf_get_addr() + 3760; - uint8_t *answer3 = BigBuf_get_addr() + 3860; - int answerLen1 = 0; int answerLen2 = 0; int answerLen3 = 0; @@ -1013,19 +1009,21 @@ void ReaderIso15693(uint32_t parameter) int elapsed = 0; uint8_t TagUID[8] = {0x00}; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + uint8_t *answer1 = BigBuf_get_addr() + 3660; + uint8_t *answer2 = BigBuf_get_addr() + 3760; + uint8_t *answer3 = BigBuf_get_addr() + 3860; // Blank arrays memset(answer1, 0x00, 300); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Setup SSC FpgaSetupSsc(); // Start from off (no field generated) - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); // Give the tags time to energize FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); @@ -1111,24 +1109,22 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) LED_C_OFF(); LED_D_OFF(); - uint8_t *buf = BigBuf_get_addr() + 3660; - int answerLen1 = 0; int samples = 0; int tsamples = 0; int wait = 0; int elapsed = 0; - memset(buf, 0x00, 100); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + uint8_t *buf = BigBuf_get_addr() + 3660; + memset(buf, 0x00, 100); + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); // Start from off (no field generated) - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelay(200); LED_A_OFF(); diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 14d2b68a..c2d85abb 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -44,10 +44,10 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -95,9 +95,11 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes){ bool turnOffField = (arg0 == 1); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); OnError(0); @@ -129,9 +131,10 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + int len = iso14443a_select_card(NULL, NULL, NULL); if(!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%02X)",len); @@ -199,11 +202,10 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -252,6 +254,10 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) // datain = KEY bytes void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { + LEDsoff(); + LED_A_ON(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + // free eventually allocated BigBuf memory BigBuf_free(); clear_trace(); @@ -269,10 +275,6 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) return; } - LEDsoff(); - LED_A_ON(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - int len = iso14443a_select_card(NULL, NULL, NULL); if (!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%d)",len); @@ -366,11 +368,10 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -472,9 +473,10 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -530,9 +532,10 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ memcpy(pwd, datain, 16); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -632,18 +635,16 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat uint32_t auth1_time, auth2_time; static uint16_t delta_time; + LED_A_ON(); + LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + // free eventually allocated BigBuf memory BigBuf_free(); - // clear trace + clear_trace(); set_tracing(false); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - - LED_A_ON(); - LED_C_OFF(); - - // statistics on nonce distance int16_t isOK = 0; #define NESTED_MAX_TRIES 12 @@ -847,15 +848,13 @@ void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) int OLD_MF_DBGLEVEL = MF_DBGLEVEL; MF_DBGLEVEL = MF_DBG_NONE; - // clear trace - clear_trace(); - set_tracing(TRUE); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + clear_trace(); + set_tracing(TRUE); for (i = 0; i < keyCount; i++) { if(mifare_classic_halt(pcs, cuid)) { @@ -902,16 +901,23 @@ void MifareSetDbgLvl(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai //----------------------------------------------------------------------------- // 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. //----------------------------------------------------------------------------- + void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); emlClearMem(); } void MifareEMemSet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); emlSetMem(datain, arg0, arg1); // data, block num, blocks count } void MifareEMemGet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); byte_t buf[USB_CMD_DATA_SIZE]; emlGetMem(buf, arg0, arg1); // data, block num, blocks count (max 4) @@ -938,15 +944,13 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai byte_t dataoutbuf2[16]; uint8_t uid[10]; - // clear trace - clear_trace(); - set_tracing(false); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + clear_trace(); + set_tracing(false); bool isOK = true; @@ -1040,10 +1044,10 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(TRUE); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } while (true) { @@ -1158,10 +1162,10 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); set_tracing(TRUE); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } while (true) { @@ -1236,7 +1240,7 @@ void MifareCIdent(){ cmd_send(CMD_ACK,isOK,0,0,0,0); } - // +// // DESFIRE // @@ -1246,8 +1250,8 @@ void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain){ uint8_t uid[10] = {0x00}; uint32_t cuid; - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); int len = iso14443a_select_card(uid, NULL, &cuid); if(!len) {