1 //----------------------------------------------------------------------------- 
   2 // Jonathan Westhues, Mar 2006 
   3 // Edits by Gerhard de Koning Gans, Sep 2007 (##) 
   5 // This code is licensed to you under the terms of the GNU GPL, version 2 or, 
   6 // at your option, any later version. See the LICENSE.txt file for the text of 
   8 //----------------------------------------------------------------------------- 
   9 // The main application code. This is the first thing called after start.c 
  11 //----------------------------------------------------------------------------- 
  17 #include "proxmark3.h" 
  24 #include "legicrfsim.h" 
  28 #include "lfsampling.h" 
  30 #include "mifareutil.h" 
  34 #include "fpgaloader.h" 
  39 static uint32_t hw_capabilities
; 
  41 // Craig Young - 14a stand-alone code 
  43  #include "iso14443a.h" 
  46 //============================================================================= 
  47 // A buffer where we can queue things up to be sent through the FPGA, for 
  48 // any purpose (fake tag, as reader, whatever). We go MSB first, since that 
  49 // is the order in which they go out on the wire. 
  50 //============================================================================= 
  52 #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  
  53 uint8_t ToSend
[TOSEND_BUFFER_SIZE
]; 
  56 struct common_area common_area 
__attribute__((section(".commonarea"))); 
  58 void ToSendReset(void) 
  64 void ToSendStuffBit(int b
) 
  68                 ToSend
[ToSendMax
] = 0; 
  73                 ToSend
[ToSendMax
] |= (1 << (7 - ToSendBit
)); 
  78         if(ToSendMax 
>= sizeof(ToSend
)) { 
  80                 DbpString("ToSendStuffBit overflowed!"); 
  84 //============================================================================= 
  85 // Debug print functions, to go out over USB, to the usual PC-side client. 
  86 //============================================================================= 
  88 void DbpString(char *str
) 
  90   byte_t len 
= strlen(str
); 
  91   cmd_send(CMD_DEBUG_PRINT_STRING
,len
,0,0,(byte_t
*)str
,len
); 
  95 void DbpIntegers(int x1
, int x2
, int x3
) 
  97   cmd_send(CMD_DEBUG_PRINT_INTEGERS
,x1
,x2
,x3
,0,0); 
 101 void Dbprintf(const char *fmt
, ...) { 
 102 // should probably limit size here; oh well, let's just use a big buffer 
 103         char output_string
[128]; 
 107         kvsprintf(fmt
, output_string
, 10, ap
); 
 110         DbpString(output_string
); 
 113 // prints HEX & ASCII 
 114 void Dbhexdump(int len
, uint8_t *d
, bool bAsci
) { 
 127                         if (ascii
[i
]<32 || ascii
[i
]>126) ascii
[i
]='.'; 
 130                         Dbprintf("%-8s %*D",ascii
,l
,d
," "); 
 132                         Dbprintf("%*D",l
,d
," "); 
 140 //----------------------------------------------------------------------------- 
 141 // Read an ADC channel and block till it completes, then return the result 
 142 // in ADC units (0 to 1023). Also a routine to average 32 samples and 
 144 //----------------------------------------------------------------------------- 
 145 static int ReadAdc(int ch
) 
 147         // Note: ADC_MODE_PRESCALE and ADC_MODE_SAMPLE_HOLD_TIME are set to the maximum allowed value.  
 148         // AMPL_HI is a high impedance (10MOhm || 1MOhm) output, the input capacitance of the ADC is 12pF (typical). This results in a time constant 
 149         // of RC = (0.91MOhm) * 12pF = 10.9us. Even after the maximum configurable sample&hold time of 40us the input capacitor will not be fully charged.  
 152         // If there is a voltage v_in at the input, the voltage v_cap at the capacitor (this is what we are measuring) will be 
 154         //       v_cap = v_in * (1 - exp(-SHTIM/RC))  =   v_in * (1 - exp(-40us/10.9us))  =  v_in * 0,97                   (i.e. an error of 3%) 
 156         AT91C_BASE_ADC
->ADC_CR 
= AT91C_ADC_SWRST
; 
 157         AT91C_BASE_ADC
->ADC_MR 
= 
 158                 ADC_MODE_PRESCALE(63) |                                                 // ADC_CLK = MCK / ((63+1) * 2) = 48MHz / 128 = 375kHz 
 159                 ADC_MODE_STARTUP_TIME(1) |                                              // Startup Time = (1+1) * 8 / ADC_CLK = 16 / 375kHz = 42,7us     Note: must be > 20us 
 160                 ADC_MODE_SAMPLE_HOLD_TIME(15);                                  // Sample & Hold Time SHTIM = 15 / ADC_CLK = 15 / 375kHz = 40us 
 162         AT91C_BASE_ADC
->ADC_CHER 
= ADC_CHANNEL(ch
); 
 163         AT91C_BASE_ADC
->ADC_CR 
= AT91C_ADC_START
; 
 165         while(!(AT91C_BASE_ADC
->ADC_SR 
& ADC_END_OF_CONVERSION(ch
))) {}; 
 167         return AT91C_BASE_ADC
->ADC_CDR
[ch
] & 0x3ff; 
 170 int AvgAdc(int ch
) // was static - merlok 
 175         for(i 
= 0; i 
< 32; i
++) { 
 179         return (a 
+ 15) >> 5; 
 182 static int AvgAdc_Voltage_HF(void) 
 184         int AvgAdc_Voltage_Low
, AvgAdc_Voltage_High
; 
 186         AvgAdc_Voltage_Low
= (MAX_ADC_HF_VOLTAGE_LOW 
* AvgAdc(ADC_CHAN_HF_LOW
)) >> 10; 
 187         // if voltage range is about to be exceeded, use high voltage ADC channel if available (RDV40 only) 
 188         if (AvgAdc_Voltage_Low 
> MAX_ADC_HF_VOLTAGE_LOW 
- 300) { 
 189                 AvgAdc_Voltage_High 
= (MAX_ADC_HF_VOLTAGE_HIGH 
* AvgAdc(ADC_CHAN_HF_HIGH
)) >> 10; 
 190                 if (AvgAdc_Voltage_High 
>= AvgAdc_Voltage_Low
) { 
 191                         return AvgAdc_Voltage_High
; 
 194         return AvgAdc_Voltage_Low
; 
 197 static int AvgAdc_Voltage_LF(void) 
 199         return (MAX_ADC_LF_VOLTAGE 
* AvgAdc(ADC_CHAN_LF
)) >> 10; 
 202 void MeasureAntennaTuningLfOnly(int *vLf125
, int *vLf134
, int *peakf
, int *peakv
, uint8_t LF_Results
[]) 
 204         int i
, adcval 
= 0, peak 
= 0; 
 207  * Sweeps the useful LF range of the proxmark from 
 208  * 46.8kHz (divisor=255) to 600kHz (divisor=19) and 
 209  * read the voltage in the antenna, the result left 
 210  * in the buffer is a graph which should clearly show 
 211  * the resonating frequency of your LF antenna 
 212  * ( hopefully around 95 if it is tuned to 125kHz!) 
 215         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
 216         FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC 
| FPGA_LF_ADC_READER_FIELD
); 
 219         for (i
=255; i
>=19; i
--) { 
 221                 FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, i
); 
 223                 adcval 
= AvgAdc_Voltage_LF(); 
 224                 if (i
==95) *vLf125 
= adcval
; // voltage at 125Khz 
 225                 if (i
==89) *vLf134 
= adcval
; // voltage at 134Khz 
 227                 LF_Results
[i
] = adcval 
>> 9; // scale int to fit in byte for graphing purposes 
 228                 if(LF_Results
[i
] > peak
) { 
 230                         peak 
= LF_Results
[i
]; 
 236         for (i
=18; i 
>= 0; i
--) LF_Results
[i
] = 0; 
 241 void MeasureAntennaTuningHfOnly(int *vHf
) 
 243         // Let the FPGA drive the high-frequency antenna around 13.56 MHz. 
 245         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 246         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
); 
 248         *vHf 
= AvgAdc_Voltage_HF(); 
 253 void MeasureAntennaTuning(int mode
) 
 255         uint8_t LF_Results
[256] = {0}; 
 256         int peakv 
= 0, peakf 
= 0; 
 257         int vLf125 
= 0, vLf134 
= 0, vHf 
= 0; // in mV 
 261         if (((mode 
& FLAG_TUNE_ALL
) == FLAG_TUNE_ALL
) && (FpgaGetCurrent() == FPGA_BITSTREAM_HF
)) { 
 262                 // Reverse "standard" order if HF already loaded, to avoid unnecessary swap. 
 263                 MeasureAntennaTuningHfOnly(&vHf
); 
 264                 MeasureAntennaTuningLfOnly(&vLf125
, &vLf134
, &peakf
, &peakv
, LF_Results
); 
 266                 if (mode 
& FLAG_TUNE_LF
) { 
 267                         MeasureAntennaTuningLfOnly(&vLf125
, &vLf134
, &peakf
, &peakv
, LF_Results
); 
 269                 if (mode 
& FLAG_TUNE_HF
) { 
 270                         MeasureAntennaTuningHfOnly(&vHf
); 
 274         cmd_send(CMD_MEASURED_ANTENNA_TUNING
, vLf125
>>1 | (vLf134
>>1<<16), vHf
, peakf 
| (peakv
>>1<<16), LF_Results
, 256); 
 275         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
 280 void MeasureAntennaTuningHf(void) 
 282         int vHf 
= 0;    // in mV 
 284         DbpString("Measuring HF antenna, press button to exit"); 
 286         // Let the FPGA drive the high-frequency antenna around 13.56 MHz. 
 287         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 288         FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
); 
 292                 vHf 
= AvgAdc_Voltage_HF(); 
 294                 Dbprintf("%d mV",vHf
); 
 295                 if (BUTTON_PRESS()) break; 
 297         DbpString("cancelled"); 
 299         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
 304 void ReadMem(int addr
) 
 306         const uint8_t *data 
= ((uint8_t *)addr
); 
 308         Dbprintf("%x: %02x %02x %02x %02x %02x %02x %02x %02x", 
 309                 addr
, data
[0], data
[1], data
[2], data
[3], data
[4], data
[5], data
[6], data
[7]); 
 312 /* osimage version information is linked in */ 
 313 extern struct version_information version_information
; 
 314 /* bootrom version information is pointed to from _bootphase1_version_pointer */ 
 315 extern char *_bootphase1_version_pointer
, _flash_start
, _flash_end
, _bootrom_start
, _bootrom_end
, __data_src_start__
; 
 318 void set_hw_capabilities(void) 
 320         if (I2C_is_available()) { 
 321                 hw_capabilities 
|= HAS_SMARTCARD_SLOT
; 
 324         if (false) { // TODO: implement a test 
 325                 hw_capabilities 
|= HAS_EXTRA_FLASH_MEM
; 
 330 void SendVersion(void) 
 332         set_hw_capabilities(); 
 334         char temp
[USB_CMD_DATA_SIZE
]; /* Limited data payload in USB packets */ 
 335         char VersionString
[USB_CMD_DATA_SIZE
] = { '\0' }; 
 337         /* Try to find the bootrom version information. Expect to find a pointer at 
 338          * symbol _bootphase1_version_pointer, perform slight sanity checks on the 
 339          * pointer, then use it. 
 341         char *bootrom_version 
= *(char**)&_bootphase1_version_pointer
; 
 342         if( bootrom_version 
< &_flash_start 
|| bootrom_version 
>= &_flash_end 
) { 
 343                 strcat(VersionString
, "bootrom version information appears invalid\n"); 
 345                 FormatVersionInformation(temp
, sizeof(temp
), "bootrom: ", bootrom_version
); 
 346                 strncat(VersionString
, temp
, sizeof(VersionString
) - strlen(VersionString
) - 1); 
 349         FormatVersionInformation(temp
, sizeof(temp
), "os: ", &version_information
); 
 350         strncat(VersionString
, temp
, sizeof(VersionString
) - strlen(VersionString
) - 1); 
 352         for (int i 
= 0; i 
< fpga_bitstream_num
; i
++) { 
 353                 strncat(VersionString
, fpga_version_information
[i
], sizeof(VersionString
) - strlen(VersionString
) - 1); 
 354                 strncat(VersionString
, "\n", sizeof(VersionString
) - strlen(VersionString
) - 1); 
 357         // test availability of SmartCard slot 
 358         if (I2C_is_available()) { 
 359                 strncat(VersionString
, "SmartCard Slot: available\n", sizeof(VersionString
) - strlen(VersionString
) - 1); 
 361                 strncat(VersionString
, "SmartCard Slot: not available\n", sizeof(VersionString
) - strlen(VersionString
) - 1); 
 364         // Send Chip ID and used flash memory 
 365         uint32_t text_and_rodata_section_size 
= (uint32_t)&__data_src_start__ 
- (uint32_t)&_flash_start
; 
 366         uint32_t compressed_data_section_size 
= common_area
.arg1
; 
 367         cmd_send(CMD_ACK
, *(AT91C_DBGU_CIDR
), text_and_rodata_section_size 
+ compressed_data_section_size
, hw_capabilities
, VersionString
, strlen(VersionString
)); 
 370 // measure the USB Speed by sending SpeedTestBufferSize bytes to client and measuring the elapsed time. 
 371 // Note: this mimics GetFromBigbuf(), i.e. we have the overhead of the UsbCommand structure included. 
 372 void printUSBSpeed(void)  
 374         Dbprintf("USB Speed:"); 
 375         Dbprintf("  Sending USB packets to client..."); 
 377         #define USB_SPEED_TEST_MIN_TIME 1500    // in milliseconds 
 378         uint8_t *test_data 
= BigBuf_get_addr(); 
 381         uint32_t start_time 
= end_time 
= GetTickCount(); 
 382         uint32_t bytes_transferred 
= 0; 
 385         while(end_time 
< start_time 
+ USB_SPEED_TEST_MIN_TIME
) { 
 386                 cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
, 0, USB_CMD_DATA_SIZE
, 0, test_data
, USB_CMD_DATA_SIZE
); 
 387                 end_time 
= GetTickCount(); 
 388                 bytes_transferred 
+= USB_CMD_DATA_SIZE
; 
 392         Dbprintf("  Time elapsed:      %dms", end_time 
- start_time
); 
 393         Dbprintf("  Bytes transferred: %d", bytes_transferred
); 
 394         Dbprintf("  USB Transfer Speed PM3 -> Client = %d Bytes/s",  
 395                 1000 * bytes_transferred 
/ (end_time 
- start_time
)); 
 400   * Prints runtime information about the PM3. 
 402 void SendStatus(void) 
 404         BigBuf_print_status(); 
 406 #ifdef WITH_SMARTCARD 
 409         printConfig(); //LF Sampling config 
 412         Dbprintf("  MF_DBGLEVEL........%d", MF_DBGLEVEL
); 
 413         Dbprintf("  ToSendMax..........%d", ToSendMax
); 
 414         Dbprintf("  ToSendBit..........%d", ToSendBit
); 
 416         cmd_send(CMD_ACK
,1,0,0,0,0); 
 419 #if defined(WITH_ISO14443a_StandAlone) || defined(WITH_LF_StandAlone) 
 423 void StandAloneMode() 
 425         DbpString("Stand-alone mode! No PC necessary."); 
 426         // Oooh pretty -- notify user we're in elite samy mode now 
 428         LED(LED_ORANGE
, 200); 
 430         LED(LED_ORANGE
, 200); 
 432         LED(LED_ORANGE
, 200); 
 434         LED(LED_ORANGE
, 200); 
 443 #ifdef WITH_ISO14443a_StandAlone 
 444 void StandAloneMode14a() 
 447         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 450         bool playing 
= false, GotoRecord 
= false, GotoClone 
= false; 
 451         bool cardRead
[OPTS
] = {false}; 
 452         uint8_t readUID
[10] = {0}; 
 453         uint32_t uid_1st
[OPTS
]={0}; 
 454         uint32_t uid_2nd
[OPTS
]={0}; 
 455         uint32_t uid_tmp1 
= 0; 
 456         uint32_t uid_tmp2 
= 0; 
 457         iso14a_card_select_t hi14a_card
[OPTS
]; 
 459         LED(selected 
+ 1, 0); 
 467                 if (GotoRecord 
|| !cardRead
[selected
]) 
 471                         LED(selected 
+ 1, 0); 
 475                         Dbprintf("Enabling iso14443a reader mode for [Bank: %u]...", selected
); 
 476                         /* need this delay to prevent catching some weird data */ 
 478                         /* Code for reading from 14a tag */ 
 479                         uint8_t uid
[10]  ={0}; 
 481                         iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
); 
 486                                 if (BUTTON_PRESS()) { 
 487                                         if (cardRead
[selected
]) { 
 488                                                 Dbprintf("Button press detected -- replaying card in bank[%d]", selected
); 
 491                                         else if (cardRead
[(selected
+1)%OPTS
]) { 
 492                                                 Dbprintf("Button press detected but no card in bank[%d] so playing from bank[%d]", selected
, (selected
+1)%OPTS
); 
 493                                                 selected 
= (selected
+1)%OPTS
; 
 497                                                 Dbprintf("Button press detected but no stored tag to play. (Ignoring button)"); 
 501                                 if (!iso14443a_select_card(uid
, &hi14a_card
[selected
], &cuid
, true, 0, true)) 
 505                                         Dbprintf("Read UID:"); Dbhexdump(10,uid
,0); 
 506                                         memcpy(readUID
,uid
,10*sizeof(uint8_t)); 
 507                                         uint8_t *dst 
= (uint8_t *)&uid_tmp1
; 
 508                                         // Set UID byte order 
 509                                         for (int i
=0; i
<4; i
++) 
 511                                         dst 
= (uint8_t *)&uid_tmp2
; 
 512                                         for (int i
=0; i
<4; i
++) 
 514                                         if (uid_1st
[(selected
+1)%OPTS
] == uid_tmp1 
&& uid_2nd
[(selected
+1)%OPTS
] == uid_tmp2
) { 
 515                                                 Dbprintf("Card selected has same UID as what is stored in the other bank. Skipping."); 
 519                                                         Dbprintf("Bank[%d] received a 7-byte UID",selected
); 
 520                                                         uid_1st
[selected
] = (uid_tmp1
)>>8; 
 521                                                         uid_2nd
[selected
] = (uid_tmp1
<<24) + (uid_tmp2
>>8); 
 524                                                         Dbprintf("Bank[%d] received a 4-byte UID",selected
); 
 525                                                         uid_1st
[selected
] = uid_tmp1
; 
 526                                                         uid_2nd
[selected
] = uid_tmp2
; 
 532                         Dbprintf("ATQA = %02X%02X",hi14a_card
[selected
].atqa
[0],hi14a_card
[selected
].atqa
[1]); 
 533                         Dbprintf("SAK = %02X",hi14a_card
[selected
].sak
); 
 536                         LED(LED_ORANGE
, 200); 
 538                         LED(LED_ORANGE
, 200); 
 541                         LED(selected 
+ 1, 0); 
 543                         // Next state is replay: 
 546                         cardRead
[selected
] = true; 
 548                 /* MF Classic UID clone */ 
 553                         LED(selected 
+ 1, 0); 
 554                         LED(LED_ORANGE
, 250); 
 558                         Dbprintf("Preparing to Clone card [Bank: %x]; uid: %08x", selected
, uid_1st
[selected
]); 
 560                         // wait for button to be released 
 561                         while(BUTTON_PRESS()) 
 563                                 // Delay cloning until card is in place 
 566                         Dbprintf("Starting clone. [Bank: %u]", selected
); 
 567                         // need this delay to prevent catching some weird data 
 569                         // Begin clone function here: 
 570                         /* Example from client/mifarehost.c for commanding a block write for "magic Chinese" cards: 
 571                                         UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}}; 
 572                                         memcpy(c.d.asBytes, data, 16); 
 575                                         Block read is similar: 
 576                                         UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}}; 
 577                                         We need to imitate that call with blockNo 0 to set a uid. 
 579                                         The get and set commands are handled in this file: 
 580                                         // Work with "magic Chinese" card 
 581                                         case CMD_MIFARE_CSETBLOCK: 
 582                                                 MifareCSetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); 
 584                                         case CMD_MIFARE_CGETBLOCK: 
 585                                                 MifareCGetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); 
 588                                 mfCSetUID provides example logic for UID set workflow: 
 589                                         -Read block0 from card in field with MifareCGetBlock() 
 590                                         -Configure new values without replacing reserved bytes 
 591                                                         memcpy(block0, uid, 4); // Copy UID bytes from byte array 
 593                                                         block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 
 594                                                         Bytes 5-7 are reserved SAK and ATQA for mifare classic 
 595                                         -Use mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER) to write it 
 597                         uint8_t oldBlock0
[16] = {0}, newBlock0
[16] = {0}, testBlock0
[16] = {0}; 
 598                         // arg0 = Flags == CSETBLOCK_SINGLE_OPER=0x1F, arg1=returnSlot, arg2=blockNo 
 599                         MifareCGetBlock(0x3F, 1, 0, oldBlock0
); 
 600                         if (oldBlock0
[0] == 0 && oldBlock0
[0] == oldBlock0
[1]  && oldBlock0
[1] == oldBlock0
[2] && oldBlock0
[2] == oldBlock0
[3]) { 
 601                                 Dbprintf("No changeable tag detected. Returning to replay mode for bank[%d]", selected
); 
 605                                 Dbprintf("UID from target tag: %02X%02X%02X%02X", oldBlock0
[0],oldBlock0
[1],oldBlock0
[2],oldBlock0
[3]); 
 606                                 memcpy(newBlock0
,oldBlock0
,16); 
 607                                 // Copy uid_1st for bank (2nd is for longer UIDs not supported if classic) 
 609                                 newBlock0
[0] = uid_1st
[selected
]>>24; 
 610                                 newBlock0
[1] = 0xFF & (uid_1st
[selected
]>>16); 
 611                                 newBlock0
[2] = 0xFF & (uid_1st
[selected
]>>8); 
 612                                 newBlock0
[3] = 0xFF & (uid_1st
[selected
]); 
 613                                 newBlock0
[4] = newBlock0
[0]^newBlock0
[1]^newBlock0
[2]^newBlock0
[3]; 
 614                                 // arg0 = needWipe, arg1 = workFlags, arg2 = blockNo, datain 
 615                                 MifareCSetBlock(0, 0xFF,0, newBlock0
); 
 616                                 MifareCGetBlock(0x3F, 1, 0, testBlock0
); 
 617                                 if (memcmp(testBlock0
,newBlock0
,16)==0) 
 619                                         DbpString("Cloned successfull!"); 
 620                                         cardRead
[selected
] = false; // Only if the card was cloned successfully should we clear it 
 623                                         selected 
= (selected
+1) % OPTS
; 
 626                                         Dbprintf("Clone failed. Back to replay mode on bank[%d]", selected
); 
 631                         LED(selected 
+ 1, 0); 
 634                 // Change where to record (or begin playing) 
 635                 else if (playing
) // button_pressed == BUTTON_SINGLE_CLICK && cardRead[selected]) 
 638                         LED(selected 
+ 1, 0); 
 640                         // Begin transmitting 
 642                         DbpString("Playing"); 
 645                                 int button_action 
= BUTTON_HELD(1000); 
 646                                 if (button_action 
== 0) { // No button action, proceed with sim 
 647                                         uint8_t data
[512] = {0}; // in case there is a read command received we shouldn't break 
 648                                         Dbprintf("Simulating ISO14443a tag with uid[0]: %08x, uid[1]: %08x [Bank: %u]", uid_1st
[selected
],uid_2nd
[selected
],selected
); 
 649                                         if (hi14a_card
[selected
].sak 
== 8 && hi14a_card
[selected
].atqa
[0] == 4 && hi14a_card
[selected
].atqa
[1] == 0) { 
 650                                                 DbpString("Mifare Classic"); 
 651                                                 SimulateIso14443aTag(1,uid_1st
[selected
], uid_2nd
[selected
], data
); // Mifare Classic 
 653                                         else if (hi14a_card
[selected
].sak 
== 0 && hi14a_card
[selected
].atqa
[0] == 0x44 && hi14a_card
[selected
].atqa
[1] == 0) { 
 654                                                 DbpString("Mifare Ultralight"); 
 655                                                 SimulateIso14443aTag(2,uid_1st
[selected
],uid_2nd
[selected
],data
); // Mifare Ultralight 
 657                                         else if (hi14a_card
[selected
].sak 
== 20 && hi14a_card
[selected
].atqa
[0] == 0x44 && hi14a_card
[selected
].atqa
[1] == 3) { 
 658                                                 DbpString("Mifare DESFire"); 
 659                                                 SimulateIso14443aTag(3,uid_1st
[selected
],uid_2nd
[selected
],data
); // Mifare DESFire 
 662                                                 Dbprintf("Unrecognized tag type -- defaulting to Mifare Classic emulation"); 
 663                                                 SimulateIso14443aTag(1,uid_1st
[selected
], uid_2nd
[selected
], data
); 
 666                                 else if (button_action 
== BUTTON_SINGLE_CLICK
) { 
 667                                         selected 
= (selected 
+ 1) % OPTS
; 
 668                                         Dbprintf("Done playing. Switching to record mode on bank %d",selected
); 
 672                                 else if (button_action 
== BUTTON_HOLD
) { 
 673                                         Dbprintf("Playtime over. Begin cloning..."); 
 680                         /* We pressed a button so ignore it here with a delay */ 
 683                         LED(selected 
+ 1, 0); 
 687 #elif WITH_LF_StandAlone 
 688 // samy's sniff and repeat routine 
 692         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
 694         int tops
[OPTS
], high
[OPTS
], low
[OPTS
]; 
 699         // Turn on selected LED 
 700         LED(selected 
+ 1, 0); 
 707                 // Was our button held down or pressed? 
 708                 int button_pressed 
= BUTTON_HELD(1000); 
 711                 // Button was held for a second, begin recording 
 712                 if (button_pressed 
> 0 && cardRead 
== 0) 
 715                         LED(selected 
+ 1, 0); 
 719                         DbpString("Starting recording"); 
 721                         // wait for button to be released 
 722                         while(BUTTON_PRESS()) 
 725                         /* need this delay to prevent catching some weird data */ 
 728                         CmdHIDdemodFSK(1, &tops
[selected
], &high
[selected
], &low
[selected
], 0); 
 729                         if (tops
[selected
] > 0) 
 730                                 Dbprintf("Recorded %x %x%08x%08x", selected
, tops
[selected
], high
[selected
], low
[selected
]); 
 732                                 Dbprintf("Recorded %x %x%08x", selected
, high
[selected
], low
[selected
]); 
 735                         LED(selected 
+ 1, 0); 
 736                         // Finished recording 
 738                         // If we were previously playing, set playing off 
 739                         // so next button push begins playing what we recorded 
 746                 else if (button_pressed 
> 0 && cardRead 
== 1) 
 749                                         LED(selected 
+ 1, 0); 
 753                                         if (tops
[selected
] > 0) 
 754                                                 Dbprintf("Cloning %x %x%08x%08x", selected
, tops
[selected
], high
[selected
], low
[selected
]); 
 756                                                 Dbprintf("Cloning %x %x%08x", selected
, high
[selected
], low
[selected
]); 
 758                                         // wait for button to be released 
 759                                         while(BUTTON_PRESS()) 
 762                                         /* need this delay to prevent catching some weird data */ 
 765                                         CopyHIDtoT55x7(tops
[selected
] & 0x000FFFFF, high
[selected
], low
[selected
], (tops
[selected
] != 0 && ((high
[selected
]& 0xFFFFFFC0) != 0)), 0x1D); 
 766                                         if (tops
[selected
] > 0) 
 767                                                 Dbprintf("Cloned %x %x%08x%08x", selected
, tops
[selected
], high
[selected
], low
[selected
]); 
 769                                                 Dbprintf("Cloned %x %x%08x", selected
, high
[selected
], low
[selected
]); 
 772                                         LED(selected 
+ 1, 0); 
 773                                         // Finished recording 
 775                                         // If we were previously playing, set playing off 
 776                                         // so next button push begins playing what we recorded 
 783                 // Change where to record (or begin playing) 
 784                 else if (button_pressed
) 
 786                         // Next option if we were previously playing 
 788                                 selected 
= (selected 
+ 1) % OPTS
; 
 792                         LED(selected 
+ 1, 0); 
 794                         // Begin transmitting 
 798                                 DbpString("Playing"); 
 799                                 // wait for button to be released 
 800                                 while(BUTTON_PRESS()) 
 802                                 if (tops
[selected
] > 0) 
 803                                         Dbprintf("%x %x%08x%08x", selected
, tops
[selected
], high
[selected
], low
[selected
]); 
 805                                         Dbprintf("%x %x%08x", selected
, high
[selected
], low
[selected
]); 
 807                                 CmdHIDsimTAG(tops
[selected
], high
[selected
], low
[selected
], 0); 
 808                                 DbpString("Done playing"); 
 809                                 if (BUTTON_HELD(1000) > 0) 
 811                                         DbpString("Exiting"); 
 816                                 /* We pressed a button so ignore it here with a delay */ 
 819                                 // when done, we're done playing, move to next option 
 820                                 selected 
= (selected 
+ 1) % OPTS
; 
 823                                 LED(selected 
+ 1, 0); 
 826                                 while(BUTTON_PRESS()) 
 835 Listen and detect an external reader. Determine the best location 
 839 Inside the ListenReaderField() function, there is two mode. 
 840 By default, when you call the function, you will enter mode 1. 
 841 If you press the PM3 button one time, you will enter mode 2. 
 842 If you press the PM3 button a second time, you will exit the function. 
 844 DESCRIPTION OF MODE 1: 
 845 This mode just listens for an external reader field and lights up green 
 846 for HF and/or red for LF. This is the original mode of the detectreader 
 849 DESCRIPTION OF MODE 2: 
 850 This mode will visually represent, using the LEDs, the actual strength of the 
 851 current compared to the maximum current detected. Basically, once you know 
 852 what kind of external reader is present, it will help you spot the best location to place 
 853 your antenna. You will probably not get some good results if there is a LF and a HF reader 
 854 at the same place! :-) 
 858 static const char LIGHT_SCHEME
[] = { 
 859                 0x0, /* ----     | No field detected */ 
 860                 0x1, /* X---     | 14% of maximum current detected */ 
 861                 0x2, /* -X--     | 29% of maximum current detected */ 
 862                 0x4, /* --X-     | 43% of maximum current detected */ 
 863                 0x8, /* ---X     | 57% of maximum current detected */ 
 864                 0xC, /* --XX     | 71% of maximum current detected */ 
 865                 0xE, /* -XXX     | 86% of maximum current detected */ 
 866                 0xF, /* XXXX     | 100% of maximum current detected */ 
 868 static const int LIGHT_LEN 
= sizeof(LIGHT_SCHEME
)/sizeof(LIGHT_SCHEME
[0]); 
 870 void ListenReaderField(int limit
) 
 872         int lf_av
, lf_av_new
=0, lf_baseline
= 0, lf_max
; 
 873         int hf_av
, hf_av_new
=0,  hf_baseline
= 0, hf_max
; 
 874         int mode
=1, display_val
, display_max
, i
; 
 878 #define REPORT_CHANGE_PERCENT      5    // report new values only if they have changed at least by REPORT_CHANGE_PERCENT 
 879 #define MIN_HF_FIELD             300    // in mode 1 signal HF field greater than MIN_HF_FIELD above baseline 
 880 #define MIN_LF_FIELD            1200    // in mode 1 signal LF field greater than MIN_LF_FIELD above baseline 
 883         // switch off FPGA - we don't want to measure our own signal 
 884         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
 885         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
 889         lf_av 
= lf_max 
= AvgAdc_Voltage_LF(); 
 891         if(limit 
!= HF_ONLY
) { 
 892                 Dbprintf("LF 125/134kHz Baseline: %dmV", lf_av
); 
 896         hf_av 
= hf_max 
= AvgAdc_Voltage_HF(); 
 898         if (limit 
!= LF_ONLY
) { 
 899                 Dbprintf("HF 13.56MHz Baseline: %dmV", hf_av
); 
 905                 if (BUTTON_PRESS()) { 
 909                                         DbpString("Signal Strength Mode"); 
 913                                         DbpString("Stopped"); 
 918                         while (BUTTON_PRESS()); 
 922                 if (limit 
!= HF_ONLY
) { 
 924                                 if (lf_av 
- lf_baseline 
> MIN_LF_FIELD
) 
 930                         lf_av_new 
= AvgAdc_Voltage_LF(); 
 931                         // see if there's a significant change 
 932                         if (ABS((lf_av 
- lf_av_new
)*100/(lf_av
?lf_av
:1)) > REPORT_CHANGE_PERCENT
) { 
 933                                 Dbprintf("LF 125/134kHz Field Change: %5dmV", lf_av_new
); 
 940                 if (limit 
!= LF_ONLY
) { 
 942                                 if (hf_av 
- hf_baseline 
> MIN_HF_FIELD
) 
 948                         hf_av_new 
= AvgAdc_Voltage_HF(); 
 950                         // see if there's a significant change 
 951                         if (ABS((hf_av 
- hf_av_new
)*100/(hf_av
?hf_av
:1)) > REPORT_CHANGE_PERCENT
) { 
 952                                 Dbprintf("HF 13.56MHz Field Change: %5dmV", hf_av_new
); 
 960                         if (limit 
== LF_ONLY
) { 
 962                                 display_max 
= lf_max
; 
 963                         } else if (limit 
== HF_ONLY
) { 
 965                                 display_max 
= hf_max
; 
 966                         } else { /* Pick one at random */ 
 967                                 if( (hf_max 
- hf_baseline
) > (lf_max 
- lf_baseline
) ) { 
 969                                         display_max 
= hf_max
; 
 972                                         display_max 
= lf_max
; 
 975                         for (i
=0; i
<LIGHT_LEN
; i
++) { 
 976                                 if (display_val 
>= ((display_max
/LIGHT_LEN
)*i
) && display_val 
<= ((display_max
/LIGHT_LEN
)*(i
+1))) { 
 977                                         if (LIGHT_SCHEME
[i
] & 0x1) LED_C_ON(); else LED_C_OFF(); 
 978                                         if (LIGHT_SCHEME
[i
] & 0x2) LED_A_ON(); else LED_A_OFF(); 
 979                                         if (LIGHT_SCHEME
[i
] & 0x4) LED_B_ON(); else LED_B_OFF(); 
 980                                         if (LIGHT_SCHEME
[i
] & 0x8) LED_D_ON(); else LED_D_OFF(); 
 988 void UsbPacketReceived(uint8_t *packet
, int len
) 
 990         UsbCommand 
*c 
= (UsbCommand 
*)packet
; 
 992 //  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]); 
 996                 case CMD_SET_LF_SAMPLING_CONFIG
: 
 997                         setSamplingConfig((sample_config 
*) c
->d
.asBytes
); 
 999                 case CMD_ACQUIRE_RAW_ADC_SAMPLES_125K
: 
1000                         cmd_send(CMD_ACK
,SampleLF(c
->arg
[0], c
->arg
[1]),0,0,0,0); 
1002                 case CMD_MOD_THEN_ACQUIRE_RAW_ADC_SAMPLES_125K
: 
1003                         ModThenAcquireRawAdcSamples125k(c
->arg
[0],c
->arg
[1],c
->arg
[2],c
->d
.asBytes
); 
1005                 case CMD_LF_SNOOP_RAW_ADC_SAMPLES
: 
1006                         cmd_send(CMD_ACK
,SnoopLF(),0,0,0,0); 
1008                 case CMD_HID_DEMOD_FSK
: 
1009                         CmdHIDdemodFSK(c
->arg
[0], 0, 0, 0, 1); 
1011                 case CMD_HID_SIM_TAG
: 
1012                         CmdHIDsimTAG(c
->arg
[0], c
->arg
[1], c
->arg
[2], 1); 
1014                 case CMD_FSK_SIM_TAG
: 
1015                         CmdFSKsimTAG(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1017                 case CMD_ASK_SIM_TAG
: 
1018                         CmdASKsimTag(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1020                 case CMD_PSK_SIM_TAG
: 
1021                         CmdPSKsimTag(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1023                 case CMD_HID_CLONE_TAG
: 
1024                         CopyHIDtoT55x7(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
[0], 0x1D); 
1026                 case CMD_PARADOX_CLONE_TAG
: 
1027                         // Paradox cards are the same as HID, with a different preamble, so we can reuse the same function 
1028                         CopyHIDtoT55x7(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
[0], 0x0F); 
1030                 case CMD_IO_DEMOD_FSK
: 
1031                         CmdIOdemodFSK(c
->arg
[0], 0, 0, 1); 
1033                 case CMD_IO_CLONE_TAG
: 
1034                         CopyIOtoT55x7(c
->arg
[0], c
->arg
[1]); 
1036                 case CMD_EM410X_DEMOD
: 
1037                         CmdEM410xdemod(c
->arg
[0], 0, 0, 1); 
1039                 case CMD_EM410X_WRITE_TAG
: 
1040                         WriteEM410x(c
->arg
[0], c
->arg
[1], c
->arg
[2]); 
1042                 case CMD_READ_TI_TYPE
: 
1045                 case CMD_WRITE_TI_TYPE
: 
1046                         WriteTItag(c
->arg
[0],c
->arg
[1],c
->arg
[2]); 
1048                 case CMD_SIMULATE_TAG_125K
: 
1050                         SimulateTagLowFrequency(c
->arg
[0], c
->arg
[1], 1); 
1053                 case CMD_LF_SIMULATE_BIDIR
: 
1054                         SimulateTagLowFrequencyBidir(c
->arg
[0], c
->arg
[1]); 
1056                 case CMD_INDALA_CLONE_TAG
: 
1057                         CopyIndala64toT55x7(c
->arg
[0], c
->arg
[1]);                                       
1059                 case CMD_INDALA_CLONE_TAG_L
: 
1060                         CopyIndala224toT55x7(c
->d
.asDwords
[0], c
->d
.asDwords
[1], c
->d
.asDwords
[2], c
->d
.asDwords
[3], c
->d
.asDwords
[4], c
->d
.asDwords
[5], c
->d
.asDwords
[6]); 
1062                 case CMD_T55XX_READ_BLOCK
: 
1063                         T55xxReadBlock(c
->arg
[0], c
->arg
[1], c
->arg
[2]); 
1065                 case CMD_T55XX_WRITE_BLOCK
: 
1066                         T55xxWriteBlock(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
[0]); 
1068                 case CMD_T55XX_WAKEUP
: 
1069                         T55xxWakeUp(c
->arg
[0]); 
1071                 case CMD_T55XX_RESET_READ
: 
1074                 case CMD_PCF7931_READ
: 
1077                 case CMD_PCF7931_WRITE
: 
1078                         WritePCF7931(c
->d
.asBytes
[0],c
->d
.asBytes
[1],c
->d
.asBytes
[2],c
->d
.asBytes
[3],c
->d
.asBytes
[4],c
->d
.asBytes
[5],c
->d
.asBytes
[6], c
->d
.asBytes
[9], c
->d
.asBytes
[7]-128,c
->d
.asBytes
[8]-128, c
->arg
[0], c
->arg
[1], c
->arg
[2]); 
1080                 case CMD_PCF7931_BRUTEFORCE
: 
1081                         BruteForcePCF7931(c
->arg
[0], (c
->arg
[1] & 0xFF), c
->d
.asBytes
[9], c
->d
.asBytes
[7]-128,c
->d
.asBytes
[8]-128); 
1083                 case CMD_EM4X_READ_WORD
: 
1084                         EM4xReadWord(c
->arg
[0], c
->arg
[1],c
->arg
[2]); 
1086                 case CMD_EM4X_WRITE_WORD
: 
1087                         EM4xWriteWord(c
->arg
[0], c
->arg
[1], c
->arg
[2]); 
1089                 case CMD_AWID_DEMOD_FSK
: // Set realtime AWID demodulation 
1090                         CmdAWIDdemodFSK(c
->arg
[0], 0, 0, 1); 
1092                 case CMD_VIKING_CLONE_TAG
: 
1093                         CopyVikingtoT55xx(c
->arg
[0], c
->arg
[1], c
->arg
[2]); 
1101                 case CMD_SNOOP_HITAG
: // Eavesdrop Hitag tag, args = type 
1102                         SnoopHitag(c
->arg
[0]); 
1104                 case CMD_SIMULATE_HITAG
: // Simulate Hitag tag, args = memory content 
1105                         SimulateHitagTag((bool)c
->arg
[0],(byte_t
*)c
->d
.asBytes
); 
1107                 case CMD_READER_HITAG
: // Reader for Hitag tags, args = type and function 
1108                         ReaderHitag((hitag_function
)c
->arg
[0],(hitag_data
*)c
->d
.asBytes
); 
1110                 case CMD_SIMULATE_HITAG_S
:// Simulate Hitag s tag, args = memory content 
1111                         SimulateHitagSTag((bool)c
->arg
[0],(byte_t
*)c
->d
.asBytes
); 
1113                 case CMD_TEST_HITAGS_TRACES
:// Tests every challenge within the given file 
1114                         check_challenges_cmd((bool)c
->arg
[0], (byte_t
*)c
->d
.asBytes
, (uint8_t)c
->arg
[1]); 
1116                 case CMD_READ_HITAG_S
://Reader for only Hitag S tags, args = key or challenge 
1117                         ReadHitagSCmd((hitag_function
)c
->arg
[0], (hitag_data
*)c
->d
.asBytes
, (uint8_t)c
->arg
[1], (uint8_t)c
->arg
[2], false); 
1119                 case CMD_READ_HITAG_S_BLK
: 
1120                         ReadHitagSCmd((hitag_function
)c
->arg
[0], (hitag_data
*)c
->d
.asBytes
, (uint8_t)c
->arg
[1], (uint8_t)c
->arg
[2], true); 
1122                 case CMD_WR_HITAG_S
://writer for Hitag tags args=data to write,page and key or challenge 
1123                         if ((hitag_function
)c
->arg
[0] < 10) { 
1124                                 WritePageHitagS((hitag_function
)c
->arg
[0],(hitag_data
*)c
->d
.asBytes
,c
->arg
[2]); 
1126                         else if ((hitag_function
)c
->arg
[0] >= 10) { 
1127                           WriterHitag((hitag_function
)c
->arg
[0],(hitag_data
*)c
->d
.asBytes
, c
->arg
[2]); 
1132 #ifdef WITH_ISO15693 
1133                 case CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_15693
: 
1134                         AcquireRawAdcSamplesIso15693(); 
1137                 case CMD_SNOOP_ISO_15693
: 
1141                 case CMD_ISO_15693_COMMAND
: 
1142                         DirectTag15693Command(c
->arg
[0],c
->arg
[1],c
->arg
[2],c
->d
.asBytes
); 
1145                 case CMD_ISO_15693_FIND_AFI
: 
1146                         BruteforceIso15693Afi(c
->arg
[0]); 
1149                 case CMD_ISO_15693_DEBUG
: 
1150                         SetDebugIso15693(c
->arg
[0]); 
1153                 case CMD_READER_ISO_15693
: 
1154                         ReaderIso15693(c
->arg
[0]); 
1156                 case CMD_SIMTAG_ISO_15693
: 
1157                         SimTagIso15693(c
->arg
[0], c
->d
.asBytes
); 
1162                 case CMD_SIMULATE_TAG_LEGIC_RF
: 
1163                         LegicRfSimulate(c
->arg
[0]); 
1166                 case CMD_WRITER_LEGIC_RF
: 
1167                         LegicRfWriter(c
->arg
[1], c
->arg
[0]); 
1170                 case CMD_READER_LEGIC_RF
: 
1171                         LegicRfReader(c
->arg
[0], c
->arg
[1]); 
1175 #ifdef WITH_ISO14443b 
1176                 case CMD_READ_SRI512_TAG
: 
1177                         ReadSTMemoryIso14443b(0x0F); 
1179                 case CMD_READ_SRIX4K_TAG
: 
1180                         ReadSTMemoryIso14443b(0x7F); 
1182                 case CMD_SNOOP_ISO_14443B
: 
1185                 case CMD_SIMULATE_TAG_ISO_14443B
: 
1186                         SimulateIso14443bTag(); 
1188                 case CMD_ISO_14443B_COMMAND
: 
1189                         SendRawCommand14443B(c
->arg
[0],c
->arg
[1],c
->arg
[2],c
->d
.asBytes
); 
1193 #ifdef WITH_ISO14443a 
1194                 case CMD_SNOOP_ISO_14443a
: 
1195                         SnoopIso14443a(c
->arg
[0]); 
1197                 case CMD_READER_ISO_14443a
: 
1200                 case CMD_SIMULATE_TAG_ISO_14443a
: 
1201                         SimulateIso14443aTag(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
);  // ## Simulate iso14443a tag - pass tag type & UID 
1204                 case CMD_EPA_PACE_COLLECT_NONCE
: 
1205                         EPA_PACE_Collect_Nonce(c
); 
1207                 case CMD_EPA_PACE_REPLAY
: 
1211                 case CMD_READER_MIFARE
: 
1212                         ReaderMifare(c
->arg
[0]); 
1214                 case CMD_MIFARE_READBL
: 
1215                         MifareReadBlock(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1217                 case CMD_MIFAREU_READBL
: 
1218                         MifareUReadBlock(c
->arg
[0],c
->arg
[1], c
->d
.asBytes
); 
1220                 case CMD_MIFAREUC_AUTH
: 
1221                         MifareUC_Auth(c
->arg
[0],c
->d
.asBytes
); 
1223                 case CMD_MIFAREU_READCARD
: 
1224                         MifareUReadCard(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1226                 case CMD_MIFAREUC_SETPWD
:  
1227                         MifareUSetPwd(c
->arg
[0], c
->d
.asBytes
); 
1229                 case CMD_MIFARE_READSC
: 
1230                         MifareReadSector(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1232                 case CMD_MIFARE_WRITEBL
: 
1233                         MifareWriteBlock(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1235                 //case CMD_MIFAREU_WRITEBL_COMPAT: 
1236                         //MifareUWriteBlockCompat(c->arg[0], c->d.asBytes); 
1238                 case CMD_MIFAREU_WRITEBL
: 
1239                         MifareUWriteBlock(c
->arg
[0], c
->arg
[1], c
->d
.asBytes
); 
1241                 case CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES
: 
1242                         MifareAcquireEncryptedNonces(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1244                 case CMD_MIFARE_NESTED
: 
1245                         MifareNested(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1247                 case CMD_MIFARE_CHKKEYS
: 
1248                         MifareChkKeys(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1250                 case CMD_SIMULATE_MIFARE_CARD
: 
1251                         Mifare1ksim(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1255                 case CMD_MIFARE_SET_DBGMODE
: 
1256                         MifareSetDbgLvl(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1258                 case CMD_MIFARE_EML_MEMCLR
: 
1259                         MifareEMemClr(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1261                 case CMD_MIFARE_EML_MEMSET
: 
1262                         MifareEMemSet(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1264                 case CMD_MIFARE_EML_MEMGET
: 
1265                         MifareEMemGet(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1267                 case CMD_MIFARE_EML_CARDLOAD
: 
1268                         MifareECardLoad(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1271                 // Work with "magic Chinese" card 
1272                 case CMD_MIFARE_CWIPE
: 
1273                         MifareCWipe(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1275                 case CMD_MIFARE_CSETBLOCK
: 
1276                         MifareCSetBlock(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1278                 case CMD_MIFARE_CGETBLOCK
: 
1279                         MifareCGetBlock(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1281                 case CMD_MIFARE_CIDENT
: 
1286                 case CMD_MIFARE_SNIFFER
: 
1287                         SniffMifare(c
->arg
[0]); 
1293                 // Makes use of ISO14443a FPGA Firmware 
1294                 case CMD_SNOOP_ICLASS
: 
1297                 case CMD_SIMULATE_TAG_ICLASS
: 
1298                         SimulateIClass(c
->arg
[0], c
->arg
[1], c
->arg
[2], c
->d
.asBytes
); 
1300                 case CMD_READER_ICLASS
: 
1301                         ReaderIClass(c
->arg
[0]); 
1303                 case CMD_READER_ICLASS_REPLAY
: 
1304                         ReaderIClass_Replay(c
->arg
[0], c
->d
.asBytes
); 
1306                 case CMD_ICLASS_EML_MEMSET
: 
1307                         emlSet(c
->d
.asBytes
,c
->arg
[0], c
->arg
[1]); 
1309                 case CMD_ICLASS_WRITEBLOCK
: 
1310                         iClass_WriteBlock(c
->arg
[0], c
->d
.asBytes
); 
1312                 case CMD_ICLASS_READCHECK
:  // auth step 1 
1313                         iClass_ReadCheck(c
->arg
[0], c
->arg
[1]); 
1315                 case CMD_ICLASS_READBLOCK
: 
1316                         iClass_ReadBlk(c
->arg
[0]); 
1318                 case CMD_ICLASS_AUTHENTICATION
: //check 
1319                         iClass_Authentication(c
->d
.asBytes
); 
1321                 case CMD_ICLASS_DUMP
: 
1322                         iClass_Dump(c
->arg
[0], c
->arg
[1]); 
1324                 case CMD_ICLASS_CLONE
: 
1325                         iClass_Clone(c
->arg
[0], c
->arg
[1], c
->d
.asBytes
); 
1330                 case CMD_HF_SNIFFER
: 
1331                         HfSnoop(c
->arg
[0], c
->arg
[1]); 
1338 #ifdef WITH_SMARTCARD 
1339                 case CMD_SMART_ATR
: { 
1343                 case CMD_SMART_SETCLOCK
:{ 
1344                         SmartCardSetClock(c
->arg
[0]); 
1347                 case CMD_SMART_RAW
: { 
1348                         SmartCardRaw(c
->arg
[0], c
->arg
[1], c
->d
.asBytes
); 
1351                 case CMD_SMART_UPLOAD
: { 
1352                         // upload file from client 
1353                         uint8_t *mem 
= BigBuf_get_addr(); 
1354                         memcpy( mem 
+ c
->arg
[0], c
->d
.asBytes
, USB_CMD_DATA_SIZE
); 
1355                         cmd_send(CMD_ACK
,1,0,0,0,0); 
1358                 case CMD_SMART_UPGRADE
: { 
1359                         SmartCardUpgrade(c
->arg
[0]); 
1364                 case CMD_BUFF_CLEAR
: 
1368                 case CMD_MEASURE_ANTENNA_TUNING
: 
1369                         MeasureAntennaTuning(c
->arg
[0]); 
1372                 case CMD_MEASURE_ANTENNA_TUNING_HF
: 
1373                         MeasureAntennaTuningHf(); 
1376                 case CMD_LISTEN_READER_FIELD
: 
1377                         ListenReaderField(c
->arg
[0]); 
1380                 case CMD_FPGA_MAJOR_MODE_OFF
:           // ## FPGA Control 
1381                         FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
); 
1383                         LED_D_OFF(); // LED D indicates field ON or OFF 
1386                 case CMD_DOWNLOAD_RAW_ADC_SAMPLES_125K
: 
1388                         uint8_t *BigBuf 
= BigBuf_get_addr(); 
1389                         for(size_t i
=0; i
<c
->arg
[1]; i 
+= USB_CMD_DATA_SIZE
) { 
1390                                 size_t len 
= MIN((c
->arg
[1] - i
),USB_CMD_DATA_SIZE
); 
1391                                 cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K
,i
,len
,BigBuf_get_traceLen(),BigBuf
+c
->arg
[0]+i
,len
); 
1393                         // Trigger a finish downloading signal with an ACK frame 
1394                         cmd_send(CMD_ACK
,1,0,BigBuf_get_traceLen(),getSamplingConfig(),sizeof(sample_config
)); 
1398                 case CMD_DOWNLOADED_SIM_SAMPLES_125K
: { 
1399                         // iceman; since changing fpga_bitstreams clears bigbuff, Its better to call it before. 
1400                         // to be able to use this one for uploading data to device  
1401                         // arg1 = 0 upload for LF usage  
1402                         //        1 upload for HF usage 
1404                                 FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1406                                 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
1408                         uint8_t *b 
= BigBuf_get_addr(); 
1409                         memcpy(b
+c
->arg
[0], c
->d
.asBytes
, USB_CMD_DATA_SIZE
); 
1410                         cmd_send(CMD_ACK
,0,0,0,0,0); 
1417                 case CMD_SET_LF_DIVISOR
: 
1418                         FpgaDownloadAndGo(FPGA_BITSTREAM_LF
); 
1419                         FpgaSendCommand(FPGA_CMD_SET_DIVISOR
, c
->arg
[0]); 
1422                 case CMD_SET_ADC_MUX
: 
1424                                 case 0: SetAdcMuxFor(GPIO_MUXSEL_LOPKD
); break; 
1425                                 case 1: SetAdcMuxFor(GPIO_MUXSEL_LORAW
); break; 
1426                                 case 2: SetAdcMuxFor(GPIO_MUXSEL_HIPKD
); break; 
1427                                 case 3: SetAdcMuxFor(GPIO_MUXSEL_HIRAW
); break; 
1438                         cmd_send(CMD_ACK
,0,0,0,0,0); 
1448                 case CMD_SETUP_WRITE
: 
1449                 case CMD_FINISH_WRITE
: 
1450                 case CMD_HARDWARE_RESET
: 
1454                         AT91C_BASE_RSTC
->RSTC_RCR 
= RST_CONTROL_KEY 
| AT91C_RSTC_PROCRST
; 
1456                                 // We're going to reset, and the bootrom will take control. 
1460                 case CMD_START_FLASH
: 
1461                         if(common_area
.flags
.bootrom_present
) { 
1462                                 common_area
.command 
= COMMON_AREA_COMMAND_ENTER_FLASH_MODE
; 
1465                         AT91C_BASE_RSTC
->RSTC_RCR 
= RST_CONTROL_KEY 
| AT91C_RSTC_PROCRST
; 
1469                 case CMD_DEVICE_INFO
: { 
1470                         uint32_t dev_info 
= DEVICE_INFO_FLAG_OSIMAGE_PRESENT 
| DEVICE_INFO_FLAG_CURRENT_MODE_OS
; 
1471                         if(common_area
.flags
.bootrom_present
) dev_info 
|= DEVICE_INFO_FLAG_BOOTROM_PRESENT
; 
1472                         cmd_send(CMD_DEVICE_INFO
,dev_info
,0,0,0,0);      
1476                         Dbprintf("%s: 0x%04x","unknown command:",c
->cmd
); 
1481 void  __attribute__((noreturn
)) AppMain(void) 
1485         if(common_area
.magic 
!= COMMON_AREA_MAGIC 
|| common_area
.version 
!= 1) { 
1486                 /* Initialize common area */ 
1487                 memset(&common_area
, 0, sizeof(common_area
)); 
1488                 common_area
.magic 
= COMMON_AREA_MAGIC
; 
1489                 common_area
.version 
= 1; 
1491         common_area
.flags
.osimage_present 
= 1; 
1501         // The FPGA gets its clock from us from PCK0 output, so set that up. 
1502         AT91C_BASE_PIOA
->PIO_BSR 
= GPIO_PCK0
; 
1503         AT91C_BASE_PIOA
->PIO_PDR 
= GPIO_PCK0
; 
1504         AT91C_BASE_PMC
->PMC_SCER 
= AT91C_PMC_PCK0
; 
1505         // PCK0 is PLL clock / 4 = 96Mhz / 4 = 24Mhz 
1506         AT91C_BASE_PMC
->PMC_PCKR
[0] = AT91C_PMC_CSS_PLL_CLK 
| 
1507                 AT91C_PMC_PRES_CLK_4
; //  4 for 24Mhz pck0, 2 for 48 MHZ pck0 
1508         AT91C_BASE_PIOA
->PIO_OER 
= GPIO_PCK0
; 
1511         AT91C_BASE_SPI
->SPI_CR 
= AT91C_SPI_SWRST
; 
1513         AT91C_BASE_SSC
->SSC_CR 
= AT91C_SSC_SWRST
; 
1515         // Load the FPGA image, which we have stored in our flash. 
1516         // (the HF version by default) 
1517         FpgaDownloadAndGo(FPGA_BITSTREAM_HF
); 
1525   byte_t rx
[sizeof(UsbCommand
)]; 
1530       rx_len 
= usb_read(rx
,sizeof(UsbCommand
)); 
1532         UsbPacketReceived(rx
,rx_len
); 
1537 #ifdef WITH_LF_StandAlone 
1538 #ifndef WITH_ISO14443a_StandAlone 
1539                 if (BUTTON_HELD(1000) > 0) 
1543 #ifdef WITH_ISO14443a 
1544 #ifdef WITH_ISO14443a_StandAlone 
1545                 if (BUTTON_HELD(1000) > 0) 
1546                         StandAloneMode14a();