]> git.zerfleddert.de Git - proxmark3-svn/commitdiff
Merge pull request #149 from marshmellow42/T55xx_tests
authorMartin Holst Swende <martin@swende.se>
Thu, 10 Dec 2015 09:44:44 +0000 (10:44 +0100)
committerMartin Holst Swende <martin@swende.se>
Thu, 10 Dec 2015 09:44:44 +0000 (10:44 +0100)
Add lf viking, lf demod/clock detection improvements

22 files changed:
CHANGELOG.md
armsrc/appmain.c
armsrc/apps.h
armsrc/lfops.c
armsrc/lfsampling.c
client/Makefile
client/cmddata.c
client/cmdlf.c
client/cmdlfawid.c
client/cmdlfio.c
client/cmdlft55xx.c
client/cmdlft55xx.h
client/cmdlfviking.c [new file with mode: 0644]
client/cmdlfviking.h [new file with mode: 0644]
client/default_pwd.dic [new file with mode: 0644]
client/hid-flasher/usb_cmd.h
client/lualibs/commands.lua
client/util.c
client/util.h
common/lfdemod.c
common/lfdemod.h
include/usb_cmd.h

index a3a0799ecf37928618e879cc5525069d606baabf..34be1b2b13072236517f1930756f006aaaabbf5c 100644 (file)
@@ -5,6 +5,11 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac
 ## [unreleased][unreleased]
 
 ### Added
+- `lf t55xx bruteforce <start password> <end password> [i <*.dic>]` - Simple bruteforce attack to find password - (iceman and others)
+- `lf viking clone`- clone viking tag to t55x7 or Q5 from 4byte hex ID input 
+- `lf viking sim`  - sim full viking tag from 4byte hex ID input
+- `lf viking read` - read viking tag and output ID
+- `lf t55xx wipe`  - sets t55xx back to factory defaults
 - Added viking demod to `lf search` (marshmellow)
 - `data askvikingdemod` demod viking id tag from graphbuffer (marshmellow)
 - `lf t55xx resetread` added reset then read command - should allow determining start
@@ -26,6 +31,12 @@ of stream transmissions (marshmellow)
 - Added option c to 'hf list' (mark CRC bytes) (piwi)
 
 ### Changed
+- Added `[l] <length>` option to data printdemodbuffer
+- Adjusted lf awid clone to optionally clone to Q5 tags
+- Adjusted lf t55xx detect to find Q5 tags (t5555) instead of just t55x7
+- Adjusted all lf NRZ demods - works more acurately and consistantly (as long as you have strong signal)
+- Adjusted lf pskindalademod to reduce false positive reads.
+- Small adjustments to psk, nrz, and ask clock detect routines - more reliable.
 - Adjusted lf em410x em410xsim to accept a clock argument
 - Adjusted lf t55xx dump to allow overriding the safety check and warning text (marshmellow)
 - Adjusted lf t55xx write input variables (marshmellow)
index e7324723f3049dc8ab3327f27d9f546f445827af..97817709a15794ce89184a28a98468a2bd2316db 100644 (file)
@@ -1001,6 +1001,9 @@ void UsbPacketReceived(uint8_t *packet, int len)
                case CMD_AWID_DEMOD_FSK: // Set realtime AWID demodulation
                        CmdAWIDdemodFSK(c->arg[0], 0, 0, 1);
                        break;
+               case CMD_VIKING_CLONE_TAG:
+                       CopyVikingtoT55xx(c->arg[0], c->arg[1], c->arg[2]);
+                       break;
 #endif
 
 #ifdef WITH_HITAG
index 4f3b50c6171ef99b6184c95505cae602fd2622cf..c8397c38cdf225cc1d810f8dc75916e653c428c4 100644 (file)
@@ -65,6 +65,7 @@ void WriteTItag(uint32_t idhi, uint32_t idlo, uint16_t crc);
 void AcquireTiType(void);
 void AcquireRawBitsTI(void);
 void SimulateTagLowFrequency(int period, int gap, int ledcontrol);
+void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen);
 void CmdHIDsimTAG(int hi, int lo, int ledcontrol);
 void CmdFSKsimTAG(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream);
 void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream);
@@ -74,8 +75,8 @@ void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol); // Realt
 void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol);
 void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol);
 void CopyIOtoT55x7(uint32_t hi, uint32_t lo); // Clone an ioProx card to T5557/T5567
-void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen);
 void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT); // Clone an HID card to T5557/T5567
+void CopyVikingtoT55xx(uint32_t block1, uint32_t block2, uint8_t Q5);
 void WriteEM410x(uint32_t card, uint32_t id_hi, uint32_t id_lo);
 void CopyIndala64toT55x7(uint32_t hi, uint32_t lo); // Clone Indala 64-bit tag by UID to T55x7
 void CopyIndala224toT55x7(uint32_t uid1, uint32_t uid2, uint32_t uid3, uint32_t uid4, uint32_t uid5, uint32_t uid6, uint32_t uid7); // Clone Indala 224-bit tag by UID to T55x7
index 01b88178169c6fe6c992e27d6b420b24a0ee24d4..47fec7c2a95d3b6737361b401e56fb0e2297847e 100644 (file)
@@ -17,7 +17,7 @@
 #include "lfdemod.h"
 #include "lfsampling.h"
 #include "protocols.h"
-#include "usb_cdc.h" //test
+#include "usb_cdc.h" // for usb_poll_validate_length
 
 /**
  * Function to do a modulation and then get samples.
@@ -73,8 +73,6 @@ void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint
        DoAcquisition_config(false);
 }
 
-
-
 /* blank r/w tag data stream
 ...0000000000000000 01111111
 1010101010101010101010101010101010101010101010101010101010101010
@@ -214,8 +212,6 @@ void ReadTItag(void)
        }
 }
 
-
-
 void WriteTIbyte(uint8_t b)
 {
        int i = 0;
@@ -250,7 +246,7 @@ void AcquireTiType(void)
 
        // clear buffer
        uint32_t *BigBuf = (uint32_t *)BigBuf_get_addr();
-       memset(BigBuf,0,BigBuf_max_traceLen()/sizeof(uint32_t));
+       BigBuf_Clear_ext(false);
 
        // Set up the synchronous serial port
        AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DIN;
@@ -312,16 +308,11 @@ void AcquireTiType(void)
        }
 }
 
-
-
-
 // arguments: 64bit data split into 32bit idhi:idlo and optional 16bit crc
 // if crc provided, it will be written with the data verbatim (even if bogus)
 // if not provided a valid crc will be computed from the data and written.
 void WriteTItag(uint32_t idhi, uint32_t idlo, uint16_t crc)
 {
-
-
        FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
        if(crc == 0) {
                crc = update_crc16(crc, (idlo)&0xff);
@@ -402,8 +393,8 @@ void SimulateTagLowFrequency(int period, int gap, int ledcontrol)
        AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
        AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK;
 
- #define SHORT_COIL()  LOW(GPIO_SSC_DOUT)
- #define OPEN_COIL()           HIGH(GPIO_SSC_DOUT)
+ #define SHORT_COIL()   LOW(GPIO_SSC_DOUT)
+ #define OPEN_COIL()    HIGH(GPIO_SSC_DOUT)
 
        i = 0;
        for(;;) {
@@ -693,13 +684,9 @@ void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream)
        //i+=16;
        //Dbprintf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", dest[i],dest[i+1],dest[i+2],dest[i+3],dest[i+4],dest[i+5],dest[i+6],dest[i+7],dest[i+8],dest[i+9],dest[i+10],dest[i+11],dest[i+12],dest[i+13],dest[i+14],dest[i+15]);
 
-       if (ledcontrol)
-               LED_A_ON();
-       
+       if (ledcontrol) LED_A_ON();
        SimulateTagLowFrequency(n, 0, ledcontrol);
-
-       if (ledcontrol)
-               LED_A_OFF();
+       if (ledcontrol) LED_A_OFF();
 }
 
 //carrier can be 2,4 or 8
@@ -749,12 +736,9 @@ void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream)
        //i+=16;
        //Dbprintf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", dest[i],dest[i+1],dest[i+2],dest[i+3],dest[i+4],dest[i+5],dest[i+6],dest[i+7],dest[i+8],dest[i+9],dest[i+10],dest[i+11],dest[i+12],dest[i+13],dest[i+14],dest[i+15]);
                   
-       if (ledcontrol)
-               LED_A_ON();
+       if (ledcontrol) LED_A_ON();
        SimulateTagLowFrequency(n, 0, ledcontrol);
-
-       if (ledcontrol)
-               LED_A_OFF();
+       if (ledcontrol) LED_A_OFF();
 }
 
 // loop to get raw HID waveform then FSK demodulate the TAG ID from it
@@ -851,7 +835,6 @@ void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol)
 void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol)
 {
        uint8_t *dest = BigBuf_get_addr();
-       //const size_t sizeOfBigBuff = BigBuf_max_traceLen();
        size_t size; 
        int idx=0;
        // Configure to go in 125Khz listen mode
@@ -864,72 +847,71 @@ void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol)
 
                DoAcquisition_default(-1,true);
                // FSK demodulator
-               //size = sizeOfBigBuff;  //variable size will change after demod so re initialize it before use
                size = 50*128*2; //big enough to catch 2 sequences of largest format
                idx = AWIDdemodFSK(dest, &size);
                
-               if (idx>0 && size==96){
-               // Index map
-               // 0            10            20            30              40            50              60
-               // |            |             |             |               |             |               |
-               // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96
-               // -----------------------------------------------------------------------------
-               // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1
-               // premable bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96
-               //          |---26 bit---|    |-----117----||-------------142-------------|
-               // b = format bit len, o = odd parity of last 3 bits
-               // f = facility code, c = card number
-               // w = wiegand parity
-               // (26 bit format shown)
-
-               //get raw ID before removing parities
-               uint32_t rawLo = bytebits_to_byte(dest+idx+64,32);
-               uint32_t rawHi = bytebits_to_byte(dest+idx+32,32);
-               uint32_t rawHi2 = bytebits_to_byte(dest+idx,32);
-
-               size = removeParity(dest, idx+8, 4, 1, 88);
-               // ok valid card found!
-
-               // Index map
-               // 0           10         20        30          40        50        60
-               // |           |          |         |           |         |         |
-               // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456
-               // -----------------------------------------------------------------------------
-               // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000
-               // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
-               // |26 bit|   |-117--| |-----142------|
-               // b = format bit len, o = odd parity of last 3 bits
-               // f = facility code, c = card number
-               // w = wiegand parity
-               // (26 bit format shown)
-
-               uint32_t fc = 0;
-               uint32_t cardnum = 0;
-               uint32_t code1 = 0;
-               uint32_t code2 = 0;
-               uint8_t fmtLen = bytebits_to_byte(dest,8);
-               if (fmtLen==26){
-                       fc = bytebits_to_byte(dest+9, 8);
-                       cardnum = bytebits_to_byte(dest+17, 16);
-                       code1 = bytebits_to_byte(dest+8,fmtLen);
-                       Dbprintf("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo);
-               } else {
-                       cardnum = bytebits_to_byte(dest+8+(fmtLen-17), 16);
-                       if (fmtLen>32){
-                        code1 = bytebits_to_byte(dest+8,fmtLen-32);
-                        code2 = bytebits_to_byte(dest+8+(fmtLen-32),32);
-                        Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo);
-                } else{
-                        code1 = bytebits_to_byte(dest+8,fmtLen);
-                        Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo);
-                }
-                       }
-                       if (findone){
-                               if (ledcontrol) LED_A_OFF();
-                               return;
+               if (idx<=0 || size!=96) continue;
+               // Index map
+               // 0            10            20            30              40            50              60
+               // |            |             |             |               |             |               |
+               // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96
+               // -----------------------------------------------------------------------------
+               // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1
+               // premable bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96
+               //          |---26 bit---|    |-----117----||-------------142-------------|
+               // b = format bit len, o = odd parity of last 3 bits
+               // f = facility code, c = card number
+               // w = wiegand parity
+               // (26 bit format shown)
+
+               //get raw ID before removing parities
+               uint32_t rawLo = bytebits_to_byte(dest+idx+64,32);
+               uint32_t rawHi = bytebits_to_byte(dest+idx+32,32);
+               uint32_t rawHi2 = bytebits_to_byte(dest+idx,32);
+
+               size = removeParity(dest, idx+8, 4, 1, 88);
+               if (size != 66) continue;
+               // ok valid card found!
+
+               // Index map
+               // 0           10         20        30          40        50        60
+               // |           |          |         |           |         |         |
+               // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456
+               // -----------------------------------------------------------------------------
+               // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000
+               // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
+               // |26 bit|   |-117--| |-----142------|
+               // b = format bit len, o = odd parity of last 3 bits
+               // f = facility code, c = card number
+               // w = wiegand parity
+               // (26 bit format shown)
+
+               uint32_t fc = 0;
+               uint32_t cardnum = 0;
+               uint32_t code1 = 0;
+               uint32_t code2 = 0;
+               uint8_t fmtLen = bytebits_to_byte(dest,8);
+               if (fmtLen==26){
+                       fc = bytebits_to_byte(dest+9, 8);
+                       cardnum = bytebits_to_byte(dest+17, 16);
+                       code1 = bytebits_to_byte(dest+8,fmtLen);
+                       Dbprintf("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo);
+               } else {
+                       cardnum = bytebits_to_byte(dest+8+(fmtLen-17), 16);
+                       if (fmtLen>32){
+                               code1 = bytebits_to_byte(dest+8,fmtLen-32);
+                               code2 = bytebits_to_byte(dest+8+(fmtLen-32),32);
+                               Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo);
+                       } else{
+                               code1 = bytebits_to_byte(dest+8,fmtLen);
+                               Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo);
                        }
-                       // reset
                }
+               if (findone){
+                       if (ledcontrol) LED_A_OFF();
+                       return;
+               }
+               // reset
                idx = 0;
                WDT_HIT();
        }
@@ -1064,11 +1046,8 @@ void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol)
 /*------------------------------
  * T5555/T5557/T5567/T5577 routines
  *------------------------------
- */
-
-/* NOTE: T55x7/T5555 configuration register definitions moved to protocols.h */
-
-/*
+ * NOTE: T55x7/T5555 configuration register definitions moved to protocols.h
+ *
  * Relevant communication times in microsecond
  * To compensate antenna falling times shorten the write times
  * and enlarge the gap ones.
@@ -1078,21 +1057,7 @@ void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol)
 #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 READ_GAP  52*8 
-
-//  VALUES TAKEN FROM EM4x function: SendForward
-//  START_GAP = 440;       (55*8) cycles at 125Khz (8us = 1cycle)
-//  WRITE_GAP = 128;       (16*8)
-//  WRITE_1   = 256 32*8;  (32*8) 
-
-//  These timings work for 4469/4269/4305 (with the 55*8 above)
-//  WRITE_0 = 23*8 , 9*8  SpinDelayUs(23*8); 
-
-// Sam7s has several timers, we will use the source TIMER_CLOCK1 (aka AT91C_TC_CLKS_TIMER_DIV1_CLOCK)
-// TIMER_CLOCK1 = MCK/2, MCK is running at 48 MHz, Timer is running at 48/2 = 24 MHz
-// Hitag units (T0) have duration of 8 microseconds (us), which is 1/125000 per second (carrier)
-// T0 = TIMER_CLOCK1 / 125000 = 192
-// 1 Cycle = 8 microseconds(us)  == 1 field clock
+#define READ_GAP  15*8 
 
 void TurnReadLFOn(int delay) {
        FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);
@@ -1191,7 +1156,7 @@ void T55xxWriteBlock(uint32_t Data, uint32_t Block, uint32_t Pwd, uint8_t arg) {
        cmd_send(CMD_ACK,0,0,0,0,0);
 }
 
-// Read one card block in page 0
+// Read one card block in page [page]
 void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd) {
        LED_A_ON();
        bool PwdMode = arg0 & 0x1;
@@ -1269,7 +1234,6 @@ void T55xxWakeUp(uint32_t Pwd){
 void WriteT55xx(uint32_t *blockdata, uint8_t startblock, uint8_t numblocks) {
        // write last block first and config block last (if included)
        for (uint8_t i = numblocks+startblock; i > startblock; i--) {
-               //Dbprintf("write- Blk: %d, d:%08X",i-1,blockdata[i-1]);
                T55xxWriteBlockExt(blockdata[i-1],i-1,0,0);
        }
 }
@@ -1277,7 +1241,6 @@ void WriteT55xx(uint32_t *blockdata, uint8_t startblock, uint8_t numblocks) {
 // Copy HID id to card and setup block 0 config
 void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT) {
        uint32_t data[] = {0,0,0,0,0,0,0};
-       //int data1=0, data2=0, data3=0, data4=0, data5=0, data6=0; //up to six blocks for long format
        uint8_t last_block = 0;
 
        if (longFMT) {
@@ -1367,6 +1330,15 @@ void CopyIndala224toT55x7(uint32_t uid1, uint32_t uid2, uint32_t uid3, uint32_t
        //      T5567WriteBlock(0x603E10E2,0);
        DbpString("DONE!");
 }
+// clone viking tag to T55xx
+void CopyVikingtoT55xx(uint32_t block1, uint32_t block2, uint8_t Q5) {
+       uint32_t data[] = {T55x7_BITRATE_RF_32 | T55x7_MODULATION_MANCHESTER | (2 << T55x7_MAXBLOCK_SHIFT), block1, block2};
+       if (Q5) data[0] = (32 << T5555_BITRATE_SHIFT) | T5555_MODULATION_MANCHESTER | 2 << T5555_MAXBLOCK_SHIFT;
+       // Program the data blocks for supplied ID and the block 0 config
+       WriteT55xx(data, 0, 3);
+       LED_D_OFF();
+       cmd_send(CMD_ACK,0,0,0,0,0);
+}
 
 // Define 9bit header for EM410x tags
 #define EM410X_HEADER            0x1FF
@@ -1464,7 +1436,6 @@ void WriteEM410x(uint32_t card, uint32_t id_hi, uint32_t id_lo) {
 #define FWD_CMD_READ 0x9
 #define FWD_CMD_DISABLE 0x5
 
-
 uint8_t forwardLink_data[64]; //array of forwarded bits
 uint8_t * forward_ptr; //ptr for forward message preparation
 uint8_t fwd_bit_sz; //forwardlink bit counter
@@ -1475,8 +1446,15 @@ uint8_t * fwd_write_ptr; //forwardlink bit pointer
 // see EM4469 spec
 //====================================================================
 //--------------------------------------------------------------------
+//  VALUES TAKEN FROM EM4x function: SendForward
+//  START_GAP = 440;       (55*8) cycles at 125Khz (8us = 1cycle)
+//  WRITE_GAP = 128;       (16*8)
+//  WRITE_1   = 256 32*8;  (32*8) 
+
+//  These timings work for 4469/4269/4305 (with the 55*8 above)
+//  WRITE_0 = 23*8 , 9*8  SpinDelayUs(23*8); 
+
 uint8_t Prepare_Cmd( uint8_t cmd ) {
-       //--------------------------------------------------------------------
 
        *forward_ptr++ = 0; //start bit
        *forward_ptr++ = 0; //second pause for 4050 code
@@ -1496,10 +1474,7 @@ uint8_t Prepare_Cmd( uint8_t cmd ) {
 // prepares address bits
 // see EM4469 spec
 //====================================================================
-
-//--------------------------------------------------------------------
 uint8_t Prepare_Addr( uint8_t addr ) {
-       //--------------------------------------------------------------------
 
        register uint8_t line_parity;
 
@@ -1520,10 +1495,7 @@ uint8_t Prepare_Addr( uint8_t addr ) {
 // prepares data bits intreleaved with parity bits
 // see EM4469 spec
 //====================================================================
-
-//--------------------------------------------------------------------
 uint8_t Prepare_Data( uint16_t data_low, uint16_t data_hi) {
-       //--------------------------------------------------------------------
 
        register uint8_t line_parity;
        register uint8_t column_parity;
@@ -1575,7 +1547,6 @@ void SendForward(uint8_t fwd_bit_count) {
        fwd_write_ptr++;
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off
        SpinDelayUs(55*8); //55 cycles off (8us each)for 4305
-       FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
        FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);//field on
        SpinDelayUs(16*8); //16 cycles on (8us each)
 
@@ -1587,7 +1558,6 @@ void SendForward(uint8_t fwd_bit_count) {
                        //These timings work for 4469/4269/4305 (with the 55*8 above)
                        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off
                        SpinDelayUs(23*8); //16-4 cycles off (8us each)
-                       FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
                        FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);//field on
                        SpinDelayUs(9*8); //16 cycles on (8us each)
                }
@@ -1606,7 +1576,6 @@ void EM4xLogin(uint32_t Password) {
 
        //Wait for command to complete
        SpinDelay(20);
-
 }
 
 void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode) {
@@ -1617,7 +1586,7 @@ void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode) {
        uint32_t i = 0;
 
        // Clear destination buffer before sending the command
-       memset(dest, 0x80, bufferlength);
+       BigBuf_Clear_ext(false);
 
        //If password mode do login
        if (PwdMode == 1) EM4xLogin(Pwd);
index 115d4b18ffaba74ef9c5da113cabb5444679375b..ab7c79dd3e31ab2b4867c2f1bb080eee0290eb4c 100644 (file)
@@ -10,7 +10,7 @@
 #include "apps.h"
 #include "util.h"
 #include "string.h"
-
+#include "usb_cdc.h" // for usb_poll_validate_length
 #include "lfsampling.h"
 
 sample_config config = { 1, 8, 1, 95, 0 } ;
@@ -255,7 +255,8 @@ uint32_t SnoopLF()
 **/
 void doT55x7Acquisition(size_t sample_size) {
 
-       #define T55xx_READ_UPPER_THRESHOLD 128+40  // 40 grph
+       #define T55xx_READ_UPPER_THRESHOLD 128+60  // 60 grph
+       #define T55xx_READ_LOWER_THRESHOLD 128-60  // -60 grph
        #define T55xx_READ_TOL   5
 
        uint8_t *dest = BigBuf_get_addr();
@@ -267,10 +268,11 @@ void doT55x7Acquisition(size_t sample_size) {
        uint16_t i = 0;
        bool startFound = false;
        bool highFound = false;
+       bool lowFound = false;
        uint8_t curSample = 0;
-       uint8_t firstSample = 0;
+       uint8_t lastSample = 0;
        uint16_t skipCnt = 0;
-       while(!BUTTON_PRESS() && skipCnt<1000) {
+       while(!BUTTON_PRESS() && !usb_poll_validate_length() && skipCnt<1000 && i<bufsize ) {
                WDT_HIT();
                if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
                        AT91C_BASE_SSC->SSC_THR = 0x43;
@@ -282,24 +284,33 @@ void doT55x7Acquisition(size_t sample_size) {
 
                        // skip until the first high sample above threshold
                        if (!startFound && curSample > T55xx_READ_UPPER_THRESHOLD) {
-                               if (curSample > firstSample) 
-                                       firstSample = curSample;
+                               //if (curSample > lastSample) 
+                               //      lastSample = curSample;
                                highFound = true;
                        } else if (!highFound) {
                                skipCnt++;
                                continue;
                        }
+                       // skip until the first Low sample below threshold
+                       if (!startFound && curSample < T55xx_READ_LOWER_THRESHOLD) {
+                               //if (curSample > lastSample) 
+                               lastSample = curSample;
+                               lowFound = true;
+                       } else if (!lowFound) {
+                               skipCnt++;
+                               continue;
+                       }
+
 
                        // skip until first high samples begin to change
-                       if (startFound || curSample < firstSample-T55xx_READ_TOL){
+                       if (startFound || curSample > T55xx_READ_LOWER_THRESHOLD+T55xx_READ_TOL){
                                // if just found start - recover last sample
                                if (!startFound) {
-                                       dest[i++] = firstSample;
+                                       dest[i++] = lastSample;
                                        startFound = true;
                                }
                                // collect samples
                                dest[i++] = curSample;
-                               if (i >= bufsize-1) break;
                        }
                }
        }
index 903cbf9ef35fa315a3a2f82ee5331d3a636c6cf6..0972f441912280439ca04265472a76ab0d31af6c 100644 (file)
@@ -98,6 +98,7 @@ CMDSRCS =     nonce2key/crapto1.c\
                        cmdmain.c \
                        cmdlft55xx.c \
                        cmdlfpcf7931.c\
+                       cmdlfviking.c\
                        pm3_binlib.c\
                        scripting.c\
                        cmdscript.c\
index 580352780720f8ce12f71885477b04ad3e312293..e8b77d1ddedfd578e565e610b60220990ec68a03 100644 (file)
@@ -58,11 +58,12 @@ int CmdSetDebugMode(const char *Cmd)
 }
 
 int usage_data_printdemodbuf(){
-               PrintAndLog("Usage: data printdemodbuffer x o <offset>");
+               PrintAndLog("Usage: data printdemodbuffer x o <offset> l <length>");
                PrintAndLog("Options:        ");
                PrintAndLog("       h          This help");
                PrintAndLog("       x          output in hex (omit for binary output)");
                PrintAndLog("       o <offset> enter offset in # of bits");
+               PrintAndLog("       l <length> enter length to print in # of bits or hex characters respectively");
                return 0;       
 }
 
@@ -87,7 +88,8 @@ int CmdPrintDemodBuff(const char *Cmd)
        char hex[512]={0x00};
        bool hexMode = false;
        bool errors = false;
-       uint8_t offset = 0;
+       uint32_t offset = 0; //could be size_t but no param_get16...
+       uint32_t length = 512;
        char cmdp = 0;
        while(param_getchar(Cmd, cmdp) != 0x00)
        {
@@ -103,10 +105,16 @@ int CmdPrintDemodBuff(const char *Cmd)
                        break;
                case 'o':
                case 'O':
-                       offset = param_get8(Cmd, cmdp+1);
+                       offset = param_get32ex(Cmd, cmdp+1, 0, 10);
                        if (!offset) errors = true;
                        cmdp += 2;
                        break;
+               case 'l':
+               case 'L':
+                       length = param_get32ex(Cmd, cmdp+1, 512, 10);
+                       if (!length) errors = true;
+                       cmdp += 2;
+                       break;
                default:
                        PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));
                        errors = true;
@@ -116,18 +124,17 @@ int CmdPrintDemodBuff(const char *Cmd)
        }
        //Validations
        if(errors) return usage_data_printdemodbuf();
-
-       int numBits = (DemodBufferLen-offset) & 0x7FC; //make sure we don't exceed our string
+       length = (length > (DemodBufferLen-offset)) ? DemodBufferLen-offset : length; 
+       int numBits = (length) & 0x00FFC; //make sure we don't exceed our string
 
        if (hexMode){
                char *buf = (char *) (DemodBuffer + offset);
+               numBits = (numBits > sizeof(hex)) ? sizeof(hex) : numBits;
                numBits = binarraytohex(hex, buf, numBits);
                if (numBits==0) return 0;
                PrintAndLog("DemodBuffer: %s",hex);             
        } else {
-               //setDemodBuf(DemodBuffer, DemodBufferLen-offset, offset);
-               char *bin = sprint_bin_break(DemodBuffer+offset,numBits,16);
-               PrintAndLog("DemodBuffer:\n%s",bin);
+               PrintAndLog("DemodBuffer:\n%s", sprint_bin_break(DemodBuffer+offset,numBits,16));
        }
        return 1;
 }
@@ -315,7 +322,7 @@ int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType)
        char amp = param_getchar(Cmd, 0);
        uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0};
        sscanf(Cmd, "%i %i %i %i %c", &clk, &invert, &maxErr, &maxLen, &amp);
-       if (!maxLen) maxLen = 512*64;
+       if (!maxLen) maxLen = BIGBUF_SIZE;
        if (invert != 0 && invert != 1) {
                PrintAndLog("Invalid argument: %s", Cmd);
                return 0;
@@ -646,7 +653,7 @@ int CmdVikingDemod(const char *Cmd)
                return 0;
        }
        size_t size = DemodBufferLen;
-       //call lfdemod.c demod for gProxII
+       //call lfdemod.c demod for Viking
        int ans = VikingDemod_AM(DemodBuffer, &size);
        if (ans < 0) {
                if (g_debugMode) PrintAndLog("Error Viking_Demod %d", ans);
@@ -656,7 +663,7 @@ int CmdVikingDemod(const char *Cmd)
        uint32_t raw1 = bytebits_to_byte(DemodBuffer+ans, 32);
        uint32_t raw2 = bytebits_to_byte(DemodBuffer+ans+32, 32);
        uint32_t cardid = bytebits_to_byte(DemodBuffer+ans+24, 32);
-       uint8_t checksum = bytebits_to_byte(DemodBuffer+ans+32+24, 8);
+       uint8_t  checksum = bytebits_to_byte(DemodBuffer+ans+32+24, 8);
        PrintAndLog("Viking Tag Found: Card ID %08X, Checksum: %02X", cardid, checksum);
        PrintAndLog("Raw: %08X%08X", raw1,raw2);
        setDemodBuf(DemodBuffer+ans, 64, 0);
@@ -936,14 +943,14 @@ char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert)
 int FSKrawDemod(const char *Cmd, bool verbose)
 {
        //raw fsk demod  no manchester decoding no start bit finding just get binary from wave
-       //set defaults
-       int rfLen = 0;
-       int invert = 0;
-       int fchigh = 0;
-       int fclow = 0;
+       uint8_t rfLen, invert, fchigh, fclow;
 
+       //set defaults
        //set options from parameters entered with the command
-       sscanf(Cmd, "%i %i %i %i", &rfLen, &invert, &fchigh, &fclow);
+       rfLen = param_get8ex(Cmd, 0, 0, 10);
+       invert = param_get8ex(Cmd, 1, 0, 10);
+       fchigh = param_get8ex(Cmd, 2, 0, 10);
+       fclow = param_get8ex(Cmd, 3, 0, 10);
 
        if (strlen(Cmd)>0 && strlen(Cmd)<=2) {
                 if (rfLen==1){
@@ -957,34 +964,34 @@ int FSKrawDemod(const char *Cmd, bool verbose)
        if (BitLen==0) return 0;
        //get field clock lengths
        uint16_t fcs=0;
-       if (fchigh==0 || fclow == 0){
+       if (!fchigh || !fclow) {
                fcs = countFC(BitStream, BitLen, 1);
-               if (fcs==0){
-                       fchigh=10;
-                       fclow=8;
-               }else{
-                       fchigh = (fcs >> 8) & 0xFF;
-                       fclow = fcs & 0xFF;
+               if (!fcs) {
+                       fchigh = 10;
+                       fclow = 8;
+               } else {
+                       fchigh = (fcs >> 8) & 0x00FF;
+                       fclow = fcs & 0x00FF;
                }
        }
        //get bit clock length
-       if (rfLen==0){
+       if (!rfLen){
                rfLen = detectFSKClk(BitStream, BitLen, fchigh, fclow);
-               if (rfLen == 0) rfLen = 50;
+               if (!rfLen) rfLen = 50;
        }
-       int size = fskdemod(BitStream,BitLen,(uint8_t)rfLen,(uint8_t)invert,(uint8_t)fchigh,(uint8_t)fclow);
-       if (size>0){
+       int size = fskdemod(BitStream, BitLen, rfLen, invert, fchigh, fclow);
+       if (size > 0){
                setDemodBuf(BitStream,size,0);
 
                // Now output the bitstream to the scrollback by line of 16 bits
                if (verbose || g_debugMode) {
-                       PrintAndLog("\nUsing Clock:%d, invert:%d, fchigh:%d, fclow:%d", rfLen, invert, fchigh, fclow);
+                       PrintAndLog("\nUsing Clock:%u, invert:%u, fchigh:%u, fclow:%u", rfLen, invert, fchigh, fclow);
                        PrintAndLog("%s decoded bitstream:",GetFSKType(fchigh,fclow,invert));
                        printDemodBuff();
                }
 
                return 1;
-       } else{
+       } else {
                if (g_debugMode) PrintAndLog("no FSK data found");
        }
        return 0;
@@ -1481,6 +1488,17 @@ int CmdFSKdemodPyramid(const char *Cmd)
 // NATIONAL CODE, ICAR database
 // COUNTRY CODE (ISO3166) or http://cms.abvma.ca/uploads/ManufacturersISOsandCountryCodes.pdf
 // FLAG (animal/non-animal)
+/*
+38 IDbits   
+10 country code 
+1 extra app bit
+14 reserved bits
+1 animal bit
+16 ccitt CRC chksum over 64bit ID CODE.
+24 appli bits.
+
+-- sample: 985121004515220  [ 37FF65B88EF94 ]
+*/
 int CmdFDXBdemodBI(const char *Cmd){
 
        int invert = 1;
@@ -1507,6 +1525,10 @@ int CmdFDXBdemodBI(const char *Cmd){
                if (g_debugMode) PrintAndLog("Error FDXBDemod , no startmarker found :: %d",preambleIndex);
                return 0;
        }
+       if (size != 128) {
+               if (g_debugMode) PrintAndLog("Error incorrect data length found");
+               return 0;
+       }
 
        setDemodBuf(BitStream, 128, preambleIndex);
 
@@ -1576,6 +1598,9 @@ int PSKDemod(const char *Cmd, bool verbose)
                //invalid carrier
                return 0;
        }
+       if (g_debugMode){
+               PrintAndLog("Carrier: rf/%d",carrier);
+       }
        int errCnt=0;
        errCnt = pskRawDemod(BitStream, &BitLen, &clk, &invert);
        if (errCnt > maxErr){
@@ -1617,7 +1642,7 @@ int CmdIndalaDecode(const char *Cmd)
        uint8_t invert=0;
        size_t size = DemodBufferLen;
        size_t startIdx = indala26decode(DemodBuffer, &size, &invert);
-       if (startIdx < 1) {
+       if (startIdx < 1 || size > 224) {
                if (g_debugMode==1)
                        PrintAndLog("Error2: %d",ans);
                return -1;
@@ -1633,7 +1658,7 @@ int CmdIndalaDecode(const char *Cmd)
        uid1=bytebits_to_byte(DemodBuffer,32);
        uid2=bytebits_to_byte(DemodBuffer+32,32);
        if (DemodBufferLen==64) {
-               PrintAndLog("Indala UID=%s (%x%08x)", sprint_bin(DemodBuffer,DemodBufferLen), uid1, uid2);
+               PrintAndLog("Indala UID=%s (%x%08x)", sprint_bin_break(DemodBuffer,DemodBufferLen,16), uid1, uid2);
        } else {
                uid3=bytebits_to_byte(DemodBuffer+64,32);
                uid4=bytebits_to_byte(DemodBuffer+96,32);
@@ -1641,7 +1666,7 @@ int CmdIndalaDecode(const char *Cmd)
                uid6=bytebits_to_byte(DemodBuffer+160,32);
                uid7=bytebits_to_byte(DemodBuffer+192,32);
                PrintAndLog("Indala UID=%s (%x%08x%08x%08x%08x%08x%08x)", 
-                   sprint_bin(DemodBuffer,DemodBufferLen), uid1, uid2, uid3, uid4, uid5, uid6, uid7);
+                   sprint_bin_break(DemodBuffer,DemodBufferLen,16), uid1, uid2, uid3, uid4, uid5, uid6, uid7);
        }
        if (g_debugMode){
                PrintAndLog("DEBUG: printing demodbuffer:");
@@ -1711,7 +1736,7 @@ int NRZrawDemod(const char *Cmd, bool verbose)
        size_t BitLen = getFromGraphBuf(BitStream);
        if (BitLen==0) return 0;
        int errCnt=0;
-       errCnt = nrzRawDemod(BitStream, &BitLen, &clk, &invert, maxErr);
+       errCnt = nrzRawDemod(BitStream, &BitLen, &clk, &invert);
        if (errCnt > maxErr){
                if (g_debugMode) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt);
                return 0;
@@ -1957,10 +1982,7 @@ int getSamples(const char *Cmd, bool silent)
 
        int n = strtol(Cmd, NULL, 0);
 
-       if (n == 0)
-               n = sizeof(got);
-
-       if (n > sizeof(got))
+       if (n == 0 || n > sizeof(got))
                n = sizeof(got);
 
        PrintAndLog("Reading %d bytes from device memory\n", n);
@@ -2370,14 +2392,14 @@ 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] [o] <offset> -- print the data in the DemodBuffer - 'x' for hex output"},
+       {"printdemodbuffer",CmdPrintDemodBuff,  1, "[x] [o] <offset> [l] <length> -- 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] ... <options> -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, "<filename> -- Save trace (from graph window)"},
        {"scale",           CmdScale,           1, "<int> -- Set cursor display scale"},
-       {"setdebugmode",    CmdSetDebugMode,    1, "<0|1> -- Turn on or off Debugging Mode for demods"},
+       {"setdebugmode",    CmdSetDebugMode,    1, "<0|1|2> -- Turn on or off Debugging Level for lf demods"},
        {"shiftgraphzero",  CmdGraphShiftZero,  1, "<shift> -- Shift 0 for Graphed wave + or - shift value"},
        {"dirthreshold",    CmdDirectionalThreshold,   1, "<thres up> <thres down> -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."},
        {"tune",            CmdTuneSamples,     0, "Get hw tune samples for graph window"},
index 616d932a25251aa46cf2fc3bee614b4702bb7675..41feec20d5b708b98636eaacaa71a5a4b7ce04c5 100644 (file)
@@ -29,6 +29,7 @@
 #include "cmdlft55xx.h"
 #include "cmdlfpcf7931.h"
 #include "cmdlfio.h"
+#include "cmdlfviking.h"
 #include "lfdemod.h"
 
 static int CmdHelp(const char *Cmd);
@@ -124,7 +125,7 @@ int CmdFlexdemod(const char *Cmd)
                }
        }
 
-#define LONG_WAIT 100
+ #define LONG_WAIT 100
        int start;
        for (start = 0; start < GraphTraceLen - LONG_WAIT; start++) {
                int first = GraphBuffer[start];
@@ -206,10 +207,13 @@ int CmdIndalaDemod(const char *Cmd)
        uint8_t rawbits[4096];
        int rawbit = 0;
        int worst = 0, worstPos = 0;
- // PrintAndLog("Expecting a bit less than %d raw bits", GraphTraceLen / 32);
+       // PrintAndLog("Expecting a bit less than %d raw bits", GraphTraceLen / 32);
+       
+       // loop through raw signal - since we know it is psk1 rf/32 fc/2 skip every other value (+=2)
        for (i = 0; i < GraphTraceLen-1; i += 2) {
                count += 1;
                if ((GraphBuffer[i] > GraphBuffer[i + 1]) && (state != 1)) {
+                       // appears redundant - marshmellow
                        if (state == 0) {
                                for (j = 0; j <  count - 8; j += 16) {
                                        rawbits[rawbit++] = 0;
@@ -222,6 +226,7 @@ int CmdIndalaDemod(const char *Cmd)
                        state = 1;
                        count = 0;
                } else if ((GraphBuffer[i] < GraphBuffer[i + 1]) && (state != 0)) {
+                       //appears redundant
                        if (state == 1) {
                                for (j = 0; j <  count - 8; j += 16) {
                                        rawbits[rawbit++] = 1;
@@ -419,6 +424,7 @@ int CmdIndalaClone(const char *Cmd)
                c.arg[1] = uid2;
        }
 
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;
 }
@@ -541,6 +547,7 @@ int CmdLFSetConfig(const char *Cmd)
        //Averaging is a flag on high-bit of arg[1]
        UsbCommand c = {CMD_SET_LF_SAMPLING_CONFIG};
        memcpy(c.d.asBytes,&config,sizeof(sample_config));
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;
 }
@@ -557,6 +564,7 @@ int CmdLFRead(const char *Cmd)
        if (param_getchar(Cmd, cmdp) == 's') arg1 = true; //suppress print
        //And ship it to device
        UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_125K, {arg1,0,0}};
+       clearCommandBuffer();
        SendCommand(&c);
        //WaitForResponse(CMD_ACK,NULL);        
        if ( !WaitForResponseTimeout(CMD_ACK,NULL,2500) ) {
@@ -576,6 +584,7 @@ int CmdLFSnoop(const char *Cmd)
        }
 
        UsbCommand c = {CMD_LF_SNOOP_RAW_ADC_SAMPLES};
+       clearCommandBuffer();
        SendCommand(&c);
        WaitForResponse(CMD_ACK,NULL);
        return 0;
@@ -622,6 +631,7 @@ int CmdLFSim(const char *Cmd)
        printf("\n");
        PrintAndLog("Starting to simulate");
        UsbCommand c = {CMD_SIMULATE_TAG_125K, {GraphTraceLen, gap, 0}};
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;
 }
@@ -771,6 +781,7 @@ int CmdLFfskSim(const char *Cmd)
        UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}};
 
        memcpy(c.d.asBytes, DemodBuffer, size);
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;
 }
@@ -864,6 +875,7 @@ int CmdLFaskSim(const char *Cmd)
        UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
        PrintAndLog("preparing to sim ask data: %d bits", size);
        memcpy(c.d.asBytes, DemodBuffer, size);
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;
 }
@@ -971,6 +983,7 @@ int CmdLFpskSim(const char *Cmd)
        UsbCommand c = {CMD_PSK_SIM_TAG, {arg1, arg2, size}};
        PrintAndLog("DEBUG: Sending DemodBuffer Length: %d", size);
        memcpy(c.d.asBytes, DemodBuffer, size);
+       clearCommandBuffer();
        SendCommand(&c);
        
        return 0;
@@ -1124,13 +1137,6 @@ int CmdLFfind(const char *Cmd)
                return 1;
        }
 
-       //add psk and indala
-       ans=CmdIndalaDecode("");
-       if (ans>0) {
-               PrintAndLog("\nValid Indala ID Found!");
-               return 1;
-       }
-
        ans=CmdAskEM410xDemod("");
        if (ans>0) {
                PrintAndLog("\nValid EM410x ID Found!");
@@ -1161,6 +1167,12 @@ int CmdLFfind(const char *Cmd)
                return 1;
        }       
 
+       ans=CmdIndalaDecode("");
+       if (ans>0) {
+               PrintAndLog("\nValid Indala ID Found!");
+               return 1;
+       }
+
        ans=CmdPSKNexWatch("");
        if (ans>0) {
                PrintAndLog("\nValid NexWatch ID Found!");
@@ -1202,14 +1214,15 @@ int CmdLFfind(const char *Cmd)
 static command_t CommandTable[] = 
 {
        {"help",        CmdHelp,            1, "This help"},
-       {"awid",        CmdLFAWID,          1, "{ AWID RFIDs... }"},
-       {"em4x",        CmdLFEM4X,          1, "{ EM4X RFIDs... }"},
-       {"hid",         CmdLFHID,           1, "{ HID RFIDs... }"},
+       {"awid",        CmdLFAWID,          1, "{ AWID RFIDs...    }"},
+       {"em4x",        CmdLFEM4X,          1, "{ EM4X RFIDs...    }"},
+       {"hid",         CmdLFHID,           1, "{ HID RFIDs...     }"},
        {"hitag",       CmdLFHitag,         1, "{ Hitag tags and transponders... }"},
-       {"io",          CmdLFIO,            1, "{ ioProx tags... }"},
+       {"io",          CmdLFIO,            1, "{ ioProx tags...   }"},
        {"pcf7931",     CmdLFPCF7931,       1, "{ PCF7931 RFIDs... }"},
-       {"t55xx",       CmdLFT55XX,         1, "{ T55xx RFIDs... }"},
-       {"ti",          CmdLFTI,            1, "{ TI RFIDs... }"},
+       {"t55xx",       CmdLFT55XX,         1, "{ T55xx RFIDs...   }"},
+       {"ti",          CmdLFTI,            1, "{ TI RFIDs...      }"},
+       {"viking",      CmdLFViking,        1, "{ Viking tags...   }"},
        {"cmdread",     CmdLFCommandRead,   0, "<d period> <z period> <o period> <c command> ['H'] -- Modulate LF reader field to send command before read (all periods in microseconds) (option 'H' for 134)"},
        {"config",      CmdLFSetConfig,     0, "Set config for LF sampling, bit/sample, decimation, frequency"},
        {"flexdemod",   CmdFlexdemod,       1, "Demodulate samples for FlexPass"},
index 06397e7086844f57a05fc0db883ca5bd8d5cbc3f..309f41180223cc80f04857c05167491b26bf1cea 100644 (file)
 #include "cmdparser.h"  // CmdsParse, CmdsHelp
 #include "cmdlfawid.h"  // AWID function declarations
 #include "lfdemod.h"    // parityTest
+#include "util.h"       // weigandparity
+#include "protocols.h"  // for T55xx config register definitions
 #include "cmdmain.h"
-static int CmdHelp(const char *Cmd);
 
+static int CmdHelp(const char *Cmd);
 
 int usage_lf_awid_fskdemod(void) {
        PrintAndLog("Enables AWID26 compatible reader mode printing details of scanned AWID26 tags.");
@@ -26,11 +28,11 @@ int usage_lf_awid_fskdemod(void) {
        PrintAndLog("If the ['1'] option is provided, reader mode is exited after reading a single AWID26 card.");
        PrintAndLog("");
        PrintAndLog("Usage:  lf awid fskdemod ['1']");
-       PrintAndLog("  Options : ");
+       PrintAndLog("Options : ");
        PrintAndLog("  1 : (optional) stop after reading a single card");
        PrintAndLog("");
-       PrintAndLog("   sample : lf awid fskdemod");
-       PrintAndLog("          : lf awid fskdemod 1");
+       PrintAndLog("Samples : lf awid fskdemod");
+       PrintAndLog("        : lf awid fskdemod 1");
        return 0;
 }
 
@@ -40,11 +42,11 @@ int usage_lf_awid_sim(void) {
        PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit.  Larger values are truncated.");
        PrintAndLog("");
        PrintAndLog("Usage:  lf awid sim <Facility-Code> <Card-Number>");
-       PrintAndLog("  Options : ");
+       PrintAndLog("Options : ");
        PrintAndLog("  <Facility-Code> : 8-bit value representing the AWID facility code");
        PrintAndLog("  <Card Number>   : 16-bit value representing the AWID card number");
        PrintAndLog("");
-       PrintAndLog("   sample : lf awid sim 224 1337");
+       PrintAndLog("Sample : lf awid sim 224 1337");
        return 0;
 }
 
@@ -54,133 +56,91 @@ int usage_lf_awid_clone(void) {
        PrintAndLog("Per AWID26 format, the facility-code is 8-bit and the card number is 16-bit.  Larger values are truncated.");
        PrintAndLog("");
        PrintAndLog("Usage:  lf awid clone <Facility-Code> <Card-Number>");
-       PrintAndLog("  Options : ");
+       PrintAndLog("Options : ");
        PrintAndLog("  <Facility-Code> : 8-bit value representing the AWID facility code");
        PrintAndLog("  <Card Number>   : 16-bit value representing the AWID card number");
+       PrintAndLog("  Q5              : optional - clone to Q5 (T5555) instead of T55x7 chip");
        PrintAndLog("");
-       PrintAndLog("   sample : lf awid clone 224 1337");
+       PrintAndLog("Sample  : lf awid clone 224 1337");
        return 0;
 }
 
-int CmdAWIDDemodFSK(const char *Cmd)
-{
+int CmdAWIDDemodFSK(const char *Cmd) {
        int findone=0;
-       if(Cmd[0]=='1') findone=1;
-       if (Cmd[0]=='h' || Cmd[0] == 'H') return usage_lf_awid_fskdemod();
-       UsbCommand c={CMD_AWID_DEMOD_FSK};
-       c.arg[0]=findone;
+       if (Cmd[0] == 'h' || Cmd[0] == 'H') return usage_lf_awid_fskdemod();
+       if (Cmd[0] == '1') findone = 1;
+
+       UsbCommand c = {CMD_AWID_DEMOD_FSK, {findone, 0, 0}};
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;   
 }
 
-int getAWIDBits(unsigned int fc, unsigned int cn, uint8_t *AWIDBits)
-{
-       int i;
-       uint32_t fcode=(fc & 0x000000FF), cnum=(cn & 0x0000FFFF), uBits=0;
-       if (fcode != fc)
-               PrintAndLog("NOTE: Facility code truncated for AWID26 format (8-bit facility code)");
-       if (cnum!=cn)
-               PrintAndLog("NOTE: Card number was truncated for AWID26 format (16-bit card number)");
-
-       AWIDBits[0] = 0x01; // 6-bit Preamble with 2 parity bits
-       AWIDBits[1] = 0x1D; // First byte from card format (26-bit) plus parity bits
-       AWIDBits[2] = 0x80; // Set the next two bits as 0b10 to finish card format
-       uBits = (fcode<<4) + (cnum>>12);
-       if (!parityTest(uBits,12,0))
-               AWIDBits[2] |= (1<<5); // If not already even parity, set bit to make even
-       uBits = AWIDBits[2]>>5;
-       if (!parityTest(uBits, 3, 1))
-               AWIDBits[2] |= (1<<4);
-       uBits = fcode>>5; // first 3 bits of facility-code
-       AWIDBits[2] += (uBits<<1);
-       if (!parityTest(uBits, 3, 1))
-               AWIDBits[2]++; // Set parity bit to make odd parity
-       uBits = (fcode & 0x1C)>>2;
-       AWIDBits[3] = 0;
-       if (!parityTest(uBits,3,1))
-               AWIDBits[3] |= (1<<4);
-       AWIDBits[3] += (uBits<<5);
-       uBits = ((fcode & 0x3)<<1) + ((cnum & 0x8000)>>15); // Grab/shift 2 LSBs from facility code and add shifted MSB from cardnum
-       if (!parityTest(uBits,3,1))
-               AWIDBits[3]++; // Set LSB for parity
-       AWIDBits[3]+= (uBits<<1);
-       uBits = (cnum & 0x7000)>>12;
-       AWIDBits[4] = uBits<<5;
-       if (!parityTest(uBits,3,1))
-               AWIDBits[4] |= (1<<4);
-       uBits = (cnum & 0x0E00)>>9;
-       AWIDBits[4] += (uBits<<1);
-       if (!parityTest(uBits,3,1))
-               AWIDBits[4]++; // Set LSB for parity
-       uBits = (cnum & 0x1C0)>>6; // Next bits from card number
-       AWIDBits[5]=(uBits<<5);
-       if (!parityTest(uBits,3,1))
-               AWIDBits[5] |= (1<<4); // Set odd parity bit as needed
-       uBits = (cnum & 0x38)>>3;
-       AWIDBits[5]+= (uBits<<1);
-       if (!parityTest(uBits,3,1))
-               AWIDBits[5]++; // Set odd parity bit as needed
-       uBits = (cnum & 0x7); // Last three bits from card number!
-       AWIDBits[6] = (uBits<<5);
-       if (!parityTest(uBits,3,1))
-               AWIDBits[6] |= (1<<4);
-       uBits = (cnum & 0x0FFF);
-       if (!parityTest(uBits,12,1))
-               AWIDBits[6] |= (1<<3);
-       else
-               AWIDBits[6]++;
-       for (i = 7; i<12; i++)
-               AWIDBits[i]=0x11;
+//refactored by marshmellow
+int getAWIDBits(uint32_t fc, uint32_t cn, uint8_t      *AWIDBits) {
+       uint8_t pre[66];
+       memset(pre, 0, sizeof(pre));
+       AWIDBits[7]=1;
+       num_to_bytebits(26, 8, pre);
+
+       uint8_t wiegand[24];
+       num_to_bytebits(fc, 8, wiegand);
+       num_to_bytebits(cn, 16, wiegand+8);
+
+       wiegand_add_parity(pre+8, wiegand, 24);
+
+       size_t bitLen = addParity(pre, AWIDBits+8, 66, 4, 1);
+       if (bitLen != 88) return 0;
+       //for (uint8_t i = 0; i<3; i++){
+       //      PrintAndLog("DEBUG: %08X", bytebits_to_byte(AWIDBits+(32*i),32));
+       //}
        return 1;
 }
 
-int CmdAWIDSim(const char *Cmd)
-{
-       uint32_t fcode = 0, cnum = 0, fc=0, cn=0, i=0;
-       uint8_t *BS, BitStream[12];
+int CmdAWIDSim(const char *Cmd) {
+       uint32_t fcode = 0, cnum = 0, fc=0, cn=0;
+       uint8_t BitStream[96];
+       uint8_t *bs = BitStream;
+       size_t size = sizeof(BitStream);
+       memset(bs, 0, size);
+
        uint64_t arg1 = (10<<8) + 8; // fcHigh = 10, fcLow = 8
        uint64_t arg2 = 50; // clk RF/50 invert=0
-       BS = BitStream;
-       if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) {
-               return usage_lf_awid_sim();
-       }
+       
+       if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) return usage_lf_awid_sim();
+
+       fcode = (fc & 0x000000FF);
+       cnum = (cn & 0x0000FFFF);
+
+       if (fc != fcode) PrintAndLog("Facility-Code (%u) truncated to 8-bits: %u",fc,fcode);
+       if (cn != cnum) PrintAndLog("Card number (%u) truncated to 16-bits: %u",cn,cnum);
 
-       fcode=(fc & 0x000000FF);
-       cnum=(cn & 0x0000FFFF);
-       if (fc!=fcode)
-               PrintAndLog("Facility-Code (%u) truncated to 8-bits: %u",fc,fcode);
-       if (cn!=cnum)
-               PrintAndLog("Card number (%u) truncated to 16-bits: %u",cn,cnum);
        PrintAndLog("Emulating AWID26 -- FC: %u; CN: %u\n",fcode,cnum);
        PrintAndLog("Press pm3-button to abort simulation or run another command");
+
+       if (!getAWIDBits(fc, cn, bs)) {
+               PrintAndLog("Error with tag bitstream generation.");
+               return 1;
+       }
        // AWID uses: fcHigh: 10, fcLow: 8, clk: 50, invert: 0
-       if (getAWIDBits(fc, cn, BS)) {
-                       PrintAndLog("Running 'lf simfsk c 50 H 10 L 8 d %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x'", 
-                                                                                                                                                               BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6],
-                                                                                                                                                               BS[7],BS[8],BS[9],BS[10],BS[11]);
-               } else
-                       PrintAndLog("Error with tag bitstream generation.");
-       UsbCommand c;
-       c.cmd = CMD_FSK_SIM_TAG;
-       c.arg[0] = arg1; // fcHigh<<8 + fcLow
-       c.arg[1] = arg2; // Inversion and clk setting
-       c.arg[2] = 96; // Bitstream length: 96-bits == 12 bytes
-       for (i=0; i < 96; i++)
-               c.d.asBytes[i] = (BS[i/8] & (1<<(7-(i%8))))?1:0;
+       UsbCommand c = {CMD_FSK_SIM_TAG, {arg1, arg2, size}};
+       memcpy(c.d.asBytes, bs, size);
+       clearCommandBuffer();
        SendCommand(&c);
        return 0;
 }
 
-int CmdAWIDClone(const char *Cmd)
-{
-       uint32_t fc=0,cn=0,blocks[4] = {0x00107060, 0, 0, 0x11111111}, i=0;
-       uint8_t BitStream[12];
-       uint8_t *BS=BitStream;
-       UsbCommand c, resp;
+int CmdAWIDClone(const char *Cmd) {
+       uint32_t blocks[4] = {T55x7_MODULATION_FSK2a | T55x7_BITRATE_RF_50 | 3<<T55x7_MAXBLOCK_SHIFT, 0, 0, 0};
+       uint32_t fc=0,cn=0;
+       uint8_t BitStream[96];
+       uint8_t *bs=BitStream;
+       memset(bs,0,sizeof(BitStream));
 
-       if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) {
-               return usage_lf_awid_clone();
-       }
+       if (sscanf(Cmd, "%u %u", &fc, &cn ) != 2) return usage_lf_awid_clone();
+
+       if (param_getchar(Cmd, 3) == 'Q' || param_getchar(Cmd, 3) == 'q')
+               blocks[0] = T5555_MODULATION_FSK2 | T5555_INVERT_OUTPUT | 50<<T5555_BITRATE_SHIFT | 3<<T5555_MAXBLOCK_SHIFT;
 
        if ((fc & 0xFF) != fc) {
                fc &= 0xFF;
@@ -190,48 +150,58 @@ int CmdAWIDClone(const char *Cmd)
                cn &= 0xFFFF;
                PrintAndLog("Card Number Truncated to 16-bits (AWID26): %u", cn);
        }
-       if (getAWIDBits(fc,cn,BS)) {
-               PrintAndLog("Preparing to clone AWID26 to T55x7 with FC: %u, CN: %u (Raw: %02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x)", 
-                                                                       fc,cn, BS[0],BS[1],BS[2],BS[3],BS[4],BS[5],BS[6],BS[7],BS[8],BS[9],BS[10],BS[11]);
-               blocks[1] = (BS[0]<<24) + (BS[1]<<16) + (BS[2]<<8) + (BS[3]);
-               blocks[2] = (BS[4]<<24) + (BS[5]<<16) + (BS[6]<<8) + (BS[7]);
-               PrintAndLog("Block 0: 0x%08x", blocks[0]);
-               PrintAndLog("Block 1: 0x%08x", blocks[1]);
-               PrintAndLog("Block 2: 0x%08x", blocks[2]);
-               PrintAndLog("Block 3: 0x%08x", blocks[3]);
-               for (i=0; i<4; i++) {
-                       c.cmd = CMD_T55XX_WRITE_BLOCK;
-                       c.arg[0] = blocks[i];
-                       c.arg[1] = i;
-                       c.arg[2] = 0;
-                       SendCommand(&c);
-                       if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){
-                               PrintAndLog("Error occurred, device did not respond during write operation.");
-                               return -1;
-                       }
 
+       if ( !getAWIDBits(fc, cn, bs)) {
+               PrintAndLog("Error with tag bitstream generation.");
+               return 1;
+       }
+
+       blocks[1] = bytebits_to_byte(bs,32);
+       blocks[2] = bytebits_to_byte(bs+32,32);
+       blocks[3] = bytebits_to_byte(bs+64,32);
+
+       PrintAndLog("Preparing to clone AWID26 to T55x7 with FC: %u, CN: %u", 
+           fc, cn);
+       PrintAndLog("Blk | Data ");
+       PrintAndLog("----+------------");
+       PrintAndLog(" 00 | 0x%08x", blocks[0]);
+       PrintAndLog(" 01 | 0x%08x", blocks[1]);
+       PrintAndLog(" 02 | 0x%08x", blocks[2]);
+       PrintAndLog(" 03 | 0x%08x", blocks[3]);
+
+       UsbCommand resp;
+       UsbCommand c = {CMD_T55XX_WRITE_BLOCK, {0,0,0}};
+
+       for (uint8_t i=0; i<4; i++) {
+               c.cmd = CMD_T55XX_WRITE_BLOCK;
+               c.arg[0] = blocks[i];
+               c.arg[1] = i;
+               c.arg[2] = 0;
+               clearCommandBuffer();
+               SendCommand(&c);
+               if (!WaitForResponseTimeout(CMD_ACK, &resp, 1000)){
+                       PrintAndLog("Error occurred, device did not respond during write operation.");
+                       return -1;
                }
+
        }
        return 0;
 }
 
-static command_t CommandTable[] = 
-{
-       {"help",      CmdHelp,        1, "This help"},
+static command_t CommandTable[] = {
+       {"help",      CmdHelp,         1, "This help"},
        {"fskdemod",  CmdAWIDDemodFSK, 0, "['1'] Realtime AWID FSK demodulator (option '1' for one tag only)"},
        {"sim",       CmdAWIDSim,      0, "<Facility-Code> <Card Number> -- AWID tag simulator"},
-       {"clone",     CmdAWIDClone,    0, "<Facility-Code> <Card Number> -- Clone AWID to T55x7 (tag must be in range of antenna)"},
+       {"clone",     CmdAWIDClone,    0, "<Facility-Code> <Card Number> <Q5> -- Clone AWID to T55x7 (tag must be in range of antenna)"},
        {NULL, NULL, 0, NULL}
 };
 
-int CmdLFAWID(const char *Cmd)
-{
+int CmdLFAWID(const char *Cmd) {
        CmdsParse(CommandTable, Cmd);
        return 0;
 }
 
-int CmdHelp(const char *Cmd)
-{
+int CmdHelp(const char *Cmd) {
        CmdsHelp(CommandTable);
        return 0;
 }
index aa21c44babed25eaf079db697c7351afcb7fcc84..e376951124fb8842cb3f7e55cbd1e1c27271e24e 100644 (file)
@@ -67,9 +67,9 @@ 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"},
+  {"clone",       CmdIOClone,         0, "Clone ioProx Tag"},
   {NULL, NULL, 0, NULL}
 };
 
index 55b4ab65284a8f921f9199fa31f4bce894f810ac..868126c900fd65a84d7c7a269744e0c1097cee12 100644 (file)
 #include "../common/iso14443crc.h"\r
 #include "cmdhf14a.h"\r
 \r
-#define CONFIGURATION_BLOCK 0x00\r
-#define TRACE_BLOCK 0x01\r
+#define T55x7_CONFIGURATION_BLOCK 0x00\r
+#define T55x7_PAGE0 0x00\r
+#define T55x7_PAGE1 0x01\r
+#define T55x7_PWD      0x00000010\r
 #define REGULAR_READ_MODE_BLOCK 0xFF\r
 \r
 // Default configuration\r
-t55xx_conf_block_t config = { .modulation = DEMOD_ASK, .inverted = FALSE, .offset = 0x00, .block0 = 0x00};\r
+t55xx_conf_block_t config = { .modulation = DEMOD_ASK, .inverted = FALSE, .offset = 0x00, .block0 = 0x00, .Q5 = FALSE };\r
 \r
 t55xx_conf_block_t Get_t55xx_Config(){\r
        return config;\r
@@ -41,13 +43,14 @@ void Set_t55xx_Config(t55xx_conf_block_t conf){
 }\r
 \r
 int usage_t55xx_config(){\r
-       PrintAndLog("Usage: lf t55xx config [d <demodulation>] [i 1] [o <offset>]");\r
+       PrintAndLog("Usage: lf t55xx config [d <demodulation>] [i 1] [o <offset>] [Q5]");\r
        PrintAndLog("Options:");\r
        PrintAndLog("       h                        This help");\r
-       PrintAndLog("       b <8|16|32|40|50|64|100|128>     Set bitrate");\r
+       PrintAndLog("       b <8|16|32|40|50|64|100|128>  Set bitrate");\r
        PrintAndLog("       d <FSK|FSK1|FSK1a|FSK2|FSK2a|ASK|PSK1|PSK2|NRZ|BI|BIa>  Set demodulation FSK / ASK / PSK / NRZ / Biphase / Biphase A");\r
-       PrintAndLog("       i [1]                            Invert data signal, defaults to normal");\r
-       PrintAndLog("       o [offset]                       Set offset, where data should start decode in bitstream");\r
+       PrintAndLog("       i [1]                         Invert data signal, defaults to normal");\r
+       PrintAndLog("       o [offset]                    Set offset, where data should start decode in bitstream");\r
+       PrintAndLog("       Q5                            Set as Q5(T5555) chip instead of T55x7");\r
        PrintAndLog("");\r
        PrintAndLog("Examples:");\r
        PrintAndLog("      lf t55xx config d FSK          - FSK demodulation");\r
@@ -123,13 +126,15 @@ int usage_t55xx_dump(){
        return 0;\r
 }\r
 int usage_t55xx_detect(){\r
-       PrintAndLog("Usage:  lf t55xx detect [1]");\r
+       PrintAndLog("Usage:  lf t55xx detect [1] [p <password>]");\r
        PrintAndLog("Options:");\r
-       PrintAndLog("     [graph buffer data]  - if set, use Graphbuffer otherwise read data from tag.");\r
+       PrintAndLog("     1             - if set, use Graphbuffer otherwise read data from tag.");\r
+       PrintAndLog("     p <password>  - OPTIONAL password (8 hex characters)");\r
        PrintAndLog("");\r
        PrintAndLog("Examples:");\r
        PrintAndLog("      lf t55xx detect");\r
        PrintAndLog("      lf t55xx detect 1");\r
+       PrintAndLog("      lf t55xx detect p 11223344");\r
        PrintAndLog("");\r
        return 0;\r
 }\r
@@ -144,9 +149,32 @@ int usage_t55xx_wakup(){
                PrintAndLog("      lf t55xx wakeup p 11223344  - send wakeup password");\r
        return 0;\r
 }\r
+int usage_t55xx_bruteforce(){\r
+       PrintAndLog("This command uses A) bruteforce to scan a number range");\r
+       PrintAndLog("                  B) a dictionary attack");\r
+       PrintAndLog("Usage: lf t55xx bruteforce <start password> <end password> [i <*.dic>]");\r
+       PrintAndLog("       password must be 4 bytes (8 hex symbols)");\r
+       PrintAndLog("Options:");\r
+       PrintAndLog("     h           - this help");\r
+       PrintAndLog("     <start_pwd> - 4 byte hex value to start pwd search at");\r
+       PrintAndLog("     <end_pwd>   - 4 byte hex value to end pwd search at");\r
+       PrintAndLog("     i <*.dic>   - loads a default keys dictionary file <*.dic>");\r
+       PrintAndLog("");\r
+       PrintAndLog("Examples:");\r
+       PrintAndLog("       lf t55xx bruteforce aaaaaaaa bbbbbbbb");\r
+       PrintAndLog("       lf t55xx bruteforce i default_pwd.dic");\r
+       PrintAndLog("");\r
+       return 0;\r
+}\r
 \r
 static int CmdHelp(const char *Cmd);\r
 \r
+void printT5xxHeader(uint8_t page){\r
+       PrintAndLog("Reading Page %d:", page);\r
+       PrintAndLog("blk | hex data | binary");\r
+       PrintAndLog("----+----------+---------------------------------");       \r
+}\r
+\r
 int CmdT55xxSetConfig(const char *Cmd) {\r
 \r
        uint8_t offset = 0;\r
@@ -155,6 +183,7 @@ int CmdT55xxSetConfig(const char *Cmd) {
        uint8_t bitRate = 0;\r
        uint8_t rates[9] = {8,16,32,40,50,64,100,128,0};\r
        uint8_t cmdp = 0;\r
+       config.Q5 = FALSE;\r
        bool errors = FALSE;\r
        while(param_getchar(Cmd, cmdp) != 0x00 && !errors)\r
        {\r
@@ -227,6 +256,11 @@ int CmdT55xxSetConfig(const char *Cmd) {
                                config.offset = offset;\r
                        cmdp+=2;\r
                        break;\r
+               case 'Q':\r
+               case 'q':               \r
+                       config.Q5 = TRUE;\r
+                       cmdp++;\r
+                       break;\r
                default:\r
                        PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));\r
                        errors = TRUE;\r
@@ -249,7 +283,7 @@ int T55xxReadBlock(uint8_t block, bool page1, bool usepwd, bool override, uint32
        if ( usepwd ) {\r
                // try reading the config block and verify that PWD bit is set before doing this!\r
                if ( !override ) {\r
-                       if ( !AquireData(0, CONFIGURATION_BLOCK, false, 0 ) ) return 0;\r
+                       if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, false, 0 ) ) return 0;\r
                        if ( !tryDetectModulation() ) {\r
                                PrintAndLog("Safety Check: Could not detect if PWD bit is set in config block. Exits.");\r
                                return 0;\r
@@ -317,8 +351,8 @@ int CmdT55xxReadBlock(const char *Cmd) {
                PrintAndLog("Block must be between 0 and 7");\r
                return 0;\r
        }\r
-       PrintAndLog("Reading Page %d:", page1); \r
-       PrintAndLog("blk | hex data | binary");\r
+\r
+       printT5xxHeader(page1);\r
        return T55xxReadBlock(block, page1, usepwd, override, password);\r
 }\r
 \r
@@ -346,18 +380,28 @@ bool DecodeT55xxBlock(){
                        ans = FSKrawDemod(cmdStr, FALSE);\r
                        break;\r
                case DEMOD_ASK:\r
-                       snprintf(cmdStr, sizeof(buf),"%d %d 0", bitRate[config.bitrate], config.inverted );\r
+                       snprintf(cmdStr, sizeof(buf),"%d %d 1", bitRate[config.bitrate], config.inverted );\r
                        ans = ASKDemod(cmdStr, FALSE, FALSE, 1);\r
                        break;\r
                case DEMOD_PSK1:\r
-                       snprintf(cmdStr, sizeof(buf),"%d %d 0", bitRate[config.bitrate], config.inverted );\r
+                       // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise)\r
+                       save_restoreGB(1);\r
+                       CmdLtrim("160");\r
+                       snprintf(cmdStr, sizeof(buf),"%d %d 6", bitRate[config.bitrate], config.inverted );\r
                        ans = PSKDemod(cmdStr, FALSE);\r
+                       //undo trim samples\r
+                       save_restoreGB(0);\r
                        break;\r
                case DEMOD_PSK2: //inverted won't affect this\r
                case DEMOD_PSK3: //not fully implemented\r
-                       snprintf(cmdStr, sizeof(buf),"%d 0 1", bitRate[config.bitrate] );\r
+                       // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise)\r
+                       save_restoreGB(1);\r
+                       CmdLtrim("160");\r
+                       snprintf(cmdStr, sizeof(buf),"%d 0 6", bitRate[config.bitrate] );\r
                        ans = PSKDemod(cmdStr, FALSE);\r
                        psk1TOpsk2(DemodBuffer, DemodBufferLen);\r
+                       //undo trim samples\r
+                       save_restoreGB(0);\r
                        break;\r
                case DEMOD_NRZ:\r
                        snprintf(cmdStr, sizeof(buf),"%d %d 1", bitRate[config.bitrate], config.inverted );\r
@@ -365,7 +409,7 @@ bool DecodeT55xxBlock(){
                        break;\r
                case DEMOD_BI:\r
                case DEMOD_BIa:\r
-                       snprintf(cmdStr, sizeof(buf),"0 %d %d 0", bitRate[config.bitrate], config.inverted );\r
+                       snprintf(cmdStr, sizeof(buf),"0 %d %d 1", bitRate[config.bitrate], config.inverted );\r
                        ans = ASKbiphaseDemod(cmdStr, FALSE);\r
                        break;\r
                default:\r
@@ -375,15 +419,41 @@ bool DecodeT55xxBlock(){
 }\r
 \r
 int CmdT55xxDetect(const char *Cmd){\r
+       bool errors = FALSE;\r
+       bool useGB = FALSE;\r
+       bool usepwd = FALSE;\r
+       uint32_t password = 0;\r
+       uint8_t cmdp = 0;\r
 \r
-       char cmdp = param_getchar(Cmd, 0);\r
-       if (strlen(Cmd) > 1 || cmdp == 'h' || cmdp == 'H')\r
-               return usage_t55xx_detect();\r
+       while(param_getchar(Cmd, cmdp) != 0x00 && !errors) {\r
+               switch(param_getchar(Cmd, cmdp)) {\r
+               case 'h':\r
+               case 'H':\r
+                       return usage_t55xx_detect();\r
+               case 'p':\r
+               case 'P':\r
+                       password = param_get32ex(Cmd, cmdp+1, 0, 16);\r
+                       usepwd = TRUE;\r
+                       cmdp += 2;\r
+                       break;\r
+               case '1':\r
+                       // use Graphbuffer data\r
+                       useGB = TRUE;\r
+                       cmdp++;\r
+                       break;\r
+               default:\r
+                       PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp));\r
+                       errors = true;\r
+                       break;\r
+               }\r
+       }\r
+       if (errors) return usage_t55xx_detect();\r
        \r
-       if (strlen(Cmd)==0)\r
-               if ( !AquireData(0, CONFIGURATION_BLOCK, false, 0) )\r
+       if ( !useGB) {\r
+               if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, usepwd, password) )\r
                        return 0;\r
-\r
+       }\r
+       \r
        if ( !tryDetectModulation() )\r
                PrintAndLog("Could not detect modulation automatically. Try setting it manually with \'lf t55xx config\'");\r
 \r
@@ -396,21 +466,21 @@ bool tryDetectModulation(){
        t55xx_conf_block_t tests[15];\r
        int bitRate=0;\r
        uint8_t fc1 = 0, fc2 = 0, clk=0;\r
-       save_restoreGB(1);\r
+\r
        if (GetFskClock("", FALSE, FALSE)){ \r
                fskClocks(&fc1, &fc2, &clk, FALSE);\r
-               if ( FSKrawDemod("0 0", FALSE) && test(DEMOD_FSK, &tests[hits].offset, &bitRate)){\r
+               if ( FSKrawDemod("0 0", FALSE) && test(DEMOD_FSK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){\r
                        tests[hits].modulation = DEMOD_FSK;\r
                        if (fc1==8 && fc2 == 5)\r
                                tests[hits].modulation = DEMOD_FSK1a;\r
-                       else if (fc1==10 && fc2 == 8)\r
+                       else if (fc1==10 && fc2 == 8)\r
                                tests[hits].modulation = DEMOD_FSK2;\r
                        tests[hits].bitrate = bitRate;\r
                        tests[hits].inverted = FALSE;\r
                        tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer);\r
                        ++hits;\r
                }\r
-               if ( FSKrawDemod("0 1", FALSE) && test(DEMOD_FSK, &tests[hits].offset, &bitRate)) {\r
+               if ( FSKrawDemod("0 1", FALSE) && test(DEMOD_FSK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                        tests[hits].modulation = DEMOD_FSK;\r
                        if (fc1 == 8 && fc2 == 5)\r
                                tests[hits].modulation = DEMOD_FSK1;\r
@@ -425,28 +495,28 @@ bool tryDetectModulation(){
        } else {\r
                clk = GetAskClock("", FALSE, FALSE);\r
                if (clk>0) {\r
-                       if ( ASKDemod("0 0 0", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) {\r
+                       if ( ASKDemod("0 0 1", FALSE, FALSE, 1) && test(DEMOD_ASK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                                tests[hits].modulation = DEMOD_ASK;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = FALSE;\r
                                tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer);\r
                                ++hits;\r
                        }\r
-                       if ( ASKDemod("0 1 0", FALSE, FALSE, 1)  && test(DEMOD_ASK, &tests[hits].offset, &bitRate)) {\r
+                       if ( ASKDemod("0 1 1", FALSE, FALSE, 1)  && test(DEMOD_ASK, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                                tests[hits].modulation = DEMOD_ASK;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = TRUE;\r
                                tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer);\r
                                ++hits;\r
                        }\r
-                       if ( ASKbiphaseDemod("0 0 0 0", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate) ) {\r
+                       if ( ASKbiphaseDemod("0 0 0 2", FALSE) && test(DEMOD_BI, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5) ) {\r
                                tests[hits].modulation = DEMOD_BI;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = FALSE;\r
                                tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer);\r
                                ++hits;\r
                        }\r
-                       if ( ASKbiphaseDemod("0 0 1 0", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate) ) {\r
+                       if ( ASKbiphaseDemod("0 0 1 2", FALSE) && test(DEMOD_BIa, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5) ) {\r
                                tests[hits].modulation = DEMOD_BIa;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = TRUE;\r
@@ -455,10 +525,10 @@ bool tryDetectModulation(){
                        }\r
                }\r
                //undo trim from ask\r
-               save_restoreGB(0);\r
+               //save_restoreGB(0);\r
                clk = GetNrzClock("", FALSE, FALSE);\r
                if (clk>0) {\r
-                       if ( NRZrawDemod("0 0 1", FALSE)  && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) {\r
+                       if ( NRZrawDemod("0 0 1", FALSE)  && test(DEMOD_NRZ, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                                tests[hits].modulation = DEMOD_NRZ;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = FALSE;\r
@@ -466,7 +536,7 @@ bool tryDetectModulation(){
                                ++hits;\r
                        }\r
 \r
-                       if ( NRZrawDemod("0 1 1", FALSE)  && test(DEMOD_NRZ, &tests[hits].offset, &bitRate)) {\r
+                       if ( NRZrawDemod("0 1 1", FALSE)  && test(DEMOD_NRZ, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                                tests[hits].modulation = DEMOD_NRZ;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = TRUE;\r
@@ -475,18 +545,20 @@ bool tryDetectModulation(){
                        }\r
                }\r
                \r
-               //undo trim from nrz\r
-               save_restoreGB(0);\r
+               // allow undo\r
+               // skip first 160 samples to allow antenna to settle in (psk gets inverted occasionally otherwise)\r
+               save_restoreGB(1);\r
+               CmdLtrim("160");\r
                clk = GetPskClock("", FALSE, FALSE);\r
                if (clk>0) {\r
-                       if ( PSKDemod("0 0 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) {\r
+                       if ( PSKDemod("0 0 6", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                                tests[hits].modulation = DEMOD_PSK1;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = FALSE;\r
                                tests[hits].block0 = PackBits(tests[hits].offset, 32, DemodBuffer);\r
                                ++hits;\r
                        }\r
-                       if ( PSKDemod("0 1 1", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate)) {\r
+                       if ( PSKDemod("0 1 6", FALSE) && test(DEMOD_PSK1, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)) {\r
                                tests[hits].modulation = DEMOD_PSK1;\r
                                tests[hits].bitrate = bitRate;\r
                                tests[hits].inverted = TRUE;\r
@@ -494,9 +566,9 @@ bool tryDetectModulation(){
                                ++hits;\r
                        }\r
                        // PSK2 - needs a call to psk1TOpsk2.\r
-                       if ( PSKDemod("0 0 1", FALSE)) {\r
+                       if ( PSKDemod("0 0 6", FALSE)) {\r
                                psk1TOpsk2(DemodBuffer, DemodBufferLen);\r
-                               if (test(DEMOD_PSK2, &tests[hits].offset, &bitRate)){\r
+                               if (test(DEMOD_PSK2, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){\r
                                        tests[hits].modulation = DEMOD_PSK2;\r
                                        tests[hits].bitrate = bitRate;\r
                                        tests[hits].inverted = FALSE;\r
@@ -505,9 +577,9 @@ bool tryDetectModulation(){
                                }\r
                        } // inverse waves does not affect this demod\r
                        // PSK3 - needs a call to psk1TOpsk2.\r
-                       if ( PSKDemod("0 0 1", FALSE)) {\r
+                       if ( PSKDemod("0 0 6", FALSE)) {\r
                                psk1TOpsk2(DemodBuffer, DemodBufferLen);\r
-                               if (test(DEMOD_PSK3, &tests[hits].offset, &bitRate)){\r
+                               if (test(DEMOD_PSK3, &tests[hits].offset, &bitRate, clk, &tests[hits].Q5)){\r
                                        tests[hits].modulation = DEMOD_PSK3;\r
                                        tests[hits].bitrate = bitRate;\r
                                        tests[hits].inverted = FALSE;\r
@@ -516,7 +588,9 @@ bool tryDetectModulation(){
                                }\r
                        } // inverse waves does not affect this demod\r
                }\r
-       }               \r
+               //undo trim samples\r
+               save_restoreGB(0);\r
+       }       \r
        if ( hits == 1) {\r
                config.modulation = tests[0].modulation;\r
                config.bitrate = tests[0].bitrate;\r
@@ -569,37 +643,28 @@ bool testModulation(uint8_t mode, uint8_t modread){
        return FALSE;\r
 }\r
 \r
-bool testBitRate(uint8_t readRate, uint8_t mod){\r
-       uint8_t expected[8] = {8, 16, 32, 40, 50, 64, 100, 128};\r
-       uint8_t detRate = 0;\r
-       switch( mod ){\r
+bool testQ5Modulation(uint8_t  mode, uint8_t   modread){\r
+       switch( mode ){\r
                case DEMOD_FSK:\r
-               case DEMOD_FSK1:\r
-               case DEMOD_FSK1a:\r
-               case DEMOD_FSK2:\r
-               case DEMOD_FSK2a:\r
-                       detRate = GetFskClock("",FALSE, FALSE); \r
-                       if (expected[readRate] == detRate) \r
-                               return TRUE;\r
+                       if (modread >= 4 && modread <= 5) return TRUE;\r
                        break;\r
                case DEMOD_ASK:\r
-               case DEMOD_BI:\r
-               case DEMOD_BIa:\r
-                       detRate = GetAskClock("",FALSE, FALSE); \r
-                       if (expected[readRate] == detRate) \r
-                               return TRUE;\r
+                       if (modread == 0) return TRUE;\r
                        break;\r
                case DEMOD_PSK1:\r
+                       if (modread == 1) return TRUE;\r
+                       break;\r
                case DEMOD_PSK2:\r
+                       if (modread == 2) return TRUE;\r
+                       break;\r
                case DEMOD_PSK3:\r
-                       detRate = GetPskClock("",FALSE, FALSE); \r
-                       if (expected[readRate] == detRate)\r
-                               return TRUE;\r
+                       if (modread == 3) return TRUE;\r
                        break;\r
                case DEMOD_NRZ:\r
-                       detRate = GetNrzClock("",FALSE, FALSE); \r
-                       if (expected[readRate] == detRate)\r
-                               return TRUE;\r
+                       if (modread == 7) return TRUE;\r
+                       break;\r
+               case DEMOD_BI:\r
+                       if (modread == 6) return TRUE;\r
                        break;\r
                default:\r
                        return FALSE;\r
@@ -607,13 +672,60 @@ bool testBitRate(uint8_t readRate, uint8_t mod){
        return FALSE;\r
 }\r
 \r
-bool test(uint8_t mode, uint8_t *offset, int *fndBitRate){\r
+bool testQ5(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t    clk){\r
+\r
+       if ( DemodBufferLen < 64 ) return FALSE;\r
+       uint8_t si = 0;\r
+       for (uint8_t idx = 28; idx < 64; idx++){\r
+               si = idx;\r
+               if ( PackBits(si, 28, DemodBuffer) == 0x00 ) continue;\r
+\r
+               uint8_t safer     = PackBits(si, 4, DemodBuffer); si += 4;     //master key\r
+               uint8_t resv      = PackBits(si, 8, DemodBuffer); si += 8;\r
+               // 2nibble must be zeroed.\r
+               if (safer != 0x6) continue;\r
+               if ( resv > 0x00) continue;\r
+               //uint8_t       pageSel   = PackBits(si, 1, DemodBuffer); si += 1;\r
+               //uint8_t fastWrite = PackBits(si, 1, DemodBuffer); si += 1;\r
+               si += 1+1;\r
+               int bitRate       = PackBits(si, 5, DemodBuffer)*2 + 2; si += 5;     //bit rate\r
+               if (bitRate > 128 || bitRate < 8) continue;\r
+\r
+               //uint8_t AOR       = PackBits(si, 1, DemodBuffer); si += 1;   \r
+               //uint8_t PWD       = PackBits(si, 1, DemodBuffer); si += 1; \r
+               //uint8_t pskcr     = PackBits(si, 2, DemodBuffer); si += 2;  //could check psk cr\r
+               //uint8_t inverse   = PackBits(si, 1, DemodBuffer); si += 1;\r
+               si += 1+1+2+1;\r
+               uint8_t modread   = PackBits(si, 3, DemodBuffer); si += 3;\r
+               uint8_t maxBlk    = PackBits(si, 3, DemodBuffer); si += 3;\r
+               //uint8_t ST        = PackBits(si, 1, DemodBuffer); si += 1;\r
+               if (maxBlk == 0) continue;\r
+               //test modulation\r
+               if (!testQ5Modulation(mode, modread)) continue;\r
+               if (bitRate != clk) continue;\r
+               *fndBitRate = bitRate;\r
+               *offset = idx;\r
+\r
+               return TRUE;\r
+       }\r
+       return FALSE;\r
+}\r
+\r
+bool testBitRate(uint8_t readRate, uint8_t clk){\r
+       uint8_t expected[] = {8, 16, 32, 40, 50, 64, 100, 128};\r
+       if (expected[readRate] == clk)\r
+               return true;\r
+\r
+       return false;\r
+}\r
+\r
+bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5){\r
 \r
        if ( DemodBufferLen < 64 ) return FALSE;\r
        uint8_t si = 0;\r
-       for (uint8_t idx = 0; idx < 64; idx++){\r
+       for (uint8_t idx = 28; idx < 64; idx++){\r
                si = idx;\r
-               if ( PackBits(si, 32, DemodBuffer) == 0x00 ) continue;\r
+               if ( PackBits(si, 28, DemodBuffer) == 0x00 ) continue;\r
 \r
                uint8_t safer    = PackBits(si, 4, DemodBuffer); si += 4;     //master key\r
                uint8_t resv     = PackBits(si, 4, DemodBuffer); si += 4;     //was 7 & +=7+3 //should be only 4 bits if extended mode\r
@@ -622,7 +734,7 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate){
                if ( resv > 0x00) continue;\r
 \r
                uint8_t xtRate   = PackBits(si, 3, DemodBuffer); si += 3;     //extended mode part of rate\r
-               int bitRate  = PackBits(si, 3, DemodBuffer); si += 3;     //bit rate\r
+               int bitRate      = PackBits(si, 3, DemodBuffer); si += 3;     //bit rate\r
                if (bitRate > 7) continue;\r
                uint8_t extend   = PackBits(si, 1, DemodBuffer); si += 1;     //bit 15 extended mode\r
                uint8_t modread  = PackBits(si, 5, DemodBuffer); si += 5+2+1; \r
@@ -638,9 +750,14 @@ bool test(uint8_t mode, uint8_t *offset, int *fndBitRate){
                }\r
                //test modulation\r
                if (!testModulation(mode, modread)) continue;\r
-               if (!testBitRate(bitRate, mode)) continue;\r
+               if (!testBitRate(bitRate, clk)) continue;\r
                *fndBitRate = bitRate;\r
                *offset = idx;\r
+               *Q5 = FALSE;\r
+               return TRUE;\r
+       }\r
+       if (testQ5(mode, offset, fndBitRate, clk)) {\r
+               *Q5 = TRUE;\r
                return TRUE;\r
        }\r
        return FALSE;\r
@@ -664,6 +781,7 @@ void printT55xxBlock(const char *blockNum){
                bits[i - config.offset]=DemodBuffer[i];\r
 \r
        blockData = PackBits(0, 32, bits);\r
+\r
        PrintAndLog("  %s | %08X | %s", blockNum, blockData, sprint_bin(bits,32));\r
 }\r
 \r
@@ -687,6 +805,7 @@ int special(const char *Cmd) {
 }\r
 \r
 int printConfiguration( t55xx_conf_block_t b){\r
+       PrintAndLog("Chip Type  : %s", (b.Q5) ? "T5555(Q5)" : "T55x7");\r
        PrintAndLog("Modulation : %s", GetSelectedModulationStr(b.modulation) );\r
        PrintAndLog("Bit Rate   : %s", GetBitRateStr(b.bitrate) );\r
        PrintAndLog("Inverted   : %s", (b.inverted) ? "Yes" : "No" );\r
@@ -728,8 +847,8 @@ int CmdT55xxWakeUp(const char *Cmd) {
 \r
 int CmdT55xxWriteBlock(const char *Cmd) {\r
        uint8_t block = 0xFF; //default to invalid block\r
-       uint32_t data = 0xFFFFFFFF; //default to blank Block \r
-       uint32_t password = 0xFFFFFFFF; //default to blank Block 7\r
+       uint32_t data = 0; //default to blank Block \r
+       uint32_t password = 0; //default to blank Block 7\r
        bool usepwd = false;\r
        bool page1 = false;     \r
        bool gotdata = false;\r
@@ -778,13 +897,15 @@ int CmdT55xxWriteBlock(const char *Cmd) {
        UsbCommand resp;\r
        c.d.asBytes[0] = (page1) ? 0x2 : 0; \r
 \r
-       PrintAndLog("Writing to page: %d  block: %d  data : 0x%08X", page1, block, data);\r
+       char pwdStr[16] = {0};\r
+       snprintf(pwdStr, sizeof(pwdStr), "pwd: 0x%08X", password);\r
+\r
+       PrintAndLog("Writing page %d  block: %02d  data: 0x%08X %s", page1, block, data,  (usepwd) ? pwdStr : "" );\r
 \r
        //Password mode\r
        if (usepwd) {\r
                c.arg[2] = password;\r
                c.d.asBytes[0] |= 0x1; \r
-               PrintAndLog("pwd   : 0x%08X", password);\r
        }\r
        clearCommandBuffer();\r
        SendCommand(&c);\r
@@ -803,7 +924,7 @@ int CmdT55xxReadTrace(const char *Cmd) {
                return usage_t55xx_trace();\r
 \r
        if (strlen(Cmd)==0)\r
-               if ( !AquireData( TRACE_BLOCK, REGULAR_READ_MODE_BLOCK, pwdmode, password ) )\r
+               if ( !AquireData( T55x7_PAGE1, REGULAR_READ_MODE_BLOCK, pwdmode, password ) )\r
                        return 0;\r
        \r
        if (!DecodeT55xxBlock()) return 0;\r
@@ -835,11 +956,11 @@ int CmdT55xxReadTrace(const char *Cmd) {
        else\r
                year += 2010;\r
 \r
+       if (config.Q5) PrintAndLog("*** Warning *** Info read off a Q5 will not work as expected");\r
        if ( acl != 0xE0 ) {\r
                PrintAndLog("The modulation is most likely wrong since the ACL is not 0xE0. ");\r
                return 0;\r
        }\r
-\r
        PrintAndLog("");\r
        PrintAndLog("-- T55xx Trace Information ----------------------------------");\r
        PrintAndLog("-------------------------------------------------------------");\r
@@ -892,7 +1013,7 @@ int CmdT55xxInfo(const char *Cmd){
                return usage_t55xx_info();\r
        \r
        if (strlen(Cmd)==0)\r
-               if ( !AquireData( 0, CONFIGURATION_BLOCK, pwdmode, password ) )\r
+               if ( !AquireData( T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, pwdmode, password ) )\r
                        return 1;\r
 \r
        if (!DecodeT55xxBlock()) return 1;\r
@@ -916,7 +1037,7 @@ int CmdT55xxInfo(const char *Cmd){
        uint32_t fw       = PackBits(si, 1, DemodBuffer); si += 1;\r
        uint32_t inv      = PackBits(si, 1, DemodBuffer); si += 1;      \r
        uint32_t por      = PackBits(si, 1, DemodBuffer); si += 1;\r
-               \r
+       if (config.Q5) PrintAndLog("*** Warning *** Config Info read off a Q5 will not display as expected");\r
        PrintAndLog("");\r
        PrintAndLog("-- T55xx Configuration & Tag Information --------------------");\r
        PrintAndLog("-------------------------------------------------------------");\r
@@ -956,32 +1077,21 @@ int CmdT55xxDump(const char *Cmd){
                        override = true;\r
        }\r
        \r
-       PrintAndLog("Reading Page 0:"); \r
-       PrintAndLog("blk | hex data | binary");\r
-       for ( uint8_t i = 0; i <8; ++i){\r
+       printT5xxHeader(0);\r
+       for ( uint8_t i = 0; i <8; ++i)\r
                T55xxReadBlock(i, 0, usepwd, override, password);\r
-               /*memset(s,0,sizeof(s));\r
-               if ( hasPwd ) {\r
-                       if ( override ) {\r
-                               sprintf(s,"b %d p %02x%02x%02x%02x o", i, pwd[0],pwd[1],pwd[2],pwd[3]);                         \r
-                       } else {\r
-                               sprintf(s,"b %d p %02x%02x%02x%02x", i, pwd[0],pwd[1],pwd[2],pwd[3]);                           \r
-                       }\r
-               } else {\r
-                       sprintf(s,"b %d", i);\r
-               }\r
-               CmdT55xxReadBlock(s);*/\r
-       }\r
-       PrintAndLog("Reading Page 1:"); \r
-       PrintAndLog("blk | hex data | binary");\r
-       for ( uint8_t   i = 0; i<4; i++){\r
+\r
+       printT5xxHeader(1);\r
+       for ( uint8_t   i = 0; i<4; i++)\r
                T55xxReadBlock(i, 1, usepwd, override, password);               \r
-       }\r
+\r
        return 1;\r
 }\r
 \r
 int AquireData( uint8_t page, uint8_t block, bool pwdmode, uint32_t password ){\r
-\r
+       // arg0 bitmodes:\r
+       // bit0 = pwdmode\r
+       // bit1 = page to read from\r
        uint8_t arg0 = (page<<1) | pwdmode;\r
        UsbCommand c = {CMD_T55XX_READ_BLOCK, {arg0, block, password}};\r
 \r
@@ -1189,30 +1299,192 @@ int CmdResetRead(const char *Cmd) {
        return 1;\r
 }\r
 \r
-static command_t CommandTable[] =\r
-{\r
-  {"help",     CmdHelp,           1, "This help"},\r
-  {"config",   CmdT55xxSetConfig, 1, "Set/Get T55XX configuration (modulation, inverted, offset, rate)"},\r
-  {"detect",   CmdT55xxDetect,    0, "[1] Try detecting the tag modulation from reading the configuration block."},\r
-  {"read",     CmdT55xxReadBlock, 0, "b <block> p [password] [o] [1] -- Read T55xx block data. Optional [p password], [override], [page1]"},\r
-  {"resetread",CmdResetRead,      0, "Send Reset Cmd then lf read the stream to attempt to identify the start of it (needs a demod and/or plot after)"},\r
-  {"write",    CmdT55xxWriteBlock,0, "b <block> d <data> p [password] [1] -- Write T55xx block data. Optional [p password], [page1]"},\r
-  {"trace",    CmdT55xxReadTrace, 0, "[1] Show T55xx traceability data (page 1/ blk 0-1)"},\r
-  {"info",     CmdT55xxInfo,      0, "[1] Show T55xx configuration data (page 0/ blk 0)"},\r
-  {"dump",     CmdT55xxDump,      0, "[password] [o] Dump T55xx card block 0-7. Optional [password], [override]"},\r
-  {"special",  special,           0, "Show block changes with 64 different offsets"},\r
-  {"wakeup",   CmdT55xxWakeUp,    0, "Send AOR wakeup command"},\r
+int CmdT55xxWipe(const char *Cmd) {\r
+       char writeData[20] = {0};\r
+       char *ptrData = writeData;\r
+\r
+       PrintAndLog("\nBeginning Wipe of a T55xx tag (assuming the tag is not password protected)\n");\r
+\r
+       //try with the default password to reset block 0  (with a pwd should work even if pwd bit not set)\r
+       snprintf(ptrData,sizeof(writeData),"b 0 d 00088040 p 0");\r
+\r
+       if (!CmdT55xxWriteBlock(ptrData))\r
+               PrintAndLog("Error writing blk 0");\r
+\r
+       for (uint8_t blk = 1; blk<8; blk++) {\r
+               snprintf(ptrData,sizeof(writeData),"b %d d 0", blk);\r
+               if (!CmdT55xxWriteBlock(ptrData))\r
+                       PrintAndLog("Error writing blk %d", blk);\r
+\r
+               memset(writeData, 0x00, sizeof(writeData));\r
+       }\r
+       return 0;\r
+}\r
+\r
+int CmdT55xxBruteForce(const char *Cmd) {\r
+\r
+       // load a default pwd file.\r
+       char buf[9];\r
+       char filename[FILE_PATH_SIZE]={0};\r
+       int keycnt = 0;\r
+       uint8_t stKeyBlock = 20;\r
+       uint8_t *keyBlock = NULL, *p;\r
+       keyBlock = calloc(stKeyBlock, 6);\r
+       if (keyBlock == NULL) return 1;\r
+\r
+       uint32_t start_password = 0x00000000; //start password\r
+       uint32_t end_password   = 0xFFFFFFFF; //end   password\r
+       bool found = false;\r
+\r
+       char cmdp = param_getchar(Cmd, 0);\r
+       if (cmdp == 'h' || cmdp == 'H') return usage_t55xx_bruteforce();\r
+\r
+       if (cmdp == 'i' || cmdp == 'I') {\r
+\r
+               int len = strlen(Cmd+2);\r
+               if (len > FILE_PATH_SIZE) len = FILE_PATH_SIZE;\r
+               memcpy(filename, Cmd+2, len);\r
+\r
+               FILE * f = fopen( filename , "r");\r
+\r
+               if ( !f ) {\r
+                       PrintAndLog("File: %s: not found or locked.", filename);\r
+                       free(keyBlock);\r
+                       return 1;\r
+               }\r
+\r
+               while( fgets(buf, sizeof(buf), f) ){\r
+                       if (strlen(buf) < 8 || buf[7] == '\n') continue;\r
+\r
+                       while (fgetc(f) != '\n' && !feof(f)) ;  //goto next line\r
+\r
+                       //The line start with # is comment, skip\r
+                       if( buf[0]=='#' ) continue;\r
+\r
+                       if (!isxdigit(buf[0])){\r
+                               PrintAndLog("File content error. '%s' must include 8 HEX symbols", buf);\r
+                               continue;\r
+                       }\r
+                       \r
+                       buf[8] = 0;\r
+\r
+                       if ( stKeyBlock - keycnt < 2) {\r
+                               p = realloc(keyBlock, 6*(stKeyBlock+=10));\r
+                               if (!p) {\r
+                                       PrintAndLog("Cannot allocate memory for defaultKeys");\r
+                                       free(keyBlock);\r
+                                       return 2;\r
+                               }\r
+                               keyBlock = p;\r
+                       }\r
+                       memset(keyBlock + 4 * keycnt, 0, 4);\r
+                       num_to_bytes(strtoll(buf, NULL, 16), 4, keyBlock + 4*keycnt);\r
+                       PrintAndLog("chk custom pwd[%2d] %08X", keycnt, bytes_to_num(keyBlock + 4*keycnt, 4));\r
+                       keycnt++;\r
+                       memset(buf, 0, sizeof(buf));\r
+               }\r
+               fclose(f);\r
+               \r
+               if (keycnt == 0) {\r
+                       PrintAndLog("No keys found in file");\r
+                       return 1;\r
+               }\r
+               PrintAndLog("Loaded %d keys", keycnt);\r
+               \r
+               // loop\r
+               uint64_t testpwd = 0x00;\r
+               for (uint16_t c = 0; c < keycnt; ++c ) {\r
+\r
+                       if (ukbhit()) {\r
+                               getchar();\r
+                               printf("\naborted via keyboard!\n");\r
+                               return 0;\r
+                       }\r
+\r
+                       testpwd = bytes_to_num(keyBlock + 4*c, 4);\r
+\r
+                       PrintAndLog("Testing %08X", testpwd);\r
+\r
+                       if ( !AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, TRUE, testpwd)) {\r
+                               PrintAndLog("Aquireing data from device failed. Quitting");\r
+                               return 0;\r
+                       }\r
+\r
+                       found = tryDetectModulation();\r
+\r
+                       if ( found ) {\r
+                               PrintAndLog("Found valid password: [%08X]", testpwd);\r
+                               return 0;\r
+                       }\r
+               }\r
+               PrintAndLog("Password NOT found.");\r
+               return 0;\r
+       }\r
+\r
+       // Try to read Block 7, first :)\r
+\r
+       // incremental pwd range search\r
+       start_password = param_get32ex(Cmd, 0, 0, 16);\r
+       end_password = param_get32ex(Cmd, 1, 0, 16);\r
+       \r
+       if ( start_password >= end_password ) return usage_t55xx_bruteforce();\r
+\r
+       PrintAndLog("Search password range [%08X -> %08X]", start_password, end_password);\r
+\r
+       uint32_t i = start_password;\r
+\r
+       while ((!found) && (i <= end_password)){\r
+\r
+       printf(".");\r
+       fflush(stdout);\r
+       if (ukbhit()) {\r
+               getchar();\r
+               printf("\naborted via keyboard!\n");\r
+               return 0;\r
+       }\r
+\r
+       if (!AquireData(T55x7_PAGE0, T55x7_CONFIGURATION_BLOCK, TRUE, i)) {\r
+               PrintAndLog("Aquireing data from device failed. Quitting");\r
+               return 0;\r
+       }\r
+       found = tryDetectModulation();\r
+           \r
+       if (found) break;\r
+       i++;\r
+       }\r
+\r
+       PrintAndLog("");\r
+\r
+       if (found)\r
+       PrintAndLog("Found valid password: [%08x]", i);\r
+       else\r
+       PrintAndLog("Password NOT found. Last tried: [%08x]", --i);\r
+       return 0;\r
+}\r
+\r
+static command_t CommandTable[] = {\r
+  {"help",      CmdHelp,           1, "This help"},\r
+       {"bruteforce",CmdT55xxBruteForce,0, "<start password> <end password> [i <*.dic>] Simple bruteforce attack to find password"},\r
+  {"config",    CmdT55xxSetConfig, 1, "Set/Get T55XX configuration (modulation, inverted, offset, rate)"},\r
+  {"detect",    CmdT55xxDetect,    1, "[1] Try detecting the tag modulation from reading the configuration block."},\r
+  {"read",      CmdT55xxReadBlock, 0, "b <block> p [password] [o] [1] -- Read T55xx block data. Optional [p password], [override], [page1]"},\r
+  {"resetread", CmdResetRead,      0, "Send Reset Cmd then lf read the stream to attempt to identify the start of it (needs a demod and/or plot after)"},\r
+  {"write",     CmdT55xxWriteBlock,0, "b <block> d <data> p [password] [1] -- Write T55xx block data. Optional [p password], [page1]"},\r
+  {"trace",     CmdT55xxReadTrace, 1, "[1] Show T55x7 traceability data (page 1/ blk 0-1)"},\r
+  {"info",      CmdT55xxInfo,      1, "[1] Show T55x7 configuration data (page 0/ blk 0)"},\r
+  {"dump",      CmdT55xxDump,      0, "[password] [o] Dump T55xx card block 0-7. Optional [password], [override]"},\r
+  {"special",   special,           0, "Show block changes with 64 different offsets"},\r
+  {"wakeup",    CmdT55xxWakeUp,    0, "Send AOR wakeup command"},\r
+  {"wipe",      CmdT55xxWipe,      0, "Wipe a T55xx tag and set defaults (will destroy any data on tag)"},\r
   {NULL, NULL, 0, NULL}\r
 };\r
 \r
-int CmdLFT55XX(const char *Cmd)\r
-{\r
+int CmdLFT55XX(const char *Cmd) {\r
   CmdsParse(CommandTable, Cmd);\r
   return 0;\r
 }\r
 \r
-int CmdHelp(const char *Cmd)\r
-{\r
+int CmdHelp(const char *Cmd) {\r
   CmdsHelp(CommandTable);\r
   return 0;\r
 }\r
index d513407987280dece9cebd78cf8905af3f5c09cb..56b1b9b778f76e34756e3d89d9f7765d6980f034 100644 (file)
@@ -38,12 +38,14 @@ typedef struct {
                RF_100 = 0x06,\r
                RF_128 = 0x07,\r
        } bitrate;\r
+       bool Q5;\r
 } t55xx_conf_block_t;\r
 t55xx_conf_block_t Get_t55xx_Config();\r
 void Set_t55xx_Config(t55xx_conf_block_t conf);\r
 \r
 \r
 int CmdLFT55XX(const char *Cmd);\r
+int CmdT55xxBruteForce(const char *Cmd);\r
 int CmdT55xxSetConfig(const char *Cmd);\r
 int CmdT55xxReadBlock(const char *Cmd);\r
 int CmdT55xxWriteBlock(const char *Cmd);\r
@@ -51,6 +53,7 @@ int CmdT55xxReadTrace(const char *Cmd);
 int CmdT55xxInfo(const char *Cmd);\r
 int CmdT55xxDetect(const char *Cmd);\r
 int CmdResetRead(const char *Cmd);\r
+int CmdT55xxWipe(const char *Cmd);\r
 \r
 char * GetBitRateStr(uint32_t id);\r
 char * GetSaferStr(uint32_t id);\r
@@ -63,7 +66,7 @@ int printConfiguration( t55xx_conf_block_t b);
 \r
 bool DecodeT55xxBlock();\r
 bool tryDetectModulation();\r
-bool test(uint8_t mode, uint8_t *offset, int *fndBitRate);\r
+bool test(uint8_t mode, uint8_t *offset, int *fndBitRate, uint8_t clk, bool *Q5);\r
 int special(const char *Cmd);\r
 int AquireData( uint8_t page, uint8_t block, bool pwdmode, uint32_t password );\r
 \r
diff --git a/client/cmdlfviking.c b/client/cmdlfviking.c
new file mode 100644 (file)
index 0000000..e43a974
--- /dev/null
@@ -0,0 +1,127 @@
+//-----------------------------------------------------------------------------
+//
+// 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.
+//-----------------------------------------------------------------------------
+// Low frequency Viking tag commands
+//-----------------------------------------------------------------------------
+#include <stdio.h>
+#include <string.h>
+#include <inttypes.h>
+#include "proxmark3.h"
+#include "ui.h"
+#include "util.h"
+#include "graph.h"
+#include "cmdparser.h"
+#include "cmddata.h"
+#include "cmdmain.h"
+#include "cmdlf.h"
+#include "cmdlfviking.h"
+#include "lfdemod.h"
+static int CmdHelp(const char *Cmd);
+
+int usage_lf_viking_clone(void) {
+       PrintAndLog("clone a Viking AM tag to a T55x7 tag.");
+       PrintAndLog("Usage: lf viking clone <Card ID - 8 hex digits> <Q5>");
+  PrintAndLog("Options :");
+  PrintAndLog("  <Card Number>  : 8 digit hex viking card number");
+  PrintAndLog("  <Q5>           : specify write to Q5 (t5555 instead of t55x7)");
+  PrintAndLog("");
+  PrintAndLog("Sample  : lf viking clone 1A337 Q5");
+       return 0;
+}
+
+int usage_lf_viking_sim(void) {
+  PrintAndLog("Enables simulation of viking card with specified card number.");
+  PrintAndLog("Simulation runs until the button is pressed or another USB command is issued.");
+  PrintAndLog("Per viking format, the card number is 8 digit hex number.  Larger values are truncated.");
+  PrintAndLog("");
+  PrintAndLog("Usage:  lf viking sim <Card-Number>");
+  PrintAndLog("Options :");
+  PrintAndLog("  <Card Number>   : 8 digit hex viking card number");
+  PrintAndLog("");
+  PrintAndLog("Sample  : lf viking sim 1A337");
+  return 0;
+}
+
+uint64_t getVikingBits(uint32_t id) {
+       //calc checksum
+       uint8_t checksum = (id>>24) ^ ((id>>16) & 0xFF) ^ ((id>>8) & 0xFF) ^ (id & 0xFF) ^ 0xF2 ^ 0xA8;
+       return ((uint64_t)0xF2 << 56) | (id << 8) | checksum;
+}
+//by marshmellow
+//see ASKDemod for what args are accepted
+int CmdVikingRead(const char *Cmd) {
+       // read lf silently
+       CmdLFRead("s");
+       // get samples silently
+       getSamples("30000",false);
+       // demod and output viking ID   
+       return CmdVikingDemod(Cmd);
+}
+
+int CmdVikingClone(const char *Cmd) {
+       uint32_t id = 0;
+       uint64_t rawID = 0;
+       bool Q5 = false;
+       char cmdp = param_getchar(Cmd, 0);
+       if (strlen(Cmd) < 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_viking_clone();
+
+       id = param_get32ex(Cmd, 0, 0, 16);
+       if (id == 0) return usage_lf_viking_clone();
+       if (param_getchar(Cmd, 1)=='Q' || param_getchar(Cmd, 1)=='q')
+               Q5 = true;
+
+       rawID = getVikingBits(id);
+
+       UsbCommand c = {CMD_VIKING_CLONE_TAG,{rawID >> 32, rawID & 0xFFFF, Q5}};
+       clearCommandBuffer();
+       SendCommand(&c);
+       //check for ACK
+       WaitForResponse(CMD_ACK,NULL);
+       return 0;
+}
+
+int CmdVikingSim(const char *Cmd) {
+       uint32_t id = 0;
+       uint64_t rawID = 0;
+       uint8_t clk = 32, encoding = 1, separator = 0, invert = 0;
+       char cmdp = param_getchar(Cmd, 0);
+
+       if (strlen(Cmd) < 0 || cmdp == 'h' || cmdp == 'H') return usage_lf_viking_sim();
+       id = param_get32ex(Cmd, 0, 0, 16);
+       if (id == 0) return usage_lf_viking_sim();
+
+       rawID = getVikingBits(id);
+
+  uint16_t arg1, arg2;
+  size_t size = 64;
+  arg1 = clk << 8 | encoding;
+  arg2 = invert << 8 | separator;
+
+  UsbCommand c = {CMD_ASK_SIM_TAG, {arg1, arg2, size}};
+  PrintAndLog("preparing to sim ask data: %d bits", size);
+  num_to_bytebits(rawID, 64, c.d.asBytes);
+       clearCommandBuffer();
+  SendCommand(&c);
+  return 0;
+}
+
+static command_t CommandTable[] = {
+       {"help",  CmdHelp,        1, "This help"},
+       {"read",  CmdVikingRead,  0, "Attempt to read and Extract tag data"},
+       {"clone", CmdVikingClone, 0, "<8 digit ID number> clone viking tag"},
+       {"sim",   CmdVikingSim,   0, "<8 digit ID number> simulate viking tag"},
+       {NULL, NULL, 0, NULL}
+};
+
+int CmdLFViking(const char *Cmd) {
+       CmdsParse(CommandTable, Cmd);
+       return 0;
+}
+
+int CmdHelp(const char *Cmd) {
+       CmdsHelp(CommandTable);
+       return 0;
+}
diff --git a/client/cmdlfviking.h b/client/cmdlfviking.h
new file mode 100644 (file)
index 0000000..2e8ac47
--- /dev/null
@@ -0,0 +1,16 @@
+//-----------------------------------------------------------------------------
+//
+// 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.
+//-----------------------------------------------------------------------------
+// Low frequency T55xx commands
+//-----------------------------------------------------------------------------
+#ifndef CMDLFVIKING_H__
+#define CMDLFVIKING_H__
+int CmdLFViking(const char *Cmd);
+int CmdVikingRead(const char *Cmd);
+int CmdVikingClone(const char *Cmd);
+int CmdVikingSim(const char *Cmd);
+#endif
+
diff --git a/client/default_pwd.dic b/client/default_pwd.dic
new file mode 100644 (file)
index 0000000..5edb83e
--- /dev/null
@@ -0,0 +1,75 @@
+# known cloners
+# ref. http://www.proxmark.org/forum/viewtopic.php?id=2022
+51243648,
+000D8787,
+# Default pwd, simple:
+00000000,
+11111111,
+22222222,
+33333333,
+44444444,
+55555555,
+66666666,
+77777777,
+88888888,
+99999999,
+AAAAAAAA,
+BBBBBBBB,
+CCCCCCCC,
+DDDDDDDD,
+EEEEEEEE,
+FFFFFFFF,
+a0a1a2a3,
+b0b1b2b3,
+aabbccdd,
+bbccddee,
+ccddeeff,
+00000001,
+00000002,
+0000000a,
+0000000b,
+01020304,
+02030405,
+03040506,
+04050607,
+05060708,
+06070809,
+0708090A,
+08090A0B,
+090A0B0C,
+0A0B0C0D,
+0B0C0D0E,
+0C0D0E0F,
+01234567,
+12345678,
+10000000,
+20000000,
+30000000,
+40000000,
+50000000,
+60000000,
+70000000,
+80000000,
+90000000,
+A0000000,
+B0000000,
+C0000000,
+D0000000,
+E0000000,
+F0000000,
+10101010,
+01010101,
+11223344,
+22334455,
+33445566,
+44556677,
+55667788,
+66778899,
+778899AA,
+8899AABB,
+99AABBCC,
+AABBCCDD,
+BBCCDDEE,
+CCDDEEFF,
+0CB7E7FC,  //rfidler?
+FABADA11,  //china?
\ No newline at end of file
index c8b576fdb06c6cd4b00e77da1269c244e66a3409..46738181e4c04453cde39e6fa4c3d259163a5645 100644 (file)
@@ -85,6 +85,7 @@ typedef struct {
 #define CMD_ASK_SIM_TAG                                                   0x021F
 #define CMD_PSK_SIM_TAG                                                   0x0220
 #define CMD_AWID_DEMOD_FSK                                                0x0221
+#define CMD_VIKING_CLONE_TAG                                              0x0223
 #define CMD_T55XX_WAKEUP                                                  0x0224
 
 /* CMD_SET_ADC_MUX: ext1 is 0 for lopkd, 1 for loraw, 2 for hipkd, 3 for hiraw */
index 8cdcfb349025f303d5f42cbff2bcf0eeae020109..fcf0f07cb578a0fd93de52c43a28c8fb9a3ec47b 100644 (file)
@@ -56,6 +56,7 @@ local _commands = {
        CMD_ASK_SIM_TAG =                                                    0x021F,
        CMD_PSK_SIM_TAG =                                                    0x0220,
        CMD_AWID_DEMOD_FSK =                                                 0x0221,
+       CMD_VIKING_CLONE_TAG =                                               0x0223,
        CMD_T55XX_WAKEUP =                                                   0x0224,
        --/* CMD_SET_ADC_MUX: ext1 is 0 for lopkd, 1 for loraw, 2 for hipkd, 3 for hiraw */
 
index 5e9fce858fe9606da93830da0eb9b4c4970883b9..e8b72e81aeebe46884507d868bc3955fa81a2a75 100644 (file)
@@ -9,11 +9,13 @@
 //-----------------------------------------------------------------------------
 
 #include "util.h"
+#define MAX_BIN_BREAK_LENGTH   (3072+384+1)
 
 #ifndef _WIN32
 #include <termios.h>
 #include <sys/ioctl.h> 
 
+
 int ukbhit(void)
 {
   int cnt = 0;
@@ -123,16 +125,30 @@ 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 > 1020) ? 1020 : len;
-       static char buf[1024];
-       memset(buf, 0x00, 1024);
+       // make sure we don't go beyond our char array memory
+       int max_len;
+       if (breaks==0)
+               max_len = ( len > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len;
+       else
+               max_len = ( len+(len/breaks) > MAX_BIN_BREAK_LENGTH ) ? MAX_BIN_BREAK_LENGTH : len+(len/breaks);
+
+       static char buf[MAX_BIN_BREAK_LENGTH]; // 3072 + end of line characters if broken at 8 bits
+       //clear memory
+       memset(buf, 0x00, sizeof(buf));
        char *tmp = buf;
 
-       for (size_t i=0; i < maxLen; ++i){
-               sprintf(tmp++, "%u", data[i]);
-               if (breaks > 0 && !((i+1) % breaks))
+       size_t in_index = 0;
+       // loop through the out_index to make sure we don't go too far
+       for (size_t out_index=0; out_index < max_len; out_index++) {
+               // set character
+               sprintf(tmp++, "%u", data[in_index]);
+               // check if a line break is needed
+               if ( (breaks > 0) && !((in_index+1) % breaks) && (out_index+1 != max_len) ) {
+                       // increment and print line break
+                       out_index++;
                        sprintf(tmp++, "%s","\n");
+               }
+               in_index++;
        }
 
        return buf;
@@ -160,6 +176,13 @@ uint64_t bytes_to_num(uint8_t* src, size_t len)
        return num;
 }
 
+void num_to_bytebits(uint64_t  n, size_t len, uint8_t *dest) {
+       while (len--) {
+               dest[len] = n & 1;
+               n >>= 1;
+       }
+}
+
 // 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
@@ -446,7 +469,7 @@ void binarraytobinstring(char *target, char *source,  int length)
 }
 
 // return parity bit required to match type
-uint8_t GetParity( char *bits, uint8_t type, int length)
+uint8_t GetParity( uint8_t *bits, uint8_t type, int length)
 {
     int x;
 
@@ -458,7 +481,7 @@ uint8_t GetParity( char *bits, uint8_t type, int length)
 }
 
 // add HID parity to binary array: EVEN prefix for 1st half of ID, ODD suffix for 2nd half
-void wiegand_add_parity(char *target, char *source, char length)
+void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length)
 {
     *(target++)= GetParity(source, EVEN, length / 2);
     memcpy(target, source, length);
index 8bf4f3881c28c624f13ec8026f0e0a03680791e5..6f9a1177f47e7e881af867ae832c545da22c8a18 100644 (file)
@@ -43,6 +43,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);
+void num_to_bytebits(uint64_t  n, size_t len, uint8_t *dest);
 char * printBits(size_t const size, void const * const ptr);
 uint8_t *SwapEndian64(const uint8_t *src, const size_t len, const uint8_t blockSize);
 
@@ -62,8 +63,8 @@ int param_getstr(const char *line, int paramnum, char * str);
  int hextobinstring( char *target,  char *source);
  int binarraytohex( char *target,  char *source,  int length);
 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);
+uint8_t GetParity( uint8_t *string, uint8_t type,  int length);
+void wiegand_add_parity(uint8_t *target, uint8_t *source, uint8_t length);
 
 void xor(unsigned char *dst, unsigned char *src, size_t len);
 int32_t le24toh(uint8_t data[3]);
index 32feab6a6589934fd7cb291b883337915e7a027d..982a724a018a02fca792b15636098ea57a8384ea 100644 (file)
 #include <stdlib.h>
 #include <string.h>
 #include "lfdemod.h"
+#include "common.h"
+
+//un_comment to allow debug print calls when used not on device
+void dummy(char *fmt, ...){}
+
+#ifndef ON_DEVICE
+#include "ui.h"
+#include "cmdparser.h"
+#include "cmddata.h"
+#define prnt PrintAndLog
+#else 
+       uint8_t g_debugMode=0;
+#define prnt dummy
+#endif
+
 uint8_t justNoise(uint8_t *BitStream, size_t size)
 {
        static const uint8_t THRESHOLD = 123;
@@ -52,6 +67,81 @@ uint8_t parityTest(uint32_t bits, uint8_t bitLen, uint8_t pType)
        return (ans == pType);
 }
 
+// by marshmellow
+// takes a array of binary values, start position, length of bits per parity (includes parity bit),
+//   Parity Type (1 for odd; 0 for even; 2 Always 1's), and binary Length (length to run) 
+size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen)
+{
+       uint32_t parityWd = 0;
+       size_t j = 0, bitCnt = 0;
+       for (int word = 0; word < (bLen); word+=pLen){
+               for (int bit=0; bit < pLen; bit++){
+                       parityWd = (parityWd << 1) | BitStream[startIdx+word+bit];
+                       BitStream[j++] = (BitStream[startIdx+word+bit]);
+               }
+               j--; // overwrite parity with next data
+               // if parity fails then return 0
+               if (pType == 2) { // then marker bit which should be a 1
+                       if (!BitStream[j]) return 0;
+               } else {
+                       if (parityTest(parityWd, pLen, pType) == 0) return 0;                   
+               }
+               bitCnt+=(pLen-1);
+               parityWd = 0;
+       }
+       // if we got here then all the parities passed
+       //return ID start index and size
+       return bitCnt;
+}
+
+// by marshmellow
+// takes a array of binary values, length of bits per parity (includes parity bit),
+//   Parity Type (1 for odd; 0 for even; 2 Always 1's), and binary Length (length to run)
+size_t addParity(uint8_t *BitSource, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType)
+{
+       uint32_t parityWd = 0;
+       size_t j = 0, bitCnt = 0;
+       for (int word = 0; word < sourceLen; word+=pLen-1) {
+               for (int bit=0; bit < pLen-1; bit++){
+                       parityWd = (parityWd << 1) | BitSource[word+bit];
+                       dest[j++] = (BitSource[word+bit]);
+               }
+               // if parity fails then return 0
+               if (pType == 2) { // then marker bit which should be a 1
+                       dest[j++]=1;
+               } else {
+                       dest[j++] = parityTest(parityWd, pLen-1, pType) ^ 1;
+               }
+               bitCnt += pLen;
+               parityWd = 0;
+       }
+       // if we got here then all the parities passed
+       //return ID start index and size
+       return bitCnt;
+}
+
+uint32_t bytebits_to_byte(uint8_t *src, size_t numbits)
+{
+       uint32_t num = 0;
+       for(int i = 0 ; i < numbits ; i++)
+       {
+               num = (num << 1) | (*src);
+               src++;
+       }
+       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 + (numbits-(i+1)));
+       }
+       return num;
+}
+
 //by marshmellow
 //search for given preamble in given BitStream and return success=1 or fail=0 and startIndex and length
 uint8_t preambleSearch(uint8_t *BitStream, uint8_t *preamble, size_t pLen, size_t *size, size_t *startIdx)
@@ -184,6 +274,7 @@ int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr
        if (*clk==0 || start < 0) return -3;
        if (*invert != 1) *invert = 0;
        if (amp==1) askAmp(BinStream, *size);
+       if (g_debugMode==2) prnt("DEBUG: clk %d, beststart %d", *clk, start);
 
        uint8_t initLoopMax = 255;
        if (initLoopMax > *size) initLoopMax = *size;
@@ -196,6 +287,7 @@ int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr
        size_t errCnt = 0;
        // if clean clipped waves detected run alternate demod
        if (DetectCleanAskWave(BinStream, *size, high, low)) {
+               if (g_debugMode==2) prnt("DEBUG: Clean Wave Detected");
                errCnt = cleanAskRawDemod(BinStream, size, *clk, *invert, high, low);
                if (askType) //askman
                        return manrawdecode(BinStream, size, 0);        
@@ -208,7 +300,7 @@ int askdemod(uint8_t *BinStream, size_t *size, int *clk, int *invert, int maxErr
        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
-       size_t MaxBits = 1024;
+       size_t MaxBits = 3072;
        lastBit = start - *clk;
 
        for (i = start; i < *size; ++i) {
@@ -385,15 +477,15 @@ size_t fsk_wave_demod(uint8_t * dest, size_t size, uint8_t fchigh, uint8_t fclow
        // sync to first lo-hi transition, and threshold
 
        // Need to threshold first sample
-
-       if(dest[0] < threshold_value) dest[0] = 0;
+       // skip 160 samples to allow antenna/samples to settle
+       if(dest[160] < threshold_value) dest[0] = 0;
        else dest[0] = 1;
 
        size_t numBits = 0;
        // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
        // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere
        // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
-       for(idx = 1; idx < size; idx++) {
+       for(idx = 161; idx < size-20; idx++) {
                // threshold current value
 
                if (dest[idx] < threshold_value) dest[idx] = 0;
@@ -404,15 +496,15 @@ size_t fsk_wave_demod(uint8_t * dest, size_t size, uint8_t fchigh, uint8_t fclow
                        preLastSample = LastSample;
                        LastSample = currSample;
                        currSample = idx-last_transition;
-                       if (currSample < (fclow-2)){            //0-5 = garbage noise
+                       if (currSample < (fclow-2)){            //0-5 = garbage noise (or 0-3)
                                //do nothing with extra garbage
-                       } else if (currSample < (fchigh-1)) { //6-8 = 8 sample waves
-                               if (LastSample > (fchigh-2) && preLastSample < (fchigh-1)){
-                                       dest[numBits-1]=1;  //correct last 9 wave surrounded by 8 waves
+                       } else if (currSample < (fchigh-1)) { //6-8 = 8 sample waves  or 3-6 = 5
+                               if (LastSample > (fchigh-2) && (preLastSample < (fchigh-1) || preLastSample     == 0 )){
+                                       dest[numBits-1]=1;  //correct previous 9 wave surrounded by 8 waves
                                }
                                dest[numBits++]=1;
 
-                       } else if (currSample > (fchigh+1) && !numBits) { //12 + and first bit = garbage 
+                       } else if (currSample > (fchigh) && !numBits) { //12 + and first bit = garbage 
                                //do nothing with beginning garbage
                        } else if (currSample == (fclow+1) && LastSample == (fclow-1)) { // had a 7 then a 9 should be two 8's
                                dest[numBits++]=1;
@@ -439,19 +531,8 @@ size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen,
                
                //if lastval was 1, we have a 1->0 crossing
                if (dest[idx-1]==1) {
-                       if (!numBits && n < rfLen/fclow) {
-                               n=0;
-                               lastval = dest[idx];
-                               continue;
-                       }
                        n = (n * fclow + rfLen/2) / rfLen;
                } else {// 0->1 crossing 
-                       //test first bitsample too small
-                       if (!numBits && n < rfLen/fchigh) {
-                               n=0;
-                               lastval = dest[idx];
-                               continue;
-                       }
                        n = (n * fchigh + rfLen/2) / rfLen; 
                }
                if (n == 0) n = 1;
@@ -473,6 +554,7 @@ size_t aggregate_bits(uint8_t *dest, size_t size, uint8_t rfLen,
        }
        return numBits;
 }
+
 //by marshmellow  (from holiman's base)
 // full fsk demod from GraphBuffer wave to decoded 1s and 0s (no mandemod)
 int fskdemod(uint8_t *dest, size_t size, uint8_t rfLen, uint8_t invert, uint8_t fchigh, uint8_t fclow)
@@ -547,28 +629,6 @@ 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 num = 0;
-       for(int i = 0 ; i < numbits ; i++)
-       {
-               num = (num << 1) | (*src);
-               src++;
-       }
-       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 + (numbits-(i+1)));
-       }
-       return num;
-}
-
 int IOdemodFSK(uint8_t *dest, size_t size)
 {
        if (justNoise(dest, size)) return -1;
@@ -618,33 +678,6 @@ int VikingDemod_AM(uint8_t *dest, size_t *size) {
        return (int) startIdx;
 }
 
-// by marshmellow
-// takes a array of binary values, start position, length of bits per parity (includes parity bit),
-//   Parity Type (1 for odd; 0 for even; 2 Always 1's), and binary Length (length to run) 
-size_t removeParity(uint8_t *BitStream, size_t startIdx, uint8_t pLen, uint8_t pType, size_t bLen)
-{
-       uint32_t parityWd = 0;
-       size_t j = 0, bitCnt = 0;
-       for (int word = 0; word < (bLen); word+=pLen){
-               for (int bit=0; bit < pLen; bit++){
-                       parityWd = (parityWd << 1) | BitStream[startIdx+word+bit];
-                       BitStream[j++] = (BitStream[startIdx+word+bit]);
-               }
-               j--; // overwrite parity with next data
-               // if parity fails then return 0
-               if (pType == 2) { // then marker bit which should be a 1
-                       if (!BitStream[j]) return 0;
-               } else {
-                       if (parityTest(parityWd, pLen, pType) == 0) return 0;                   
-               }
-               bitCnt+=(pLen-1);
-               parityWd = 0;
-       }
-       // if we got here then all the parities passed
-       //return ID start index and size
-       return bitCnt;
-}
-
 // Ask/Biphase Demod then try to locate an ISO 11784/85 ID
 // BitStream must contain previously askrawdemod and biphasedemoded data
 int FDXBdemodBI(uint8_t *dest, size_t *size)
@@ -682,7 +715,7 @@ int AWIDdemodFSK(uint8_t *dest, size_t *size)
 }
 
 // by marshmellow
-// FSK Demod then try to locate an Farpointe Data (pyramid) ID
+// FSK Demod then try to locate a Farpointe Data (pyramid) ID
 int PyramiddemodFSK(uint8_t *dest, size_t *size)
 {
        //make sure buffer has data
@@ -707,22 +740,21 @@ int PyramiddemodFSK(uint8_t *dest, size_t *size)
 // 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;
+       bool allArePeaks = true;
        uint16_t cntPeaks=0;
-       size_t loopEnd = 512+60;
+       size_t loopEnd = 512+160;
        if (loopEnd > size) loopEnd = size;
-       for (size_t i=60; i<loopEnd; i++){
+       for (size_t i=160; i<loopEnd; i++){
                if (dest[i]>low && dest[i]<high) 
-                       allPeaks=0;
+                       allArePeaks = false;
                else
                        cntPeaks++;
        }
-       if (allPeaks == 0){
-               if (cntPeaks > 300) return 1;
+       if (!allArePeaks){
+               if (cntPeaks > 300) return true;
        }
-       return allPeaks;
+       return allArePeaks;
 }
-
 // by marshmellow
 // to help detect clocks on heavily clipped samples
 // based on count of low to low
@@ -730,7 +762,7 @@ int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low)
 {
        uint8_t fndClk[] = {8,16,32,40,50,64,128};
        size_t startwave;
-       size_t i = 0;
+       size_t i = 100;
        size_t minClk = 255;
                // get to first full low to prime loop and skip incomplete first pulse
        while ((dest[i] < high) && (i < size))
@@ -753,6 +785,7 @@ int DetectStrongAskClock(uint8_t dest[], size_t size, uint8_t high, uint8_t low)
                        minClk = i - startwave;
        }
        // set clock
+       if (g_debugMode==2) prnt("DEBUG ASK: detectstrongASKclk smallest wave: %d",minClk);
        for (uint8_t clkCnt = 0; clkCnt<7; clkCnt++) {
                if (minClk >= fndClk[clkCnt]-(fndClk[clkCnt]/8) && minClk <= fndClk[clkCnt]+1)
                        return fndClk[clkCnt];
@@ -770,8 +803,8 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
        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 <= loopCnt) return -1; //not enough samples
-
+       if (size <= loopCnt+60) return -1; //not enough samples
+       size -= 60; //sometimes there is a strange end wave - filter out this....
        //if we already have a valid clock
        uint8_t clockFnd=0;
        for (;i<clkEnd;++i)
@@ -786,6 +819,7 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
        if (!clockFnd){
                if (DetectCleanAskWave(dest, size, peak, low)==1){
                        int ans = DetectStrongAskClock(dest, size, peak, low);
+                       if (g_debugMode==2) prnt("DEBUG ASK: detectaskclk Clean Ask Wave Detected: clk %d",ans);
                        for (i=clkEnd-1; i>0; i--){
                                if (clk[i] == ans) {
                                        *clock = ans;
@@ -796,7 +830,6 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
                        }
                }
        }
-       
        uint8_t ii;
        uint8_t clkCnt, tol = 0;
        uint16_t bestErr[]={1000,1000,1000,1000,1000,1000,1000,1000,1000};
@@ -838,7 +871,7 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
                        }
                        //if we found no errors then we can stop here and a low clock (common clocks)
                        //  this is correct one - return this clock
-                                       //PrintAndLog("DEBUG: clk %d, err %d, ii %d, i %d",clk[clkCnt],errCnt,ii,i);
+                       if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, err %d, startpos %d, endpos %d",clk[clkCnt],errCnt,ii,i);
                        if(errCnt==0 && clkCnt<7) { 
                                if (!clockFnd) *clock = clk[clkCnt];
                                return ii;
@@ -860,8 +893,8 @@ int DetectASKClock(uint8_t dest[], size_t size, int *clock, int maxErr)
                                best = iii;
                        }
                }
+               if (g_debugMode == 2) prnt("DEBUG ASK: clk %d, # Errors %d, Current Best Clk %d, bestStart %d",clk[iii],bestErr[iii],clk[best],bestStart[best]);
        }
-       //if (bestErr[best] > maxErr) return -1;
        if (!clockFnd) *clock = clk[best];
        return bestStart[best];
 }
@@ -874,7 +907,7 @@ int DetectPSKClock(uint8_t dest[], size_t size, int clock)
        uint8_t clk[]={255,16,32,40,50,64,100,128,255}; //255 is not a valid clock
        uint16_t loopCnt = 4096;  //don't need to loop through entire array...
        if (size == 0) return 0;
-       if (size<loopCnt) loopCnt = size;
+       if (size<loopCnt) loopCnt = size-20;
 
        //if we already have a valid clock quit
        size_t i=1;
@@ -888,17 +921,17 @@ int DetectPSKClock(uint8_t dest[], size_t size, int clock)
        uint16_t peaksdet[]={0,0,0,0,0,0,0,0,0};
        fc = countFC(dest, size, 0);
        if (fc!=2 && fc!=4 && fc!=8) return -1;
-       //PrintAndLog("DEBUG: FC: %d",fc);
+       if (g_debugMode==2) prnt("DEBUG PSK: FC: %d",fc);
 
        //find first full wave
-       for (i=0; i<loopCnt; i++){
+       for (i=160; i<loopCnt; i++){
                if (dest[i] < dest[i+1] && dest[i+1] >= dest[i+2]){
                        if (waveStart == 0) {
                                waveStart = i+1;
-                               //PrintAndLog("DEBUG: waveStart: %d",waveStart);
+                               //prnt("DEBUG: waveStart: %d",waveStart);
                        } else {
                                waveEnd = i+1;
-                               //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
+                               //prnt("DEBUG: waveEnd: %d",waveEnd);
                                waveLenCnt = waveEnd-waveStart;
                                if (waveLenCnt > fc){
                                        firstFullWave = waveStart;
@@ -909,7 +942,7 @@ int DetectPSKClock(uint8_t dest[], size_t size, int clock)
                        }
                }
        }
-       //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
+       if (g_debugMode ==2) prnt("DEBUG PSK: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);
        
        //test each valid clock from greatest to smallest to see which lines up
        for(clkCnt=7; clkCnt >= 1 ; clkCnt--){
@@ -917,7 +950,7 @@ int DetectPSKClock(uint8_t dest[], size_t size, int clock)
                waveStart = 0;
                errCnt=0;
                peakcnt=0;
-               //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit);
+               if (g_debugMode == 2) prnt("DEBUG PSK: clk: %d, lastClkBit: %d",clk[clkCnt],lastClkBit);
 
                for (i = firstFullWave+fullWaveLen-1; i < loopCnt-2; i++){
                        //top edge of wave = start of new wave 
@@ -930,7 +963,7 @@ int DetectPSKClock(uint8_t dest[], size_t size, int clock)
                                        waveLenCnt = waveEnd-waveStart;
                                        if (waveLenCnt > fc){ 
                                                //if this wave is a phase shift
-                                               //PrintAndLog("DEBUG: phase shift at: %d, len: %d, nextClk: %d, ii: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,ii+1,fc);
+                                               if (g_debugMode == 2) prnt("DEBUG PSK: phase shift at: %d, len: %d, nextClk: %d, i: %d, fc: %d",waveStart,waveLenCnt,lastClkBit+clk[clkCnt]-tol,i+1,fc);
                                                if (i+1 >= lastClkBit + clk[clkCnt] - tol){ //should be a clock bit
                                                        peakcnt++;
                                                        lastClkBit+=clk[clkCnt];
@@ -959,11 +992,40 @@ int DetectPSKClock(uint8_t dest[], size_t size, int clock)
                if (peaksdet[i] > peaksdet[best]) {
                        best = i;
                }
-               //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
+               if (g_debugMode == 2) prnt("DEBUG PSK: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[i],peaksdet[i],bestErr[i],clk[best]);
        }
        return clk[best];
 }
 
+int DetectStrongNRZClk(uint8_t *dest, size_t size, int peak, int low){
+       //find shortest transition from high to low
+       size_t i = 0;
+       size_t transition1 = 0;
+       int lowestTransition = 255;
+       bool lastWasHigh = false;
+
+       //find first valid beginning of a high or low wave
+       while ((dest[i] >= peak || dest[i] <= low) && (i < size))
+               ++i;
+       while ((dest[i] < peak && dest[i] > low) && (i < size))
+               ++i;
+       lastWasHigh = (dest[i] >= peak);
+
+       if (i==size) return 0;
+       transition1 = i;
+
+       for (;i < size; i++) {
+               if ((dest[i] >= peak && !lastWasHigh) || (dest[i] <= low && lastWasHigh)) {
+                       lastWasHigh = (dest[i] >= peak);
+                       if (i-transition1 < lowestTransition) lowestTransition = i-transition1;
+                       transition1 = i;
+               }
+       }
+       if (lowestTransition == 255) lowestTransition = 0;
+       if (g_debugMode==2) prnt("DEBUG NRZ: detectstrongNRZclk smallest wave: %d",lowestTransition);
+       return lowestTransition;
+}
+
 //by marshmellow
 //detect nrz clock by reading #peaks vs no peaks(or errors)
 int DetectNRZClock(uint8_t dest[], size_t size, int clock)
@@ -972,8 +1034,7 @@ int DetectNRZClock(uint8_t dest[], size_t size, int clock)
        uint8_t clk[]={8,16,32,40,50,64,100,128,255};
        size_t loopCnt = 4096;  //don't need to loop through entire array...
        if (size == 0) return 0;
-       if (size<loopCnt) loopCnt = size;
-
+       if (size<loopCnt) loopCnt = size-20;
        //if we already have a valid clock quit
        for (; i < 8; ++i)
                if (clk[i] == clock) return clock;
@@ -982,38 +1043,82 @@ int DetectNRZClock(uint8_t dest[], size_t size, int clock)
        int peak, low;
        if (getHiLo(dest, loopCnt, &peak, &low, 75, 75) < 1) return 0;
 
-       //PrintAndLog("DEBUG: peak: %d, low: %d",peak,low);
+       int lowestTransition = DetectStrongNRZClk(dest, size-20, peak, low);
        size_t ii;
        uint8_t clkCnt;
        uint8_t tol = 0;
-       uint16_t peakcnt=0;
-       uint16_t peaksdet[]={0,0,0,0,0,0,0,0};
-       uint16_t maxPeak=0;
+       uint16_t smplCnt = 0;
+       int16_t peakcnt = 0;
+       int16_t peaksdet[] = {0,0,0,0,0,0,0,0};
+       uint16_t maxPeak = 255;
+       bool firstpeak = false;
        //test for large clipped waves
        for (i=0; i<loopCnt; i++){
                if (dest[i] >= peak || dest[i] <= low){
-                       peakcnt++;
+                       if (!firstpeak) continue;
+                       smplCnt++;
                } else {
-                       if (peakcnt>0 && maxPeak < peakcnt){
-                               maxPeak = peakcnt;
+                       firstpeak=true;
+                       if (smplCnt > 6 ){
+                               if (maxPeak > smplCnt){
+                                       maxPeak = smplCnt;
+                                       //prnt("maxPk: %d",maxPeak);
+                               }
+                               peakcnt++;
+                               //prnt("maxPk: %d, smplCnt: %d, peakcnt: %d",maxPeak,smplCnt,peakcnt);
+                               smplCnt=0;
                        }
-                       peakcnt=0;
                }
        }
+       bool errBitHigh = 0;
+       bool bitHigh = 0;
+       uint8_t ignoreCnt = 0;
+       uint8_t ignoreWindow = 4;
+       bool lastPeakHigh = 0;
+       int lastBit = 0; 
        peakcnt=0;
        //test each valid clock from smallest to greatest to see which lines up
        for(clkCnt=0; clkCnt < 8; ++clkCnt){
-               //ignore clocks smaller than largest peak
-               if (clk[clkCnt]<maxPeak) continue;
-
+               //ignore clocks smaller than smallest peak
+               if (clk[clkCnt] < maxPeak - (clk[clkCnt]/4)) continue;
                //try lining up the peaks by moving starting point (try first 256)
-               for (ii=0; ii< loopCnt; ++ii){
+               for (ii=20; ii < loopCnt; ++ii){
                        if ((dest[ii] >= peak) || (dest[ii] <= low)){
-                               peakcnt=0;
-                               // now that we have the first one lined up test rest of wave array
-                               for (i=0; i < ((int)((size-ii-tol)/clk[clkCnt])-1); ++i){
-                                       if (dest[ii+(i*clk[clkCnt])]>=peak || dest[ii+(i*clk[clkCnt])]<=low){
-                                               peakcnt++;
+                               peakcnt = 0;
+                               bitHigh = false;
+                               ignoreCnt = 0;
+                               lastBit = ii-clk[clkCnt]; 
+                               //loop through to see if this start location works
+                               for (i = ii; i < size-20; ++i) {
+                                       //if we are at a clock bit
+                                       if ((i >= lastBit + clk[clkCnt] - tol) && (i <= lastBit + clk[clkCnt] + tol)) {
+                                               //test high/low
+                                               if (dest[i] >= peak || dest[i] <= low) {
+                                                       //if same peak don't count it
+                                                       if ((dest[i] >= peak && !lastPeakHigh) || (dest[i] <= low && lastPeakHigh)) {
+                                                               peakcnt++;
+                                                       }
+                                                       lastPeakHigh = (dest[i] >= peak);
+                                                       bitHigh = true;
+                                                       errBitHigh = false;
+                                                       ignoreCnt = ignoreWindow;
+                                                       lastBit += clk[clkCnt];
+                                               } else if (i == lastBit + clk[clkCnt] + tol) {
+                                                       lastBit += clk[clkCnt];
+                                               }
+                                       //else if not a clock bit and no peaks
+                                       } else if (dest[i] < peak && dest[i] > low){
+                                               if (ignoreCnt==0){
+                                                       bitHigh=false;
+                                                       if (errBitHigh==true) peakcnt--;
+                                                       errBitHigh=false;
+                                               } else {
+                                                       ignoreCnt--;
+                                               }
+                                               // else if not a clock bit but we have a peak
+                                       } else if ((dest[i]>=peak || dest[i]<=low) && (!bitHigh)) {
+                                               //error bar found no clock...
+                                               errBitHigh=true;
                                        }
                                }
                                if(peakcnt>peaksdet[clkCnt]) {
@@ -1025,11 +1130,16 @@ int DetectNRZClock(uint8_t dest[], size_t size, int clock)
        int iii=7;
        uint8_t best=0;
        for (iii=7; iii > 0; iii--){
-               if (peaksdet[iii] > peaksdet[best]){
+               if ((peaksdet[iii] >= (peaksdet[best]-1)) && (peaksdet[iii] <= peaksdet[best]+1) && lowestTransition) {
+                       if (clk[iii] > (lowestTransition - (clk[iii]/8)) && clk[iii] < (lowestTransition + (clk[iii]/8))) {
+                               best = iii;
+                       }
+               } else if (peaksdet[iii] > peaksdet[best]){
                        best = iii;
                }
-               //PrintAndLog("DEBUG: Clk: %d, peaks: %d, errs: %d, bestClk: %d",clk[iii],peaksdet[iii],bestErr[iii],clk[best]);
+               if (g_debugMode==2) prnt("DEBUG NRZ: Clk: %d, peaks: %d, maxPeak: %d, bestClk: %d, lowestTrs: %d",clk[iii],peaksdet[iii],maxPeak, clk[best], lowestTransition);
        }
+
        return clk[best];
 }
 
@@ -1089,123 +1199,37 @@ int indala26decode(uint8_t *bitStream, size_t *size, uint8_t *invert)
        return (int) startidx;
 }
 
-// by marshmellow - demodulate NRZ wave (both similar enough)
+// by marshmellow - demodulate NRZ wave
 // peaks invert bit (high=1 low=0) each clock cycle = 1 bit determined by last peak
-// there probably is a much simpler way to do this.... 
-int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert, int maxErr)
-{
+int nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert){
        if (justNoise(dest, *size)) return -1;
        *clk = DetectNRZClock(dest, *size, *clk);
        if (*clk==0) return -2;
        size_t i, gLen = 4096;
-       if (gLen>*size) gLen = *size;
+       if (gLen>*size) gLen = *size-20;
        int high, low;
        if (getHiLo(dest, gLen, &high, &low, 75, 75) < 1) return -3; //25% fuzz on high 25% fuzz on low
-       int lastBit = 0;  //set first clock check
-       size_t iii = 0, bitnum = 0; //bitnum counter
-       uint16_t errCnt = 0, MaxBits = 1000;
-       size_t bestErrCnt = maxErr+1;
-       size_t bestPeakCnt = 0, bestPeakStart = 0;
-       uint8_t bestFirstPeakHigh=0, firstPeakHigh=0, curBit=0, bitHigh=0, errBitHigh=0;
-       uint8_t tol = 1;  //clock tolerance adjust - waves will be accepted as within the clock if they fall + or - this value + clock from last valid wave
-       uint16_t peakCnt=0;
-       uint8_t ignoreWindow=4;
-       uint8_t ignoreCnt=ignoreWindow; //in case of noise near peak
-       //loop to find first wave that works - align to clock
-       for (iii=0; iii < gLen; ++iii){
-               if ((dest[iii]>=high) || (dest[iii]<=low)){
-                       if (dest[iii]>=high) firstPeakHigh=1;
-                       else firstPeakHigh=0;
-                       lastBit=iii-*clk;
-                       peakCnt=0;
-                       errCnt=0;
-                       //loop through to see if this start location works
-                       for (i = iii; i < *size; ++i) {
-                               // if we are at a clock bit
-                               if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
-                                       //test high/low
-                                       if (dest[i] >= high || dest[i] <= low) {
-                                               bitHigh = 1;
-                                               peakCnt++;
-                                               errBitHigh = 0;
-                                               ignoreCnt = ignoreWindow;
-                                               lastBit += *clk;
-                                       } else if (i == lastBit + *clk + tol) {
-                                               lastBit += *clk;
-                                       }
-                               //else if no bars found
-                               } else if (dest[i] < high && dest[i] > low){
-                                       if (ignoreCnt==0){
-                                               bitHigh=0;
-                                               if (errBitHigh==1) errCnt++;
-                                               errBitHigh=0;
-                                       } else {
-                                               ignoreCnt--;
-                                       }
-                               } else if ((dest[i]>=high || dest[i]<=low) && (bitHigh==0)) {
-                                       //error bar found no clock...
-                                       errBitHigh=1;
-                               }
-                               if (((i-iii) / *clk)>=MaxBits) break;
-                       }
-                       //we got more than 64 good bits and not all errors
-                       if (((i-iii) / *clk) > 64 && (errCnt <= (maxErr))) {
-                               //possible good read
-                               if (!errCnt || peakCnt > bestPeakCnt){
-                                       bestFirstPeakHigh=firstPeakHigh;
-                                       bestErrCnt = errCnt;
-                                       bestPeakCnt = peakCnt;
-                                       bestPeakStart = iii;
-                                       if (!errCnt) break;  //great read - finish
-                               }
-                       }
-               }
+       
+       uint8_t bit=0;
+       //convert wave samples to 1's and 0's
+       for(i=20; i < *size-20; i++){
+               if (dest[i] >= high) bit = 1;
+               if (dest[i] <= low)  bit = 0;
+               dest[i] = bit;
        }
-       //PrintAndLog("DEBUG: bestErrCnt: %d, maxErr: %d, bestStart: %d, bestPeakCnt: %d, bestPeakStart: %d",bestErrCnt,maxErr,bestStart,bestPeakCnt,bestPeakStart);
-       if (bestErrCnt > maxErr) return bestErrCnt;             
-
-       //best run is good enough set to best run and set overwrite BinStream
-       lastBit = bestPeakStart - *clk;
-       memset(dest, bestFirstPeakHigh^1, bestPeakStart / *clk);
-       bitnum += (bestPeakStart / *clk);
-       for (i = bestPeakStart; i < *size; ++i) {
-               // if expecting a clock bit
-               if ((i >= lastBit + *clk - tol) && (i <= lastBit + *clk + tol)) {
-                       // test high/low
-                       if (dest[i] >= high || dest[i] <= low) {
-                               peakCnt++;
-                               bitHigh = 1;
-                               errBitHigh = 0;
-                               ignoreCnt = ignoreWindow;
-                               curBit = *invert;
-                               if (dest[i] >= high) curBit ^= 1;
-                               dest[bitnum++] = curBit;
-                               lastBit += *clk;
-                       //else no bars found in clock area
-                       } else if (i == lastBit + *clk + tol) {
-                               dest[bitnum++] = curBit;
-                               lastBit += *clk;
-                       }
-               //else if no bars found
-               } else if (dest[i] < high && dest[i] > low){
-                       if (ignoreCnt == 0){
-                               bitHigh = 0;
-                               if (errBitHigh == 1){
-                                       dest[bitnum++] = 7;
-                                       errCnt++;
-                               }
-                               errBitHigh=0;
-                       } else {
-                               ignoreCnt--;
-                       }
-               } else if ((dest[i] >= high || dest[i] <= low) && (bitHigh == 0)) {
-                       //error bar found no clock...
-                       errBitHigh=1;
+       //now demod based on clock (rf/32 = 32 1's for one 1 bit, 32 0's for one 0 bit) 
+       size_t lastBit = 0;
+       size_t numBits = 0;
+       for(i=21; i < *size-20; i++) {
+               //if transition detected or large number of same bits - store the passed bits
+               if (dest[i] != dest[i-1] || (i-lastBit) == (10 * *clk)) {
+                       memset(dest+numBits, dest[i-1] ^ *invert, (i - lastBit + (*clk/4)) / *clk);
+                       numBits += (i - lastBit + (*clk/4)) / *clk;
+                       lastBit = i-1;
                }
-               if (bitnum >= MaxBits) break;
        }
-       *size = bitnum;
-       return bestErrCnt;
+       *size = numBits;
+       return 0;
 }
 
 //by marshmellow
@@ -1223,18 +1247,18 @@ uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fc
        size_t i;
        if (size == 0) return 0;
 
-       uint8_t fcTol = (uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
+       uint8_t fcTol = ((fcHigh*100 - fcLow*100)/2 + 50)/100; //(uint8_t)(0.5+(float)(fcHigh-fcLow)/2);
        rfLensFnd=0;
        fcCounter=0;
        rfCounter=0;
        firstBitFnd=0;
        //PrintAndLog("DEBUG: fcTol: %d",fcTol);
-       // prime i to first up transition
-       for (i = 1; i < size-1; i++)
+       // prime i to first peak / up transition
+       for (i = 160; i < size-20; i++)
                if (BitStream[i] > BitStream[i-1] && BitStream[i]>=BitStream[i+1])
                        break;
 
-       for (; i < size-1; i++){
+       for (; i < size-20; i++){
                fcCounter++;
                rfCounter++;
 
@@ -1252,7 +1276,7 @@ uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fc
                        //not the same size as the last wave - start of new bit sequence
                        if (firstBitFnd > 1){ //skip first wave change - probably not a complete bit
                                for (int ii=0; ii<15; ii++){
-                                       if (rfLens[ii] == rfCounter){
+                                       if (rfLens[ii] >= (rfCounter-4) && rfLens[ii] <= (rfCounter+4)){
                                                rfCnts[ii]++;
                                                rfCounter = 0;
                                                break;
@@ -1274,7 +1298,6 @@ uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fc
        uint8_t rfHighest=15, rfHighest2=15, rfHighest3=15;
 
        for (i=0; i<15; i++){
-               //PrintAndLog("DEBUG: RF %d, cnts %d",rfLens[i], rfCnts[i]);
                //get highest 2 RF values  (might need to get more values to compare or compare all?)
                if (rfCnts[i]>rfCnts[rfHighest]){
                        rfHighest3=rfHighest2;
@@ -1286,20 +1309,23 @@ uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fc
                } else if(rfCnts[i]>rfCnts[rfHighest3]){
                        rfHighest3=i;
                }
+               if (g_debugMode==2) prnt("DEBUG FSK: RF %d, cnts %d",rfLens[i], rfCnts[i]);
        }  
        // set allowed clock remainder tolerance to be 1 large field clock length+1 
        //   we could have mistakenly made a 9 a 10 instead of an 8 or visa versa so rfLens could be 1 FC off  
        uint8_t tol1 = fcHigh+1; 
        
-       //PrintAndLog("DEBUG: hightest: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]);
+       if (g_debugMode==2) prnt("DEBUG FSK: most counted rf values: 1 %d, 2 %d, 3 %d",rfLens[rfHighest],rfLens[rfHighest2],rfLens[rfHighest3]);
 
        // loop to find the highest clock that has a remainder less than the tolerance
        //   compare samples counted divided by
+       // test 128 down to 32 (shouldn't be possible to have fc/10 & fc/8 and rf/16 or less)
        int ii=7;
-       for (; ii>=0; ii--){
+       for (; ii>=2; ii--){
                if (rfLens[rfHighest] % clk[ii] < tol1 || rfLens[rfHighest] % clk[ii] > clk[ii]-tol1){
                        if (rfLens[rfHighest2] % clk[ii] < tol1 || rfLens[rfHighest2] % clk[ii] > clk[ii]-tol1){
                                if (rfLens[rfHighest3] % clk[ii] < tol1 || rfLens[rfHighest3] % clk[ii] > clk[ii]-tol1){
+                                       if (g_debugMode==2) prnt("DEBUG FSK: clk %d divides into the 3 most rf values within tolerance",clk[ii]);
                                        break;
                                }
                        }
@@ -1317,8 +1343,8 @@ uint8_t detectFSKClk(uint8_t *BitStream, size_t size, uint8_t fcHigh, uint8_t fc
 //mainly used for FSK field clock detection
 uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
 {
-       uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0};
-       uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0};
+       uint8_t fcLens[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
+       uint16_t fcCnts[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        uint8_t fcLensFnd = 0;
        uint8_t lastFCcnt=0;
        uint8_t fcCounter = 0;
@@ -1326,11 +1352,11 @@ uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
        if (size == 0) return 0;
 
        // prime i to first up transition
-       for (i = 1; i < size-1; i++)
+       for (i = 160; i < size-20; i++)
                if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1])
                        break;
 
-       for (; i < size-1; i++){
+       for (; i < size-20; i++){
                if (BitStream[i] > BitStream[i-1] && BitStream[i] >= BitStream[i+1]){
                        // new up transition
                        fcCounter++;
@@ -1343,14 +1369,14 @@ uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
                        lastFCcnt = fcCounter;
                        }
                        // find which fcLens to save it to:
-                       for (int ii=0; ii<10; ii++){
+                       for (int ii=0; ii<15; ii++){
                                if (fcLens[ii]==fcCounter){
                                        fcCnts[ii]++;
                                        fcCounter=0;
                                        break;
                                }
                        }
-                       if (fcCounter>0 && fcLensFnd<10){
+                       if (fcCounter>0 && fcLensFnd<15){
                                //add new fc length 
                                fcCnts[fcLensFnd]++;
                                fcLens[fcLensFnd++]=fcCounter;
@@ -1362,11 +1388,10 @@ uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
                }
        }
        
-       uint8_t best1=9, best2=9, best3=9;
+       uint8_t best1=14, best2=14, best3=14;
        uint16_t maxCnt1=0;
        // go through fclens and find which ones are bigest 2  
-       for (i=0; i<10; i++){
-               // PrintAndLog("DEBUG: FC %d, Cnt %d, Errs %d",fcLens[i],fcCnts[i],errCnt);    
+       for (i=0; i<15; i++){
                // get the 3 best FC values
                if (fcCnts[i]>maxCnt1) {
                        best3=best2;
@@ -1379,7 +1404,9 @@ uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
                } else if(fcCnts[i]>fcCnts[best3]){
                        best3=i;
                }
+               if (g_debugMode==2) prnt("DEBUG countfc: FC %u, Cnt %u, best fc: %u, best2 fc: %u",fcLens[i],fcCnts[i],fcLens[best1],fcLens[best2]);
        }
+       if (fcLens[best1]==0) return 0;
        uint8_t fcH=0, fcL=0;
        if (fcLens[best1]>fcLens[best2]){
                fcH=fcLens[best1];
@@ -1388,11 +1415,13 @@ uint16_t countFC(uint8_t *BitStream, size_t size, uint8_t fskAdj)
                fcH=fcLens[best2];
                fcL=fcLens[best1];
        }
-
+       if ((size-180)/fcH/3 > fcCnts[best1]+fcCnts[best2]) {
+               if (g_debugMode==2) prnt("DEBUG countfc: fc is too large: %u > %u. Not psk or fsk",(size-180)/fcH/3,fcCnts[best1]+fcCnts[best2]);
+               return 0; //lots of waves not psk or fsk
+       }
        // TODO: take top 3 answers and compare to known Field clocks to get top 2
 
        uint16_t fcs = (((uint16_t)fcH)<<8) | fcL;
-       // PrintAndLog("DEBUG: Best %d  best2 %d best3 %d",fcLens[best1],fcLens[best2],fcLens[best3]);
        if (fskAdj) return fcs; 
        return fcLens[best1];
 }
@@ -1405,6 +1434,7 @@ int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert)
        uint16_t loopCnt = 4096;  //don't need to loop through entire array...
        if (*size<loopCnt) loopCnt = *size;
 
+       size_t numBits=0;
        uint8_t curPhase = *invert;
        size_t i, waveStart=1, waveEnd=0, firstFullWave=0, lastClkBit=0;
        uint8_t fc=0, fullWaveLen=0, tol=1;
@@ -1421,7 +1451,7 @@ int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert)
                        waveEnd = i+1;
                        //PrintAndLog("DEBUG: waveEnd: %d",waveEnd);
                        waveLenCnt = waveEnd-waveStart;
-                       if (waveLenCnt > fc && waveStart > fc){ //not first peak and is a large wave 
+                       if (waveLenCnt > fc && waveStart > fc && !(waveLenCnt > fc+2)){ //not first peak and is a large wave but not out of whack
                                lastAvgWaveVal = avgWaveVal/(waveLenCnt);
                                firstFullWave = waveStart;
                                fullWaveLen=waveLenCnt;
@@ -1434,14 +1464,21 @@ int pskRawDemod(uint8_t dest[], size_t *size, int *clock, int *invert)
                }
                avgWaveVal += dest[i+2];
        }
+       if (firstFullWave == 0) {
+               // no phase shift detected - could be all 1's or 0's - doesn't matter where we start
+               // so skip a little to ensure we are past any Start Signal
+               firstFullWave = 160;
+               memset(dest, curPhase, firstFullWave / *clock);
+       } else {
+               memset(dest, curPhase^1, firstFullWave / *clock);
+       }
+       //advance bits
+       numBits += (firstFullWave / *clock);
+       //set start of wave as clock align
+       lastClkBit = firstFullWave;
        //PrintAndLog("DEBUG: firstFullWave: %d, waveLen: %d",firstFullWave,fullWaveLen);  
-       lastClkBit = firstFullWave; //set start of wave as clock align
        //PrintAndLog("DEBUG: clk: %d, lastClkBit: %d", *clock, lastClkBit);
        waveStart = 0;
-       size_t numBits=0;
-       //set skipped bits
-       memset(dest, curPhase^1, firstFullWave / *clock);
-       numBits += (firstFullWave / *clock);
        dest[numBits++] = curPhase; //set first read bit
        for (i = firstFullWave + fullWaveLen - 1; i < *size-3; i++){
                //top edge of wave = start of new wave 
index cc4fa27a3b07a12fcc5e6911a13ea41de8832c96..20eb6769502283d7972d438c6a44d5d6a245b14d 100644 (file)
@@ -16,6 +16,7 @@
 #include <stdint.h>
 
 //generic
+size_t   addParity(uint8_t *BitSource, uint8_t *dest, uint8_t sourceLen, uint8_t pLen, uint8_t pType);
 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);
@@ -32,7 +33,7 @@ int      getHiLo(uint8_t *BitStream, size_t size, int *high, int *low, uint8_t f
 uint32_t manchesterEncode2Bytes(uint16_t datain);
 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);
+int      nrzRawDemod(uint8_t *dest, size_t *size, int *clk, int *invert);
 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);
index b8a1296640f9319ed6231f7021be54fe19231dbb..38f8617a84c14c2c23e152c8b45b1742aa025738 100644 (file)
@@ -99,6 +99,7 @@ typedef struct{
 #define CMD_ASK_SIM_TAG                                                   0x021F
 #define CMD_PSK_SIM_TAG                                                   0x0220
 #define CMD_AWID_DEMOD_FSK                                                0x0221
+#define CMD_VIKING_CLONE_TAG                                              0x0223
 #define CMD_T55XX_WAKEUP                                                  0x0224
 
 
Impressum, Datenschutz