when you need to add too much changes at the same time...

fix: 'hf mf hardnested'  test cases doesn't need to verify key.
add: 'hf mf ' - collect nonces from classic tag.
chg: switch_off on armside,  a more unified way,  so we don't forget to turn of the antenna ...
chg:  renamed 'hf iclass snoop'  into 'hf iclass sniff'   in an attempt to make all sniff/snoop commands only SNIFF

chg: 'standalone' ->  starting the work of moving all standalone mods into a plugin kind of style, in its own folder.
This commit is contained in:
iceman1001
2017-08-26 12:57:18 +02:00
parent 26f786bfe4
commit 94f70caa7a
17 changed files with 968 additions and 1142 deletions
+4 -3
View File
@@ -21,15 +21,13 @@ APP_CFLAGS = -DWITH_CRC \
-DWITH_ISO14443a \
-DWITH_ICLASS \
-DWITH_HFSNOOP \
-DWITH_HF_YOUNG \
-DWITH_LF_SAMYRUN \
-fno-strict-aliasing -ffunction-sections -fdata-sections
### IMPORTANT - move the commented variable below this line
# -DWITH_LCD \
#
# Standalone Mods
#-------------------------------------------------------
# -DWITH_ICEMAN
# -DWITH_LF_ICERUN
# -DWITH_LF_SAMYRUN
# -DWITH_LF_PROXBRUTE
# -DWITH_LF_HIDCORP
@@ -78,6 +76,9 @@ THUMBSRC = start.c \
random.c \
hfsnoop.c
# Standalone/hf_young.c \
# Standalone/lf_samyrun.c
# These are to be compiled in ARM mode
ARMSRC = fpgaloader.c \
$(SRC_ISO14443a) \
+53 -456
View File
File diff suppressed because it is too large Load Diff
+6 -2
View File
@@ -30,6 +30,7 @@ extern "C" {
#include "desfire.h"
#include "iso14443b.h"
#include "emvcard.h"
#include "Standalone/standalone.h"
extern const uint8_t OddByteParity[256];
extern int rsamples; // = 0;
@@ -43,7 +44,6 @@ extern uint8_t trigger;
/// appmain.h
void ReadMem(int addr);
void __attribute__((noreturn)) AppMain(void);
void SamyRun(void);
//void DbpIntegers(int a, int b, int c);
void DbpString(char *str);
void Dbprintf(const char *fmt, ...);
@@ -64,6 +64,9 @@ void ListenReaderField(int limit);
extern int ToSendMax;
extern uint8_t ToSend[];
extern void StandAloneMode(void);
extern void printStandAloneModes(void);
/// lfops.h
extern uint8_t decimation;
extern uint8_t bits_per_sample ;
@@ -139,6 +142,7 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain);
void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain);
void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain);
void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain);
void MifareSetDbgLvl(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
@@ -195,7 +199,7 @@ void DirectTag15693Command(uint32_t datalen,uint32_t speed, uint32_t recv, uint8
void SetDebugIso15693(uint32_t flag);
// iclass.h
void RAMFUNC SnoopIClass(void);
void RAMFUNC SniffIClass(void);
void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain);
void ReaderIClass(uint8_t arg0);
void ReaderIClass_Replay(uint8_t arg0,uint8_t *MAC);
+54 -63
View File
@@ -11,6 +11,7 @@
//-----------------------------------------------------------------------------
#include "fpgaloader.h"
extern void DbpString(char *str);
extern void Dbprintf(const char *fmt, ...);
// remember which version of the bitstream we have already downloaded to the FPGA
@@ -32,8 +33,7 @@ static const uint8_t _bitparse_fixed_header[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0
// Used to write the FPGA config word
// May also be used to write to other SPI attached devices like an LCD
//-----------------------------------------------------------------------------
void SetupSpi(int mode)
{
void SetupSpi(int mode) {
// PA10 -> SPI_NCS2 chip select (LCD)
// PA11 -> SPI_NCS0 chip select (FPGA)
// PA12 -> SPI_MISO Master-In Slave-Out
@@ -163,13 +163,11 @@ bool FpgaSetupSscDma(uint8_t *buf, int len) {
return true;
}
//----------------------------------------------------------------------------
// Uncompress (inflate) the FPGA data. Returns one decompressed byte with
// each call.
//----------------------------------------------------------------------------
static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer)
{
static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8_t *output_buffer) {
if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data
compressed_fpga_stream->next_out = output_buffer;
compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN;
@@ -182,9 +180,7 @@ static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8
if (res < 0)
return res;
}
uncompressed_bytes_cnt++;
return *fpga_image_ptr++;
}
@@ -193,8 +189,7 @@ static int get_from_fpga_combined_stream(z_streamp compressed_fpga_stream, uint8
// are combined into one big file:
// 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc.
//----------------------------------------------------------------------------
static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
{
static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) {
while((uncompressed_bytes_cnt / FPGA_INTERLEAVE_SIZE) % FPGA_BITSTREAM_MAX != (bitstream_version - 1)) {
// skip undesired data belonging to other bitstream_versions
get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer);
@@ -203,25 +198,19 @@ static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga
return get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer);
}
static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size)
{
static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size) {
return BigBuf_malloc(items*size);
}
static void fpga_inflate_free(voidpf opaque, voidpf address)
{
// free eventually allocated BigBuf memory
// free eventually allocated BigBuf memory
static void fpga_inflate_free(voidpf opaque, voidpf address) {
BigBuf_free(); BigBuf_Clear_ext(false);
}
//----------------------------------------------------------------------------
// Initialize decompression of the respective (HF or LF) FPGA stream
//----------------------------------------------------------------------------
static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
{
static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) {
uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE];
uncompressed_bytes_cnt = 0;
@@ -248,9 +237,7 @@ static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_s
return false;
}
static void DownloadFPGA_byte(unsigned char w)
{
static void DownloadFPGA_byte(unsigned char w) {
#define SEND_BIT(x) { if(w & (1<<x) ) HIGH(GPIO_FPGA_DIN); else LOW(GPIO_FPGA_DIN); HIGH(GPIO_FPGA_CCLK); LOW(GPIO_FPGA_CCLK); }
SEND_BIT(7);
SEND_BIT(6);
@@ -263,8 +250,7 @@ static void DownloadFPGA_byte(unsigned char w)
}
// Download the fpga image starting at current stream position with length FpgaImageLen bytes
static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
{
static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp compressed_fpga_stream, uint8_t *output_buffer) {
int i=0;
AT91C_BASE_PIOA->PIO_OER = GPIO_FPGA_ON;
@@ -340,28 +326,26 @@ static void DownloadFPGA(int bitstream_version, int FpgaImageLen, z_streamp comp
LED_D_OFF();
}
/* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence
* 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01
* After that the format is 1 byte section type (ASCII character), 2 byte length
* (big endian), <length> bytes content. Except for section 'e' which has 4 bytes
* length.
*/
static int bitparse_find_section(int bitstream_version, char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer)
{
static int bitparse_find_section(int bitstream_version, char section_name, uint32_t *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) {
int result = 0;
#define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section
uint16_t numbytes = 0;
while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) {
char current_name = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer);
numbytes++;
unsigned int current_length = 0;
if(current_name < 'a' || current_name > 'e') {
uint32_t current_length = 0;
if (current_name < 'a' || current_name > 'e') {
/* Strange section name, abort */
break;
}
current_length = 0;
switch(current_name) {
switch (current_name) {
case 'e':
/* Four byte length field */
current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 24;
@@ -373,12 +357,12 @@ static int bitparse_find_section(int bitstream_version, char section_name, unsig
numbytes += 2;
}
if(current_name != 'e' && current_length > 255) {
if (current_name != 'e' && current_length > 255) {
/* Maybe a parse error */
break;
}
if(current_name == section_name) {
if (current_name == section_name) {
/* Found it */
*section_length = current_length;
result = 1;
@@ -390,33 +374,32 @@ static int bitparse_find_section(int bitstream_version, char section_name, unsig
numbytes++;
}
}
return result;
}
//----------------------------------------------------------------------------
// Check which FPGA image is currently loaded (if any). If necessary
// decompress and load the correct (HF or LF) image to the FPGA
//----------------------------------------------------------------------------
void FpgaDownloadAndGo(int bitstream_version)
{
z_stream compressed_fpga_stream;
uint8_t output_buffer[OUTPUT_BUFFER_LEN] = {0x00};
void FpgaDownloadAndGo(int bitstream_version) {
// check whether or not the bitstream is already loaded
if (downloaded_bitstream == bitstream_version)
return;
z_stream compressed_fpga_stream;
uint8_t output_buffer[OUTPUT_BUFFER_LEN] = {0x00};
bool verbose = (MF_DBGLEVEL > 3);
// make sure that we have enough memory to decompress
BigBuf_free(); BigBuf_Clear_ext(false);
BigBuf_free(); BigBuf_Clear_ext(verbose);
if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) {
if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer))
return;
}
unsigned int bitstream_length;
if(bitparse_find_section(bitstream_version, 'e', &bitstream_length, &compressed_fpga_stream, output_buffer)) {
uint32_t bitstream_length;
if (bitparse_find_section(bitstream_version, 'e', &bitstream_length, &compressed_fpga_stream, output_buffer)) {
DownloadFPGA(bitstream_version, bitstream_length, &compressed_fpga_stream, output_buffer);
downloaded_bitstream = bitstream_version;
}
@@ -427,16 +410,14 @@ void FpgaDownloadAndGo(int bitstream_version)
BigBuf_free(); BigBuf_Clear_ext(false);
}
//-----------------------------------------------------------------------------
// Gather version information from FPGA image. Needs to decompress the begin
// of the respective (HF or LF) image.
// Note: decompression makes use of (i.e. overwrites) BigBuf[]. It is therefore
// advisable to call this only once and store the results for later use.
//-----------------------------------------------------------------------------
void FpgaGatherVersion(int bitstream_version, char *dst, int len)
{
unsigned int fpga_info_len;
void FpgaGatherVersion(int bitstream_version, char *dst, int len) {
uint32_t fpga_info_len;
char tempstr[40] = {0x00};
z_stream compressed_fpga_stream;
uint8_t output_buffer[OUTPUT_BUFFER_LEN] = {0x00};
@@ -449,7 +430,7 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len)
if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer))
return;
if(bitparse_find_section(bitstream_version, 'a', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
if (bitparse_find_section(bitstream_version, 'a', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
for (uint16_t i = 0; i < fpga_info_len; i++) {
char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
if (i < sizeof(tempstr)) {
@@ -462,7 +443,7 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len)
strncat(dst, "HF ", len-1);
}
strncat(dst, "FPGA image built", len-1);
if(bitparse_find_section(bitstream_version, 'b', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
if (bitparse_find_section(bitstream_version, 'b', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
strncat(dst, " for ", len-1);
for (uint16_t i = 0; i < fpga_info_len; i++) {
char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
@@ -472,7 +453,7 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len)
}
strncat(dst, tempstr, len-1);
}
if(bitparse_find_section(bitstream_version, 'c', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
if (bitparse_find_section(bitstream_version, 'c', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
strncat(dst, " on ", len-1);
for (uint16_t i = 0; i < fpga_info_len; i++) {
char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
@@ -482,7 +463,7 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len)
}
strncat(dst, tempstr, len-1);
}
if(bitparse_find_section(bitstream_version, 'd', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
if (bitparse_find_section(bitstream_version, 'd', &fpga_info_len, &compressed_fpga_stream, output_buffer)) {
strncat(dst, " at ", len-1);
for (uint16_t i = 0; i < fpga_info_len; i++) {
char c = (char)get_from_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer);
@@ -498,16 +479,14 @@ void FpgaGatherVersion(int bitstream_version, char *dst, int len)
inflateEnd(&compressed_fpga_stream);
}
//-----------------------------------------------------------------------------
// Send a 16 bit command/data pair to the FPGA.
// The bit format is: C3 C2 C1 C0 D11 D10 D9 D8 D7 D6 D5 D4 D3 D2 D1 D0
// where C is the 4 bit command and D is the 12 bit data
//-----------------------------------------------------------------------------
void FpgaSendCommand(uint16_t cmd, uint16_t v)
{
void FpgaSendCommand(uint16_t cmd, uint16_t v) {
SetupSpi(SPI_FPGA_MODE);
while ((AT91C_BASE_SPI->SPI_SR & AT91C_SPI_TXEMPTY) == 0); // wait for the transfer to complete
while ((AT91C_BASE_SPI->SPI_SR & AT91C_SPI_TXEMPTY) == 0); // wait for the transfer to complete
AT91C_BASE_SPI->SPI_TDR = AT91C_SPI_LASTXFER | cmd | v; // send the data
}
//-----------------------------------------------------------------------------
@@ -515,8 +494,7 @@ void FpgaSendCommand(uint16_t cmd, uint16_t v)
// vs. clone vs. etc.). This is now a special case of FpgaSendCommand() to
// avoid changing this function's occurence everywhere in the source code.
//-----------------------------------------------------------------------------
void FpgaWriteConfWord(uint8_t v)
{
void FpgaWriteConfWord(uint8_t v) {
FpgaSendCommand(FPGA_CMD_SET_CONFREG, v);
}
@@ -525,8 +503,7 @@ void FpgaWriteConfWord(uint8_t v)
// closable, but should only close one at a time. Not an FPGA thing, but
// the samples from the ADC always flow through the FPGA.
//-----------------------------------------------------------------------------
void SetAdcMuxFor(uint32_t whichGpio)
{
void SetAdcMuxFor(uint32_t whichGpio) {
AT91C_BASE_PIOA->PIO_OER =
GPIO_MUXSEL_HIPKD |
GPIO_MUXSEL_LOPKD |
@@ -548,14 +525,28 @@ void SetAdcMuxFor(uint32_t whichGpio)
}
void Fpga_print_status(void) {
Dbprintf("Fgpa");
DbpString("Fgpa");
switch(downloaded_bitstream) {
case FPGA_BITSTREAM_HF: Dbprintf(" mode....................HF"); break;
case FPGA_BITSTREAM_LF: Dbprintf(" mode....................LF"); break;
default: Dbprintf(" mode....................%d", downloaded_bitstream); break;
case FPGA_BITSTREAM_HF: DbpString(" mode....................HF"); break;
case FPGA_BITSTREAM_LF: DbpString(" mode....................LF"); break;
default: Dbprintf(" mode....................%d", downloaded_bitstream); break;
}
}
int FpgaGetCurrent() {
return downloaded_bitstream;
}
// Turns off the antenna,
// log message
// if HF, Disable SSC DMA
// turn off trace and leds off.
void switch_off() {
if (MF_DBGLEVEL > 3) Dbprintf("switch_off");
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
SpinDelay(100);
if (downloaded_bitstream == FPGA_BITSTREAM_HF )
FpgaDisableSscDma();
set_tracing(false);
LEDsoff();
}
+2 -1
View File
@@ -14,7 +14,6 @@
#include "common.h" // standard definitions
#include "proxmark3.h" // common area
//#include "util.h"
#include "string.h"
#include "BigBuf.h" // bigbuf mem
#include "zlib.h" // uncompress
@@ -33,6 +32,8 @@ int FpgaGetCurrent();
#define FpgaEnableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN;
void SetAdcMuxFor(uint32_t whichGpio);
extern void switch_off();
// definitions for multiple FPGA config files support
#define FPGA_BITSTREAM_MAX 2 // the total number of FPGA bitstreams (configs)
#define FPGA_BITSTREAM_ERR 0
+510 -428
View File
File diff suppressed because it is too large Load Diff
+84 -110
View File
@@ -213,8 +213,7 @@ void UartReset() {
Uart.parityBits = 0; // holds 8 parity bits
Uart.startTime = 0;
Uart.endTime = 0;
Uart.byteCntMax = 0;
Uart.posCnt = 0;
Uart.syncBit = 9999;
}
@@ -344,15 +343,11 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) {
}
}
}
}
}
}
return false; // not finished yet, need more data
}
//=============================================================================
// ISO 14443 Type A - Manchester decoder
//=============================================================================
@@ -425,7 +420,7 @@ static RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non
else if ((Demod.twoBits & 0x01DC) == 0x01C0) Demod.syncBit = 1;
else if ((Demod.twoBits & 0x00EE) == 0x00E0) Demod.syncBit = 0;
if (Demod.syncBit != 0xFFFF) {
Demod.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8);
Demod.startTime = non_real_time ? non_real_time : (GetCountSspClk() & 0xfffffff8);
Demod.startTime -= Demod.syncBit;
Demod.bitCount = offset; // number of decoded data bits
Demod.state = DEMOD_MANCHESTER_DATA;
@@ -505,11 +500,10 @@ static RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non
// "hf 14a sniff"
//-----------------------------------------------------------------------------
void RAMFUNC SniffIso14443a(uint8_t param) {
LEDsoff();
// param:
// bit 0 - trigger from first card answer
// bit 1 - trigger from first reader 7-bit request
LEDsoff();
iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER);
// Allocate memory from BigBuf for some buffers
@@ -528,8 +522,8 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
// The DMA buffer, used to stream samples from the FPGA
uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
uint8_t *data = dmaBuf;
uint8_t previous_data = 0;
int maxDataLen = 0;
int dataLen = 0;
@@ -554,33 +548,31 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
// triggered == false -- to wait first for card
bool triggered = !(param & 0x03);
// And now we loop, receiving samples.
for(uint32_t rsamples = 0; true; ) {
uint32_t rsamples = 0;
if(BUTTON_PRESS()) {
DbpString("cancelled by button");
break;
}
LED_A_ON();
WDT_HIT();
DbpString("Starting to sniff");
// loop and listen
while (!BUTTON_PRESS()) {
WDT_HIT();
LED_A_ON();
int register readBufDataP = data - dmaBuf;
int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
if (readBufDataP <= dmaBufDataP){
if (readBufDataP <= dmaBufDataP)
dataLen = dmaBufDataP - readBufDataP;
} else {
else
dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP;
}
// test for length of buffer
if(dataLen > maxDataLen) {
if (dataLen > maxDataLen) {
maxDataLen = dataLen;
if(dataLen > (9 * DMA_BUFFER_SIZE / 10)) {
if (dataLen > (9 * DMA_BUFFER_SIZE / 10)) {
Dbprintf("blew circular buffer! dataLen=%d", dataLen);
break;
}
}
if(dataLen < 1) continue;
if (dataLen < 1) continue;
// primary buffer was stopped( <-- we lost data!
if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
@@ -596,9 +588,9 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
LED_A_OFF();
if (rsamples & 0x01) { // Need two samples to feed Miller and Manchester-Decoder
if (rsamples & 0x01) { // Need two samples to feed Miller and Manchester-Decoder
if(!TagIsActive) { // no need to try decoding reader data if the tag is sending
if (!TagIsActive) { // no need to try decoding reader data if the tag is sending
uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
if (MillerDecoding(readerdata, (rsamples-1)*4)) {
LED_C_ON();
@@ -606,7 +598,7 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
// check - if there is a short 7bit request from reader
if ((!triggered) && (param & 0x02) && (Uart.len == 1) && (Uart.bitCount == 7)) triggered = true;
if(triggered) {
if (triggered) {
if (!LogTrace(receivedCmd,
Uart.len,
Uart.startTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER,
@@ -614,9 +606,9 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
Uart.parity,
true)) break;
}
/* And ready to receive another command. */
/* ready to receive another command. */
UartReset();
/* And also reset the demod code, which might have been */
/* reset the demod code, which might have been */
/* false-triggered by the commands from the reader. */
DemodReset();
LED_B_OFF();
@@ -624,9 +616,10 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
ReaderIsActive = (Uart.state != STATE_UNSYNCD);
}
if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time
// no need to try decoding tag data if the reader is sending - and we cannot afford the time
if (!ReaderIsActive) {
uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
if(ManchesterDecoding(tagdata, 0, (rsamples-1)*4)) {
if (ManchesterDecoding(tagdata, 0, (rsamples-1)*4)) {
LED_B_ON();
if (!LogTrace(receivedResponse,
@@ -638,9 +631,9 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
if ((!triggered) && (param & 0x01)) triggered = true;
// And ready to receive another response.
// ready to receive another response.
DemodReset();
// And reset the Miller decoder including itS (now outdated) input buffer
// reset the Miller decoder including its (now outdated) input buffer
UartInit(receivedCmd, receivedCmdPar);
LED_C_OFF();
}
@@ -651,19 +644,16 @@ void RAMFUNC SniffIso14443a(uint8_t param) {
previous_data = *data;
rsamples++;
data++;
if(data == dmaBuf + DMA_BUFFER_SIZE) {
if (data == dmaBuf + DMA_BUFFER_SIZE) {
data = dmaBuf;
}
} // main cycle
} // end main loop
if (MF_DBGLEVEL >= 1) {
Dbprintf("maxDataLen=%d, Uart.state=%x, Uart.len=%d", maxDataLen, Uart.state, Uart.len);
Dbprintf("traceLen=%d, Uart.output[0]=%08x", BigBuf_get_traceLen(), (uint32_t)Uart.output[0]);
}
FpgaDisableSscDma();
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff();
set_tracing(false);
switch_off();
}
//-----------------------------------------------------------------------------
@@ -779,9 +769,9 @@ int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len)
while (!BUTTON_PRESS()) {
WDT_HIT();
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
if(MillerDecoding(b, 0)) {
if (MillerDecoding(b, 0)) {
*len = Uart.len;
return true;
}
@@ -1050,11 +1040,11 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
tag_response_info_t* p_response;
LED_A_ON();
for(;;) {
for (;;) {
WDT_HIT();
// Clean receive command buffer
if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
if (!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, BigBuf_get_traceLen());
break;
}
@@ -1062,19 +1052,19 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
// Okay, look at the command now.
lastorder = order;
if(receivedCmd[0] == ISO14443A_CMD_REQA) { // Received a REQUEST
if (receivedCmd[0] == ISO14443A_CMD_REQA) { // Received a REQUEST
p_response = &responses[0]; order = 1;
} else if(receivedCmd[0] == ISO14443A_CMD_WUPA) { // Received a WAKEUP
} else if (receivedCmd[0] == ISO14443A_CMD_WUPA) { // Received a WAKEUP
p_response = &responses[0]; order = 6;
} else if(receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received request for UID (cascade 1)
} else if (receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received request for UID (cascade 1)
p_response = &responses[1]; order = 2;
} else if(receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received request for UID (cascade 2)
} else if (receivedCmd[1] == 0x20 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received request for UID (cascade 2)
p_response = &responses[2]; order = 20;
} else if(receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received a SELECT (cascade 1)
} else if (receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) { // Received a SELECT (cascade 1)
p_response = &responses[3]; order = 3;
} else if(receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received a SELECT (cascade 2)
} else if (receivedCmd[1] == 0x70 && receivedCmd[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2) { // Received a SELECT (cascade 2)
p_response = &responses[4]; order = 30;
} else if(receivedCmd[0] == ISO14443A_CMD_READBLOCK) { // Received a (plain) READ
} else if (receivedCmd[0] == ISO14443A_CMD_READBLOCK) { // Received a (plain) READ
uint8_t block = receivedCmd[1];
// if Ultralight or NTAG (4 byte blocks)
if ( tagType == 7 || tagType == 2 ) {
@@ -1096,7 +1086,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
// We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
p_response = NULL;
}
} else if(receivedCmd[0] == MIFARE_ULEV1_FASTREAD) { // Received a FAST READ (ranged read)
} else if (receivedCmd[0] == MIFARE_ULEV1_FASTREAD) { // Received a FAST READ (ranged read)
uint8_t emdata[MAX_FRAME_SIZE];
// first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
int start = (receivedCmd[1]+12) * 4;
@@ -1105,7 +1095,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
AppendCrc14443a(emdata, len);
EmSendCmd(emdata, len+2);
p_response = NULL;
} else if(receivedCmd[0] == MIFARE_ULEV1_READSIG && tagType == 7) { // Received a READ SIGNATURE --
} else if (receivedCmd[0] == MIFARE_ULEV1_READSIG && tagType == 7) { // Received a READ SIGNATURE --
// first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
uint16_t start = 4 * 4;
uint8_t emdata[34];
@@ -1149,7 +1139,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
}
}
p_response = NULL;
} else if(receivedCmd[0] == MIFARE_ULEV1_CHECKTEAR && tagType == 7) { // Received a CHECK_TEARING_EVENT --
} else if (receivedCmd[0] == MIFARE_ULEV1_CHECKTEAR && tagType == 7) { // Received a CHECK_TEARING_EVENT --
// first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
uint8_t emdata[3];
uint8_t index = receivedCmd[1];
@@ -1163,10 +1153,10 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
EmSendCmd(emdata, sizeof(emdata));
}
p_response = NULL;
} else if(receivedCmd[0] == ISO14443A_CMD_HALT) { // Received a HALT
} else if (receivedCmd[0] == ISO14443A_CMD_HALT) { // Received a HALT
LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, true);
p_response = NULL;
} else if(receivedCmd[0] == MIFARE_AUTH_KEYA || receivedCmd[0] == MIFARE_AUTH_KEYB) { // Received an authentication request
} else if (receivedCmd[0] == MIFARE_AUTH_KEYA || receivedCmd[0] == MIFARE_AUTH_KEYB) { // Received an authentication request
if ( tagType == 7 ) { // IF NTAG /EV1 0x60 == GET_VERSION, not a authentication request.
uint8_t emdata[10];
emlGetMemBt( emdata, 0, 8 );
@@ -1190,7 +1180,7 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
//p_response = &responses[5];
order = 7;
}
} else if(receivedCmd[0] == ISO14443A_CMD_RATS) { // Received a RATS request
} else if (receivedCmd[0] == ISO14443A_CMD_RATS) { // Received a RATS request
if (tagType == 1 || tagType == 2) { // RATS not supported
EmSend4bit(CARD_NACK_NA);
p_response = NULL;
@@ -1345,21 +1335,11 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
}
// Count number of wakeups received after a halt
if(order == 6 && lastorder == 5) { happened++; }
if (order == 6 && lastorder == 5) { happened++; }
// Count number of other messages after a halt
if(order != 6 && lastorder == 5) { happened2++; }
if (order != 6 && lastorder == 5) { happened2++; }
// comment this limit if you want to simulation longer
if (!tracing) {
DbpString("Trace Full. Simulation stopped.");
break;
}
// comment this limit if you want to simulation longer
if(cmdsRecvd > 999) {
DbpString("1000 commands later...");
break;
}
cmdsRecvd++;
if (p_response != NULL) {
@@ -1381,19 +1361,17 @@ void SimulateIso14443aTag(int tagType, int flags, uint8_t* data) {
}
}
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
set_tracing(false);
cmd_send(CMD_ACK,1,0,0,0,0);
switch_off();
BigBuf_free_keep_EM();
LED_A_OFF();
if (MF_DBGLEVEL >= 4){
Dbprintf("-[ Wake ups after halt [%d]", happened);
Dbprintf("-[ Messages after halt [%d]", happened2);
Dbprintf("-[ Num of received cmd [%d]", cmdsRecvd);
Dbprintf("-[ Num of moebius tries [%d]", moebius_count);
}
cmd_send(CMD_ACK,1,0,0,0,0);
}
// prepare a delayed transfer. This simply shifts ToSend[] by a number
@@ -1433,21 +1411,23 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
uint32_t ThisTransferTime = 0;
if (timing) {
if(*timing == 0) { // Measure time
if (*timing == 0) // Measure time
*timing = (GetCountSspClk() + 8) & 0xfffffff8;
} else {
else
PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
}
if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
while(GetCountSspClk() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8))
Dbprintf("TransmitFor14443a: Missed timing");
while (GetCountSspClk() < (*timing & 0xfffffff8)) {}; // Delay transfer (multiple of 8 MF clock ticks)
LastTimeProxToAirStart = *timing;
} else {
uint32_t ThisTransferTime = 0;
ThisTransferTime = ((MAX(NextTransferTime, GetCountSspClk()) & 0xfffffff8) + 8);
while(GetCountSspClk() < ThisTransferTime);
while (GetCountSspClk() < ThisTransferTime);
LastTimeProxToAirStart = ThisTransferTime;
}
@@ -1455,13 +1435,11 @@ static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing
// clear TXRDY
AT91C_BASE_SSC->SSC_THR = SEC_Y;
uint16_t c = 0;
for(;;) {
uint16_t c = 0;
while (c < len) {
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
AT91C_BASE_SSC->SSC_THR = cmd[c];
c++;
if(c >= len)
break;
}
}
@@ -3087,21 +3065,17 @@ void RAMFUNC SniffMifare(uint8_t param) {
return;
}
// Signal field is off with the appropriate LED
LED_D_OFF();
MfSniffInit();
// And now we loop, receiving samples.
for(uint32_t sniffCounter = 0;; ) {
LED_A_ON();
uint32_t sniffCounter = 0;
// loop and listen
while (!BUTTON_PRESS()) {
WDT_HIT();
if(BUTTON_PRESS()) {
DbpString("cancelled by button");
break;
}
LED_A_ON();
if ((sniffCounter & 0x0000FFFF) == 0) { // from time to time
// check if a transaction is completed (timeout after 2000ms).
// if yes, stop the DMA transfer and send what we have so far to the client
@@ -3119,9 +3093,11 @@ void RAMFUNC SniffMifare(uint8_t param) {
}
}
}
int register readBufDataP = data - dmaBuf; // number of bytes we have processed so far
int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR; // number of bytes already transferred
// number of bytes we have processed so far
int register readBufDataP = data - dmaBuf;
// number of bytes already transferred
int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
if (readBufDataP <= dmaBufDataP) // we are processing the same block of data which is currently being transferred
dataLen = dmaBufDataP - readBufDataP; // number of bytes still to be processed
@@ -3155,21 +3131,21 @@ void RAMFUNC SniffMifare(uint8_t param) {
if (sniffCounter & 0x01) {
// no need to try decoding tag data if the reader is sending
if(!TagIsActive) {
if (!TagIsActive) {
uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
if(MillerDecoding(readerdata, (sniffCounter-1)*4)) {
LED_C_INV();
if (MfSniffLogic(receivedCmd, Uart.len, Uart.parity, Uart.bitCount, true)) break;
UartInit(receivedCmd, receivedCmdPar);
DemodReset();
UartInit(receivedCmd, receivedCmdPar);
}
ReaderIsActive = (Uart.state != STATE_UNSYNCD);
}
// no need to try decoding tag data if the reader is sending
if(!ReaderIsActive) {
if (!ReaderIsActive) {
uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
if(ManchesterDecoding(tagdata, 0, (sniffCounter-1)*4)) {
LED_C_INV();
@@ -3192,11 +3168,9 @@ void RAMFUNC SniffMifare(uint8_t param) {
} // main cycle
if (MF_DBGLEVEL >= 1) Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.len=%x", maxDataLen, Uart.state, Uart.len);
if (MF_DBGLEVEL >= 1)
Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.len=%x", maxDataLen, Uart.state, Uart.len);
FpgaDisableSscDma();
MfSniffEnd();
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff();
set_tracing(false);
switch_off();
}
+1 -1
View File
@@ -71,7 +71,7 @@ typedef struct {
uint16_t shiftReg;
int16_t bitCount;
uint16_t len;
uint16_t byteCntMax;
//uint16_t byteCntMax;
uint16_t posCnt;
uint16_t syncBit;
uint8_t parityBits;
+21 -35
View File
@@ -45,13 +45,11 @@
static void iso14b_set_timeout(uint32_t timeout);
static void iso14b_set_maxframesize(uint16_t size);
static void switch_off(void);
// the block number for the ISO14443-4 PCB (used with APDUs)
static uint8_t pcb_blocknum = 0;
static uint32_t iso14b_timeout = FWT_TIMEOUT_14B;
//=============================================================================
// An ISO 14443 Type B tag. We listen for commands from the reader, using
// a UART kind of thing that's implemented in software. When we get a
@@ -170,14 +168,6 @@ static void iso14b_set_maxframesize(uint16_t size) {
Uart.byteCntMax = size;
if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443B Max frame size set to %d bytes", Uart.byteCntMax);
}
static void switch_off(void){
if (MF_DBGLEVEL > 3) Dbprintf("switch_off");
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
SpinDelay(100);
FpgaDisableSscDma();
set_tracing(false);
LEDsoff();
}
void AppendCrc14443b(uint8_t* data, int len) {
ComputeCrc14443(CRC_14443_B, data, len, data+len, data+len+1);
@@ -543,8 +533,7 @@ static void TransmitFor14443b_AsTag( uint8_t *response, uint16_t len) {
AT91C_BASE_SSC->SSC_THR = response[++i];
}
if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
b = AT91C_BASE_SSC->SSC_RHR;
(void)b;
b = AT91C_BASE_SSC->SSC_RHR;(void)b;
}
}
@@ -560,18 +549,18 @@ void SimulateIso14443bTag(uint32_t pupi) {
///////////// setup device.
FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
// allocate command receive buffer
BigBuf_free();
BigBuf_Clear_ext(false);
clear_trace(); //sim
set_tracing(true);
// connect Demodulated Signal to ADC:
SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
// Set up the synchronous serial port
FpgaSetupSsc();
/////////////
// allocate command receive buffer
BigBuf_free();
BigBuf_Clear_ext(false);
clear_trace(); //sim
set_tracing(true);
uint16_t len, cmdsReceived = 0;
int cardSTATE = SIM_NOFIELD;
@@ -712,13 +701,9 @@ void SimulateIso14443bTag(uint32_t pupi) {
}
++cmdsReceived;
// iceman, could add a switch to turn this on/off (if off, no logging?)
if(cmdsReceived > 1000) {
DbpString("14B Simulate, 1000 commands later...");
break;
}
}
if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, BigBuf_get_traceLen());
if (MF_DBGLEVEL >= 2)
Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, BigBuf_get_traceLen());
switch_off(); //simulate
}
@@ -1022,7 +1007,6 @@ static void GetTagSamplesFor14443bDemod() {
LogTrace(Demod.output, Demod.len, time_0, time_stop, NULL, false);
}
//-----------------------------------------------------------------------------
// Transmit the command (to the tag) that was placed in ToSend[].
//-----------------------------------------------------------------------------
@@ -1382,17 +1366,16 @@ void iso14443b_setup() {
//-----------------------------------------------------------------------------
void ReadSTMemoryIso14443b(uint8_t numofblocks)
{
FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
// Make sure that we start from off, since the tags are stateful;
// confusing things will happen if we don't reset them between reads.
switch_off(); // before ReadStMemory
switch_off();
FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
set_tracing(true);
uint8_t i = 0x00;
SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
FpgaSetupSsc();
// Now give it time to spin up.
@@ -1400,6 +1383,8 @@ void ReadSTMemoryIso14443b(uint8_t numofblocks)
LED_D_ON();
FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ);
SpinDelay(20);
uint8_t i = 0x00;
// First command: wake up the tag using the INITIATE command
uint8_t cmd1[] = {ISO14443B_INITIATE, 0x00, 0x97, 0x5b};
@@ -1673,12 +1658,13 @@ void RAMFUNC SnoopIso14443b(void) {
}
}
switch_off(); // Snoop
switch_off();
DbpString("Snoop statistics:");
Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart.state, Uart.byteCnt, Uart.byteCntMax);
Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
if (MF_DBGLEVEL >= 2) {
DbpString("Snoop statistics:");
Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart.state, Uart.byteCnt, Uart.byteCntMax);
Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
}
// free mem refs.
if ( upTo ) upTo = NULL;
+109 -7
View File
@@ -598,6 +598,109 @@ int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, uint8_t *parity) {
(oddparity8((Nt >> 8) & 0xFF) == ((parity[2]) ^ oddparity8((NtEnc >> 8) & 0xFF) ^ BIT(Ks1,0)))) ? 1 : 0;
}
#define AUTHENTICATION_TIMEOUT 848 //848 // card times out 1ms after wrong authentication (according to NXP documentation)
#define PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
void MifareAcquireNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain) {
uint32_t cuid = 0;
uint8_t uid[10] = {0x00};
uint8_t cascade_levels = 0;
uint8_t answer[MAX_MIFARE_FRAME_SIZE] = {0x00};
uint8_t par[1] = {0x00};
int16_t isOK = 0;
uint8_t buf[USB_CMD_DATA_SIZE] = {0x00};
uint32_t timeout = 0;
uint8_t blockNo = arg0 & 0xff;
uint8_t keyType = (arg0 >> 8) & 0xff;
bool initialize = flags & 0x0001;
bool field_off = flags & 0x0004;
LED_A_ON();
LED_C_OFF();
BigBuf_free(); BigBuf_Clear_ext(false);
clear_trace();
set_tracing(true);
if (initialize) {
iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
}
LED_C_ON();
uint8_t dummy_answer = 0;
uint16_t num_nonces = 0;
bool have_uid = false;
for (uint16_t i = 0; i <= USB_CMD_DATA_SIZE-4; i += 4 ) {
// Test if the action was cancelled
if(BUTTON_PRESS()) {
isOK = 2;
field_off = true;
break;
}
if (!have_uid) { // need a full select cycle to get the uid first
iso14a_card_select_t card_info;
if(!iso14443a_select_card(uid, &card_info, &cuid, true, 0)) {
if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Can't select card (ALL)");
continue;
}
switch (card_info.uidlen) {
case 4 : cascade_levels = 1; break;
case 7 : cascade_levels = 2; break;
case 10: cascade_levels = 3; break;
default: break;
}
have_uid = true;
} else { // no need for anticollision. We can directly select the card
if(!iso14443a_select_card(uid, NULL, NULL, false, cascade_levels)) {
if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Can't select card (UID)");
continue;
}
}
// Transmit MIFARE_CLASSIC_AUTH
uint8_t dcmd[4] = {0x60 + (keyType & 0x01), blockNo, 0x00, 0x00};
AppendCrc14443a(dcmd, 2);
ReaderTransmit(dcmd, sizeof(dcmd), NULL);
int len = ReaderReceive(answer, par);
// send a dummy byte as reader response in order to trigger the cards authentication timeout
ReaderTransmit(&dummy_answer, 1, NULL);
timeout = GetCountSspClk() + AUTHENTICATION_TIMEOUT;
if (len != 4) {
if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Auth1 error");
continue;
}
num_nonces++;
// Save the tag nonce (nt)
buf[i] = answer[0];
buf[i+1] = answer[1];
buf[i+2] = answer[2];
buf[i+3] = answer[3];
// wait for the card to become ready again
while (GetCountSspClk() < timeout) {};
}
LED_C_OFF();
LED_B_ON();
cmd_send(CMD_ACK, isOK, cuid, num_nonces-1, buf, sizeof(buf));
LED_B_OFF();
if (MF_DBGLEVEL >= 3) DbpString("AcquireNonces finished");
if (field_off) {
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff();
set_tracing(false);
}
}
//-----------------------------------------------------------------------------
// acquire encrypted nonces in order to perform the attack described in
@@ -605,8 +708,6 @@ int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, uint8_t *parity) {
// Mifare Classic Cards" in Proceedings of the 22nd ACM SIGSAC Conference on
// Computer and Communications Security, 2015
//-----------------------------------------------------------------------------
#define AUTHENTICATION_TIMEOUT 848 //848 // card times out 1ms after wrong authentication (according to NXP documentation)
#define PRE_AUTHENTICATION_LEADTIME 400 // some (non standard) cards need a pause after select before they are ready for first authentication
void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags, uint8_t *datain)
{
@@ -691,15 +792,16 @@ void MifareAcquireEncryptedNonces(uint32_t arg0, uint32_t arg1, uint32_t flags,
// nested authentication
uint16_t len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par_enc, NULL);
// send a dummy byte as reader response in order to trigger the cards authentication timeout
ReaderTransmit(&dummy_answer, 1, NULL);
timeout = GetCountSspClk() + AUTHENTICATION_TIMEOUT;
if (len != 4) {
if (MF_DBGLEVEL >= 1) Dbprintf("AcquireNonces: Auth2 error len=%d", len);
continue;
}
// send a dummy byte as reader response in order to trigger the cards authentication timeout
ReaderTransmit(&dummy_answer, 1, NULL);
timeout = GetCountSspClk() + AUTHENTICATION_TIMEOUT;
num_nonces++;
if (num_nonces % 2) {
memcpy(buf+i, receivedAnswer, 4);
@@ -1019,7 +1121,7 @@ void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) {
timeout = GetCountSspClk() + AUTHENTICATION_TIMEOUT;
// wait for the card to become ready again
while(GetCountSspClk() < timeout);
while(GetCountSspClk() < timeout) {};
continue;
}
+1 -3
View File
@@ -556,9 +556,7 @@ void OnSuccess(){
pcb_blocknum = 0;
ReaderTransmit(deselect_cmd, 3 , NULL);
mifare_ultra_halt();
FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
LEDsoff();
set_tracing(false);
switch_off();
}
void OnError(uint8_t reason){
+11 -9
View File
@@ -193,7 +193,7 @@ int usage_hf_iclass_replay(void) {
PrintAndLog(" hf iclass replay 00112233");
return 0;
}
int usage_hf_iclass_snoop(void) {
int usage_hf_iclass_sniff(void) {
PrintAndLog("HELP: Snoops the communication between reader and tag");
PrintAndLog("Usage: hf iclass snoop [h]");
PrintAndLog("Samples:");
@@ -230,10 +230,9 @@ int CmdHFiClassList(const char *Cmd) {
return 0;
}
int CmdHFiClassSnoop(const char *Cmd) {
int CmdHFiClassSniff(const char *Cmd) {
char cmdp = param_getchar(Cmd, 0);
if (cmdp == 'h' || cmdp == 'H') return usage_hf_iclass_snoop();
if (cmdp == 'h' || cmdp == 'H') return usage_hf_iclass_sniff();
UsbCommand c = {CMD_SNOOP_ICLASS};
SendCommand(&c);
return 0;
@@ -263,7 +262,7 @@ int CmdHFiClassSim(const char *Cmd) {
uint8_t numberOfCSNs = 0;
if (simType == 2) {
UsbCommand c = {CMD_SIMULATE_TAG_ICLASS, {simType,NUM_CSNS}};
UsbCommand c = {CMD_SIMULATE_TAG_ICLASS, {simType, NUM_CSNS}};
UsbCommand resp = {0};
/*
@@ -325,7 +324,7 @@ int CmdHFiClassSim(const char *Cmd) {
}
uint8_t num_mac_responses = resp.arg[1];
PrintAndLog("Mac responses: %d MACs obtained (should be %d)", num_mac_responses,NUM_CSNS);
PrintAndLog("Mac responses: %d MACs obtained (should be %d)", num_mac_responses, NUM_CSNS);
size_t datalen = NUM_CSNS*24;
/*
@@ -351,7 +350,7 @@ int CmdHFiClassSim(const char *Cmd) {
saveFile("iclass_mac_attack", "bin", dump, datalen);
free(dump);
} else {
UsbCommand c = {CMD_SIMULATE_TAG_ICLASS, {simType,numberOfCSNs}};
UsbCommand c = {CMD_SIMULATE_TAG_ICLASS, {simType, numberOfCSNs}};
memcpy(c.d.asBytes, CSN, 8);
clearCommandBuffer();
SendCommand(&c);
@@ -392,7 +391,10 @@ int HFiClassReader(const char *Cmd, bool loop, bool verbose) {
}
if (readStatus & FLAG_ICLASS_READER_AA) {
bool legacy = true;
PrintAndLog(" AppIA: %s",sprint_hex(data+8*5,8));
PrintAndLog(" AppIA: %s", sprint_hex(data+8*5,8));
//if ( memcmp(data+8*5, '\xff\xff\xff\xff\xff\xff\xff\xff',8) != 0 )
// legacy = false;
for (int i = 0; i<8; i++) {
if (data[8*5+i] != 0xFF) {
legacy = false;
@@ -1731,7 +1733,7 @@ static command_t CommandTable[] = {
{"readtagfile", CmdHFiClassReadTagFile, 1, "[options..] Display Content from tagfile"},
{"replay", CmdHFiClassReader_Replay, 0, "<mac> Read an iClass tag via Reply Attack"},
{"sim", CmdHFiClassSim, 0, "[options..] Simulate iClass tag"},
{"snoop", CmdHFiClassSnoop, 0, " Eavesdrop iClass communication"},
{"sniff", CmdHFiClassSniff, 0, " Eavesdrop iClass communication"},
{"writeblk", CmdHFiClass_WriteBlock, 0, "[options..] Authenticate and Write iClass block"},
{NULL, NULL, 0, NULL}
};
+2 -2
View File
@@ -8,7 +8,6 @@
//-----------------------------------------------------------------------------
// High frequency iClass support
//-----------------------------------------------------------------------------
#ifndef CMDHFICLASS_H__
#define CMDHFICLASS_H__
@@ -55,10 +54,11 @@ extern int CmdHFiClass_ReadBlock(const char *Cmd);
extern int CmdHFiClass_TestMac(const char *Cmd);
extern int CmdHFiClassManageKeys(const char *Cmd);
extern int CmdHFiClass_loclass(const char *Cmd);
extern int CmdHFiClassSnoop(const char *Cmd);
extern int CmdHFiClassSniff(const char *Cmd);
extern int CmdHFiClassSim(const char *Cmd);
extern int CmdHFiClassWriteKeyFile(const char *Cmd);
extern int CmdHFiClass_WriteBlock(const char *Cmd);
void printIclassDumpContents(uint8_t *iclass_dump, uint8_t startblock, uint8_t endblock, size_t filesize);
void HFiClassCalcDivKey(uint8_t *CSN, uint8_t *KEY, uint8_t *div_key, bool elite);
#endif
+90 -10
View File
@@ -1100,14 +1100,16 @@ int CmdHF14AMfNestedHard(const char *Cmd) {
}
}
uint64_t key64 = 0;
// check if we can authenticate to sector
int res = mfCheckKeys(blockNo, keyType, true, 1, key, &key64);
if (res) {
PrintAndLog("Key is wrong. Can't authenticate to block:%3d key type:%c", blockNo, keyType ? 'B' : 'A');
return 3;
}
if ( !know_target_key ) {
uint64_t key64 = 0;
// check if we can authenticate to sector
int res = mfCheckKeys(blockNo, keyType, true, 1, key, &key64);
if (res) {
PrintAndLog("Key is wrong. Can't authenticate to block:%3d key type:%c", blockNo, keyType ? 'B' : 'A');
return 3;
}
}
PrintAndLog("--target block no:%3d, target key type:%c, known target key: 0x%02x%02x%02x%02x%02x%02x%s, file action: %s, Slow: %s, Tests: %d ",
trgBlockNo,
trgKeyType?'B':'A',
@@ -2444,7 +2446,7 @@ int CmdHF14AMfCSave(const char *Cmd) {
}
//needs nt, ar, at, Data to decrypt
int CmdHf14MfDecryptBytes(const char *Cmd){
int CmdHf14AMfDecryptBytes(const char *Cmd){
uint8_t data[50];
uint32_t nt = param_get32ex(Cmd,0,0,16);
uint32_t ar_enc = param_get32ex(Cmd,1,0,16);
@@ -2498,6 +2500,83 @@ int CmdHf14AMfSetMod(const char *Cmd) {
return 0;
}
int CmdHF14AMfice(const char *Cmd) {
uint8_t blockNo = 0;
uint8_t keyType = 0;
uint8_t trgBlockNo = 0;
uint8_t trgKeyType = 1;
bool slow = false;
bool initialize = true;
bool acquisition_completed = false;
uint32_t flags = 0;
uint32_t total_num_nonces = 0;
FILE *fnonces = NULL;
UsbCommand resp;
uint32_t part_limit = 3000;
uint32_t limit = param_get32ex(Cmd, 0, 50000, 10);
printf("Collecting %u nonces \n", limit);
if ((fnonces = fopen("nonces.bin","wb")) == NULL) {
PrintAndLog("Could not create file nonces.bin");
return 3;
}
clearCommandBuffer();
uint64_t t1 = msclock();
do {
if (ukbhit()) {
int gc = getchar(); (void)gc;
printf("\naborted via keyboard!\n");
break;
}
flags = 0;
flags |= initialize ? 0x0001 : 0;
flags |= slow ? 0x0002 : 0;
UsbCommand c = {CMD_MIFARE_ACQUIRE_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, flags}};
clearCommandBuffer();
SendCommand(&c);
if (!WaitForResponseTimeout(CMD_ACK, &resp, 3000)) goto out;
if (resp.arg[0]) goto out;
uint32_t items = resp.arg[2];
if (fnonces) {
fwrite(resp.d.asBytes, 1, items*4, fnonces);
fflush(fnonces);
}
total_num_nonces += items;
if ( total_num_nonces > part_limit ) {
printf("Total nonces %u\n", total_num_nonces);
part_limit += 3000;
}
acquisition_completed = ( total_num_nonces > limit);
initialize = false;
} while (!acquisition_completed);
out:
printf("time: %" PRIu64 " seconds\n", (msclock()-t1)/1000);
if ( fnonces ) {
fflush(fnonces);
fclose(fnonces);
}
UsbCommand c = {CMD_MIFARE_ACQUIRE_NONCES, {blockNo + keyType * 0x100, trgBlockNo + trgKeyType * 0x100, 4}};
clearCommandBuffer();
SendCommand(&c);
return 0;
}
static command_t CommandTable[] = {
{"help", CmdHelp, 1, "This help"},
{"dbg", CmdHF14AMfDbg, 0, "Set default debug mode"},
@@ -2526,8 +2605,9 @@ static command_t CommandTable[] = {
{"cgetsc", CmdHF14AMfCGetSc, 0, "Read sector - Magic Chinese card"},
{"cload", CmdHF14AMfCLoad, 0, "Load dump into magic Chinese card"},
{"csave", CmdHF14AMfCSave, 0, "Save dump from magic Chinese card into file or emulator"},
{"decrypt", CmdHf14MfDecryptBytes, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
{"decrypt", CmdHf14AMfDecryptBytes, 1, "[nt] [ar_enc] [at_enc] [data] - to decrypt snoop or trace"},
{"setmod", CmdHf14AMfSetMod, 0, "Set MIFARE Classic EV1 load modulation strength"},
{"ice", CmdHF14AMfice, 0, "collect Mifare Classic nonces to file"},
{NULL, NULL, 0, NULL}
};
+1 -1
View File
@@ -119,7 +119,7 @@ void hardnested_print_progress(uint32_t nonces, char *activity, float brute_forc
} else {
sprintf(brute_force_time_string, "%2.0fd", brute_force_time/(60*60*24));
}
PrintAndLog(" %7.0f | %7d | %-55s | %15.0f | %5s", (float)total_time/1000.0, nonces, activity, brute_force, brute_force_time_string);
PrintAndLog(" %7.0f | %7u | %-55s | %15.0f | %5s", (float)total_time/1000.0, nonces, activity, brute_force, brute_force_time_string);
}
}
+18 -11
View File
@@ -119,19 +119,26 @@ ISO 7816-4 Basic interindustry commands. For command APDU's.
90 00 = OK
6x xx = ERROR
*/
#define ICLASS_CMD_ACTALL 0x0A
#define ICLASS_CMD_READ_OR_IDENTIFY 0x0C
#define ICLASS_CMD_SELECT 0x81
#define ICLASS_CMD_PAGESEL 0x84
#define ICLASS_CMD_READCHECK_KD 0x88
#define ICLASS_CMD_READCHECK_KC 0x18
#define ICLASS_CMD_CHECK 0x05
#define ICLASS_CMD_DETECT 0x0F
// these cmds are adjusted to ISO15693 and Manchester encoding requests.
// for instance ICLASS_CMD_SELECT 0x81 tells if ISO14443b/BPSK coding/106 kbits/s
// for instance ICLASS_CMD_SELECT 0x41 tells if ISO14443b/BPSK coding/423 kbits/s
//
#define ICLASS_CMD_HALT 0x00
#define ICLASS_CMD_UPDATE 0x87
#define ICLASS_CMD_ACT 0x8E
#define ICLASS_CMD_SELECT_15 0x01
#define ICLASS_CMD_ACTALL 0x0A
#define ICLASS_CMD_DETECT 0x0F
#define ICLASS_CMD_CHECK 0x05
#define ICLASS_CMD_READ4 0x06
#define ICLASS_CMD_READ_OR_IDENTIFY 0x0C
#define ICLASS_CMD_SELECT 0x81
#define ICLASS_CMD_PAGESEL 0x84
#define ICLASS_CMD_UPDATE 0x87
#define ICLASS_CMD_READCHECK_KC 0x18
#define ICLASS_CMD_READCHECK_KD 0x88
#define ICLASS_CMD_ACT 0x8E
#define ISO14443A_CMD_REQA 0x26
+1
View File
@@ -190,6 +190,7 @@ typedef struct{
#define CMD_READER_MIFARE 0x0611
#define CMD_MIFARE_NESTED 0x0612
#define CMD_MIFARE_ACQUIRE_ENCRYPTED_NONCES 0x0613
#define CMD_MIFARE_ACQUIRE_NONCES 0x0614
#define CMD_MIFARE_READBL 0x0620
#define CMD_MIFAREU_READBL 0x0720