]> cvs.zerfleddert.de Git - proxmark3-svn/commitdiff
Merge branch 'master' of https://github.com/Proxmark/proxmark3
authoriceman1001 <iceman@iuse.se>
Thu, 29 Jan 2015 20:39:33 +0000 (21:39 +0100)
committericeman1001 <iceman@iuse.se>
Thu, 29 Jan 2015 20:39:33 +0000 (21:39 +0100)
Conflicts:
armsrc/Makefile
armsrc/appmain.c
armsrc/apps.h
armsrc/epa.c
armsrc/iclass.c
armsrc/iso14443a.c
armsrc/iso14443a.h
armsrc/iso15693.c
armsrc/lfops.c
armsrc/mifarecmd.c
armsrc/mifareutil.c
armsrc/mifareutil.h
armsrc/string.h
armsrc/util.h
bootrom/bootrom.c
client/Makefile
client/cmddata.c
client/cmddata.h
client/cmdhf.c
client/cmdhf14a.c
client/cmdhf14b.c
client/cmdhf15.c
client/cmdhficlass.c
client/cmdhfmf.c
client/cmdhfmfu.c
client/cmdlf.c
client/cmdlfem4x.c
client/cmdlfhid.c
client/cmdlfhitag.c
client/cmdlfio.c
client/cmdmain.c
client/data.h
client/flash.c
client/graph.c
client/graph.h
client/loclass/elite_crack.c
client/loclass/fileutils.c
client/lualibs/commands.lua
client/lualibs/html_dumplib.lua
client/lualibs/mf_default_keys.lua
client/lualibs/utils.lua
client/mifarehost.c
client/nonce2key/crapto1.c
client/proxmark3.c
client/scripting.c
client/scripts/tnp3dump.lua
client/scripts/tnp3sim.lua
client/scripts/tracetest.lua
common/Makefile.common
common/cmd.c
common/cmd.h
common/lfdemod.c
common/lfdemod.h
common/usb_cdc.c
common/usb_cdc.h
include/usb_cmd.h

21 files changed:
1  2 
armsrc/Makefile
armsrc/appmain.c
armsrc/apps.h
armsrc/epa.c
armsrc/hitag2.c
armsrc/iclass.c
armsrc/iso14443.c
armsrc/iso14443a.h
armsrc/legicrf.c
armsrc/mifarecmd.c
armsrc/mifareutil.c
client/loclass/cipher.c
client/lualibs/commands.lua
client/lualibs/html_dumplib.lua
client/lualibs/mf_default_keys.lua
client/lualibs/utils.lua
client/mifarehost.c
client/nonce2key/crapto1.c
client/proxmark3.c
client/scripting.c
common/Makefile.common

diff --combined armsrc/Makefile
index 69e4738ad544e1328c96968c32887767c7f1b943,bbcbcb1c4263819f861abb13acf465456d90bba7..523171656925a585c3440d9aa5403307f0573ac9
@@@ -16,9 -16,9 +16,9 @@@ APP_CFLAGS    = -DWITH_LF -DWITH_ISO15693 
  #SRC_LCD = fonts.c LCD.c
  SRC_LF = lfops.c hitag2.c
  SRC_ISO15693 = iso15693.c iso15693tools.c 
- SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c 
- SRC_ISO14443b = iso14443.c 
- SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c desfire_key.c desfire_crypto.c mifaredesfire.c
+ SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c
+ SRC_ISO14443b = iso14443.c
+ SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c 
  SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c 
  
  THUMBSRC = start.c \
@@@ -41,9 -41,9 +41,10 @@@ ARMSRC = fpgaloader.c 
        $(SRC_CRAPTO1) \
        $(SRC_CRC) \
        legic_prng.c \
-       iclass.c
+       iclass.c \
+       BigBuf.c \
  
 +
  # stdint.h provided locally until GCC 4.5 becomes C99 compliant
  APP_CFLAGS += -I.
  
diff --combined armsrc/appmain.c
index c158ad2c2d005bfd507625dd4ec273655444110d,791ad4f861bcdb64e5003fdfe17087b66cb47502..00e9ba4dadc85d9b95e43c8ac9742981ff24d8ae
  // executes.
  //-----------------------------------------------------------------------------
  
 -#include "usb_cdc.h"
 -#include "cmd.h"
 +#include "../common/usb_cdc.h"
 +#include "../common/cmd.h"
  
 -#include "proxmark3.h"
 +#include "../include/proxmark3.h"
  #include "apps.h"
  #include "util.h"
  #include "printf.h"
  #include "string.h"
 -
  #include <stdarg.h>
  
  #include "legicrf.h"
 -#include <hitag2.h>
 +#include "../include/hitag2.h"
 +
  
  #ifdef WITH_LCD
   #include "LCD.h"
  // is the order in which they go out on the wire.
  //=============================================================================
  
- #define TOSEND_BUFFER_SIZE (9*MAX_FRAME_SIZE + 1 + 1 + 2) // 8 data bits and 1 parity bit per payload byte, 1 correction bit, 1 SOC bit, 2 EOC bits
+ #define TOSEND_BUFFER_SIZE (9*MAX_FRAME_SIZE + 1 + 1 + 2)  // 8 data bits and 1 parity bit per payload byte, 1 correction bit, 1 SOC bit, 2 EOC bits 
  uint8_t ToSend[TOSEND_BUFFER_SIZE];
  int ToSendMax;
  static int ToSendBit;
  struct common_area common_area __attribute__((section(".commonarea")));
  
- void BufferClear(void)
- {
-       memset(BigBuf,0,sizeof(BigBuf));
-       Dbprintf("Buffer cleared (%i bytes)",sizeof(BigBuf));
- }
  void ToSendReset(void)
  {
        ToSendMax = -1;
@@@ -68,7 -62,7 +62,7 @@@ void ToSendStuffBit(int b
  
        ToSendBit++;
  
-       if(ToSendMax  >= sizeof(ToSend)) {
+       if(ToSendMax >= sizeof(ToSend)) {
                ToSendBit = 0;
                DbpString("ToSendStuffBit overflowed!");
        }
@@@ -172,7 -166,7 +166,7 @@@ void MeasureAntennaTuning(void
        int i, adcval = 0, peak = 0, peakv = 0, peakf = 0; //ptr = 0 
        int vLf125 = 0, vLf134 = 0, vHf = 0;    // in mV
  
 -      LED_B_ON();
 +  LED_B_ON();
  
  /*
   * Sweeps the useful LF range of the proxmark from
  
        for (i=18; i >= 0; i--) LF_Results[i] = 0;
        
 -      LED_A_ON();
 +  LED_A_ON();
        // Let the FPGA drive the high-frequency antenna around 13.56 MHz.
        FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
        FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
  
        cmd_send(CMD_MEASURED_ANTENNA_TUNING,vLf125|(vLf134<<16),vHf,peakf|(peakv<<16),LF_Results,256);
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
 -      LED_A_OFF();
 -      LED_B_OFF();
 -      return;
 +  LED_A_OFF();
 +  LED_B_OFF();
 +  return;
  }
  
  void MeasureAntennaTuningHf(void)
  
  void SimulateTagHfListen(void)
  {
-       uint8_t *dest = (uint8_t *)BigBuf+FREE_BUFFER_OFFSET;
+       // ToDo: historically this used the free buffer, which was 2744 Bytes long. 
+       // There might be a better size to be defined:
+       #define HF_14B_SNOOP_BUFFER_SIZE 2744
+       uint8_t *dest = BigBuf_malloc(HF_14B_SNOOP_BUFFER_SIZE);
        uint8_t v = 0;
        int i;
        int p = 0;
                                p = 0;
                                i++;
  
-                               if(i >= FREE_BUFFER_SIZE) {
+                               if(i >= HF_14B_SNOOP_BUFFER_SIZE) {
                                        break;
                                }
                        }
@@@ -361,7 -358,7 +358,7 @@@ void SamyRun(
        for (;;)
        {
                usb_poll();
 -    WDT_HIT();
 +              WDT_HIT();
  
                // Was our button held down or pressed?
                int button_pressed = BUTTON_HELD(1000);
@@@ -625,7 -622,7 +622,7 @@@ void UsbPacketReceived(uint8_t *packet
  {
        UsbCommand *c = (UsbCommand *)packet;
  
 -//  Dbprintf("received %d bytes, with command: 0x%04x and args: %d %d %d",len,c->cmd,c->arg[0],c->arg[1],c->arg[2]);
 +  //Dbprintf("received %d bytes, with command: 0x%04x and args: %d %d %d",len,c->cmd,c->arg[0],c->arg[1],c->arg[2]);
    
        switch(c->cmd) {
  #ifdef WITH_LF
                        WriteTItag(c->arg[0],c->arg[1],c->arg[2]);
                        break;
                case CMD_SIMULATE_TAG_125K:
 -                      LED_A_ON();
 -                      SimulateTagLowFrequency(c->arg[0], c->arg[1], 1);
 -                      LED_A_OFF();
 +                      SimulateTagLowFrequency(c->arg[0], c->arg[1], 0);
 +                      //SimulateTagLowFrequencyA(c->arg[0], c->arg[1]);
                        break;
                case CMD_LF_SIMULATE_BIDIR:
                        SimulateTagLowFrequencyBidir(c->arg[0], c->arg[1]);
                        EPA_PACE_Collect_Nonce(c);
                        break;
                        
 +              // case CMD_EPA_:
 +              //      EpaFoo(c);
 +              // break;
 +                      
                case CMD_READER_MIFARE:
              ReaderMifare(c->arg[0]);
                        break;
                        MifareUC_Auth2(c->arg[0],c->d.asBytes);
                        break;
                case CMD_MIFAREU_READCARD:
-                       MifareUReadCard(c->arg[0],c->arg[1],c->d.asBytes);
+                       MifareUReadCard(c->arg[0], c->arg[1], c->d.asBytes);
 -                      break;
 +                        break;
                case CMD_MIFAREUC_READCARD:
-                       MifareUReadCard(c->arg[0],c->arg[1],c->d.asBytes);
-                         break;
+                       MifareUReadCard(c->arg[0], c->arg[1], c->d.asBytes);
+                       break;
                case CMD_MIFARE_READSC:
                        MifareReadSector(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes);
                        break;
                case CMD_MIFARE_SNIFFER:
                        SniffMifare(c->arg[0]);
                        break;
-                       
-               // mifare desfire
-               case CMD_MIFARE_DESFIRE_READBL:
-                       break;
-               case CMD_MIFARE_DESFIRE_WRITEBL:
-                       break;
-               case CMD_MIFARE_DESFIRE_AUTH1:
-                       MifareDES_Auth1(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes);
-                       break;
-               case CMD_MIFARE_DESFIRE_AUTH2:
-                       //MifareDES_Auth2(c->arg[0],c->d.asBytes);
-                       break;
-               // case CMD_MIFARE_DES_READER:
-                       // ReaderMifareDES(c->arg[0], c->arg[1], c->d.asBytes);
-                       //break;
-               case CMD_MIFARE_DESFIRE_INFO:
-                       MifareDesfireGetInformation();
-                       break;
-               case CMD_MIFARE_DESFIRE:
-                       MifareSendCommand(c->arg[0], c->arg[1], c->d.asBytes);
-                       break;
  
  #endif
  
                        ReaderIClass(c->arg[0]);
                        break;
                case CMD_READER_ICLASS_REPLAY:
 -                  ReaderIClass_Replay(c->arg[0], c->d.asBytes);
 +                      ReaderIClass_Replay(c->arg[0], c->d.asBytes);
                        break;
  #endif
  
                        break;
  
                case CMD_BUFF_CLEAR:
-                       BufferClear();
+                       BigBuf_Clear();
                        break;
  
                case CMD_MEASURE_ANTENNA_TUNING:
                case CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K:
  
                        LED_B_ON();
+                       uint8_t *BigBuf = BigBuf_get_addr();
                        for(size_t i=0; i<c->arg[1]; i += USB_CMD_DATA_SIZE) {
                                size_t len = MIN((c->arg[1] - i),USB_CMD_DATA_SIZE);
-                               cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K,i,len,0,((byte_t*)BigBuf)+c->arg[0]+i,len);
+                               cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K,i,len,traceLen,BigBuf+c->arg[0]+i,len);
                        }
                        // Trigger a finish downloading signal with an ACK frame
-                       cmd_send(CMD_ACK,0,0,0,0,0);
+                       cmd_send(CMD_ACK,0,0,traceLen,0,0);
                        LED_B_OFF();
                        break;
  
                case CMD_DOWNLOADED_SIM_SAMPLES_125K: {
-                       uint8_t *b = (uint8_t *)BigBuf;
+                       uint8_t *b = BigBuf_get_addr();
                        memcpy(b+c->arg[0], c->d.asBytes, USB_CMD_DATA_SIZE);
                        cmd_send(CMD_ACK,0,0,0,0,0);
                        break;
@@@ -1035,7 -1009,7 +1012,7 @@@ void  __attribute__((noreturn)) AppMain
        LED_A_OFF();
  
        // Init USB device
 -  usb_enable();
 +      usb_enable();
  
        // The FPGA gets its clock from us from PCK0 output, so set that up.
        AT91C_BASE_PIOA->PIO_BSR = GPIO_PCK0;
        size_t rx_len;
    
        for(;;) {
 -    if (usb_poll()) {
 -      rx_len = usb_read(rx,sizeof(UsbCommand));
 -      if (rx_len) {
 -        UsbPacketReceived(rx,rx_len);
 -      }
 -    }
 +              if (usb_poll()) {
 +                      rx_len = usb_read(rx,sizeof(UsbCommand));
 +                      if (rx_len) {
 +                              UsbPacketReceived(rx,rx_len);
 +                      }
 +              }
                WDT_HIT();
  
  #ifdef WITH_LF
diff --combined armsrc/apps.h
index 30010f1b3290b34a1799743fa22790529e98bc98,5ef876232ceb2230596e93e7428f8507866ca765..39ee321154db33209c104f66ac42fa121a22cacd
  
  #include <stdint.h>
  #include <stddef.h>
 -#include "common.h"
 -#include "hitag2.h"
 -#include "mifare.h"
 +#include <stdlib.h>
 +#include <sys/types.h>
 +#include <string.h>
 +#include <strings.h>
- #include "../include/common.h"
- #include "../include/hitag2.h"
- #include "../include/mifare.h"
- //#include <openssl/des.h>
- //#include <openssl/aes.h>
- //#include "des.h"
- //#include "aes.h"
- #include "../common/desfire.h"
  #include "../common/crc32.h"
- // The large multi-purpose buffer, typically used to hold A/D samples,
- // maybe processed in some way.
- #define BIGBUF_SIZE   40000      
- uint32_t BigBuf[BIGBUF_SIZE / sizeof(uint32_t)];
- #define TRACE_OFFSET  0
- #define TRACE_SIZE    3000
- #define RECV_CMD_OFFSET       (TRACE_OFFSET + TRACE_SIZE)
- #define MAX_FRAME_SIZE        256
- #define MAX_PARITY_SIZE       ((MAX_FRAME_SIZE + 1)/ 8)
- #define RECV_CMD_PAR_OFFSET   (RECV_CMD_OFFSET + MAX_FRAME_SIZE)
- #define RECV_RESP_OFFSET      (RECV_CMD_PAR_OFFSET + MAX_PARITY_SIZE)
- #define RECV_RESP_PAR_OFFSET (RECV_RESP_OFFSET + MAX_FRAME_SIZE)
- #define CARD_MEMORY_OFFSET    (RECV_RESP_PAR_OFFSET + MAX_PARITY_SIZE)
- #define CARD_MEMORY_SIZE      4096    
- #define DMA_BUFFER_OFFSET CARD_MEMORY_OFFSET
- #define DMA_BUFFER_SIZE CARD_MEMORY_SIZE
- #define FREE_BUFFER_OFFSET (CARD_MEMORY_OFFSET + CARD_MEMORY_SIZE)
- #define FREE_BUFFER_SIZE (BIGBUF_SIZE - FREE_BUFFER_OFFSET - 1)
+ #include "BigBuf.h"
  
  extern const uint8_t OddByteParity[256];
- extern uint8_t *trace; // = (uint8_t *) BigBuf;
- extern int traceLen;   // = 0;
  extern int rsamples;   // = 0;
  extern int tracing;    // = TRUE;
  extern uint8_t trigger;
@@@ -76,13 -45,9 +46,12 @@@ void ToSendReset(void)
  void ListenReaderField(int limit);
  void AcquireRawAdcSamples125k(int at134khz);
  void SnoopLFRawAdcSamples(int divisor, int trigger_threshold);
 -void DoAcquisition125k(int trigger_threshold);
 +void DoAcquisition125k_internal(int trigger_threshold, bool silent);
 +void DoAcquisition125k_threshold(int trigger_threshold);
 +void DoAcquisition125k();
 +
  extern int ToSendMax;
  extern uint8_t ToSend[];
- extern uint32_t BigBuf[];
  
  /// fpga.h
  void FpgaSendCommand(uint16_t cmd, uint16_t v);
@@@ -130,6 -95,8 +99,8 @@@ void SetAdcMuxFor(uint32_t whichGpio)
  #define FPGA_HF_SIMULATOR_MODULATE_BPSK                               (1<<0)
  #define FPGA_HF_SIMULATOR_MODULATE_212K                               (2<<0)
  #define FPGA_HF_SIMULATOR_MODULATE_424K                               (4<<0)
+ #define FPGA_HF_SIMULATOR_MODULATE_424K_8BIT          0x5//101
  // Options for ISO14443A
  #define FPGA_HF_ISO14443A_SNIFFER                             (0<<0)
  #define FPGA_HF_ISO14443A_TAGSIM_LISTEN                               (1<<0)
@@@ -144,10 -111,8 +115,10 @@@ void ReadTItag(void)
  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 CmdHIDsimTAG(int hi, int lo, int ledcontrol);
 +void SimulateTagLowFrequency( uint16_t period, uint32_t gap, uint8_t ledcontrol);
 +void SimulateTagLowFrequencyA(int period, int gap);
 +
 +void CmdHIDsimTAG(int hi, int lo, uint8_t ledcontrol);
  void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol);
  void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol);
  void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol);
@@@ -160,7 -125,6 +131,7 @@@ void CopyIndala224toT55x7(int uid1, in
  void T55xxWriteBlock(uint32_t Data, uint32_t Block, uint32_t Pwd, uint8_t PwdMode);
  void T55xxReadBlock(uint32_t Block, uint32_t Pwd, uint8_t PwdMode );
  void T55xxReadTrace(void);
 +void TurnReadLFOn();
  int DemodPCF7931(uint8_t **outBlocks);
  int IsBlock0PCF7931(uint8_t *Block);
  int IsBlock1PCF7931(uint8_t *Block);
@@@ -181,7 -145,7 +152,7 @@@ void SimulateIso14443aTag(int tagType, 
  void ReaderIso14443a(UsbCommand * c);
  // Also used in iclass.c
  bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t len, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag);
- void GetParity(const uint8_t * pbtCmd, uint16_t len, uint8_t *parity);
+ void GetParity(const uint8_t *pbtCmd, uint16_t len, uint8_t *parity);
  void iso14a_set_trigger(bool enable);
  void iso14a_clear_trace();
  void iso14a_set_tracing(bool enable);
@@@ -231,17 -195,6 +202,6 @@@ void      OnError(uint8_t reason)
  
  
  
- // desfire_crypto.h
- void  *mifare_cryto_preprocess_data (desfiretag_t tag, void *data, size_t *nbytes, off_t offset, int communication_settings);
- void    *mifare_cryto_postprocess_data (desfiretag_t tag, void *data, ssize_t *nbytes, int communication_settings);
- void    mifare_cypher_single_block (desfirekey_t  key, uint8_t *data, uint8_t *ivect, MifareCryptoDirection direction, MifareCryptoOperation operation, size_t block_size);
- void    mifare_cypher_blocks_chained (desfiretag_t tag, desfirekey_t key, uint8_t *ivect, uint8_t *data, size_t data_size, MifareCryptoDirection direction, MifareCryptoOperation operation);
- size_t  key_block_size (const desfirekey_t  key);
- size_t  padded_data_length (const size_t nbytes, const size_t block_size);
- size_t  maced_data_length (const desfirekey_t  key, const size_t nbytes);
- size_t  enciphered_data_length (const desfiretag_t tag, const size_t nbytes, int communication_settings);
- void    cmac_generate_subkeys (desfirekey_t key);
- void    cmac (const desfirekey_t  key, uint8_t *ivect, const uint8_t *data, size_t len, uint8_t *cmac);
  
  
  /// iso15693.h
diff --combined armsrc/epa.c
index 0bbd2dd786e18af9a43a927dcf66c5b6618a9446,bec79e61d075852c3d088c4667c21e8c97faf53d..a04b76280d8f387a9f35504735e6670c112e29e8
@@@ -13,7 -13,7 +13,7 @@@
  
  #include "iso14443a.h"
  #include "epa.h"
 -#include "cmd.h"
 +#include "../common/cmd.h"
  
  // Protocol and Parameter Selection Request
  // use regular (1x) speed in both directions
@@@ -224,7 -224,7 +224,7 @@@ static void EPA_PACE_Collect_Nonce_Abor
        EPA_Finish();
        
        // send the USB packet
 -  cmd_send(CMD_ACK,step,func_return,0,0,0);
 +      cmd_send(CMD_ACK,step,func_return,0,0,0);
  }
  
  //-----------------------------------------------------------------------------
@@@ -252,15 -252,13 +252,15 @@@ void EPA_PACE_Collect_Nonce(UsbCommand 
        
        // set up communication
        func_return = EPA_Setup();
 -      if (func_return != 0) {
 +      if (func_return != 0) { 
                EPA_PACE_Collect_Nonce_Abort(1, func_return);
 +              Dbprintf("epa: setup fucked up! %d", func_return);
                return;
        }
  
        // increase the timeout (at least some cards really do need this!)
        iso14a_set_timeout(0x0002FFFF);
 +      Dbprintf("epa: Epic!");
        
        // read the CardAccess file
        // this array will hold the CardAccess file
        int card_access_length = EPA_Read_CardAccess(card_access, 256);
        // the response has to be at least this big to hold the OID
        if (card_access_length < 18) {
 +              Dbprintf("epa: Too small!");
                EPA_PACE_Collect_Nonce_Abort(2, card_access_length);
                return;
        }
  
 +      Dbprintf("epa: foo!");
 +      
        // this will hold the PACE info of the card
        pace_version_info_t pace_version_info;
        // search for the PACE OID
                return;
        }
        
 +      Dbprintf("epa: bar!");
 +      
        // initiate the PACE protocol
        // use the CAN for the password since that doesn't change
        func_return = EPA_PACE_MSE_Set_AT(pace_version_info, 2);
        // save received information
  //    ack->arg[1] = func_return;
  //    memcpy(ack->d.asBytes, nonce, func_return);
 -  cmd_send(CMD_ACK,0,func_return,0,nonce,func_return);
 +      cmd_send(CMD_ACK,0,func_return,0,nonce,func_return);
  }
  
  //-----------------------------------------------------------------------------
@@@ -432,9 -425,9 +432,11 @@@ int EPA_Setup(
  
        // power up the field
        iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
 -
 +      
 +      iso14a_set_timeout(10500);
 +      
+       iso14a_set_timeout(10500);
+       
        // select the card
        return_code = iso14443a_select_card(uid, &card_select_info, NULL);
        if (return_code != 1) {
diff --combined armsrc/hitag2.c
index d25fe4c8293cf7c4b71d4a2536ffe82c855c8757,4a2d9d9d46ea47f13c88d4f67f7e3af89aa99db1..f9005c7176bcfe412526dca28e5a9bc221b89598
  // (c) 2012 Roel Verdult
  //-----------------------------------------------------------------------------
  
 -#include "proxmark3.h"
 +#include "../include/proxmark3.h"
  #include "apps.h"
  #include "util.h"
 -#include "hitag2.h"
 +#include "../include/hitag2.h"
  #include "string.h"
  
  static bool bQuiet;
  
- bool bCrypto;
- bool bAuthenticating;
- bool bPwd;
- bool bSuccessful;
static bool bCrypto;
static bool bAuthenticating;
static bool bPwd;
static bool bSuccessful;
  
- int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int bReader)
+ static int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int bReader)
  {
+   static uint16_t traceLen = 0;
+   uint8_t *trace = BigBuf_get_addr();
    // Return when trace is full
-   if (traceLen >= TRACE_SIZE) return FALSE;
+   if (traceLen + sizeof(rsamples) + sizeof(dwParity) + sizeof(iBits) + nbytes(iBits) > BigBuf_max_traceLen()) return FALSE;
    
    // Trace the random, i'm curious
    rsamples += iSamples;
@@@ -85,21 -89,17 +89,17 @@@ static struct hitag2_tag tag = 
      },
  };
  
- //#define TRACE_LENGTH 3000
- //uint8_t *trace = (uint8_t *) BigBuf;
- //int traceLen = 0;
- //int rsamples = 0;
+ // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces. 
+ // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
+ #define AUTH_TABLE_LENGTH 2744
+ static byte_t* auth_table;
+ static size_t auth_table_pos = 0;
+ static size_t auth_table_len = AUTH_TABLE_LENGTH;
  
- #define AUTH_TABLE_OFFSET FREE_BUFFER_OFFSET
- #define AUTH_TABLE_LENGTH FREE_BUFFER_SIZE
- byte_t* auth_table = (byte_t *)BigBuf+AUTH_TABLE_OFFSET;
- size_t auth_table_pos = 0;
- size_t auth_table_len = AUTH_TABLE_LENGTH;
- byte_t password[4];
- byte_t NrAr[8];
- byte_t key[8];
- uint64_t cipher_state;
+ static byte_t password[4];
+ static byte_t NrAr[8];
+ static byte_t key[8];
+ static uint64_t cipher_state;
  
  /* Following is a modified version of cryptolib.com/ciphers/hitag2/ */
  // Software optimized 48-bit Philips/NXP Mifare Hitag2 PCF7936/46/47/52 stream cipher algorithm by I.C. Wiener 2006-2007.
@@@ -177,14 -177,14 +177,14 @@@ static u32 _hitag2_byte (u64 * x
        return c;
  }
  
- int hitag2_reset(void)
static int hitag2_reset(void)
  {
        tag.state = TAG_STATE_RESET;
        tag.crypto_active = 0;
        return 0;
  }
  
- int hitag2_init(void)
static int hitag2_init(void)
  {
  //    memcpy(&tag, &resetdata, sizeof(tag));
        hitag2_reset();
@@@ -300,7 -300,8 +300,8 @@@ static void hitag_send_frame(const byte
        LOW(GPIO_SSC_DOUT);
  }
  
- void hitag2_handle_reader_command(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen)
+ static void hitag2_handle_reader_command(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen)
  {
        byte_t rx_air[HITAG_FRAME_LEN];
        
@@@ -457,6 -458,7 +458,7 @@@ static void hitag_reader_send_bit(int b
        LED_A_OFF();
  }
  
  static void hitag_reader_send_frame(const byte_t* frame, size_t frame_len)
  {
        // Send the content of the frame
  
  size_t blocknr;
  
- bool hitag2_password(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
static bool hitag2_password(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
        // Reset the transmission frame length
        *txlen = 0;
        
        return true;
  }
  
- bool hitag2_crypto(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
static bool hitag2_crypto(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
        // Reset the transmission frame length
        *txlen = 0;
        
  }
  
  
- bool hitag2_authenticate(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
static bool hitag2_authenticate(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
        // Reset the transmission frame length 
        *txlen = 0;
        
        return true;
  }
  
- bool hitag2_test_auth_attempts(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
+ static bool hitag2_test_auth_attempts(byte_t* rx, const size_t rxlen, byte_t* tx, size_t* txlen) {
        // Reset the transmission frame length 
        *txlen = 0;
        
                        if (bCrypto) {
                                Dbprintf("auth: %02x%02x%02x%02x%02x%02x%02x%02x Failed, removed entry!",NrAr[0],NrAr[1],NrAr[2],NrAr[3],NrAr[4],NrAr[5],NrAr[6],NrAr[7]);
  
-         // Removing failed entry from authentiations table
-         memcpy(auth_table+auth_table_pos,auth_table+auth_table_pos+8,8);
-         auth_table_len -= 8;
+                               // Removing failed entry from authentiations table
+                               memcpy(auth_table+auth_table_pos,auth_table+auth_table_pos+8,8);
+                               auth_table_len -= 8;
  
-         // Return if we reached the end of the authentiactions table
+                               // Return if we reached the end of the authentications table
                                bCrypto = false;
                                if (auth_table_pos == auth_table_len) {
                                        return false;
                                }
-         
-         // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
+                               // Copy the next authentication attempt in row (at the same position, b/c we removed last failed entry)
                                memcpy(NrAr,auth_table+auth_table_pos,8);
                        }
                        *txlen = 5;
        return true;
  }
  
  void SnoopHitag(uint32_t type) {
        int frame_count;
        int response;
        byte_t rx[HITAG_FRAME_LEN];
        size_t rxlen=0;
        
-       // Clean up trace and prepare it for storing frames
-       iso14a_set_tracing(TRUE);
-       iso14a_clear_trace();
        auth_table_len = 0;
        auth_table_pos = 0;
+       BigBuf_free();
+     auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
        memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
+       // Clean up trace and prepare it for storing frames
+       iso14a_set_tracing(TRUE);
+       iso14a_clear_trace();
        
        DbpString("Starting Hitag2 snoop");
        LED_D_ON();
        AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
        AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
        
-   // Disable timer during configuration       
+       // Disable timer during configuration   
        AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
        
        // Capture mode, defaul timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
@@@ -940,13 -947,17 +947,17 @@@ void SimulateHitagTag(bool tag_mem_supp
        bool bQuitTraceFull = false;
        bQuiet = false;
        
-       // Clean up trace and prepare it for storing frames
-   iso14a_set_tracing(TRUE);
-   iso14a_clear_trace();
        auth_table_len = 0;
        auth_table_pos = 0;
+     byte_t* auth_table;
+       BigBuf_free();
+     auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH);
        memset(auth_table, 0x00, AUTH_TABLE_LENGTH);
  
+       // Clean up trace and prepare it for storing frames
+       iso14a_set_tracing(TRUE);
+       iso14a_clear_trace();
        DbpString("Starting Hitag2 simulation");
        LED_D_ON();
        hitag2_init();
        AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
        AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
        
 -  // Disable timer during configuration       
 +    // Disable timer during configuration     
        AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
  
        // Capture mode, default timer source = MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
@@@ -1126,21 -1137,22 +1137,22 @@@ void ReaderHitag(hitag_function htf, hi
        bool bStop;
        bool bQuitTraceFull = false;
    
-   FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
-   // Reset the return status
-   bSuccessful = false;
+       FpgaDownloadAndGo(FPGA_BITSTREAM_LF);
+       // Reset the return status
+       bSuccessful = false;
    
        // Clean up trace and prepare it for storing frames
-   iso14a_set_tracing(TRUE);
-   iso14a_clear_trace();
+       iso14a_set_tracing(TRUE);
+       iso14a_clear_trace();
        DbpString("Starting Hitag reader family");
  
        // Check configuration
        switch(htf) {
                case RHT2F_PASSWORD: {
-       Dbprintf("List identifier in password mode");
+                       Dbprintf("List identifier in password mode");
                        memcpy(password,htd->pwd.password,4);
-       blocknr = 0;
+                       blocknr = 0;
                        bQuitTraceFull = false;
                        bQuiet = false;
                        bPwd = false;
                        Dbhexdump(8,NrAr,false);
                        bQuiet = false;
                        bCrypto = false;
-       bAuthenticating = false;
+                       bAuthenticating = false;
                        bQuitTraceFull = true;
                } break;
        
                        DbpString("Authenticating using key:");
                        memcpy(key,htd->crypto.key,4);    //HACK; 4 or 6??  I read both in the code.
                        Dbhexdump(6,key,false);
-       blocknr = 0;
+                       blocknr = 0;
                        bQuiet = false;
                        bCrypto = false;
-       bAuthenticating = false;
+                       bAuthenticating = false;
                        bQuitTraceFull = true;
                } break;
  
                case RHT2F_TEST_AUTH_ATTEMPTS: {
                        Dbprintf("Testing %d authentication attempts",(auth_table_len/8));
                        auth_table_pos = 0;
-                       memcpy(NrAr,auth_table,8);
+                       memcpy(NrAr, auth_table, 8);
                        bQuitTraceFull = false;
                        bQuiet = false;
                        bCrypto = false;
diff --combined armsrc/iclass.c
index aca2c91833363f7357bda1506c657e59fe31446a,1a3751182f6e9553bb944ba405fe081861e4d3c8..c0edc1e08db6156c57060a94961efcf93f8d69d6
@@@ -36,7 -36,7 +36,7 @@@
  //
  //-----------------------------------------------------------------------------
  
 -#include "proxmark3.h"
 +#include "../include/proxmark3.h"
  #include "apps.h"
  #include "util.h"
  #include "string.h"
  // Needed for CRC in emulation mode;
  // same construction as in ISO 14443;
  // different initial value (CRC_ICLASS)
 -#include "iso14443crc.h"
 -#include "iso15693tools.h"
 +#include "../common/iso14443crc.h"
 +#include "../common/iso15693tools.h"
 +//#include "iso15693tools.h"
 +
  
  static int timeout = 4096;
  
@@@ -353,7 -351,7 +353,7 @@@ static struct 
                SUB_SECOND_HALF,
                SUB_BOTH
        }               sub;
 -    uint8_t *output;
 +    uint8_t   *output;
  } Demod;
  
  static RAMFUNC int ManchesterDecoding(int v)
        else {
                modulation = bit & Demod.syncBit;
                modulation |= ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
-       
                Demod.samples += 4;
  
                if(Demod.posCount==0) {
@@@ -642,21 -640,25 +642,25 @@@ void RAMFUNC SnoopIClass(void
      // The command (reader -> tag) that we're receiving.
        // The length of a received command will in most cases be no more than 18 bytes.
        // So 32 should be enough!
-       uint8_t *readerToTagCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
+       #define ICLASS_BUFFER_SIZE 32
+       uint8_t readerToTagCmd[ICLASS_BUFFER_SIZE];
      // The response (tag -> reader) that we're receiving.
-       uint8_t *tagToReaderResponse = (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);
+       uint8_t tagToReaderResponse[ICLASS_BUFFER_SIZE];
+       
      FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
   
 -      // reset traceLen to 0
+       // free all BigBuf memory
+       BigBuf_free();
+     // The DMA buffer, used to stream samples from the FPGA
+     uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
+  
 +    // reset traceLen to 0
      iso14a_set_tracing(TRUE);
      iso14a_clear_trace();
      iso14a_set_trigger(FALSE);
  
-     // The DMA buffer, used to stream samples from the FPGA
-     int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
 -      int lastRxCounter;
 +    int lastRxCounter;
-     int8_t *upTo;
+     uint8_t *upTo;
      int smpl;
      int maxBehindBy = 0;
  
      SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
  
        uint32_t time_0 = GetCountSspClk();
+       uint32_t time_start = 0;
+       uint32_t time_stop  = 0;
  
      int div = 0;
      //int div2 = 0;
                                  (DMA_BUFFER_SIZE-1);
          if(behindBy > maxBehindBy) {
              maxBehindBy = behindBy;
-             if(behindBy > 400) {
+             if(behindBy > (9 * DMA_BUFFER_SIZE / 10)) {
                  Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
                  goto done;
              }
                smpl = decbyter;        
                if(OutOfNDecoding((smpl & 0xF0) >> 4)) {
                    rsamples = samples - Uart.samples;
+                       time_stop = (GetCountSspClk()-time_0) << 4;
                    LED_C_ON();
  
                        //if(!LogTrace(Uart.output,Uart.byteCnt, rsamples, Uart.parityBits,TRUE)) break;
                        //if(!LogTrace(NULL, 0, Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, 0, TRUE)) break;
-                       if(tracing) {
+                       if(tracing)     {
                                uint8_t parity[MAX_PARITY_SIZE];
                                GetParity(Uart.output, Uart.byteCnt, parity);
-                               LogTrace(Uart.output,Uart.byteCnt, (GetCountSspClk()-time_0) << 4, (GetCountSspClk()-time_0) << 4, parity, TRUE);
+                               LogTrace(Uart.output,Uart.byteCnt, time_start, time_stop, parity, TRUE);
                        }
  
  
                    Demod.state = DEMOD_UNSYNCD;
                    LED_B_OFF();
                    Uart.byteCnt = 0;
+               }else{
+                       time_start = (GetCountSspClk()-time_0) << 4;
                }
                decbyter = 0;
        }
        if(div > 3) {
                smpl = decbyte;
                if(ManchesterDecoding(smpl & 0x0F)) {
 -                      rsamples = samples - Demod.samples;
+                       time_stop = (GetCountSspClk()-time_0) << 4;
 +                  rsamples = samples - Demod.samples;
                    LED_B_ON();
  
-                       if(tracing) {
+                       if(tracing)     {
                                uint8_t parity[MAX_PARITY_SIZE];
                                GetParity(Demod.output, Demod.len, parity);
-                               LogTrace(Demod.output, Demod.len, (GetCountSspClk()-time_0) << 4, (GetCountSspClk()-time_0) << 4, parity, FALSE);
+                               LogTrace(Demod.output, Demod.len, time_start, time_stop, parity, FALSE);
                        }
  
                    // And ready to receive another response.
                    memset(&Demod, 0, sizeof(Demod));
                        Demod.output = tagToReaderResponse;
                    Demod.state = DEMOD_UNSYNCD;
                    LED_C_OFF();
+               }else{
+                       time_start = (GetCountSspClk()-time_0) << 4;
                }
                
                div = 0;
@@@ -852,57 -861,93 +863,93 @@@ static int GetIClassCommandFromReader(u
      }
  }
  
+ static uint8_t encode4Bits(const uint8_t b)
+ {
+       uint8_t c = b & 0xF;
+       // OTA, the least significant bits first
+       //         The columns are
+       //               1 - Bit value to send
+       //               2 - Reversed (big-endian)
+       //               3 - Encoded
+       //               4 - Hex values
+       switch(c){
+       //                          1       2         3         4
+         case 15: return 0x55; // 1111 -> 1111 -> 01010101 -> 0x55
+         case 14: return 0x95; // 1110 -> 0111 -> 10010101 -> 0x95
+         case 13: return 0x65; // 1101 -> 1011 -> 01100101 -> 0x65
+         case 12: return 0xa5; // 1100 -> 0011 -> 10100101 -> 0xa5
+         case 11: return 0x59; // 1011 -> 1101 -> 01011001 -> 0x59
+         case 10: return 0x99; // 1010 -> 0101 -> 10011001 -> 0x99
+         case 9:  return 0x69; // 1001 -> 1001 -> 01101001 -> 0x69
+         case 8:  return 0xa9; // 1000 -> 0001 -> 10101001 -> 0xa9
+         case 7:  return 0x56; // 0111 -> 1110 -> 01010110 -> 0x56
+         case 6:  return 0x96; // 0110 -> 0110 -> 10010110 -> 0x96
+         case 5:  return 0x66; // 0101 -> 1010 -> 01100110 -> 0x66
+         case 4:  return 0xa6; // 0100 -> 0010 -> 10100110 -> 0xa6
+         case 3:  return 0x5a; // 0011 -> 1100 -> 01011010 -> 0x5a
+         case 2:  return 0x9a; // 0010 -> 0100 -> 10011010 -> 0x9a
+         case 1:  return 0x6a; // 0001 -> 1000 -> 01101010 -> 0x6a
+         default: return 0xaa; // 0000 -> 0000 -> 10101010 -> 0xaa
+       }
+ }
  
  //-----------------------------------------------------------------------------
  // Prepare tag messages
  //-----------------------------------------------------------------------------
  static void CodeIClassTagAnswer(const uint8_t *cmd, int len)
  {
-       //So far a dummy implementation, not used
-       //int lastProxToAirDuration =0;
+       /*
+        * SOF comprises 3 parts;
+        * * An unmodulated time of 56.64 us
+        * * 24 pulses of 423.75 KHz (fc/32)
+        * * A logic 1, which starts with an unmodulated time of 18.88us
+        *   followed by 8 pulses of 423.75kHz (fc/32)
+        *
+        *
+        * EOF comprises 3 parts:
+        * - A logic 0 (which starts with 8 pulses of fc/32 followed by an unmodulated
+        *   time of 18.88us.
+        * - 24 pulses of fc/32
+        * - An unmodulated time of 56.64 us
+        *
+        *
+        * A logic 0 starts with 8 pulses of fc/32
+        * followed by an unmodulated time of 256/fc (~18,88us).
+        *
+        * A logic 0 starts with unmodulated time of 256/fc (~18,88us) followed by
+        * 8 pulses of fc/32 (also 18.88us)
+        *
+        * The mode FPGA_HF_SIMULATOR_MODULATE_424K_8BIT which we use to simulate tag,
+        * works like this.
+        * - A 1-bit input to the FPGA becomes 8 pulses on 423.5kHz (fc/32) (18.88us).
+        * - A 0-bit inptu to the FPGA becomes an unmodulated time of 18.88us
+        *
+        * In this mode the SOF can be written as 00011101 = 0x1D
+        * The EOF can be written as 10111000 = 0xb8
+        * A logic 1 is 01
+        * A logic 0 is 10
+        *
+        * */
        int i;
  
        ToSendReset();
  
        // Send SOF
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0xff;//Proxtoair duration starts here
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0xff;
+       ToSend[++ToSendMax] = 0x1D;
  
        for(i = 0; i < len; i++) {
-               int j;
                uint8_t b = cmd[i];
-               // Data bits
-               for(j = 0; j < 8; j++) {
-                       if(b & 1) {
-                               ToSend[++ToSendMax] = 0x00;
-                               ToSend[++ToSendMax] = 0xff;
-                       } else {
-                               ToSend[++ToSendMax] = 0xff;
-                               ToSend[++ToSendMax] = 0x00;
+               ToSend[++ToSendMax] = encode4Bits(b & 0xF); //Least significant half
+               ToSend[++ToSendMax] = encode4Bits((b >>4) & 0xF);//Most significant half
 -      }
 +                      }
-                       b >>= 1;
-               }
-       }
  
        // Send EOF
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0xff;     
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0x00;
+       ToSend[++ToSendMax] = 0xB8;
        //lastProxToAirDuration  = 8*ToSendMax - 3*8 - 3*8;//Not counting zeroes in the beginning or end
        // Convert from last byte pos to length
        ToSendMax++;
  }
@@@ -915,21 -960,13 +962,13 @@@ static void CodeIClassTagSOF(
  
        ToSendReset();
        // Send SOF
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0xff;
-       ToSend[++ToSendMax] = 0x00;
-       ToSend[++ToSendMax] = 0xff;
+       ToSend[++ToSendMax] = 0x1D;
  //    lastProxToAirDuration  = 8*ToSendMax - 3*8;//Not counting zeroes in the beginning
  
-       
        // Convert from last byte pos to length
        ToSendMax++;
  }
  int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf);
  /**
   * @brief SimulateIClass simulates an iClass card.
@@@ -965,7 -1002,7 +1004,7 @@@ void SimulateIClass(uint32_t arg0, uint
        else if(simType == 2)
        {
  
-               uint8_t mac_responses[64] = { 0 };
+               uint8_t mac_responses[USB_CMD_DATA_SIZE] = { 0 };
                Dbprintf("Going into attack mode, %d CSNS sent", numberOfCSNS);
                // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
                // in order to collect MAC's from the reader. This can later be used in an offlne-attack
                        memcpy(csn_crc, datain+(i*8), 8);
                        if(doIClassSimulation(csn_crc,1,mac_responses+i*8))
                        {
+                               cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
                                return; // Button pressed
                        }
                }
   */
  int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf)
  {
        // CSN followed by two CRC bytes
+       uint8_t response1[] = { 0x0F} ;
        uint8_t response2[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        uint8_t response3[] = { 0,0,0,0,0,0,0,0,0,0};
        memcpy(response3,csn,sizeof(response3));
        // Reader 81 anticoll. CSN
        // Tag    CSN
  
-       uint8_t *resp;
-       int respLen;
-       uint8_t* respdata = NULL;
-       int respsize = 0;
-       uint8_t sof = 0x0f;
+       uint8_t *modulated_response;
+       int modulated_response_size;
+       uint8_t* trace_data = NULL;
+       int trace_data_size = 0;
+       //uint8_t sof = 0x0f;
  
-       // Respond SOF -- takes 8 bytes
-       uint8_t *resp1 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
+       // free eventually allocated BigBuf memory
+       BigBuf_free();
+       // Respond SOF -- takes 1 bytes
+       uint8_t *resp1 = BigBuf_malloc(2);
        int resp1Len;
  
        // Anticollision CSN (rotated CSN)
-       // 176: Takes 16 bytes for SOF/EOF and 10 * 16 = 160 bytes (2 bytes/bit)
-       uint8_t *resp2 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 10);
+       // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
+       uint8_t *resp2 = BigBuf_malloc(28);
        int resp2Len;
  
        // CSN
-       // 176: Takes 16 bytes for SOF/EOF and 10 * 16 = 160 bytes (2 bytes/bit)
-       uint8_t *resp3 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 190);
+       // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
+       uint8_t *resp3 = BigBuf_malloc(30);
        int resp3Len;
  
        // e-Purse
-       // 144: Takes 16 bytes for SOF/EOF and 8 * 16 = 128 bytes (2 bytes/bit)
-       uint8_t *resp4 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 370);
+       // 18: Takes 2 bytes for SOF/EOF and 8 * 2 = 16 bytes (2 bytes/bit)
+       uint8_t *resp4 = BigBuf_malloc(20);
        int resp4Len;
  
-       // + 1720..
-       uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
+       uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
        memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
        int len;
  
        LED_A_ON();
        bool buttonPressed = false;
  
-       /** Hack  for testing
-       memcpy(reader_mac_buf,csn,8);
-       exitLoop = true;
-       end hack **/
        while(!exitLoop) {
  
                LED_B_OFF();
                // Okay, look at the command now.
                if(receivedCmd[0] == 0x0a ) {
                        // Reader in anticollission phase
-                       resp = resp1; respLen = resp1Len; //order = 1;
-                       respdata = &sof;
-                       respsize = sizeof(sof);
+                       modulated_response = resp1; modulated_response_size = resp1Len; //order = 1;
+                       trace_data = response1;
+                       trace_data_size = sizeof(response1);
                } else if(receivedCmd[0] == 0x0c) {
                        // Reader asks for anticollission CSN
-                       resp = resp2; respLen = resp2Len; //order = 2;
-                       respdata = response2;
-                       respsize = sizeof(response2);
+                       modulated_response = resp2; modulated_response_size = resp2Len; //order = 2;
+                       trace_data = response2;
+                       trace_data_size = sizeof(response2);
                        //DbpString("Reader requests anticollission CSN:");
                } else if(receivedCmd[0] == 0x81) {
                        // Reader selects anticollission CSN.
                        // Tag sends the corresponding real CSN
-                       resp = resp3; respLen = resp3Len; //order = 3;
-                       respdata = response3;
-                       respsize = sizeof(response3);
+                       modulated_response = resp3; modulated_response_size = resp3Len; //order = 3;
+                       trace_data = response3;
+                       trace_data_size = sizeof(response3);
                        //DbpString("Reader selects anticollission CSN:");
                } else if(receivedCmd[0] == 0x88) {
                        // Read e-purse (88 02)
-                       resp = resp4; respLen = resp4Len; //order = 4;
-                       respdata = response4;
-                       respsize = sizeof(response4);
+                       modulated_response = resp4; modulated_response_size = resp4Len; //order = 4;
+                       trace_data = response4;
+                       trace_data_size = sizeof(response4);
                        LED_B_ON();
                } else if(receivedCmd[0] == 0x05) {
                        // Reader random and reader MAC!!!
                        // Do not respond
              // We do not know what to answer, so lets keep quiet
-                       resp = resp1; respLen = 0; //order = 5;
-                       respdata = NULL;
-                       respsize = 0;
+                       modulated_response = resp1; modulated_response_size = 0; //order = 5;
+                       trace_data = NULL;
+                       trace_data_size = 0;
                        if (breakAfterMacReceived){
                                // dbprintf:ing ...
                                Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x"
                        }
                } else if(receivedCmd[0] == 0x00 && len == 1) {
                        // Reader ends the session
-                       resp = resp1; respLen = 0; //order = 0;
-                       respdata = NULL;
-                       respsize = 0;
+                       modulated_response = resp1; modulated_response_size = 0; //order = 0;
+                       trace_data = NULL;
+                       trace_data_size = 0;
                } else {
                        //#db# Unknown command received from reader (len=5): 26 1 0 f6 a 44 44 44 44
                        // Never seen this command before
                        receivedCmd[3], receivedCmd[4], receivedCmd[5],
                        receivedCmd[6], receivedCmd[7], receivedCmd[8]);
                        // Do not respond
-                       resp = resp1; respLen = 0; //order = 0;
-                       respdata = NULL;
-                       respsize = 0;
+                       modulated_response = resp1; modulated_response_size = 0; //order = 0;
+                       trace_data = NULL;
+                       trace_data_size = 0;
                }
  
                if(cmdsRecvd >  100) {
                else {
                        cmdsRecvd++;
                }
-               if(respLen > 0) {
-                       SendIClassAnswer(resp, respLen, 21);
+               /**
+               A legit tag has about 380us delay between reader EOT and tag SOF.
+               **/
+               if(modulated_response_size > 0) {
+                       SendIClassAnswer(modulated_response, modulated_response_size, 1);
                        t2r_time = GetCountSspClk();
                }
  
                        GetParity(receivedCmd, len, parity);
                        LogTrace(receivedCmd,len, (r2t_time-time_0)<< 4, (r2t_time-time_0) << 4, parity, TRUE);
  
-                       if (respdata != NULL) {
-                               GetParity(respdata, respsize, parity);
-                               LogTrace(respdata, respsize, (t2r_time-time_0) << 4, (t2r_time-time_0) << 4, parity, FALSE);
+                       if (trace_data != NULL) {
+                               GetParity(trace_data, trace_data_size, parity);
+                               LogTrace(trace_data, trace_data_size, (t2r_time-time_0) << 4, (t2r_time-time_0) << 4, parity, FALSE);
                        }
                        if(!tracing) {
                                DbpString("Trace full");
        //Dbprintf("%x", cmdsRecvd);
        LED_A_OFF();
        LED_B_OFF();
+       LED_C_OFF();
        if(buttonPressed)
        {
                DbpString("Button pressed");
@@@ -1222,7 -1262,8 +1264,8 @@@ static int SendIClassAnswer(uint8_t *re
        int i = 0, d=0;//, u = 0, d = 0;
        uint8_t b = 0;
  
-       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K);
+       //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K);
+       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K_8BIT);
  
        AT91C_BASE_SSC->SSC_THR = 0x00;
        FpgaSetupSsc();
                        AT91C_BASE_SSC->SSC_THR = b;
                }
  
-               if (i > respLen +4) break;
+ //            if (i > respLen +4) break;
+               if (i > respLen +1) break;
        }
  
        return 0;
@@@ -1267,18 -1309,18 +1311,18 @@@ static void TransmitIClassCommand(cons
     if (wait)
     {
       if(*wait < 10) *wait = 10;
+      
 -     for(c = 0; c < *wait;) {
 -       if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
 -         AT91C_BASE_SSC->SSC_THR = 0x00;              // For exact timing!
 -         c++;
 -       }
 -       if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
 -         volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
 -         (void)r;
 -       }
 -       WDT_HIT();
 -     }
 +  for(c = 0; c < *wait;) {
 +    if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
 +      AT91C_BASE_SSC->SSC_THR = 0x00;         // For exact timing!
 +      c++;
 +    }
 +    if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
 +      volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
 +      (void)r;
 +    }
 +    WDT_HIT();
 +  }
  
     }
  
@@@ -1361,19 -1403,19 +1405,19 @@@ void CodeIClassCommand(const uint8_t * 
  
  void ReaderTransmitIClass(uint8_t* frame, int len)
  {
 -      int wait = 0;
 -      int samples = 0;
 +  int wait = 0;
 +  int samples = 0;
  
 -      // This is tied to other size changes
 -      CodeIClassCommand(frame,len);
 +  // This is tied to other size changes
 +  CodeIClassCommand(frame,len);
  
 -      // Select the card
 -      TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
 -      if(trigger)
 -              LED_A_ON();
 +  // Select the card
 +  TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
 +  if(trigger)
 +      LED_A_ON();
  
 -      // Store reader command in buffer
 +  // Store reader command in buffer
-   if (tracing) {
+       if (tracing) {
                uint8_t par[MAX_PARITY_SIZE];
                GetParity(frame, len, par);
                LogTrace(frame, len, rsamples, rsamples, par, TRUE);
@@@ -1408,7 -1450,7 +1452,7 @@@ static int GetIClassAnswer(uint8_t *rec
        for(;;) {
                WDT_HIT();
  
 -              if(BUTTON_PRESS()) return FALSE;
 +          if(BUTTON_PRESS()) return FALSE;
  
                if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
                        AT91C_BASE_SSC->SSC_THR = 0x00;  // To make use of exact timing of next command from reader!!
@@@ -1433,10 -1475,10 +1477,10 @@@ int ReaderReceiveIClass(uint8_t* receiv
    int samples = 0;
    if (!GetIClassAnswer(receivedAnswer,160,&samples,0)) return FALSE;
    rsamples += samples;
-   if (tracing){
-               uint8_t parity[MAX_PARITY_SIZE];
-               GetParity(receivedAnswer, Demod.len, parity);
-               LogTrace(receivedAnswer,Demod.len,rsamples,rsamples,parity,FALSE);
+   if (tracing) {
+       uint8_t parity[MAX_PARITY_SIZE];
+       GetParity(receivedAnswer, Demod.len, parity);
+       LogTrace(receivedAnswer,Demod.len,rsamples,rsamples,parity,FALSE);
    }
    if(samples == 0) return FALSE;
    return Demod.len;
@@@ -1492,7 -1534,7 +1536,7 @@@ uint8_t handshakeIclassTag(uint8_t *car
        static uint8_t identify[]    = { 0x0c };
        static uint8_t select[]      = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        static uint8_t readcheck_cc[]= { 0x88, 0x02 };
-       uint8_t *resp = (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);
+       uint8_t resp[ICLASS_BUFFER_SIZE];
  
        uint8_t read_status = 0;
  
@@@ -1539,7 -1581,7 +1583,7 @@@ void ReaderIClass(uint8_t arg0) 
  
      uint8_t card_data[24]={0};
      uint8_t last_csn[8]={0};
+       
      int read_status= 0;
      bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE;
        bool get_cc = arg0 & FLAG_ICLASS_READER_GET_CC;
      while(!BUTTON_PRESS())
      {
  
-               if(traceLen > TRACE_SIZE) {
+               if(traceLen > BigBuf_max_traceLen()) {
                        DbpString("Trace full");
                        break;
                }
-         WDT_HIT();
+               WDT_HIT();
  
                read_status = handshakeIclassTag(card_data);
  
                if(read_status == 1) datasize = 8;
                if(read_status == 2) datasize = 16;
  
 -              LED_B_ON();
 -              //Send back to client, but don't bother if we already sent this
 -              if(memcmp(last_csn, card_data, 8) != 0)
 +                    LED_B_ON();
 +                    //Send back to client, but don't bother if we already sent this
 +                    if(memcmp(last_csn, card_data, 8) != 0)
                {
  
                        if(!get_cc || (get_cc && read_status == 2))
                        {
 -                              cmd_send(CMD_ACK,read_status,0,0,card_data,datasize);
 +                        cmd_send(CMD_ACK,read_status,0,0,card_data,datasize);
                                if(abort_after_read) {
                                        LED_A_OFF();
                                        return;
                                }
 -                              //Save that we already sent this....
 -                              memcpy(last_csn, card_data, 8);
 +                    //Save that we already sent this....
 +                        memcpy(last_csn, card_data, 8);
                        }
                        //If 'get_cc' was specified and we didn't get a CC, we'll just keep trying...
                }
-                     LED_B_OFF();
+               LED_B_OFF();
      }
      cmd_send(CMD_ACK,0,0,0,card_data, 0);
      LED_A_OFF();
@@@ -1613,16 -1655,16 +1657,16 @@@ void ReaderIClass_Replay(uint8_t arg0, 
          int keyaccess;
        } memory;
        
-       uint8_t* resp = (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);
+       uint8_t resp[ICLASS_BUFFER_SIZE];
+       
      setupIclassReader();
  
  
        while(!BUTTON_PRESS()) {
        
                WDT_HIT();
-       
-               if(traceLen > TRACE_SIZE) {
+               if(traceLen > BigBuf_max_traceLen()) {
                        DbpString("Trace full");
                        break;
                }
                uint8_t read_status = handshakeIclassTag(card_data);
                if(read_status < 2) continue;
  
 -              //for now replay captured auth (as cc not updated)
 -              memcpy(check+5,MAC,4);
 +                              //for now replay captured auth (as cc not updated)
 +                              memcpy(check+5,MAC,4);
  
                if(sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5))
                {
 -                      Dbprintf("Error: Authentication Fail!");
 +                                Dbprintf("Error: Authentication Fail!");
                        continue;
 -              }
 +                              }
  
                //first get configuration block (block 1)
                crc = block_crc_LUT[1];
 -              read[1]=1;
 -              read[2] = crc >> 8;
 -              read[3] = crc & 0xff;
 +                              read[1]=1;
 +                              read[2] = crc >> 8;
 +                              read[3] = crc & 0xff;
  
                if(sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10))
                {
                        continue;
                }
  
 -              mem=resp[5];
 -              memory.k16= (mem & 0x80);
 -              memory.book= (mem & 0x20);
 -              memory.k2= (mem & 0x8);
 -              memory.lockauth= (mem & 0x2);
 -              memory.keyaccess= (mem & 0x1);
 +                                       mem=resp[5];
 +                                       memory.k16= (mem & 0x80);
 +                                       memory.book= (mem & 0x20);
 +                                       memory.k2= (mem & 0x8);
 +                                       memory.lockauth= (mem & 0x2);
 +                                       memory.keyaccess= (mem & 0x1);
  
                cardsize = memory.k16 ? 255 : 32;
                WDT_HIT();
                memset(card_data,0x0,USB_CMD_DATA_SIZE);
                uint8_t failedRead =0;
                uint8_t stored_data_length =0;
 -              //then loop around remaining blocks
 +                              //then loop around remaining blocks
                for(int block=0; block < cardsize; block++){
  
                        read[1]= block;
                        crc = block_crc_LUT[block];
 -                      read[2] = crc >> 8;
 -                      read[3] = crc & 0xff;
 +                                  read[2] = crc >> 8;
 +                                  read[3] = crc & 0xff;
  
                        if(!sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10))
                        {
 -                              Dbprintf("     %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
 +                                       Dbprintf("     %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
                                                 block, resp[0], resp[1], resp[2],
 -                                              resp[3], resp[4], resp[5],
 -                                              resp[6], resp[7]);
 +                                        resp[3], resp[4], resp[5],
 +                                        resp[6], resp[7]);
  
                                //Fill up the buffer
                                memcpy(card_data+stored_data_length,resp,8);
@@@ -1741,7 -1783,7 +1785,7 @@@ void IClass_iso14443A_write(uint8_t arg
        uint8_t* resp = (((uint8_t *)BigBuf) + 3560);
  
        // Reset trace buffer
 -    memset(trace, 0x44, RECV_CMD_OFFSET);
 +      memset(trace, 0x44, RECV_CMD_OFFSET);
        traceLen = 0;
  
        // Setup SSC
diff --combined armsrc/iso14443.c
index 775c583aaea4505331324e30262bb8987364aafa,6a2e4d6a41b90e3a11d4392b42b4a15ed43211b0..48a32b1024db8ef59e024421c938715a0b4be246
  // supported.
  //-----------------------------------------------------------------------------
  
 -#include "proxmark3.h"
 +#include "../include/proxmark3.h"
  #include "apps.h"
  #include "util.h"
  #include "string.h"
  
 -#include "iso14443crc.h"
 +#include "../common/iso14443crc.h"
  
  //static void GetSamplesFor14443(int weTx, int n);
  
@@@ -339,10 -339,10 +339,10 @@@ void SimulateIso14443Tag(void
      uint8_t *resp;
      int respLen;
  
-     uint8_t *resp1 = (((uint8_t *)BigBuf) + 800);
+     uint8_t *resp1 = BigBuf_get_addr() + 800;
      int resp1Len;
  
-     uint8_t *receivedCmd = (uint8_t *)BigBuf;
+     uint8_t *receivedCmd = BigBuf_get_addr();
      int len;
  
      int i;
@@@ -629,31 -629,32 +629,32 @@@ static void GetSamplesFor14443Demod(in
      int gotFrame = FALSE;
  
  //#   define DMA_BUFFER_SIZE 8
-     int8_t *dmaBuf;
+     uint8_t *dmaBuf;
  
      int lastRxCounter;
-     int8_t *upTo;
+     uint8_t *upTo;
  
      int ci, cq;
  
      int samples = 0;
  
      // Clear out the state of the "UART" that receives from the tag.
+       uint8_t *BigBuf = BigBuf_get_addr();
      memset(BigBuf, 0x00, 400);
-     Demod.output = (uint8_t *)BigBuf;
+     Demod.output = BigBuf;
      Demod.len = 0;
      Demod.state = DEMOD_UNSYNCD;
  
      // And the UART that receives from the reader
-     Uart.output = (((uint8_t *)BigBuf) + 1024);
+     Uart.output = BigBuf + 1024;
      Uart.byteCntMax = 100;
      Uart.state = STATE_UNSYNCD;
  
      // Setup for the DMA.
-     dmaBuf = (int8_t *)(BigBuf + 32);
+     dmaBuf = BigBuf + 32;
      upTo = dmaBuf;
      lastRxCounter = DEMOD_DMA_BUFFER_SIZE;
-     FpgaSetupSscDma((uint8_t *)dmaBuf, DEMOD_DMA_BUFFER_SIZE);
+     FpgaSetupSscDma(dmaBuf, DEMOD_DMA_BUFFER_SIZE);
  
      // Signal field is ON with the appropriate LED:
      if (weTx) LED_D_ON(); else LED_D_OFF();
@@@ -1012,20 -1013,21 +1013,21 @@@ void RAMFUNC SnoopIso14443(void
      int triggered = TRUE;
  
      FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
+       BigBuf_free();
      // The command (reader -> tag) that we're working on receiving.
-     uint8_t *receivedCmd = (uint8_t *)(BigBuf) + DEMOD_TRACE_SIZE;
+     uint8_t *receivedCmd = BigBuf_malloc(READER_TAG_BUFFER_SIZE);
      // The response (tag -> reader) that we're working on receiving.
-     uint8_t *receivedResponse = (uint8_t *)(BigBuf) + DEMOD_TRACE_SIZE + READER_TAG_BUFFER_SIZE;
+     uint8_t *receivedResponse = BigBuf_malloc(TAG_READER_BUFFER_SIZE);
  
      // As we receive stuff, we copy it from receivedCmd or receivedResponse
      // into trace, along with its length and other annotations.
-     uint8_t *trace = (uint8_t *)BigBuf;
-     int traceLen = 0;
+     uint8_t *trace = BigBuf_get_addr();
+     traceLen = 0;
  
      // The DMA buffer, used to stream samples from the FPGA.
-     int8_t *dmaBuf = (int8_t *)(BigBuf) + DEMOD_TRACE_SIZE + READER_TAG_BUFFER_SIZE + TAG_READER_BUFFER_SIZE;
+     uint8_t *dmaBuf = BigBuf_malloc(DEMOD_DMA_BUFFER_SIZE);
      int lastRxCounter;
-     int8_t *upTo;
+     uint8_t *upTo;
      int ci, cq;
      int maxBehindBy = 0;
  
      int samples = 0;
  
      // Initialize the trace buffer
-     memset(trace, 0x44, DEMOD_TRACE_SIZE);
+     memset(trace, 0x44, BigBuf_max_traceLen());
  
      // Set up the demodulator for tag -> reader responses.
      Demod.output = receivedResponse;
  
      // Print some debug information about the buffer sizes
      Dbprintf("Snooping buffers initialized:");
-     Dbprintf("  Trace: %i bytes", DEMOD_TRACE_SIZE);
+     Dbprintf("  Trace: %i bytes", BigBuf_max_traceLen());
      Dbprintf("  Reader -> tag: %i bytes", READER_TAG_BUFFER_SIZE);
      Dbprintf("  tag -> Reader: %i bytes", TAG_READER_BUFFER_SIZE);
      Dbprintf("  DMA: %i bytes", DEMOD_DMA_BUFFER_SIZE);
                                  (DEMOD_DMA_BUFFER_SIZE-1);
          if(behindBy > maxBehindBy) {
              maxBehindBy = behindBy;
-             if(behindBy > (DEMOD_DMA_BUFFER_SIZE-2)) { // TODO: understand whether we can increase/decrease as we want or not?
+             if(behindBy > (9*DEMOD_DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not?
                  Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
                  goto done;
              }
              trace[traceLen++] = Demod.len;
              memcpy(trace+traceLen, receivedResponse, Demod.len);
              traceLen += Demod.len;
-             if(traceLen > DEMOD_TRACE_SIZE) {
+             if(traceLen > BigBuf_max_traceLen()) {
                                DbpString("Reached trace limit");
                                goto done;
                        }
@@@ -1173,9 -1175,9 +1175,9 @@@ done
        LED_A_OFF();
        LED_B_OFF();
        LED_C_OFF();
-   AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
+       AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
        DbpString("Snoop statistics:");
-   Dbprintf("  Max behind by: %i", maxBehindBy);
+       Dbprintf("  Max behind by: %i", maxBehindBy);
        Dbprintf("  Uart State: %x", Uart.state);
        Dbprintf("  Uart ByteCnt: %i", Uart.byteCnt);
        Dbprintf("  Uart ByteCntMax: %i", Uart.byteCntMax);
diff --combined armsrc/iso14443a.h
index 15e2a2f0259f27aa90b2b3804d40133ae8b41203,c595d5e128da9e085e40bec6dbc9b2b0ccba1d74..771a6f59513a3993f7f09e36b73f897d2238ed9e
@@@ -12,7 -12,7 +12,7 @@@
  
  #ifndef __ISO14443A_H
  #define __ISO14443A_H
 -#include "common.h"
 +#include "../include/common.h"
  #include "mifaresniff.h"
  
  typedef struct {
@@@ -28,8 -28,8 +28,8 @@@
        uint16_t bitCount;
        uint16_t collisionPos;
        uint16_t syncBit;
-       uint8_t parityBits;
-       uint8_t parityLen;
+       uint8_t  parityBits;
+       uint8_t  parityLen;
        uint16_t shiftReg;
        uint16_t samples;
        uint16_t len;
@@@ -61,8 -61,8 +61,8 @@@ typedef struct 
        uint16_t byteCntMax;
        uint16_t posCnt;
        uint16_t syncBit;
-       uint8_t parityBits;
-       uint8_t parityLen;
+       uint8_t  parityBits;
+       uint8_t  parityLen;
        uint16_t highCnt;
        uint16_t twoBits;
        uint32_t startTime, endTime;
diff --combined armsrc/legicrf.c
index 0e63ef5e4b49d0636fbab5b8d2c2866e2ddcdda6,074a0f7896333bc5ece3020bb63aaa989029eecc..d11436ec72c21905bf89c19764012b3148e80536
@@@ -8,14 -8,14 +8,14 @@@
  // LEGIC RF simulation code
  //-----------------------------------------------------------------------------
  
 -#include "proxmark3.h"
 +#include "../include/proxmark3.h"
  #include "apps.h"
  #include "util.h"
  #include "string.h"
  
  #include "legicrf.h"
 -#include "legic_prng.h"
 -#include "crc.h"
 +#include "../include/legic_prng.h"
 +#include "../common/crc.h"
  
  static struct legic_frame {
        int bits;
@@@ -98,13 -98,14 +98,14 @@@ static uint32_t get_key_stream(int skip
    }
  
    /* Write Time Data into LOG */
+   uint8_t *BigBuf = BigBuf_get_addr();
    if(count == 6) { i = -1; } else { i = legic_read_count; }
-   ((uint8_t*)BigBuf)[OFFSET_LOG+128+i] = legic_prng_count();
-   ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4]   = (legic_prng_bc >> 0) & 0xff;
-   ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
-   ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
-   ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
-   ((uint8_t*)BigBuf)[OFFSET_LOG+384+i] = count;
+   BigBuf[OFFSET_LOG+128+i] = legic_prng_count();
+   BigBuf[OFFSET_LOG+256+i*4]   = (legic_prng_bc >> 0) & 0xff;
+   BigBuf[OFFSET_LOG+256+i*4+1] = (legic_prng_bc >> 8) & 0xff;
+   BigBuf[OFFSET_LOG+256+i*4+2] = (legic_prng_bc >>16) & 0xff;
+   BigBuf[OFFSET_LOG+256+i*4+3] = (legic_prng_bc >>24) & 0xff;
+   BigBuf[OFFSET_LOG+384+i] = count;
  
    /* Generate KeyStream */
    for(i=0; i<count; i++) {
@@@ -426,6 -427,7 +427,7 @@@ int LegicRfReader(int offset, int bytes
  
        LegicCommonInit();
  
+       uint8_t *BigBuf = BigBuf_get_addr();
        memset(BigBuf, 0, 1024);
  
        DbpString("setting up legic card");
                        LED_C_OFF();
                return -1;
                }
-               ((uint8_t*)BigBuf)[byte_index] = r;
+               BigBuf[byte_index] = r;
          WDT_HIT();
                byte_index++;
                if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
  
  void LegicRfWriter(int bytes, int offset) {
        int byte_index=0, addr_sz=0;
-       
+       uint8_t *BigBuf = BigBuf_get_addr();
        LegicCommonInit();
        
        DbpString("setting up legic card");
        perform_setup_phase_rwd(SESSION_IV);
      legic_prng_forward(2);
        while(byte_index < bytes) {
-               int r = legic_write_byte(((uint8_t*)BigBuf)[byte_index+offset], byte_index+offset, addr_sz);
+               int r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz);
                if((r != 0) || BUTTON_PRESS()) {
                        Dbprintf("operation aborted @ 0x%03.3x", byte_index);
                        switch_off_tag_rwd();
@@@ -534,6 -537,8 +537,8 @@@ int timestamp
  /* Handle (whether to respond) a frame in tag mode */
  static void frame_handle_tag(struct legic_frame const * const f)
  {
+       uint8_t *BigBuf = BigBuf_get_addr();
     /* First Part of Handshake (IV) */
     if(f->bits == 7) {
       if(f->data == SESSION_IV) {
        if(legic_state == STATE_CON) {
           int key   = get_key_stream(-1, 11); //legic_phase_drift, 11);
           int addr  = f->data ^ key; addr = addr >> 1;
-          int data = ((uint8_t*)BigBuf)[addr];
+          int data = BigBuf[addr];
           int hash = LegicCRC(addr, data, 11) << 8;
-          ((uint8_t*)BigBuf)[OFFSET_LOG+legic_read_count] = (uint8_t)addr;
+          BigBuf[OFFSET_LOG+legic_read_count] = (uint8_t)addr;
           legic_read_count++;
  
           //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
        int i;
        Dbprintf("IV: %03.3x", legic_prng_iv);
        for(i = 0; i<legic_read_count; i++) {
-          Dbprintf("Read Nb: %u, Addr: %u", i, ((uint8_t*)BigBuf)[OFFSET_LOG+i]);
+          Dbprintf("Read Nb: %u, Addr: %u", i, BigBuf[OFFSET_LOG+i]);
        }
  
        for(i = -1; i<legic_read_count; i++) {
           uint32_t t;
-          t  = ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4];
-          t |= ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4+1] << 8;
-          t |= ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4+2] <<16;
-          t |= ((uint8_t*)BigBuf)[OFFSET_LOG+256+i*4+3] <<24;
+          t  = BigBuf[OFFSET_LOG+256+i*4];
+          t |= BigBuf[OFFSET_LOG+256+i*4+1] << 8;
+          t |= BigBuf[OFFSET_LOG+256+i*4+2] <<16;
+          t |= BigBuf[OFFSET_LOG+256+i*4+3] <<24;
  
           Dbprintf("Cycles: %u, Frame Length: %u, Time: %u", 
-             ((uint8_t*)BigBuf)[OFFSET_LOG+128+i],
-             ((uint8_t*)BigBuf)[OFFSET_LOG+384+i],
+             BigBuf[OFFSET_LOG+128+i],
+             BigBuf[OFFSET_LOG+384+i],
              t);
        }
     }
diff --combined armsrc/mifarecmd.c
index 7a33afbba343a545d19bcebf98cea8dac44d6bf8,4279e63f2295e0f7e9e03e3cb22453bf1646f0c7..50a5634dc2d694db6f0a64ae1093bb750f020b10
@@@ -16,8 -16,8 +16,8 @@@
  #include "mifarecmd.h"\r
  #include "apps.h"\r
  #include "util.h"\r
- #include "desfire.h"\r
- #include "../common/crc.h"\r
\r
+ #include "crc.h"\r
  \r
  //-----------------------------------------------------------------------------\r
  // Select, Authenticate, Read a MIFARE tag. \r
@@@ -76,7 -76,7 +76,7 @@@ void MifareReadBlock(uint8_t arg0, uint
        //  ----------------------------- crypto1 destroy\r
        crypto1_destroy(pcs);\r
        \r
-       if (MF_DBGLEVEL >= 2) DbpString("READ BLOCK FINISHED");\r
+       if (MF_DBGLEVEL >= 2)   DbpString("READ BLOCK FINISHED");\r
  \r
        LED_B_ON();\r
        cmd_send(CMD_ACK,isOK,0,0,dataoutbuf,16);\r
@@@ -104,14 -104,14 +104,14 @@@ void MifareUC_Auth1(uint8_t arg0, uint8
        if(!iso14443a_select_card(uid, NULL, &cuid)) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
                        Dbprintf("Can't select card");\r
-               OnError(0);\r
+               //OnError(0);\r
                return;\r
        };\r
        \r
        if(mifare_ultra_auth1(cuid, dataoutbuf)){\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)        \r
                        Dbprintf("Authentication part1: Fail.");\r
-               OnError(1);\r
+               //OnError(1);\r
                return;\r
        }\r
  \r
@@@ -138,7 -138,7 +138,7 @@@ void MifareUC_Auth2(uint32_t arg0, uint
        if(mifare_ultra_auth2(cuid, key, dataoutbuf)){\r
            if (MF_DBGLEVEL >= MF_DBG_ERROR) \r
                        Dbprintf("Authentication part2: Fail...");\r
-               OnError(1);\r
+               //OnError(1);\r
                return;                 \r
        }\r
        \r
@@@ -161,30 -161,30 +161,30 @@@ void MifareUReadBlock(uint8_t arg0,uint
        LED_A_ON();\r
        LED_B_OFF();\r
        LED_C_OFF();\r
\r
+     \r
        iso14a_clear_trace();\r
        iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);\r
      \r
        int len = iso14443a_select_card(uid, NULL, &cuid);\r
        if(!len) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)        Dbprintf("Can't select card");\r
-               OnError(1);\r
+               //OnError(1);\r
                return;\r
-       };\r
-       \r
+               };\r
+         \r
        len = mifare_ultra_readblock(cuid, blockNo, dataout);\r
        if(len) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)        Dbprintf("Read block error");\r
-               OnError(2);\r
+               //OnError(2);\r
                return;\r
-       };\r
-       \r
+               };\r
+         \r
        len = mifare_ultra_halt(cuid);\r
        if(len) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)        Dbprintf("Halt error");\r
-               OnError(3);\r
+               //OnError(3);\r
                return;\r
-       };\r
+               };\r
                \r
      cmd_send(CMD_ACK,1,0,0,dataout,16);\r
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);\r
@@@ -261,14 -261,14 +261,14 @@@ void MifareReadSector(uint8_t arg0, uin
  \r
  void MifareUReadCard(uint8_t arg0, int arg1, uint8_t *datain)\r
  {\r
-       // params\r
-       uint8_t sectorNo = arg0;\r
+   // params\r
+         uint8_t sectorNo = arg0;\r
        int Pages = arg1;\r
        int count_Pages = 0;\r
        byte_t dataout[176] = {0x00};;\r
        uint8_t uid[10] = {0x00};\r
        uint32_t cuid;\r
-       \r
\r
        LED_A_ON();\r
        LED_B_OFF();\r
        LED_C_OFF();\r
        if (!len) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
                        Dbprintf("Can't select card");\r
-               OnError(1);\r
+               //OnError(1);\r
                return;\r
        }\r
        \r
                if (len) {\r
                        if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
                                Dbprintf("Read block %d error",i);\r
-                       OnError(2);\r
+                       //OnError(2);\r
                        return;\r
                } else {\r
                        count_Pages++;\r
        if (len) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
                        Dbprintf("Halt error");\r
-               OnError(3);\r
+               //OnError(3);\r
                return;\r
        }\r
        \r
@@@ -400,49 -400,49 +400,49 @@@ void MifareWriteBlock(uint8_t arg0, uin
  \r
  void MifareUWriteBlock(uint8_t arg0, uint8_t *datain)\r
  {\r
-       // params\r
-       uint8_t blockNo = arg0;\r
+         // params\r
+         uint8_t blockNo = arg0;\r
        byte_t blockdata[16] = {0x00};\r
  \r
-       memcpy(blockdata, datain, 16);\r
-       \r
-       // variables\r
-       byte_t isOK = 0;\r
+         memcpy(blockdata, datain,16);\r
+         \r
+         // variables\r
+         byte_t isOK = 0;\r
        uint8_t uid[10] = {0x00};\r
-       uint32_t cuid;\r
+         uint32_t cuid;\r
  \r
-       iso14a_clear_trace();\r
-       iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);\r
\r
-       LED_A_ON();\r
-       LED_B_OFF();\r
-       LED_C_OFF();\r
\r
-       while (true) {\r
-               if(!iso14443a_select_card(uid, NULL, &cuid)) {\r
-                               if (MF_DBGLEVEL >= 1)   Dbprintf("Can't select card");\r
-                               break;\r
-               };\r
\r
-               if(mifare_ultra_writeblock(cuid, blockNo, blockdata)) {\r
-                               if (MF_DBGLEVEL >= 1)   Dbprintf("Write block error");\r
-                               break;\r
-               };\r
+         iso14a_clear_trace();\r
+               iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);\r
  \r
-               if(mifare_ultra_halt(cuid)) {\r
-                               if (MF_DBGLEVEL >= 1)   Dbprintf("Halt error");\r
-                               break;\r
-               };\r
-               \r
-               isOK = 1;\r
-               break;\r
-       }\r
+         LED_A_ON();\r
+         LED_B_OFF();\r
+         LED_C_OFF();\r
\r
+         while (true) {\r
+                 if(!iso14443a_select_card(uid, NULL, &cuid)) {\r
+                         if (MF_DBGLEVEL >= 1)   Dbprintf("Can't select card");\r
+                         break;\r
+                 };\r
\r
+                 if(mifare_ultra_writeblock(cuid, blockNo, blockdata)) {\r
+                         if (MF_DBGLEVEL >= 1)   Dbprintf("Write block error");\r
+                         break;\r
+                 };\r
\r
+                 if(mifare_ultra_halt(cuid)) {\r
+                         if (MF_DBGLEVEL >= 1)   Dbprintf("Halt error");\r
+                         break;\r
+                 };\r
+                 \r
+                 isOK = 1;\r
+                 break;\r
+         }\r
          \r
-       if (MF_DBGLEVEL >= 2)   DbpString("WRITE BLOCK FINISHED");\r
+         if (MF_DBGLEVEL >= 2)   DbpString("WRITE BLOCK FINISHED");\r
  \r
-       cmd_send(CMD_ACK,isOK,0,0,0,0);\r
-       FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);\r
-       LEDsoff();\r
+               cmd_send(CMD_ACK,isOK,0,0,0,0);\r
+         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);\r
+         LEDsoff();\r
  }\r
  \r
  void MifareUWriteBlock_Special(uint8_t arg0, uint8_t *datain)\r
  }\r
  \r
  // Return 1 if the nonce is invalid else return 0\r
- int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, uint8_t * parity) {\r
+ int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, uint8_t *parity) {\r
        return ((oddparity((Nt >> 24) & 0xFF) == ((parity[0]) ^ oddparity((NtEnc >> 24) & 0xFF) ^ BIT(Ks1,16))) & \\r
        (oddparity((Nt >> 16) & 0xFF) == ((parity[1]) ^ oddparity((NtEnc >> 16) & 0xFF) ^ BIT(Ks1,8))) & \\r
        (oddparity((Nt >> 8) & 0xFF) == ((parity[2]) ^ oddparity((NtEnc >> 8) & 0xFF) ^ BIT(Ks1,0)))) ? 1 : 0;\r
@@@ -529,11 -529,13 +529,13 @@@ void MifareNested(uint32_t arg0, uint32
        struct Crypto1State mpcs = {0, 0};\r
        struct Crypto1State *pcs;\r
        pcs = &mpcs;\r
-       uint8_t* receivedAnswer =  get_bigbufptr_recvrespbuf();\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
  \r
        uint32_t auth1_time, auth2_time;\r
        static uint16_t delta_time;\r
  \r
+       // free eventually allocated BigBuf memory\r
+       BigBuf_free();\r
        // clear trace\r
        iso14a_clear_trace();\r
        iso14a_set_tracing(false);\r
                WDT_HIT();\r
  \r
                davg = dmax = 0;\r
-               dmin = 2000; \r
+               dmin = 2000;\r
                delta_time = 0;\r
                \r
                for (rtr = 0; rtr < 17; rtr++) {\r
                        }\r
                }\r
                \r
-               if (rtr <= 1) return;\r
+               if (rtr <= 1)   return;\r
  \r
                davg = (davg + (rtr - 1)/2) / (rtr - 1);\r
                \r
        //  get crypted nonces for target sector\r
        for(i=0; i < 2; i++) { // look for exactly two different nonces\r
  \r
-               WDT_HIT();      \r
-           if(BUTTON_PRESS()) {\r
-                       DbpString("Nested: cancelled");\r
-                       crypto1_destroy(pcs);\r
-                       FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);\r
-                       LEDsoff();\r
-                       return;\r
-               }\r
\r
                target_nt[i] = 0;\r
                while(target_nt[i] == 0) { // continue until we have an unambiguous nonce\r
-                \r
+               \r
                        // prepare next select. No need to power down the card.\r
                        if(mifare_classic_halt(pcs, cuid)) {\r
                                if (MF_DBGLEVEL >= 1)   Dbprintf("Nested: Halt error");\r
                        if (target_nt[i] == 0 && j == dmax+1 && MF_DBGLEVEL >= 3) Dbprintf("Nonce#%d: dismissed (all invalid)", i+1);\r
                }\r
        }\r
-       \r
\r
        LED_C_OFF();\r
        \r
        //  ----------------------------- crypto1 destroy\r
@@@ -929,15 -922,15 +922,15 @@@ void MifareCSetBlock(uint32_t arg0, uin
        uint8_t d_block[18] = {0x00};\r
        uint32_t cuid;\r
        \r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
-       \r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
\r
        // reset FPGA and LED\r
        if (workFlags & 0x08) {\r
                LED_A_ON();\r
                LED_B_OFF();\r
                LED_C_OFF();\r
-               \r
+       \r
                iso14a_clear_trace();\r
                iso14a_set_tracing(TRUE);\r
                iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);\r
@@@ -1048,14 -1041,14 +1041,14 @@@ void MifareCGetBlock(uint32_t arg0, uin
        uint8_t data[18] = {0x00};\r
        uint32_t cuid = 0;\r
        \r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        if (workFlags & 0x08) {\r
                LED_A_ON();\r
                LED_B_OFF();\r
                LED_C_OFF();\r
\r
+       \r
                iso14a_clear_trace();\r
                iso14a_set_tracing(TRUE);\r
                iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);\r
@@@ -1113,8 -1106,8 +1106,8 @@@ void MifareCIdent()
        // variables\r
        byte_t isOK = 1;\r
        \r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
  \r
        ReaderTransmitBitsPar(wupC1,7,0, NULL);\r
        if(!ReaderReceive(receivedAnswer, receivedAnswerPar) || (receivedAnswer[0] != 0x0a)) {\r
        cmd_send(CMD_ACK,isOK,0,0,0,0);\r
  }\r
  \r
- //\r
                      //\r
  // DESFIRE\r
  //\r
  \r
@@@ -1150,14 -1143,14 +1143,14 @@@ void Mifare_DES_Auth1(uint8_t arg0, uin
        if(!len) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)        \r
                        Dbprintf("Can't select card");\r
-               OnError(1);\r
+               //OnError(1);\r
                return;\r
        };\r
  \r
        if(mifare_desfire_des_auth1(cuid, dataout)){\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)        \r
                        Dbprintf("Authentication part1: Fail.");\r
-               OnError(4);\r
+               //OnError(4);\r
                return;\r
        }\r
  \r
@@@ -1180,7 -1173,7 +1173,7 @@@ void Mifare_DES_Auth2(uint32_t arg0, ui
        if( isOK) {\r
            if (MF_DBGLEVEL >= MF_DBG_EXTENDED) \r
                        Dbprintf("Authentication part2: Failed");  \r
-               OnError(4);\r
+               //OnError(4);\r
                return;\r
        }\r
  \r
        cmd_send(CMD_ACK, isOK, 0, 0, dataout, sizeof(dataout));\r
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);\r
        LEDsoff();\r
--}
++}\r
diff --combined armsrc/mifareutil.c
index 1859819194c66bd2e1ddd41230d6a2e85e0b4b01,f79c2ede2d78676ddc6aef7b373129e3198a23ca..c3ba1b816a0b1388da9915a256ff1c790e7bdbb6
@@@ -9,29 -9,18 +9,18 @@@
  // Work with mifare cards.\r
  //-----------------------------------------------------------------------------\r
  \r
- #include "../include/proxmark3.h"\r
+ #include "proxmark3.h"\r
  #include "apps.h"\r
  #include "util.h"\r
  #include "string.h"\r
  \r
- #include "../common/iso14443crc.h"\r
+ #include "iso14443crc.h"\r
  #include "iso14443a.h"\r
  #include "crapto1.h"\r
  #include "mifareutil.h"\r
  \r
  int MF_DBGLEVEL = MF_DBG_ALL;\r
  \r
- // memory management\r
- uint8_t* get_bigbufptr_recvrespbuf(void) {\r
-       return (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);\r
- }\r
- uint8_t* get_bigbufptr_recvcmdbuf(void) {\r
-       return (((uint8_t *)BigBuf) + RECV_CMD_OFFSET); \r
- }\r
- uint8_t* get_bigbufptr_emlcardmem(void) {\r
-       return (((uint8_t *)BigBuf) + CARD_MEMORY_OFFSET);\r
- }\r
\r
  // crypto1 helpers\r
  void mf_crypto1_decrypt(struct Crypto1State *pcs, uint8_t *data, int len){\r
        uint8_t bt = 0;\r
@@@ -76,26 -65,26 +65,26 @@@ uint8_t mf_crypto1_encrypt4bit(struct C
  }\r
  \r
  // send commands\r
- int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing)\r
+ int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_tanswer, uint8_t *answer_parity, uint32_t *timing)\r
  {\r
--      return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing);
--}
--
--int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing)
--{
--      uint8_t dcmd[8];
-       dcmd[0] = cmd;\r
 -    dcmd[0] = cmd;
 -    dcmd[1] = data[0];
 -      dcmd[2] = data[1];
 -      dcmd[3] = data[2];
 -      dcmd[4] = data[3];
 -      dcmd[5] = data[4];
 -      AppendCrc14443a(dcmd, 6);
 -      ReaderTransmit(dcmd, sizeof(dcmd), NULL);
 -      int len = ReaderReceive(answer, answer_parity);
 -      if(!len) {
 -                if (MF_DBGLEVEL >= 1)   Dbprintf("Authentication failed. Card timeout.");
 -                return 2;
++      return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing);\r
++}\r
++\r
++int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing)\r
++{\r
++      uint8_t dcmd[8];\r
++    dcmd[0] = cmd;\r
 +    dcmd[1] = data[0];\r
-       dcmd[2] = data[1];
++      dcmd[2] = data[1];\r
 +      dcmd[3] = data[2];\r
 +      dcmd[4] = data[3];\r
 +      dcmd[5] = data[4];\r
-       AppendCrc14443a(dcmd, 6);
-       ReaderTransmit(dcmd, sizeof(dcmd), NULL);
-       int len = ReaderReceive(answer, answer_parity);
-       if(!len) {
-         if (MF_DBGLEVEL >= 1)   Dbprintf("Authentication failed. Card timeout.");
-         return 2;
++      AppendCrc14443a(dcmd, 6);\r
++      ReaderTransmit(dcmd, sizeof(dcmd), NULL);\r
++      int len = ReaderReceive(answer, answer_parity);\r
++      if(!len) {\r
++                if (MF_DBGLEVEL >= 1)   Dbprintf("Authentication failed. Card timeout.");\r
++                return 2;\r
      }\r
        return len;\r
  }\r
@@@ -117,13 -106,13 +106,13 @@@ int mifare_sendcmd_short_mfucauth(struc
      if(len==1)        {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)   Dbprintf("NAK - Authentication failed.");\r
                return 1;\r
--        }
--      return len;
--}
--
--int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing)
--{
--      uint8_t dcmd[4], ecmd[4];
++        }\r
++      return len;\r
++}\r
++\r
++int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing)\r
++{\r
++      uint8_t dcmd[4], ecmd[4];\r
        uint16_t pos, res;\r
        uint8_t par[1];                 // 1 Byte parity is enough here\r
        dcmd[0] = cmd;\r
        int len = ReaderReceive(answer, par);\r
        \r
        if (answer_parity) *answer_parity = par[0];\r
\r
+       \r
        if (crypted == CRYPT_ALL) {\r
                if (len == 1) {\r
                        res = 0;\r
@@@ -175,7 -164,7 +164,7 @@@ int mifare_classic_auth(struct Crypto1S
        return mifare_classic_authex(pcs, uid, blockNo, keyType, ui64Key, isNested, NULL, NULL);\r
  }\r
  \r
- int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t * ntptr, uint32_t *timing) \r
+ int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t *ntptr, uint32_t *timing) \r
  {\r
        // variables\r
        int len;        \r
        uint32_t nt, ntpp; // Supplied tag nonce\r
        \r
        uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };\r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
+       \r
        // Transmit MIFARE_CLASSIC_AUTH\r
        len = mifare_sendcmd_short(pcs, isNested, 0x60 + (keyType & 0x01), blockNo, receivedAnswer, receivedAnswerPar, timing);\r
        if (MF_DBGLEVEL >= 4)   Dbprintf("rand tag nonce len: %x", len);  \r
@@@ -273,8 -262,8 +262,8 @@@ int mifare_classic_readblock(struct Cry
        int len;        \r
        uint8_t bt[2];\r
        \r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t* receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        // command MIFARE_CLASSIC_READBLOCK\r
        len = mifare_sendcmd_short(pcs, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL);\r
        }\r
        \r
        memcpy(blockData, receivedAnswer, 16);\r
--      return 0;
 -}
 -
++      return 0;\r
 +}\r
 +\r
  // mifare ultralight commands\r
  int mifare_ultra_auth1(uint32_t uid, uint8_t *blockData){\r
  \r
        uint16_t len;\r
-       uint8_t *receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        len = mifare_sendcmd_short(NULL, 1, 0x1A, 0x00, receivedAnswer,receivedAnswerPar ,NULL);\r
        if (len == 1) {\r
  int mifare_ultra_auth2(uint32_t uid, uint8_t *key, uint8_t *blockData){\r
  \r
        uint16_t len;\r
-       uint8_t *receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, key, receivedAnswer, receivedAnswerPar, NULL);\r
        if (len == 1) {\r
        }\r
        memcpy(blockData, receivedAnswer, 11);\r
        return 0;\r
- }
- int mifare_ultra_readblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData)
- {
-       uint16_t len;
-       uint8_t bt[2];
-       uint8_t *receivedAnswer = get_bigbufptr_recvrespbuf();
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
-       \r
-       
-       // command MIFARE_CLASSIC_READBLOCK
-       len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL);
-       if (len == 1) {
+ }\r
\r
 -int mifare_ultra_readblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData)
 -{
 -      uint16_t len;
 -      uint8_t bt[2];
++int mifare_ultra_readblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData)\r
++{\r
++      uint16_t len;\r
++      uint8_t bt[2];\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
 -      
+       \r
 -      // command MIFARE_CLASSIC_READBLOCK
 -      len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL);
 -      if (len == 1) {
++      \r
++      // command MIFARE_CLASSIC_READBLOCK\r
++      len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL);\r
++      if (len == 1) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("Cmd Error: %02x", receivedAnswer[0]);
--              return 1;
--      }
--      if (len != 18) {
++                      Dbprintf("Cmd Error: %02x", receivedAnswer[0]);\r
++              return 1;\r
++      }\r
++      if (len != 18) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("Cmd Error: card timeout. len: %x", len);
--              return 2;
--      }
--    
--      memcpy(bt, receivedAnswer + 16, 2);
--      AppendCrc14443a(receivedAnswer, 16);
--      if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {
++                      Dbprintf("Cmd Error: card timeout. len: %x", len);\r
++              return 2;\r
++      }\r
++    \r
++      memcpy(bt, receivedAnswer + 16, 2);\r
++      AppendCrc14443a(receivedAnswer, 16);\r
++      if (bt[0] != receivedAnswer[16] || bt[1] != receivedAnswer[17]) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("Cmd CRC response error.");
--              return 3;
--      }
--      
--      memcpy(blockData, receivedAnswer, 14);
--      return 0;
--}
--
--
--int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) 
--{
--      // variables
++                      Dbprintf("Cmd CRC response error.");\r
++              return 3;\r
++      }\r
++      \r
++      memcpy(blockData, receivedAnswer, 14);\r
++      return 0;\r
++}\r
++\r
++\r
++int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData) \r
++{\r
++      // variables\r
        uint16_t len, i;        \r
        uint32_t pos;\r
        uint8_t par[3] = {0};           // enough for 18 Bytes to send\r
        byte_t res;\r
        \r
        uint8_t d_block[18], d_block_enc[18];\r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t* receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        // command MIFARE_CLASSIC_WRITEBLOCK\r
        len = mifare_sendcmd_short(pcs, 1, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL);\r
                return 2;\r
        }\r
        \r
--      return 0;
--}
--
--int mifare_ultra_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData) 
--{
-       uint16_t len;     
-       uint8_t par[3] = {0}; // enough for 18 parity bits
 -    uint16_t len;     
 -    uint8_t par[3] = {0};  // enough for 18 parity bits
--      uint8_t d_block[18] = {0x00};
-       uint8_t *receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;
-       
-       // command MIFARE_CLASSIC_WRITEBLOCK
-       len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL);
-       if ((len != 1) || (receivedAnswer[0] != 0x0A)) {   //  0x0a - ACK
++      return 0;\r
++}\r
++\r
++int mifare_ultra_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData) \r
++{\r
++    uint16_t len;     \r
++    uint8_t par[3] = {0};  // enough for 18 parity bits\r
++      uint8_t d_block[18] = {0x00};\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
 -        
 -    // command MIFARE_CLASSIC_WRITEBLOCK
 -    len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL);
 -
 -    if ((len != 1) || (receivedAnswer[0] != 0x0A)) {   //  0x0a - ACK
++        \r
++    // command MIFARE_CLASSIC_WRITEBLOCK\r
++    len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL);\r
++\r
++    if ((len != 1) || (receivedAnswer[0] != 0x0A)) {   //  0x0a - ACK\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("Cmd Addr Error: %02x", receivedAnswer[0]);  
-               return 1;
-       }
 -        return 1;
 -    }
--
--      memcpy(d_block, blockData, 16);
--    AppendCrc14443a(d_block, 16);
--
--      ReaderTransmitPar(d_block, sizeof(d_block), par, NULL);
\r
 -
--    len = ReaderReceive(receivedAnswer, receivedAnswerPar);    
--
--      if ((len != 1) || (receivedAnswer[0] != 0x0A)) {   //  0x0a - ACK
++                      Dbprintf("Cmd Addr Error: %02x", receivedAnswer[0]);  \r
++        return 1;\r
++    }\r
++\r
++      memcpy(d_block, blockData, 16);\r
++    AppendCrc14443a(d_block, 16);\r
++\r
++      ReaderTransmitPar(d_block, sizeof(d_block), par, NULL);\r
++\r
++    len = ReaderReceive(receivedAnswer, receivedAnswerPar);    \r
++\r
++      if ((len != 1) || (receivedAnswer[0] != 0x0A)) {   //  0x0a - ACK\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("Cmd Data Error: %02x %d", receivedAnswer[0],len);
-               return 2;
-       }        
 -        return 2;
 -    }        
--    return 0;
--} 
--
--int mifare_ultra_special_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData)
--{
--    uint16_t len;
--      uint8_t d_block[8] = {0x00};
-       uint8_t *receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;
-     // command MIFARE_CLASSIC_WRITEBLOCK
-       d_block[0]= blockNo;
-       memcpy(d_block+1,blockData,4);
-       AppendCrc14443a(d_block, 6);
-     len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL);
-       if (receivedAnswer[0] != 0x0A) {   //  0x0a - ACK
++                      Dbprintf("Cmd Data Error: %02x %d", receivedAnswer[0],len);\r
++        return 2;\r
++    }        \r
++    return 0;\r
++} \r
++\r
++int mifare_ultra_special_writeblock(uint32_t uid, uint8_t blockNo, uint8_t *blockData)\r
++{\r
++    uint16_t len;\r
++      uint8_t d_block[8] = {0x00};\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
 -
 -    // command MIFARE_CLASSIC_WRITEBLOCK
 -      d_block[0]= blockNo;
 -      memcpy(d_block+1,blockData,4);
 -      AppendCrc14443a(d_block, 6);
 -
 -    len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL);
 -
 -    if (receivedAnswer[0] != 0x0A) {   //  0x0a - ACK
++\r
++    // command MIFARE_CLASSIC_WRITEBLOCK\r
++      d_block[0]= blockNo;\r
++      memcpy(d_block+1,blockData,4);\r
++      AppendCrc14443a(d_block, 6);\r
++\r
++    len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL);\r
++\r
++    if (receivedAnswer[0] != 0x0A) {   //  0x0a - ACK\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0],len);
-               return 1;
-       }
-       return 0;
 -        return 1;
 -    }
 -\r    return 0;
--}
--
--int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid) 
--{
++                      Dbprintf("Cmd Send Error: %02x %d", receivedAnswer[0],len);\r
++        return 1;\r
++    }\r
++    return 0;\r
++}\r
++\r
++int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid) \r
++{\r
        uint16_t len;   \r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
  \r
        len = mifare_sendcmd_short(pcs, pcs == NULL ? false:true, 0x50, 0x00, receivedAnswer, receivedAnswerPar, NULL);\r
        if (len != 0) {\r
                return 1;\r
        }\r
  \r
--      return 0;
--}
--
--int mifare_ultra_halt(uint32_t uid)
--{
-       uint16_t len;   \r
-       uint8_t *receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
-     
-       len = mifare_sendcmd_short(NULL, true, 0x50, 0x00, receivedAnswer, receivedAnswerPar, NULL);
-       if (len != 0) {
 -      uint16_t len;
++      return 0;\r
++}\r
++\r
++int mifare_ultra_halt(uint32_t uid)\r
++{\r
++      uint16_t len;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
 -    
 -      len = mifare_sendcmd_short(NULL, true, 0x50, 0x00, receivedAnswer, receivedAnswerPar, NULL);
 -      if (len != 0) {
++    \r
++      len = mifare_sendcmd_short(NULL, true, 0x50, 0x00, receivedAnswer, receivedAnswerPar, NULL);\r
++      if (len != 0) {\r
                if (MF_DBGLEVEL >= MF_DBG_ERROR)\r
--                      Dbprintf("halt error. response len: %x", len);
--              return 1;
 -      }
 -      return 0;
 -}
 -
++                      Dbprintf("halt error. response len: %x", len);\r
++              return 1;\r
 +      }\r
-       return 0;
- }
++      return 0;\r
++}\r
++\r
  \r
  // Mifare Memory Structure: up to 32 Sectors with 4 blocks each (1k and 2k cards),\r
  // plus evtl. 8 sectors with 16 blocks each (4k cards)\r
@@@ -536,24 -525,24 +525,24 @@@ uint8_t FirstBlockOfSector(uint8_t sect
  }\r
  \r
  \r
--// work with emulator memory
--void emlSetMem(uint8_t *data, int blockNum, int blocksCount) {
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
 -      uint8_t* emCARD = BigBuf_get_EM_addr();
++// work with emulator memory\r
++void emlSetMem(uint8_t *data, int blockNum, int blocksCount) {\r
++      uint8_t* emCARD = BigBuf_get_EM_addr();\r
        memcpy(emCARD + blockNum * 16, data, blocksCount * 16);\r
  }\r
  \r
  void emlGetMem(uint8_t *data, int blockNum, int blocksCount) {\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        memcpy(data, emCARD + blockNum * 16, blocksCount * 16);\r
  }\r
  \r
  void emlGetMemBt(uint8_t *data, int bytePtr, int byteCount) {\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        memcpy(data, emCARD + bytePtr, byteCount);\r
  }\r
  \r
  int emlCheckValBl(int blockNum) {\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        uint8_t* data = emCARD + blockNum * 16;\r
  \r
        if ((data[0] != (data[4] ^ 0xff)) || (data[0] != data[8]) ||\r
  }\r
  \r
  int emlGetValBl(uint32_t *blReg, uint8_t *blBlock, int blockNum) {\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        uint8_t* data = emCARD + blockNum * 16;\r
        \r
        if (emlCheckValBl(blockNum)) {\r
        }\r
        \r
        memcpy(blReg, data, 4);\r
-       *blBlock = data[12];    \r
+       *blBlock = data[12];\r
        return 0;\r
  }\r
  \r
  int emlSetValBl(uint32_t blReg, uint8_t blBlock, int blockNum) {\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        uint8_t* data = emCARD + blockNum * 16;\r
        \r
        memcpy(data + 0, &blReg, 4);\r
  \r
  uint64_t emlGetKey(int sectorNum, int keyType) {\r
        uint8_t key[6];\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        \r
        memcpy(key, emCARD + 16 * (FirstBlockOfSector(sectorNum) + NumBlocksPerSector(sectorNum) - 1) + keyType * 10, 6);\r
        return bytes_to_num(key, 6);\r
@@@ -610,7 -599,7 +599,7 @@@ void emlClearMem(void) 
        \r
        const uint8_t trailer[] = {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x07, 0x80, 0x69, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};\r
        const uint8_t uid[]   =   {0xe6, 0x84, 0x87, 0xf3, 0x16, 0x88, 0x04, 0x00, 0x46, 0x8e, 0x45, 0x55, 0x4d, 0x70, 0x41, 0x04};\r
-       uint8_t* emCARD = get_bigbufptr_emlcardmem();\r
+       uint8_t* emCARD = BigBuf_get_EM_addr();\r
        \r
        memset(emCARD, 0, CARD_MEMORY_SIZE);\r
        \r
@@@ -665,8 -654,8 +654,8 @@@ int mifare_desfire_des_auth1(uint32_t u
        int len;\r
        // load key, keynumber\r
        uint8_t data[2]={0x0a, 0x00};\r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        len = mifare_sendcmd_special(NULL, 1, 0x02, data, receivedAnswer,receivedAnswerPar,NULL);\r
        if (len == 1) {\r
@@@ -695,8 -684,8 +684,8 @@@ int mifare_desfire_des_auth2(uint32_t u
        data[0] = 0xAF;\r
        memcpy(data+1,key,16);\r
        \r
-       uint8_t* receivedAnswer = get_bigbufptr_recvrespbuf();\r
-       uint8_t *receivedAnswerPar = receivedAnswer + MAX_FRAME_SIZE;\r
+       uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE];\r
+       uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE];\r
        \r
        len = mifare_sendcmd_special2(NULL, 1, 0x03, data, receivedAnswer, receivedAnswerPar ,NULL);\r
        \r
                return 0;\r
        }\r
        return 1;\r
--}
++}\r
diff --combined client/loclass/cipher.c
index 1c9dae8b5a535266936af39d942aece4961c4185,d3b1e7997beb0971319e3a17d3b3d9db1e5102e6..9c1c2cfd4cbd63c09d6c1b6fa7d11049922c9bb1
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
-  * along with IClassCipher.  If not, see <http://www.gnu.org/licenses/>.
+  * along with loclass.  If not, see <http://www.gnu.org/licenses/>.
+  * 
+  * 
+  * 
   ****************************************************************************/
  
  #include "cipher.h"
  #include "cipherutils.h"
  #include <stdio.h>
@@@ -215,7 -219,7 +219,7 @@@ void MAC(uint8_t* k, BitstreamIn input
        BitstreamIn input_32_zeroes = {zeroes_32,sizeof(zeroes_32)*8,0};
        State initState = suc(k,init(k),&input);
        output(k,initState,&input_32_zeroes,&out);
 -}
 +}      
  
  void doMAC(uint8_t *cc_nr_p, int length, uint8_t *div_key_p, uint8_t mac[4])
  {
      cc_nr=(uint8_t*)malloc(length+1);
      memcpy(cc_nr,cc_nr_p,length);
      memcpy(div_key,div_key_p,8);
 -
 -    reverse_arraybytes(cc_nr,length);
 -    BitstreamIn bitstream = {cc_nr,length * 8,0};
 -    uint8_t dest []= {0,0,0,0,0,0,0,0};
 -    BitstreamOut out = { dest, sizeof(dest)*8, 0 };
 -    MAC(div_key,bitstream, out);
 -    //The output MAC must also be reversed
 -    reverse_arraybytes(dest, sizeof(dest));
 -    memcpy(mac, dest, 4);
 +    
 +      reverse_arraybytes(cc_nr,length);
 +      BitstreamIn bitstream = {cc_nr,length * 8,0};
 +      uint8_t dest []= {0,0,0,0,0,0,0,0};
 +      BitstreamOut out = { dest, sizeof(dest)*8, 0 };
 +      MAC(div_key,bitstream, out);
 +      //The output MAC must also be reversed
 +      reverse_arraybytes(dest, sizeof(dest));
 +      memcpy(mac,dest,4);
      //printf("Calculated_MAC\t%02x%02x%02x%02x\n", dest[0],dest[1],dest[2],dest[3]);
 -    free(cc_nr);
 +      free(cc_nr);
      return;
  }
  
@@@ -260,8 -264,8 +264,8 @@@ int testMAC(
                prnlog("[+] FAILED: MAC calculation failed:");
                printarr("    Calculated_MAC", calculated_mac, 4);
                printarr("    Correct_MAC   ", correct_MAC, 4);
 -              return 1;
 -      }
 +      return 1;
 +}
  
        return 0;
  }
index d2acb3be4dfc9d488ccd8908cc6de19a9ebe426c,a5442f2a8b221ee565f07b3da9c857477755c63e..6f309001da3b31dd96af6627f4c57dc103db788c
@@@ -48,7 -48,7 +48,7 @@@ local _commands = 
        CMD_EM4X_READ_WORD =                                                 0x0218,
        CMD_EM4X_WRITE_WORD =                                                0x0219,
        CMD_IO_DEMOD_FSK =                                                   0x021A,
-       CMD_IO_CLONE_TAG =                                                   0x021B,
+   CMD_IO_CLONE_TAG =                                                   0x021B,
        CMD_EM410X_DEMOD =                                                                                                   0x021c,
        --/* CMD_SET_ADC_MUX: ext1 is 0 for lopkd, 1 for loraw, 2 for hipkd, 3 for hiraw */
  
        CMD_MIFARE_CSETBLOCK =                                               0x0605,
        CMD_MIFARE_CGETBLOCK =                                               0x0606,
        CMD_MIFARE_CIDENT =                                                  0x0607,
-       
        CMD_SIMULATE_MIFARE_CARD =                                           0x0610,
  
        CMD_READER_MIFARE =                                                  0x0611,
  
  
  local _reverse_lookup,k,v = {}
 -for k, v in pairs(_commands) do
 -      _reverse_lookup[v] =  k
 -end
 -_commands.tostring = function(command)
 +      for k, v in pairs(_commands) do
 +              _reverse_lookup[v] =  k
 +      end
 +      _commands.tostring = function(command)
        if(type(command) == 'number') then
                return ("%s (%d)"):format(_reverse_lookup[command]or "ERROR UNDEFINED!", command) 
        end
@@@ -212,7 -212,7 +212,6 @@@ function Command:getBytes(
        local data  = self.data
        local cmd = self.cmd 
        local arg1, arg2, arg3 = self.arg1, self.arg2, self.arg3
 -      
        return bin.pack("LLLLH",cmd, arg1, arg2, arg3,data);
  end
  return _commands
index a7890885153350a995313f9f481a2d6ef13aabd7,3a28d5ae6f988cf5b30c0ffb40094342bca797e6..bd8e6d0cc20ea2942ba2b370c9907e01ea02b570
@@@ -49,7 -49,7 +49,7 @@@ en
  
  local function save_TEXT(data,filename)
        -- Open the output file
-       local outfile = io.open(filename, "wb")
+       local outfile = io.open(filename, "w")
        if outfile == nil then 
                return oops(string.format("Could not write to file %s",tostring(filename)))
        end
@@@ -192,7 -192,7 +192,9 @@@ en
  return {
        convert_bin_to_html = convert_bin_to_html,
        convert_eml_to_html = convert_eml_to_html,
 -    convert_eml_to_bin = convert_eml_to_bin,  
 +    convert_eml_to_bin = convert_eml_to_bin,
 +    SaveAsBinary = save_BIN,
 +      SaveAsText = save_TEXT,
+     SaveAsBinary = save_BIN,
+       SaveAsText = save_TEXT,
  }
index 810f0d6eab466b7fd8a6b40f06d4e9468bbb4249,757112c671f0169fc26ea53f76326bd0db073f77..cca4699e9741e36040221e43f58774c1a5166828
@@@ -158,9 -158,9 +158,23 @@@ local _keys = 
        'eff603e1efe9',
        '644672bd4afe',
  
+       'b5ff67cba951',
+   }
++      --[[
++    Kiev metro cards
++    --]]      
++      '8fe644038790',
++      'f14ee7cae863',
++      '632193be1c3c',
++      '569369c5a0e5',
++      '9de89e070277',
++      'eff603e1efe9',
++      '644672bd4afe',
++
 +      'b5ff67cba951',
 +}
 +
  ---
  --    The keys above have just been pasted in, for completeness sake. They contain duplicates. 
  --    We need to weed the duplicates out before we expose the list to someone who actually wants to use them
diff --combined client/lualibs/utils.lua
index 9b36dfc862239736e0f16a9fc455883dc5dcb88c,c5baa406955d067012d525e9b57c8bf9cc525a42..3015c4195c98c55080bb50477a2fc1930a7a9046
@@@ -108,6 -108,24 +108,24 @@@ local Utils 
                return retval\r
        end,\r
        \r
+       -- input parameter is a string\r
+       -- Swaps the endianess and returns a string,  \r
+       -- IE:  'cd7a' -> '7acd'  -> 0x7acd\r
+       SwapEndiannessStr = function(s, len)\r
+               if s == nil then return nil end\r
+               if #s == 0 then return '' end\r
+               if  type(s) ~= 'string' then return nil end\r
+               \r
+               local retval\r
+               if len == 16 then\r
+                       retval = s:sub(3,4)..s:sub(1,2)\r
+               elseif len == 24 then\r
+                       retval = s:sub(5,6)..s:sub(3,4)..s:sub(1,2)\r
+               elseif len == 32 then\r
+                       retval = s:sub(7,8)..s:sub(5,6)..s:sub(3,4)..s:sub(1,2)\r
+               end\r
+               return retval\r
+       end,    \r
        ------------ CONVERSIONS\r
        \r
        --\r
                local B,K,OUT,I,D=16,"0123456789ABCDEF","",0\r
                while IN>0 do\r
                        I=I+1\r
-                       IN,D=math.floor(IN/B),math.mod(IN,B)+1\r
+                       IN , D = math.floor(IN/B), math.modf(IN,B)+1\r
                        OUT=string.sub(K,D,D)..OUT\r
                end\r
                return OUT\r
                end\r
                local s={}\r
                for i = 1, #(bytes) do\r
 -                      s[i] =   string.format("%02X",bytes[i]) \r
 +                      s[i] = string.format("%02X",bytes[i]) \r
                end\r
                return table.concat(s)\r
        end,    \r
diff --combined client/mifarehost.c
index 3516fca499fd3daa921345b7b4e0eb0d39f0dd85,7f784850841095713a0a54284259bf9e1b552d05..60dba6c07800849bafb38ec3fe8152ec160698dd
@@@ -72,7 -72,7 +72,6 @@@ int mfnested(uint8_t blockNo, uint8_t k
        uint16_t i, len;\r
        uint32_t uid;\r
        UsbCommand resp;\r
-       \r
 -\r
        StateList_t statelists[2];\r
        struct Crypto1State *p1, *p2, *p3, *p4;\r
        \r
@@@ -216,7 -216,7 +215,7 @@@ int mfEmlGetMem(uint8_t *data, int bloc
        UsbCommand c = {CMD_MIFARE_EML_MEMGET, {blockNum, blocksCount, 0}};\r
        SendCommand(&c);\r
  \r
 -  UsbCommand resp;\r
 +      UsbCommand resp;\r
        if (!WaitForResponseTimeout(CMD_ACK,&resp,1500)) return 1;\r
        memcpy(data, resp.d.asBytes, blocksCount * 16);\r
        return 0;\r
@@@ -232,14 -232,27 +231,27 @@@ int mfEmlSetMem(uint8_t *data, int bloc
  // "MAGIC" CARD\r
  \r
  int mfCSetUID(uint8_t *uid, uint8_t *oldUID, bool wantWipe) {\r
+       \r
+       uint8_t oldblock0[16] = {0x00};\r
        uint8_t block0[16] = {0x00};\r
        memcpy(block0, uid, 4); \r
        block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // Mifare UID BCC\r
        // mifare classic SAK(byte 5) and ATQA(byte 6 and 7)\r
-       block0[5] = 0x08;\r
-       block0[6] = 0x04;\r
-       block0[7] = 0x00;\r
+       //block0[5] = 0x08;\r
+       //block0[6] = 0x04;\r
+       //block0[7] = 0x00;\r
+       \r
+       block0[5] = 0x01;  //sak\r
+       block0[6] = 0x01;\r
+       block0[7] = 0x0f;\r
        \r
+       int old = mfCGetBlock(0, oldblock0, CSETBLOCK_SINGLE_OPER);\r
+       if ( old == 0) {\r
+               memcpy(block0+8, oldblock0+8, 8);\r
+               PrintAndLog("block 0:  %s", sprint_hex(block0,16));\r
+       } else {\r
+               PrintAndLog("Couldn't get olddata. Will write over the last bytes of Block 0.");\r
+       }\r
        return mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER);\r
  }\r
  \r
@@@ -250,11 -263,13 +262,13 @@@ int mfCSetBlock(uint8_t blockNo, uint8_
        memcpy(c.d.asBytes, data, 16); \r
        SendCommand(&c);\r
  \r
 -  UsbCommand resp;\r
 +      UsbCommand resp;\r
        if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) {\r
                isOK  = resp.arg[0] & 0xff;\r
-               if (uid != NULL) memcpy(uid, resp.d.asBytes, 4);\r
-               if (!isOK) return 2;\r
+               if (uid != NULL) \r
+                       memcpy(uid, resp.d.asBytes, 4);\r
+               if (!isOK) \r
+                       return 2;\r
        } else {\r
                PrintAndLog("Command execute timeout");\r
                return 1;\r
@@@ -286,9 -301,9 +300,9 @@@ int mfCGetBlock(uint8_t blockNo, uint8_
  static uint8_t trailerAccessBytes[4] = {0x08, 0x77, 0x8F, 0x00};\r
  \r
  // variables\r
- char logHexFileName[200] = {0x00};\r
+ char logHexFileName[FILE_PATH_SIZE] = {0x00};\r
  static uint8_t traceCard[4096] = {0x00};\r
- static char traceFileName[200] = {0x00};\r
+ static char traceFileName[FILE_PATH_SIZE] = {0x00};\r
  static int traceState = TRACE_IDLE;\r
  static uint8_t traceCurBlock = 0;\r
  static uint8_t traceCurKey = 0;\r
@@@ -323,26 -338,34 +337,34 @@@ int isBlockTrailer(int blockN) 
  \r
  int loadTraceCard(uint8_t *tuid) {\r
        FILE * f;\r
-       char buf[64];\r
-       uint8_t buf8[64];\r
+       char buf[64] = {0x00};\r
+       uint8_t buf8[64] = {0x00};\r
        int i, blockNum;\r
        \r
-       if (!isTraceCardEmpty()) saveTraceCard();\r
+       if (!isTraceCardEmpty()) \r
+               saveTraceCard();\r
+               \r
        memset(traceCard, 0x00, 4096);\r
        memcpy(traceCard, tuid + 3, 4);\r
\r
        FillFileNameByUID(traceFileName, tuid, ".eml", 7);\r
  \r
        f = fopen(traceFileName, "r");\r
-       if (!f) return 1;\r
+       if (!f) {\r
+               fclose(f);\r
+               return 1;\r
+       }\r
        \r
        blockNum = 0;\r
+               \r
        while(!feof(f)){\r
+       \r
                memset(buf, 0, sizeof(buf));\r
                if (fgets(buf, sizeof(buf), f) == NULL) {\r
 -                      PrintAndLog("File reading error.");\r
 +      PrintAndLog("File reading error.");\r
                        fclose(f);\r
                        return 2;\r
 -      }\r
 +    }\r
  \r
                if (strlen(buf) < 32){\r
                        if (feof(f)) break;\r
@@@ -368,22 -391,30 +390,30 @@@ int saveTraceCard(void) 
        if ((!strlen(traceFileName)) || (isTraceCardEmpty())) return 0;\r
        \r
        f = fopen(traceFileName, "w+");\r
+       if ( !f ) {\r
+               fclose(f);\r
+               return 1;\r
+       }\r
+       \r
        for (int i = 0; i < 64; i++) {  // blocks\r
                for (int j = 0; j < 16; j++)  // bytes\r
                        fprintf(f, "%02x", *(traceCard + i * 16 + j)); \r
                fprintf(f,"\n");\r
        }\r
        fclose(f);\r
\r
        return 0;\r
  }\r
  \r
  int mfTraceInit(uint8_t *tuid, uint8_t *atqa, uint8_t sak, bool wantSaveToEmlFile) {\r
  \r
-       if (traceCrypto1) crypto1_destroy(traceCrypto1);\r
+       if (traceCrypto1) \r
+               crypto1_destroy(traceCrypto1);\r
\r
        traceCrypto1 = NULL;\r
  \r
-       if (wantSaveToEmlFile) loadTraceCard(tuid);\r
+       if (wantSaveToEmlFile) \r
+               loadTraceCard(tuid);\r
+               \r
        traceCard[4] = traceCard[0] ^ traceCard[1] ^ traceCard[2] ^ traceCard[3];\r
        traceCard[5] = sak;\r
        memcpy(&traceCard[6], atqa, 2);\r
@@@ -440,7 -471,7 +470,7 @@@ int mfTraceDecode(uint8_t *data_src, in
                }\r
                \r
                // AUTHENTICATION\r
 -              if ((len ==4) && ((data[0] == 0x60) || (data[0] == 0x61))) {\r
 +              if ((len == 4) && ((data[0] == 0x60) || (data[0] == 0x61))) {\r
                        traceState = TRACE_AUTH1;\r
                        traceCurBlock = data[1];\r
                        traceCurKey = data[0] == 60 ? 1:0;\r
index c2dd7a547bfff60365f3b6a36ac87e280aeb4409,6c0fcafa09ef6bb9c038a6f593de93a0495d9400..ca926a7382a8d3e77b1d5078e65154452dce7bfa
@@@ -545,10 -545,10 +545,10 @@@ lfsr_common_prefix(uint32_t pfx, uint32
        statelist = malloc((sizeof *statelist) << 21);  //how large should be? \r
        if(!statelist || !odd || !even)\r
        {\r
-          free(statelist);\r
-          free(odd);\r
-          free(even);\r
+                               free(statelist);\r
+                               free(odd);\r
+                               free(even);\r
 -                return 0;\r
 +         return 0;\r
        }\r
  \r
        s = statelist;\r
diff --combined client/proxmark3.c
index 7d50c35aecc4c79a0e353a7b72a98a47d2fa78d6,0e2a698c1b8ca3783f2a1bc16d980539c423ce22..c100bbea0985d05222f580adbf90d05d887540bd
@@@ -34,123 -34,123 +34,123 @@@ static UsbCommand txcmd
  volatile static bool txcmd_pending = false;
  
  void SendCommand(UsbCommand *c) {
- #if 0
      #if 0
 -              printf("Sending %d bytes\n", sizeof(UsbCommand));
 +  printf("Sending %d bytes\n", sizeof(UsbCommand));
- #endif
      #endif
  
        if (offline) {
        PrintAndLog("Sending bytes to proxmark failed - offline");
        return;
      }
-       /**
+   /**
        The while-loop below causes hangups at times, when the pm3 unit is unresponsive
        or disconnected. The main console thread is alive, but comm thread just spins here.
        Not good.../holiman
        **/
 -      while(txcmd_pending);
 -      txcmd = *c;
 -      txcmd_pending = true;
 +  while(txcmd_pending);
 +  txcmd = *c;
 +  txcmd_pending = true;
  }
  
  struct receiver_arg {
 -      int run;
 +  int run;
  };
  
  struct main_loop_arg {
 -      int usb_present;
 -      char *script_cmds_file;
 +  int usb_present;
 +  char *script_cmds_file;
  };
  
  byte_t rx[0x1000000];
  byte_t* prx = rx;
  
  static void *uart_receiver(void *targ) {
 -      struct receiver_arg *arg = (struct receiver_arg*)targ;
 -      size_t rxlen;
 -      size_t cmd_count;
 +  struct receiver_arg *arg = (struct receiver_arg*)targ;
 +  size_t rxlen;
 +  size_t cmd_count;
-   
 -      while (arg->run) {
 -              rxlen = sizeof(UsbCommand);
 +  while (arg->run) {
 +    rxlen = sizeof(UsbCommand);
-     if (uart_receive(sp,prx,&rxlen)) {
+               if (uart_receive(sp, prx, &rxlen)) {
 -                      prx += rxlen;
 -                      if (((prx-rx) % sizeof(UsbCommand)) != 0) {
 -                              continue;
 -                      }
 -                      cmd_count = (prx-rx) / sizeof(UsbCommand);
 +      prx += rxlen;
 +      if (((prx-rx) % sizeof(UsbCommand)) != 0) {
 +        continue;
 +      }
 +      cmd_count = (prx-rx) / sizeof(UsbCommand);
  
-       for (size_t i=0; i<cmd_count; i++) {
+                       for (size_t i = 0; i < cmd_count; i++) {
 -                              UsbCommandReceived((UsbCommand*)(rx+(i*sizeof(UsbCommand))));
 -                      }
 -              }
 -              prx = rx;
 +        UsbCommandReceived((UsbCommand*)(rx+(i*sizeof(UsbCommand))));
 +      }
 +    }
 +    prx = rx;
-     
 -              if(txcmd_pending) {
 +    if(txcmd_pending) {
-       if (!uart_send(sp,(byte_t*)&txcmd,sizeof(UsbCommand))) {
+                       if (!uart_send(sp, (byte_t*) &txcmd, sizeof(UsbCommand))) {
 -                              PrintAndLog("Sending bytes to proxmark failed");
 -                      }
 -                      txcmd_pending = false;
 -              }
 -      }
 +        PrintAndLog("Sending bytes to proxmark failed");
 +      }
 +      txcmd_pending = false;
 +    }
 +  }
-   
 -      pthread_exit(NULL);
 -      return NULL;
 +  pthread_exit(NULL);
 +  return NULL;
  }
  
  static void *main_loop(void *targ) {
 -      struct main_loop_arg *arg = (struct main_loop_arg*)targ;
 -      struct receiver_arg rarg;
 -      char *cmd = NULL;
 -      pthread_t reader_thread;
 +  struct main_loop_arg *arg = (struct main_loop_arg*)targ;
 +  struct receiver_arg rarg;
 +  char *cmd = NULL;
 +  pthread_t reader_thread;
    
 -      if (arg->usb_present == 1) {
 +  if (arg->usb_present == 1) {
-     rarg.run=1;
+               rarg.run = 1;
 -              pthread_create(&reader_thread, NULL, &uart_receiver, &rarg);
 -      }
 +    pthread_create(&reader_thread, NULL, &uart_receiver, &rarg);
 +  }
-   
 -      FILE *script_file = NULL;
 +  FILE *script_file = NULL;
-   char script_cmd_buf[256];  // iceman, needs lua script the same file_path_buffer as the rest
-   
+       char script_cmd_buf[256];  // iceman, needs lua script the same file_path_buffer as the rest
        if (arg->script_cmds_file) {
 -              script_file = fopen(arg->script_cmds_file, "r");
 +    script_file = fopen(arg->script_cmds_file, "r");
                if (script_file) {
 -                      printf("using 'scripting' commands file %s\n", arg->script_cmds_file);
 -              }
 -      }
 +      printf("using 'scripting' commands file %s\n", arg->script_cmds_file);
 +    }
 +  }
  
        read_history(".history");
  
        while(1)  {
  
 -              // If there is a script file
 -              if (script_file)
 -              {
 +    // If there is a script file
 +    if (script_file)
 +    {
                        if (!fgets(script_cmd_buf, sizeof(script_cmd_buf), script_file)) {
 -                              fclose(script_file);
 -                              script_file = NULL;
 +        fclose(script_file);
 +        script_file = NULL;
                        } else {
 -                              char *nl;
 -                              nl = strrchr(script_cmd_buf, '\r');
 -                              if (nl) *nl = '\0';
 +        char *nl;
 +        nl = strrchr(script_cmd_buf, '\r');
 +        if (nl) *nl = '\0';
                                
 -                              nl = strrchr(script_cmd_buf, '\n');
 -                              if (nl) *nl = '\0';
 +        nl = strrchr(script_cmd_buf, '\n');
 +        if (nl) *nl = '\0';
-         
                                if ((cmd = (char*) malloc(strlen(script_cmd_buf) + 1)) != NULL) {
 -                                      memset(cmd, 0, strlen(script_cmd_buf));
 -                                      strcpy(cmd, script_cmd_buf);
 -                                      printf("%s\n", cmd);
 -                              }
 -                      }
 -              }
 +          memset(cmd, 0, strlen(script_cmd_buf));
 +          strcpy(cmd, script_cmd_buf);
 +          printf("%s\n", cmd);
 +        }
 +      }
 +    }
                
                if (!script_file) {
 -                      cmd = readline(PROXPROMPT);
 +      cmd = readline(PROXPROMPT);
                }
                
                if (cmd) {
  
                        while(cmd[strlen(cmd) - 1] == ' ')
 -                              cmd[strlen(cmd) - 1] = 0x00;
 +        cmd[strlen(cmd) - 1] = 0x00;
                        
                        if (cmd[0] != 0x00) {
                                if (strncmp(cmd, "quit", 4) == 0) {
    
        write_history(".history");
    
 -      if (arg->usb_present == 1) {
 -              rarg.run = 0;
 -              pthread_join(reader_thread, NULL);
 -      }
 +  if (arg->usb_present == 1) {
 +    rarg.run = 0;
 +    pthread_join(reader_thread, NULL);
 +  }
-   
        if (script_file) {
 -              fclose(script_file);
 -              script_file = NULL;
 -      }
 +    fclose(script_file);
 +    script_file = NULL;
 +  }
-   
 -      ExitGraphics();
 -      pthread_exit(NULL);
 -      return NULL;
 +  ExitGraphics();
 +  pthread_exit(NULL);
 +  return NULL;
  }
  
  static void dumpAllHelp(int markdown)
diff --combined client/scripting.c
index cc59f995bfc36255ab403e0fe502f2011f902399,0ccdeeec7a8d497d5a288fef2fcc0e8998a0e865..cf149b6e6773051166b186f70843c15fa239e641
@@@ -18,8 -18,8 +18,8 @@@
  #include "util.h"
  #include "nonce2key/nonce2key.h"
  #include "../common/iso15693tools.h"
- #include <openssl/aes.h>   
  #include "../common/crc16.h"
+ #include "aes.h"
  /**
   * The following params expected:
   *  UsbCommand c
@@@ -240,10 -240,10 +240,10 @@@ static int l_aes(lua_State *L
  
      const char *p_encTxt = luaL_checklstring(L, 2, &size);
      
-       unsigned char indata[AES_BLOCK_SIZE] = {0x00};
-       unsigned char outdata[AES_BLOCK_SIZE] = {0x00};
-     unsigned char aes_key[AES_BLOCK_SIZE] = {0x00};
-       unsigned char iv[AES_BLOCK_SIZE] = {0x00};
+       unsigned char indata[16] = {0x00};
+       unsigned char outdata[16] = {0x00};
+     unsigned char aes_key[16] = {0x00};
+       unsigned char iv[16] = {0x00};
        
        // convert key to bytearray
        for (i = 0; i < 32; i += 2) {
                sscanf(&p_key[i], "%02x", (unsigned int *)&aes_key[i / 2]);
        }
        
-       AES_KEY key;
-       AES_set_decrypt_key(aes_key, 128, &key);
-     AES_cbc_encrypt(indata, outdata, sizeof(indata), &key, iv, AES_DECRYPT);
+       //AES_KEY key;
+     //AES_set_decrypt_key(aes_key, 128, &key);
+     //AES_cbc_encrypt(indata, outdata, sizeof(indata), &key, iv, AES_DECRYPT);
+     aes_context ctx;
+     aes_init(&ctx);
+     aes_setkey_enc(&ctx,(const unsigned char *)p_key,128);
+       aes_crypt_cbc(&ctx,AES_DECRYPT,sizeof(indata), iv, indata,outdata );
      //Push decrypted array as a string
        lua_pushlstring(L,(const char *)&outdata, sizeof(outdata));
        return 1;// return 1 to signal one return value
@@@ -309,8 -313,8 +313,8 @@@ int set_pm3_libraries(lua_State *L
          {"foobar",                      l_foobar},
          {"ukbhit",                      l_ukbhit},
          {"clearCommandBuffer",          l_clearCommandBuffer},
 -        {"console",                      l_CmdConsole},
 -        {"iso15693_crc",                 l_iso15693_crc},
 +        {"console",                     l_CmdConsole},
 +        {"iso15693_crc",                l_iso15693_crc},
                {"aes",                         l_aes},
                {"crc16",                       l_crc16},
          {NULL, NULL}
diff --combined common/Makefile.common
index b30294a8e940dff2a3cc717f7f77f9eda1d1165b,2b2bb2fbd7c47fa514d5d2c05dadd890b9a69400..9e8bfdf0e30530d2554f13bfb1ffe1a5c7bf0114
@@@ -69,8 -69,8 +69,10 @@@ INCLUDES = ../include/proxmark3.h ../in
  CFLAGS =  -c $(INCLUDE) -Wall -Werror -pedantic -std=c99 $(APP_CFLAGS) -Os
  LDFLAGS = -nostartfiles -nodefaultlibs -Wl,-gc-sections -n
  
+ LIBS = -lgcc
 +LIBS = -lgcc 
 +
  THUMBOBJ = $(patsubst %.c,$(OBJDIR)/%.o,$(THUMBSRC))
  ARMOBJ   = $(ARMSRC:%.c=$(OBJDIR)/%.o)
  ASMOBJ   = $(patsubst %.s,$(OBJDIR)/%.o,$(ASMSRC))
Impressum, Datenschutz