From: Martin Holst Swende Date: Sun, 3 Apr 2016 19:55:54 +0000 (+0200) Subject: Merge pull request #168 from zhovner/master X-Git-Tag: v2.3.0~3 X-Git-Url: http://git.zerfleddert.de/cgi-bin/gitweb.cgi/proxmark3-svn/commitdiff_plain/90858b95ad0ae44ed2fdf2e7525c170135ce00b7?hp=c36d994b32a8bb7f39d642f770e6cfb0074cb046 Merge pull request #168 from zhovner/master mfkey64: Added optional decryption of communication using keystream --- diff --git a/.gitignore b/.gitignore index 07669e14..fa74326e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ # .gitignore # don't push these files to the repository +.history *.log *.eml *.o @@ -12,6 +13,7 @@ *.bin *.dll *.moc.cpp +*.z *.exe proxmark proxmark3 diff --git a/CHANGELOG.md b/CHANGELOG.md index 85e7f915..d3d71de5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,8 +2,79 @@ All notable changes to this project will be documented in this file. This project uses the changelog in accordance with [keepchangelog](http://keepachangelog.com/). Please use this to write notable changes, which is not the same as git commit log... -## [Unreleased][unreleased] +## [unreleased][unreleased] + +### Added +- Added a LF ASK Sequence Terminator detection option to the standard ask demod - and applied it to `lf search u`, `lf t55xx detect`, and `data rawdemod am s` (marshmellow) +- `lf t55xx bruteforce [i <*.dic>]` - Simple bruteforce attack to find password - (iceman and others) +- `lf viking clone`- clone viking tag to t55x7 or Q5 from 4byte hex ID input +- `lf viking sim` - sim full viking tag from 4byte hex ID input +- `lf viking read` - read viking tag and output ID +- `lf t55xx wipe` - sets t55xx back to factory defaults +- Added viking demod to `lf search` (marshmellow) +- `data askvikingdemod` demod viking id tag from graphbuffer (marshmellow) +- `lf t55xx resetread` added reset then read command - should allow determining start +of stream transmissions (marshmellow) +- `lf t55xx wakeup` added wake with password (AOR) to allow lf search or standard lf read after (iceman, marshmellow) +- `hf iclass managekeys` to save, load and manage iclass keys. (adjusted most commands to accept a loaded key in memory) (marshmellow) +- `hf iclass readblk` to select, authenticate, and read 1 block from an iclass card (marshmellow) +- `hf iclass writeblk` to select, authenticate, and write 1 block to an iclass card (or picopass) (marshmellow + others) +- `hf iclass clone` to take a saved dump file and clone selected blocks to a new tag (marshmellow + others) +- `hf iclass calcnewkey` - to calculate the div_key change to change a key - (experimental) (marshmellow + others) +- `hf iclass encryptblk` - to encrypt a data block hex to prep for writing that block (marshmellow) +- ISO14443a stand-alone operation with ARM CFLAG="WITH_ISO14443a_StandAlone". This code can read & emulate two banks of 14a tag UIDs and write to "magic" cards (Craig Young) +- AWID26 command context added as 'lf awid' containing realtime demodulation as well as cloning/simulation based on tag numbers (Craig Young) +- Added 'hw status'. This command makes the ARM print out some runtime information. (holiman) +- Added 'hw ping'. This command just sends a usb packets and checks if the pm3 is responsive. Can be used to abort certain operations which supports abort over usb. (holiman) +- Added `data hex2bin` and `data bin2hex` for command line conversion between binary and hexadecimal (holiman) +- Added 'hf snoop'. This command take digitalized signal from FPGA and put in BigBuffer. (pwpiwi + enio) +- Added Topaz (NFC type 1) protocol support ('hf topaz reader', 'hf list topaz', 'hf 14a raw -T', 'hf topaz snoop'). (piwi) +- Added option c to 'hf list' (mark CRC bytes) (piwi) + +### Changed +- Added `[l] ` option to data printdemodbuffer +- Adjusted lf awid clone to optionally clone to Q5 tags +- Adjusted lf t55xx detect to find Q5 tags (t5555) instead of just t55x7 +- Adjusted all lf NRZ demods - works more accurately and consistently (as long as you have strong signal) +- Adjusted lf pskindalademod to reduce false positive reads. +- Small adjustments to psk, nrz, and ask clock detect routines - more reliable. +- Adjusted lf em410x em410xsim to accept a clock argument +- Adjusted lf t55xx dump to allow overriding the safety check and warning text (marshmellow) +- Adjusted lf t55xx write input variables (marshmellow) +- Adjusted lf t55xx read with password safety check and warning text and adjusted the input variables (marshmellow & iceman) +- Adjusted LF FSK demod to account for cross threshold fluctuations (898 count waves will adjust the 9 to 8 now...) more accurate. +- Adjusted timings for t55xx commands. more reliable now. (marshmellow & iceman) +- `lf cmdread` adjusted input methods and added help text (marshmellow & iceman) +- changed `lf config t ` to be 0 - 128 and will trigger on + or - threshold value (marshmellow) +- `hf iclass dump` cli options - can now dump AA1 and AA2 with different keys in one run (does not go to multiple pages for the larger tags yet) +- Revised workflow for StandAloneMode14a (Craig Young) +- EPA functions (`hf epa`) now support both ISO 14443-A and 14443-B cards (frederikmoellers) +- 'hw version' only talks to ARM at startup, after that the info is cached. (pwpiwi) +- Added `r` option to iclass functions - allows key to be provided in raw block 3/4 format + +## [2.2.0][2015-07-12] + +### Changed +- Added `hf 14b raw -s` option to auto select a 14b std tag before raw command +- Changed `hf 14b write` to `hf 14b sriwrite` as it only applied to sri tags (marshmellow) +- Added `hf 14b info` to `hf search` (marshmellow) +- Added compression of fpga config and data, *BOOTROM REFLASH REQUIRED* (piwi) +- Implemented better detection of mifare-tags that are not vulnerable to classic attacks (`hf mf mifare`, `hf mf nested`) (piwi) + +### Added +- Add `hf 14b info` to find and print info about std 14b tags and sri tags (using 14b raw commands in the client) (marshmellow) +- Add PACE replay functionality (frederikmoellers) + +### Fixed +- t55xx write timing (marshmellow) + + +## [2.1.0][2015-06-23] + ### Changed +- Added ultralight/ntag tag type detection to `hf 14a read` (marshmellow) +- Improved ultralight dump command to auto detect tag type, take authentication, and dump full memory (or subset specified) of known tag types (iceman1001 / marshmellow) +- Combined ultralight read/write commands and added authentication (iceman1001) - Improved LF manchester and biphase demodulation and ask clock detection especially for reads with heavy clipping. (marshmellow) - Iclass read, `hf iclass read` now also reads tag config and prints configuration. (holiman) - *bootrom* needs to be flashed, due to new address boundaries between os and fpga, after a size optimization (piwi) @@ -11,8 +82,12 @@ This project uses the changelog in accordance with [keepchangelog](http://keepac ### Fixed - Fixed EM4x50 read/demod of the tags broadcasted memory blocks. 'lf em4x em4x50read' (not page read) (marshmellow) - Fixed issue #19, problems with LF T55xx commands (iceman1001, marshmellow) +- Fixed various problems with iso14443b, issue #103 (piwi, marshmellow) ### Added +- Added `hf search` - currently tests for 14443a tags, iclass tags, and 15693 tags (marshmellow) +- Added `hf mfu info` Ultralight/NTAG info command - reads tag configuration and info, allows authentication if needed (iceman1001, marshmellow) +- Added Mifare Ultralight C and Ultralight EV1/NTAG authentication. (iceman1001) - Added changelog ## [2.0.0] - 2015-03-25 diff --git a/Makefile b/Makefile index b558da2d..bafd8161 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,8 @@ include common/Makefile.common -GZIP=gzip FLASH_PORT=/dev/ttyACM0 -all clean: %: bootrom/% armsrc/% client/% recovery/% +all clean: %: client/% bootrom/% armsrc/% recovery/% bootrom/%: FORCE $(MAKE) -C bootrom $(patsubst bootrom/%,%,$@) @@ -15,18 +14,16 @@ recovery/%: FORCE $(MAKE) -C recovery $(patsubst recovery/%,%,$@) FORCE: # Dummy target to force remake in the subdirectories, even if files exist (this Makefile doesn't know about the prerequisites) +.PHONY: all clean help _test flash-bootrom flash-os flash-all FORCE -.PHONY: all clean help _test flash-bootrom flash-os flash-fpga flash-both flash-all FORCE help: @echo Multi-OS Makefile, you are running on $(DETECTED_OS) @echo Possible targets: @echo + all - Make bootrom, armsrc and the OS-specific host directory @echo + client - Make only the OS-specific host directory @echo + flash-bootrom - Make bootrom and flash it - @echo + flash-os - Make armsrc and flash os (includes fpga) - @echo + flash-fpga - (Deprecated:) Make armsrc and flash fpga - @echo + flash-both - Make armsrc and flash os and fpga image - @echo + flash-all - Make bootrom and armsrc and flash bootrom, os and fpga image + @echo + flash-os - Make armsrc and flash os \(includes fpga\) + @echo + flash-all - Make bootrom and armsrc and flash bootrom and os image @echo + clean - Clean in bootrom, armsrc and the OS-specific host directory client: client/all @@ -34,16 +31,10 @@ client: client/all flash-bootrom: bootrom/obj/bootrom.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) -b $(subst /,$(PATHSEP),$<) -flash-os: armsrc/obj/osimage.elf $(FLASH_TOOL) +flash-os: armsrc/obj/fullimage.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$<) -#flash-fpga: armsrc/obj/fpgaimage.elf $(FLASH_TOOL) -# $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$<) - -flash-both: armsrc/obj/osimage.elf $(FLASH_TOOL) - $(FLASH_TOOL) $(FLASH_PORT) $(subst /,$(PATHSEP),$(filter-out $(FLASH_TOOL),$^)) - -flash-all: bootrom/obj/bootrom.elf armsrc/obj/osimage.elf $(FLASH_TOOL) +flash-all: bootrom/obj/bootrom.elf armsrc/obj/fullimage.elf $(FLASH_TOOL) $(FLASH_TOOL) $(FLASH_PORT) -b $(subst /,$(PATHSEP),$(filter-out $(FLASH_TOOL),$^)) newtarbin: diff --git a/armsrc/BigBuf.c b/armsrc/BigBuf.c index 703ade65..851cf390 100644 --- a/armsrc/BigBuf.c +++ b/armsrc/BigBuf.c @@ -50,11 +50,21 @@ uint8_t *BigBuf_get_EM_addr(void) // clear ALL of BigBuf void BigBuf_Clear(void) +{ + BigBuf_Clear_ext(true); +} +// clear ALL of BigBuf +void BigBuf_Clear_ext(bool verbose) { memset(BigBuf,0,BIGBUF_SIZE); - Dbprintf("Buffer cleared (%i bytes)",BIGBUF_SIZE); + if (verbose) + Dbprintf("Buffer cleared (%i bytes)",BIGBUF_SIZE); } +void BigBuf_Clear_keep_EM(void) +{ + memset(BigBuf,0,BigBuf_hi); +} // allocate a chunk of memory from BigBuf. We allocate high memory first. The unallocated memory // at the beginning of BigBuf is always for traces/samples @@ -88,6 +98,16 @@ void BigBuf_free_keep_EM(void) } } +void BigBuf_print_status(void) +{ + Dbprintf("Memory"); + Dbprintf(" BIGBUF_SIZE.............%d", BIGBUF_SIZE); + Dbprintf(" BigBuf_hi .............%d", BigBuf_hi); + Dbprintf("Tracing"); + Dbprintf(" tracing ................%d", tracing); + Dbprintf(" traceLen ...............%d", traceLen); +} + // return the maximum trace length (i.e. the unallocated size of BigBuf) uint16_t BigBuf_max_traceLen(void) @@ -96,9 +116,6 @@ uint16_t BigBuf_max_traceLen(void) } void clear_trace() { - uint8_t *trace = BigBuf_get_addr(); - uint16_t max_traceLen = BigBuf_max_traceLen(); - memset(trace, 0x44, max_traceLen); traceLen = 0; } @@ -171,18 +188,19 @@ bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_ traceLen += iLen; // parity bytes - if (parity != NULL && iLen != 0) { - memcpy(trace + traceLen, parity, num_paritybytes); + if (num_paritybytes != 0) { + if (parity != NULL) { + memcpy(trace + traceLen, parity, num_paritybytes); + } else { + memset(trace + traceLen, 0x00, num_paritybytes); + } } traceLen += num_paritybytes; - if(traceLen +4 < max_traceLen) - { //If it hadn't been cleared, for whatever reason.. - memset(trace+traceLen,0x44, 4); - } - return TRUE; } + + int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int readerToTag) { /** @@ -224,6 +242,8 @@ int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwP return TRUE; } + + // Emulator memory uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length){ uint8_t* mem = BigBuf_get_EM_addr(); diff --git a/armsrc/BigBuf.h b/armsrc/BigBuf.h index b44a1263..11e02c7a 100644 --- a/armsrc/BigBuf.h +++ b/armsrc/BigBuf.h @@ -24,15 +24,17 @@ extern uint8_t *BigBuf_get_addr(void); extern uint8_t *BigBuf_get_EM_addr(void); extern uint16_t BigBuf_max_traceLen(void); -void BigBuf_Clear(void); +extern void BigBuf_Clear(void); +extern void BigBuf_Clear_ext(bool verbose); +extern void BigBuf_Clear_keep_EM(void); extern uint8_t *BigBuf_malloc(uint16_t); extern void BigBuf_free(void); extern void BigBuf_free_keep_EM(void); - -uint16_t BigBuf_get_traceLen(void); -void clear_trace(); -void set_tracing(bool enable); -bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag); -int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int bReader); -uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length); +extern void BigBuf_print_status(void); +extern uint16_t BigBuf_get_traceLen(void); +extern void clear_trace(); +extern void set_tracing(bool enable); +extern bool RAMFUNC LogTrace(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag); +extern int LogTraceHitag(const uint8_t * btBytes, int iBits, int iSamples, uint32_t dwParity, int bReader); +extern uint8_t emlSet(uint8_t *data, uint32_t offset, uint32_t length); #endif /* __BIGBUF_H */ diff --git a/armsrc/Makefile b/armsrc/Makefile index 899b0307..69ea2300 100644 --- a/armsrc/Makefile +++ b/armsrc/Makefile @@ -9,22 +9,39 @@ APP_INCLUDES = apps.h #remove one of the following defines and comment out the relevant line -#in the next section to remove that particular feature from compilation -APP_CFLAGS = -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -fno-strict-aliasing -ffunction-sections -fdata-sections -#-DWITH_LCD +#in the next section to remove that particular feature from compilation +APP_CFLAGS = -DWITH_ISO14443a_StandAlone -DWITH_LF -DWITH_ISO15693 -DWITH_ISO14443a -DWITH_ISO14443b -DWITH_ICLASS -DWITH_LEGICRF -DWITH_HITAG -DWITH_CRC -DON_DEVICE -DWITH_HFSNOOP \ + -fno-strict-aliasing -ffunction-sections -fdata-sections +#-DWITH_LCD #SRC_LCD = fonts.c LCD.c -SRC_LF = lfops.c hitag2.c lfsampling.c +SRC_LF = lfops.c hitag2.c lfsampling.c pcf7931.c lfdemod.c protocols.c SRC_ISO15693 = iso15693.c iso15693tools.c SRC_ISO14443a = epa.c iso14443a.c mifareutil.c mifarecmd.c mifaresniff.c -SRC_ISO14443b = iso14443.c -SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c -SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c +SRC_ISO14443b = iso14443b.c +SRC_CRAPTO1 = crapto1.c crypto1.c des.c aes.c +SRC_CRC = iso14443crc.c crc.c crc16.c crc32.c +#the FPGA bitstream files. Note: order matters! +FPGA_BITSTREAMS = fpga_lf.bit fpga_hf.bit + +#the zlib source files required for decompressing the fpga config at run time +SRC_ZLIB = inflate.c inffast.c inftrees.c adler32.c zutil.c +#additional defines required to compile zlib +ZLIB_CFLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED +APP_CFLAGS += $(ZLIB_CFLAGS) +# zlib includes: +APP_CFLAGS += -I../zlib + +# stdint.h provided locally until GCC 4.5 becomes C99 compliant +APP_CFLAGS += -I. + +# Compile these in thumb mode (small size) THUMBSRC = start.c \ $(SRC_LCD) \ $(SRC_ISO15693) \ $(SRC_LF) \ + $(SRC_ZLIB) \ appmain.c \ printf.c \ util.c \ @@ -35,7 +52,6 @@ THUMBSRC = start.c \ # These are to be compiled in ARM mode ARMSRC = fpgaloader.c \ legicrf.c \ - lfdemod.c \ $(SRC_ISO14443a) \ $(SRC_ISO14443b) \ $(SRC_CRAPTO1) \ @@ -43,52 +59,66 @@ ARMSRC = fpgaloader.c \ legic_prng.c \ iclass.c \ BigBuf.c \ - optimized_cipher.c - -# stdint.h provided locally until GCC 4.5 becomes C99 compliant -APP_CFLAGS += -I. + optimized_cipher.c \ + hfsnoop.c # Do not move this inclusion before the definition of {THUMB,ASM,ARM}SRC include ../common/Makefile.common -OBJS = $(OBJDIR)/osimage.s19 -#$(OBJDIR)/fpgaimage.s19 +OBJS = $(OBJDIR)/fullimage.s19 +FPGA_COMPRESSOR = ../client/fpga_compress all: $(OBJS) -$(OBJDIR)/fpga_lf.o: fpga_lf.bit - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary____fpga_fpga_lf_bit_start=_binary_fpga_lf_bit_start --redefine-sym _binary____fpga_fpga_lf_bit_end=_binary_fpga_lf_bit_end --prefix-sections=fpga_lf_bit $^ $@ +.DELETE_ON_ERROR: -$(OBJDIR)/fpga_hf.o: fpga_hf.bit - $(OBJCOPY) -O elf32-littlearm -I binary -B arm --redefine-sym _binary____fpga_fpga_hf_bit_start=_binary_fpga_hf_bit_start --redefine-sym _binary____fpga_fpga_hf_bit_end=_binary_fpga_hf_bit_end --prefix-sections=fpga_hf_bit $^ $@ +$(OBJDIR)/fpga_all.o: $(OBJDIR)/fpga_all.bit.z + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --prefix-sections=fpga_all_bit $^ $@ -$(OBJDIR)/fullimage.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_lf.o $(OBJDIR)/fpga_hf.o $(THUMBOBJ) $(ARMOBJ) +$(OBJDIR)/fpga_all.bit.z: $(FPGA_BITSTREAMS) $(FPGA_COMPRESSOR) + $(FPGA_COMPRESSOR) $(filter %.bit,$^) $@ + +$(FPGA_COMPRESSOR): + make -C ../client $(notdir $(FPGA_COMPRESSOR)) + +$(OBJDIR)/fullimage.stage1.elf: $(VERSIONOBJ) $(OBJDIR)/fpga_all.o $(THUMBOBJ) $(ARMOBJ) $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ $(LIBS) -#$(OBJDIR)/fpgaimage.elf: $(OBJDIR)/fullimage.elf -# $(OBJCOPY) -F elf32-littlearm --only-section .fpgaimage $^ $@ +$(OBJDIR)/fullimage.nodata.bin: $(OBJDIR)/fullimage.stage1.elf + $(OBJCOPY) -O binary -I elf32-littlearm --remove-section .data $^ $@ + +$(OBJDIR)/fullimage.nodata.o: $(OBJDIR)/fullimage.nodata.bin + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --rename-section .data=stage1_image $^ $@ + +$(OBJDIR)/fullimage.data.bin: $(OBJDIR)/fullimage.stage1.elf + $(OBJCOPY) -O binary -I elf32-littlearm --only-section .data $^ $@ -$(OBJDIR)/osimage.elf: $(OBJDIR)/fullimage.elf - $(OBJCOPY) -F elf32-littlearm $^ $@ +$(OBJDIR)/fullimage.data.bin.z: $(OBJDIR)/fullimage.data.bin $(FPGA_COMPRESSOR) + $(FPGA_COMPRESSOR) $(filter %.bin,$^) $@ + +$(OBJDIR)/fullimage.data.o: $(OBJDIR)/fullimage.data.bin.z + $(OBJCOPY) -O elf32-littlearm -I binary -B arm --rename-section .data=compressed_data $^ $@ + +$(OBJDIR)/fullimage.elf: $(OBJDIR)/fullimage.nodata.o $(OBJDIR)/fullimage.data.o + $(CC) $(LDFLAGS) -Wl,-T,ldscript,-Map,$(patsubst %.elf,%.map,$@) -o $@ $^ tarbin: $(OBJS) $(TAR) $(TARFLAGS) ../proxmark3-$(platform)-bin.tar $(OBJS:%=armsrc/%) $(OBJS:%.s19=armsrc/%.elf) - clean: $(DELETE) $(OBJDIR)$(PATHSEP)*.o $(DELETE) $(OBJDIR)$(PATHSEP)*.elf $(DELETE) $(OBJDIR)$(PATHSEP)*.s19 $(DELETE) $(OBJDIR)$(PATHSEP)*.map $(DELETE) $(OBJDIR)$(PATHSEP)*.d + $(DELETE) $(OBJDIR)$(PATHSEP)*.z + $(DELETE) $(OBJDIR)$(PATHSEP)*.bin $(DELETE) version.c .PHONY: all clean help help: @echo Multi-OS Makefile, you are running on $(DETECTED_OS) @echo Possible targets: - @echo + all - Make both: - @echo + $(OBJDIR)/osimage.s19 - The OS image - @echo + $(OBJDIR)/fpgaimage.s19 - The FPGA image - @echo + clean - Clean $(OBJDIR) + @echo + all - Build the full image $(OBJDIR)/fullimage.s19 + @echo + clean - Clean $(OBJDIR) diff --git a/armsrc/aes.c b/armsrc/aes.c index 3df006bb..a199d04b 100644 --- a/armsrc/aes.c +++ b/armsrc/aes.c @@ -1,4 +1,3 @@ -#include "stdio.h" #include "aes.h" static const unsigned int Te0[256] = { @@ -1138,6 +1137,9 @@ int AesDecrypt(AesCtx *pCtx, unsigned char *pCipher, unsigned char *pData, unsig ////////////////////////////////////////////////////////////////////////////// #ifndef EMBEDDED + +#include + int main() { AesCtx ctx; diff --git a/armsrc/appmain.c b/armsrc/appmain.c index 96644b9a..782c57fa 100644 --- a/armsrc/appmain.c +++ b/armsrc/appmain.c @@ -25,10 +25,17 @@ #include #include "lfsampling.h" #include "BigBuf.h" +#include "mifareutil.h" +#include "pcf7931.h" #ifdef WITH_LCD #include "LCD.h" #endif +// Craig Young - 14a stand-alone code +#ifdef WITH_ISO14443a_StandAlone + #include "iso14443a.h" +#endif + #define abs(x) ( ((x)<0) ? -(x) : (x) ) //============================================================================= @@ -250,55 +257,6 @@ void MeasureAntennaTuningHf(void) } -void SimulateTagHfListen(void) -{ - // ToDo: historically this used the free buffer, which was 2744 Bytes long. - // There might be a better size to be defined: - #define HF_14B_SNOOP_BUFFER_SIZE 2744 - uint8_t *dest = BigBuf_malloc(HF_14B_SNOOP_BUFFER_SIZE); - uint8_t v = 0; - int i; - int p = 0; - - // We're using this mode just so that I can test it out; the simulated - // tag mode would work just as well and be simpler. - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP); - - // We need to listen to the high-frequency, peak-detected path. - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - - FpgaSetupSsc(); - - i = 0; - for(;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0xff; - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - uint8_t r = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - - v <<= 1; - if(r & 1) { - v |= 1; - } - p++; - - if(p >= 8) { - dest[i] = v; - v = 0; - p = 0; - i++; - - if(i >= HF_14B_SNOOP_BUFFER_SIZE) { - break; - } - } - } - } - DbpString("simulate tag (now type bitsamples)"); -} - void ReadMem(int addr) { const uint8_t *data = ((uint8_t *)addr); @@ -310,11 +268,11 @@ void ReadMem(int addr) /* osimage version information is linked in */ extern struct version_information version_information; /* bootrom version information is pointed to from _bootphase1_version_pointer */ -extern char *_bootphase1_version_pointer, _flash_start, _flash_end; +extern char *_bootphase1_version_pointer, _flash_start, _flash_end, _bootrom_start, _bootrom_end, __data_src_start__; void SendVersion(void) { - char temp[512]; /* Limited data payload in USB packets */ - DbpString("Prox/RFID mark3 RFID instrument"); + char temp[USB_CMD_DATA_SIZE]; /* Limited data payload in USB packets */ + char VersionString[USB_CMD_DATA_SIZE] = { '\0' }; /* Try to find the bootrom version information. Expect to find a pointer at * symbol _bootphase1_version_pointer, perform slight sanity checks on the @@ -322,33 +280,79 @@ void SendVersion(void) */ char *bootrom_version = *(char**)&_bootphase1_version_pointer; if( bootrom_version < &_flash_start || bootrom_version >= &_flash_end ) { - DbpString("bootrom version information appears invalid"); + strcat(VersionString, "bootrom version information appears invalid\n"); } else { FormatVersionInformation(temp, sizeof(temp), "bootrom: ", bootrom_version); - DbpString(temp); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); } FormatVersionInformation(temp, sizeof(temp), "os: ", &version_information); - DbpString(temp); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); - FpgaGatherVersion(temp, sizeof(temp)); - DbpString(temp); - // Send Chip ID - cmd_send(CMD_ACK,*(AT91C_DBGU_CIDR),0,0,NULL,0); + FpgaGatherVersion(FPGA_BITSTREAM_LF, temp, sizeof(temp)); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); + FpgaGatherVersion(FPGA_BITSTREAM_HF, temp, sizeof(temp)); + strncat(VersionString, temp, sizeof(VersionString) - strlen(VersionString) - 1); + + // Send Chip ID and used flash memory + uint32_t text_and_rodata_section_size = (uint32_t)&__data_src_start__ - (uint32_t)&_flash_start; + uint32_t compressed_data_section_size = common_area.arg1; + cmd_send(CMD_ACK, *(AT91C_DBGU_CIDR), text_and_rodata_section_size + compressed_data_section_size, 0, VersionString, strlen(VersionString)); } -#ifdef WITH_LF -// samy's sniff and repeat routine -void SamyRun() +// measure the USB Speed by sending SpeedTestBufferSize bytes to client and measuring the elapsed time. +// Note: this mimics GetFromBigbuf(), i.e. we have the overhead of the UsbCommand structure included. +void printUSBSpeed(void) { - DbpString("Stand-alone mode! No PC necessary."); - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + Dbprintf("USB Speed:"); + Dbprintf(" Sending USB packets to client..."); - // 3 possible options? no just 2 for now -#define OPTS 2 + #define USB_SPEED_TEST_MIN_TIME 1500 // in milliseconds + uint8_t *test_data = BigBuf_get_addr(); + uint32_t end_time; - int high[OPTS], low[OPTS]; + uint32_t start_time = end_time = GetTickCount(); + uint32_t bytes_transferred = 0; + + LED_B_ON(); + while(end_time < start_time + USB_SPEED_TEST_MIN_TIME) { + cmd_send(CMD_DOWNLOADED_RAW_ADC_SAMPLES_125K, 0, USB_CMD_DATA_SIZE, 0, test_data, USB_CMD_DATA_SIZE); + end_time = GetTickCount(); + bytes_transferred += USB_CMD_DATA_SIZE; + } + LED_B_OFF(); + + Dbprintf(" Time elapsed: %dms", end_time - start_time); + Dbprintf(" Bytes transferred: %d", bytes_transferred); + Dbprintf(" USB Transfer Speed PM3 -> Client = %d Bytes/s", + 1000 * bytes_transferred / (end_time - start_time)); +} + +/** + * Prints runtime information about the PM3. +**/ +void SendStatus(void) +{ + BigBuf_print_status(); + Fpga_print_status(); + printConfig(); //LF Sampling config + printUSBSpeed(); + Dbprintf("Various"); + Dbprintf(" MF_DBGLEVEL......%d", MF_DBGLEVEL); + Dbprintf(" ToSendMax........%d",ToSendMax); + Dbprintf(" ToSendBit........%d",ToSendBit); + + cmd_send(CMD_ACK,1,0,0,0,0); +} + +#if defined(WITH_ISO14443a_StandAlone) || defined(WITH_LF) + +#define OPTS 2 + +void StandAloneMode() +{ + DbpString("Stand-alone mode! No PC necessary."); // Oooh pretty -- notify user we're in elite samy mode now LED(LED_RED, 200); LED(LED_ORANGE, 200); @@ -360,6 +364,270 @@ void SamyRun() LED(LED_ORANGE, 200); LED(LED_RED, 200); +} + +#endif + + + +#ifdef WITH_ISO14443a_StandAlone +void StandAloneMode14a() +{ + StandAloneMode(); + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + + int selected = 0; + int playing = 0, iGotoRecord = 0, iGotoClone = 0; + int cardRead[OPTS] = {0}; + uint8_t readUID[10] = {0}; + uint32_t uid_1st[OPTS]={0}; + uint32_t uid_2nd[OPTS]={0}; + uint32_t uid_tmp1 = 0; + uint32_t uid_tmp2 = 0; + iso14a_card_select_t hi14a_card[OPTS]; + + LED(selected + 1, 0); + + for (;;) + { + usb_poll(); + WDT_HIT(); + SpinDelay(300); + + if (iGotoRecord == 1 || cardRead[selected] == 0) + { + iGotoRecord = 0; + LEDsoff(); + LED(selected + 1, 0); + LED(LED_RED2, 0); + + // record + Dbprintf("Enabling iso14443a reader mode for [Bank: %u]...", selected); + /* need this delay to prevent catching some weird data */ + SpinDelay(500); + /* Code for reading from 14a tag */ + uint8_t uid[10] ={0}; + uint32_t cuid; + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + + for ( ; ; ) + { + WDT_HIT(); + if (BUTTON_PRESS()) { + if (cardRead[selected]) { + Dbprintf("Button press detected -- replaying card in bank[%d]", selected); + break; + } + else if (cardRead[(selected+1)%OPTS]) { + Dbprintf("Button press detected but no card in bank[%d] so playing from bank[%d]", selected, (selected+1)%OPTS); + selected = (selected+1)%OPTS; + break; // playing = 1; + } + else { + Dbprintf("Button press detected but no stored tag to play. (Ignoring button)"); + SpinDelay(300); + } + } + if (!iso14443a_select_card(uid, &hi14a_card[selected], &cuid)) + continue; + else + { + Dbprintf("Read UID:"); Dbhexdump(10,uid,0); + memcpy(readUID,uid,10*sizeof(uint8_t)); + uint8_t *dst = (uint8_t *)&uid_tmp1; + // Set UID byte order + for (int i=0; i<4; i++) + dst[i] = uid[3-i]; + dst = (uint8_t *)&uid_tmp2; + for (int i=0; i<4; i++) + dst[i] = uid[7-i]; + if (uid_1st[(selected+1)%OPTS] == uid_tmp1 && uid_2nd[(selected+1)%OPTS] == uid_tmp2) { + Dbprintf("Card selected has same UID as what is stored in the other bank. Skipping."); + } + else { + if (uid_tmp2) { + Dbprintf("Bank[%d] received a 7-byte UID",selected); + uid_1st[selected] = (uid_tmp1)>>8; + uid_2nd[selected] = (uid_tmp1<<24) + (uid_tmp2>>8); + } + else { + Dbprintf("Bank[%d] received a 4-byte UID",selected); + uid_1st[selected] = uid_tmp1; + uid_2nd[selected] = uid_tmp2; + } + break; + } + } + } + Dbprintf("ATQA = %02X%02X",hi14a_card[selected].atqa[0],hi14a_card[selected].atqa[1]); + Dbprintf("SAK = %02X",hi14a_card[selected].sak); + LEDsoff(); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + LED(LED_GREEN, 200); + LED(LED_ORANGE, 200); + + LEDsoff(); + LED(selected + 1, 0); + + // Next state is replay: + playing = 1; + + cardRead[selected] = 1; + } + /* MF Classic UID clone */ + else if (iGotoClone==1) + { + iGotoClone=0; + LEDsoff(); + LED(selected + 1, 0); + LED(LED_ORANGE, 250); + + + // record + Dbprintf("Preparing to Clone card [Bank: %x]; uid: %08x", selected, uid_1st[selected]); + + // wait for button to be released + while(BUTTON_PRESS()) + { + // Delay cloning until card is in place + WDT_HIT(); + } + Dbprintf("Starting clone. [Bank: %u]", selected); + // need this delay to prevent catching some weird data + SpinDelay(500); + // Begin clone function here: + /* Example from client/mifarehost.c for commanding a block write for "magic Chinese" cards: + UsbCommand c = {CMD_MIFARE_CSETBLOCK, {wantWipe, params & (0xFE | (uid == NULL ? 0:1)), blockNo}}; + memcpy(c.d.asBytes, data, 16); + SendCommand(&c); + + Block read is similar: + UsbCommand c = {CMD_MIFARE_CGETBLOCK, {params, 0, blockNo}}; + We need to imitate that call with blockNo 0 to set a uid. + + The get and set commands are handled in this file: + // Work with "magic Chinese" card + case CMD_MIFARE_CSETBLOCK: + MifareCSetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + break; + case CMD_MIFARE_CGETBLOCK: + MifareCGetBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); + break; + + mfCSetUID provides example logic for UID set workflow: + -Read block0 from card in field with MifareCGetBlock() + -Configure new values without replacing reserved bytes + memcpy(block0, uid, 4); // Copy UID bytes from byte array + // Mifare UID BCC + block0[4] = block0[0]^block0[1]^block0[2]^block0[3]; // BCC on byte 5 + Bytes 5-7 are reserved SAK and ATQA for mifare classic + -Use mfCSetBlock(0, block0, oldUID, wantWipe, CSETBLOCK_SINGLE_OPER) to write it + */ + uint8_t oldBlock0[16] = {0}, newBlock0[16] = {0}, testBlock0[16] = {0}; + // arg0 = Flags == CSETBLOCK_SINGLE_OPER=0x1F, arg1=returnSlot, arg2=blockNo + MifareCGetBlock(0x3F, 1, 0, oldBlock0); + if (oldBlock0[0] == 0 && oldBlock0[0] == oldBlock0[1] && oldBlock0[1] == oldBlock0[2] && oldBlock0[2] == oldBlock0[3]) { + Dbprintf("No changeable tag detected. Returning to replay mode for bank[%d]", selected); + playing = 1; + } + else { + Dbprintf("UID from target tag: %02X%02X%02X%02X", oldBlock0[0],oldBlock0[1],oldBlock0[2],oldBlock0[3]); + memcpy(newBlock0,oldBlock0,16); + // Copy uid_1st for bank (2nd is for longer UIDs not supported if classic) + + newBlock0[0] = uid_1st[selected]>>24; + newBlock0[1] = 0xFF & (uid_1st[selected]>>16); + newBlock0[2] = 0xFF & (uid_1st[selected]>>8); + newBlock0[3] = 0xFF & (uid_1st[selected]); + newBlock0[4] = newBlock0[0]^newBlock0[1]^newBlock0[2]^newBlock0[3]; + // arg0 = needWipe, arg1 = workFlags, arg2 = blockNo, datain + MifareCSetBlock(0, 0xFF,0, newBlock0); + MifareCGetBlock(0x3F, 1, 0, testBlock0); + if (memcmp(testBlock0,newBlock0,16)==0) + { + DbpString("Cloned successfull!"); + cardRead[selected] = 0; // Only if the card was cloned successfully should we clear it + playing = 0; + iGotoRecord = 1; + selected = (selected+1) % OPTS; + } + else { + Dbprintf("Clone failed. Back to replay mode on bank[%d]", selected); + playing = 1; + } + } + LEDsoff(); + LED(selected + 1, 0); + + } + // Change where to record (or begin playing) + else if (playing==1) // button_pressed == BUTTON_SINGLE_CLICK && cardRead[selected]) + { + LEDsoff(); + LED(selected + 1, 0); + + // Begin transmitting + if (playing) + { + LED(LED_GREEN, 0); + DbpString("Playing"); + for ( ; ; ) { + WDT_HIT(); + int button_action = BUTTON_HELD(1000); + if (button_action == 0) { // No button action, proceed with sim + uint8_t data[512] = {0}; // in case there is a read command received we shouldn't break + Dbprintf("Simulating ISO14443a tag with uid[0]: %08x, uid[1]: %08x [Bank: %u]", uid_1st[selected],uid_2nd[selected],selected); + if (hi14a_card[selected].sak == 8 && hi14a_card[selected].atqa[0] == 4 && hi14a_card[selected].atqa[1] == 0) { + DbpString("Mifare Classic"); + SimulateIso14443aTag(1,uid_1st[selected], uid_2nd[selected], data); // Mifare Classic + } + else if (hi14a_card[selected].sak == 0 && hi14a_card[selected].atqa[0] == 0x44 && hi14a_card[selected].atqa[1] == 0) { + DbpString("Mifare Ultralight"); + SimulateIso14443aTag(2,uid_1st[selected],uid_2nd[selected],data); // Mifare Ultralight + } + else if (hi14a_card[selected].sak == 20 && hi14a_card[selected].atqa[0] == 0x44 && hi14a_card[selected].atqa[1] == 3) { + DbpString("Mifare DESFire"); + SimulateIso14443aTag(3,uid_1st[selected],uid_2nd[selected],data); // Mifare DESFire + } + else { + Dbprintf("Unrecognized tag type -- defaulting to Mifare Classic emulation"); + SimulateIso14443aTag(1,uid_1st[selected], uid_2nd[selected], data); + } + } + else if (button_action == BUTTON_SINGLE_CLICK) { + selected = (selected + 1) % OPTS; + Dbprintf("Done playing. Switching to record mode on bank %d",selected); + iGotoRecord = 1; + break; + } + else if (button_action == BUTTON_HOLD) { + Dbprintf("Playtime over. Begin cloning..."); + iGotoClone = 1; + break; + } + WDT_HIT(); + } + + /* We pressed a button so ignore it here with a delay */ + SpinDelay(300); + LEDsoff(); + LED(selected + 1, 0); + } + else + while(BUTTON_PRESS()) + WDT_HIT(); + } + } +} +#elif WITH_LF +// samy's sniff and repeat routine +void SamyRun() +{ + StandAloneMode(); + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + int high[OPTS], low[OPTS]; int selected = 0; int playing = 0; int cardRead = 0; @@ -370,7 +638,7 @@ void SamyRun() for (;;) { usb_poll(); - WDT_HIT(); + WDT_HIT(); // Was our button held down or pressed? int button_pressed = BUTTON_HELD(1000); @@ -394,7 +662,7 @@ void SamyRun() SpinDelay(500); CmdHIDdemodFSK(1, &high[selected], &low[selected], 0); - Dbprintf("Recorded %x %x %x", selected, high[selected], low[selected]); + Dbprintf("Recorded %x %x%08x", selected, high[selected], low[selected]); LEDsoff(); LED(selected + 1, 0); @@ -415,7 +683,7 @@ void SamyRun() LED(LED_ORANGE, 0); // record - Dbprintf("Cloning %x %x %x", selected, high[selected], low[selected]); + Dbprintf("Cloning %x %x%08x", selected, high[selected], low[selected]); // wait for button to be released while(BUTTON_PRESS()) @@ -424,8 +692,8 @@ void SamyRun() /* need this delay to prevent catching some weird data */ SpinDelay(500); - CopyHIDtoT55x7(high[selected], low[selected], 0, 0); - Dbprintf("Cloned %x %x %x", selected, high[selected], low[selected]); + CopyHIDtoT55x7(0, high[selected], low[selected], 0); + Dbprintf("Cloned %x %x%08x", selected, high[selected], low[selected]); LEDsoff(); LED(selected + 1, 0); @@ -458,7 +726,7 @@ void SamyRun() // wait for button to be released while(BUTTON_PRESS()) WDT_HIT(); - Dbprintf("%x %x %x", selected, high[selected], low[selected]); + Dbprintf("%x %x%08x", selected, high[selected], low[selected]); CmdHIDsimTAG(high[selected], low[selected], 0); DbpString("Done playing"); if (BUTTON_HELD(1000) > 0) @@ -483,8 +751,8 @@ void SamyRun() } } } -#endif +#endif /* OBJECTIVE Listen and detect an external reader. Determine the best location @@ -678,7 +946,7 @@ void UsbPacketReceived(uint8_t *packet, int len) CmdIOdemodFSK(c->arg[0], 0, 0, 1); break; case CMD_IO_CLONE_TAG: - CopyIOtoT55x7(c->arg[0], c->arg[1], c->d.asBytes[0]); + CopyIOtoT55x7(c->arg[0], c->arg[1]); break; case CMD_EM410X_DEMOD: CmdEM410xdemod(c->arg[0], 0, 0, 1); @@ -707,17 +975,22 @@ void UsbPacketReceived(uint8_t *packet, int len) 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]); break; case CMD_T55XX_READ_BLOCK: - T55xxReadBlock(c->arg[1], c->arg[2],c->d.asBytes[0]); + T55xxReadBlock(c->arg[0], c->arg[1], c->arg[2]); break; case CMD_T55XX_WRITE_BLOCK: T55xxWriteBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes[0]); break; - case CMD_T55XX_READ_TRACE: - T55xxReadTrace(); + case CMD_T55XX_WAKEUP: + T55xxWakeUp(c->arg[0]); + break; + case CMD_T55XX_RESET_READ: + T55xxResetRead(); break; case CMD_PCF7931_READ: ReadPCF7931(); - cmd_send(CMD_ACK,0,0,0,0,0); + break; + case CMD_PCF7931_WRITE: + 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]); break; case CMD_EM4X_READ_WORD: EM4xReadWord(c->arg[1], c->arg[2],c->d.asBytes[0]); @@ -725,6 +998,12 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_EM4X_WRITE_WORD: EM4xWriteWord(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes[0]); break; + case CMD_AWID_DEMOD_FSK: // Set realtime AWID demodulation + CmdAWIDdemodFSK(c->arg[0], 0, 0, 1); + break; + case CMD_VIKING_CLONE_TAG: + CopyVikingtoT55xx(c->arg[0], c->arg[1], c->arg[2]); + break; #endif #ifdef WITH_HITAG @@ -782,20 +1061,17 @@ void UsbPacketReceived(uint8_t *packet, int len) #endif #ifdef WITH_ISO14443b - case CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443: - AcquireRawAdcSamplesIso14443(c->arg[0]); - break; case CMD_READ_SRI512_TAG: - ReadSTMemoryIso14443(0x0F); + ReadSTMemoryIso14443b(0x0F); break; case CMD_READ_SRIX4K_TAG: - ReadSTMemoryIso14443(0x7F); + ReadSTMemoryIso14443b(0x7F); break; - case CMD_SNOOP_ISO_14443: - SnoopIso14443(); + case CMD_SNOOP_ISO_14443B: + SnoopIso14443b(); break; - case CMD_SIMULATE_TAG_ISO_14443: - SimulateIso14443Tag(); + case CMD_SIMULATE_TAG_ISO_14443B: + SimulateIso14443bTag(); break; case CMD_ISO_14443B_COMMAND: SendRawCommand14443B(c->arg[0],c->arg[1],c->arg[2],c->d.asBytes); @@ -816,6 +1092,9 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_EPA_PACE_COLLECT_NONCE: EPA_PACE_Collect_Nonce(c); break; + case CMD_EPA_PACE_REPLAY: + EPA_PACE_Replay(c); + break; case CMD_READER_MIFARE: ReaderMifare(c->arg[0]); @@ -841,11 +1120,11 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_MIFARE_WRITEBL: MifareWriteBlock(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); break; - case CMD_MIFAREU_WRITEBL_COMPAT: - MifareUWriteBlock(c->arg[0], c->d.asBytes); - break; + //case CMD_MIFAREU_WRITEBL_COMPAT: + //MifareUWriteBlockCompat(c->arg[0], c->d.asBytes); + //break; case CMD_MIFAREU_WRITEBL: - MifareUWriteBlock_Special(c->arg[0], c->d.asBytes); + MifareUWriteBlock(c->arg[0], c->arg[1], c->d.asBytes); break; case CMD_MIFARE_NESTED: MifareNested(c->arg[0], c->arg[1], c->arg[2], c->d.asBytes); @@ -904,16 +1183,35 @@ void UsbPacketReceived(uint8_t *packet, int len) ReaderIClass(c->arg[0]); break; case CMD_READER_ICLASS_REPLAY: - ReaderIClass_Replay(c->arg[0], c->d.asBytes); + ReaderIClass_Replay(c->arg[0], c->d.asBytes); break; - case CMD_ICLASS_EML_MEMSET: + case CMD_ICLASS_EML_MEMSET: emlSet(c->d.asBytes,c->arg[0], c->arg[1]); break; + case CMD_ICLASS_WRITEBLOCK: + iClass_WriteBlock(c->arg[0], c->d.asBytes); + break; + case CMD_ICLASS_READCHECK: // auth step 1 + iClass_ReadCheck(c->arg[0], c->arg[1]); + break; + case CMD_ICLASS_READBLOCK: + iClass_ReadBlk(c->arg[0]); + break; + case CMD_ICLASS_AUTHENTICATION: //check + iClass_Authentication(c->d.asBytes); + break; + case CMD_ICLASS_DUMP: + iClass_Dump(c->arg[0], c->arg[1]); + break; + case CMD_ICLASS_CLONE: + iClass_Clone(c->arg[0], c->arg[1], c->d.asBytes); + break; #endif - - case CMD_SIMULATE_TAG_HF_LISTEN: - SimulateTagHfListen(); +#ifdef WITH_HFSNOOP + case CMD_HF_SNIFFER: + HfSnoop(c->arg[0], c->arg[1]); break; +#endif case CMD_BUFF_CLEAR: BigBuf_Clear(); @@ -977,7 +1275,12 @@ void UsbPacketReceived(uint8_t *packet, int len) case CMD_VERSION: SendVersion(); break; - + case CMD_STATUS: + SendStatus(); + break; + case CMD_PING: + cmd_send(CMD_ACK,0,0,0,0,0); + break; #ifdef WITH_LCD case CMD_LCD_RESET: LCDReset(); @@ -1045,7 +1348,7 @@ void __attribute__((noreturn)) AppMain(void) AT91C_BASE_PMC->PMC_SCER = AT91C_PMC_PCK0; // PCK0 is PLL clock / 4 = 96Mhz / 4 = 24Mhz AT91C_BASE_PMC->PMC_PCKR[0] = AT91C_PMC_CSS_PLL_CLK | - AT91C_PMC_PRES_CLK_4; + AT91C_PMC_PRES_CLK_4; // 4 for 24Mhz pck0, 2 for 48 MHZ pck0 AT91C_BASE_PIOA->PIO_OER = GPIO_PCK0; // Reset SPI @@ -1076,8 +1379,16 @@ void __attribute__((noreturn)) AppMain(void) WDT_HIT(); #ifdef WITH_LF +#ifndef WITH_ISO14443a_StandAlone if (BUTTON_HELD(1000) > 0) SamyRun(); +#endif +#endif +#ifdef WITH_ISO14443a +#ifdef WITH_ISO14443a_StandAlone + if (BUTTON_HELD(1000) > 0) + StandAloneMode14a(); +#endif #endif } } diff --git a/armsrc/apps.h b/armsrc/apps.h index 57fb55fd..c8397c38 100644 --- a/armsrc/apps.h +++ b/armsrc/apps.h @@ -19,6 +19,7 @@ #include "mifare.h" #include "../common/crc32.h" #include "BigBuf.h" +#include "fpgaloader.h" extern const uint8_t OddByteParity[256]; extern int rsamples; // = 0; @@ -50,60 +51,6 @@ void ListenReaderField(int limit); extern int ToSendMax; extern uint8_t ToSend[]; -/// fpga.h -void FpgaSendCommand(uint16_t cmd, uint16_t v); -void FpgaWriteConfWord(uint8_t v); -void FpgaDownloadAndGo(int bitstream_version); -int FpgaGatherBitstreamVersion(); -void FpgaGatherVersion(char *dst, int len); -void FpgaSetupSsc(void); -void SetupSpi(int mode); -bool FpgaSetupSscDma(uint8_t *buf, int len); -#define FpgaDisableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; -#define FpgaEnableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; -void SetAdcMuxFor(uint32_t whichGpio); - -// Definitions for the FPGA commands. -#define FPGA_CMD_SET_CONFREG (1<<12) -#define FPGA_CMD_SET_DIVISOR (2<<12) -#define FPGA_CMD_SET_USER_BYTE1 (3<<12) -// Definitions for the FPGA configuration word. -// LF -#define FPGA_MAJOR_MODE_LF_ADC (0<<5) -#define FPGA_MAJOR_MODE_LF_EDGE_DETECT (1<<5) -#define FPGA_MAJOR_MODE_LF_PASSTHRU (2<<5) -// HF -#define FPGA_MAJOR_MODE_HF_READER_TX (0<<5) -#define FPGA_MAJOR_MODE_HF_READER_RX_XCORR (1<<5) -#define FPGA_MAJOR_MODE_HF_SIMULATOR (2<<5) -#define FPGA_MAJOR_MODE_HF_ISO14443A (3<<5) -// BOTH -#define FPGA_MAJOR_MODE_OFF (7<<5) -// Options for LF_ADC -#define FPGA_LF_ADC_READER_FIELD (1<<0) -// Options for LF_EDGE_DETECT -#define FPGA_CMD_SET_EDGE_DETECT_THRESHOLD FPGA_CMD_SET_USER_BYTE1 -#define FPGA_LF_EDGE_DETECT_READER_FIELD (1<<0) -#define FPGA_LF_EDGE_DETECT_TOGGLE_MODE (1<<1) -// Options for the HF reader, tx to tag -#define FPGA_HF_READER_TX_SHALLOW_MOD (1<<0) -// Options for the HF reader, correlating against rx from tag -#define FPGA_HF_READER_RX_XCORR_848_KHZ (1<<0) -#define FPGA_HF_READER_RX_XCORR_SNOOP (1<<1) -#define FPGA_HF_READER_RX_XCORR_QUARTER_FREQ (1<<2) -// Options for the HF simulated tag, how to modulate -#define FPGA_HF_SIMULATOR_NO_MODULATION (0<<0) -#define FPGA_HF_SIMULATOR_MODULATE_BPSK (1<<0) -#define FPGA_HF_SIMULATOR_MODULATE_212K (2<<0) -#define FPGA_HF_SIMULATOR_MODULATE_424K (4<<0) -#define FPGA_HF_SIMULATOR_MODULATE_424K_8BIT 0x5//101 - -// Options for ISO14443A -#define FPGA_HF_ISO14443A_SNIFFER (0<<0) -#define FPGA_HF_ISO14443A_TAGSIM_LISTEN (1<<0) -#define FPGA_HF_ISO14443A_TAGSIM_MOD (2<<0) -#define FPGA_HF_ISO14443A_READER_LISTEN (3<<0) -#define FPGA_HF_ISO14443A_READER_MOD (4<<0) /// lfops.h extern uint8_t decimation; @@ -111,40 +58,42 @@ extern uint8_t bits_per_sample ; extern bool averaging; void AcquireRawAdcSamples125k(int divisor); -void ModThenAcquireRawAdcSamples125k(int delay_off,int period_0,int period_1,uint8_t *command); +void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint32_t period_1, uint8_t *command); void ReadTItag(void); void WriteTItag(uint32_t idhi, uint32_t idlo, uint16_t crc); + void AcquireTiType(void); void AcquireRawBitsTI(void); void SimulateTagLowFrequency(int period, int gap, int ledcontrol); +void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen); void CmdHIDsimTAG(int hi, int lo, int ledcontrol); void CmdFSKsimTAG(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream); void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream); void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream); void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol); +void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol); // Realtime demodulation mode for AWID26 void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol); void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol); -void CopyIOtoT55x7(uint32_t hi, uint32_t lo, uint8_t longFMT); // Clone an ioProx card to T5557/T5567 -void SimulateTagLowFrequencyBidir(int divisor, int max_bitlen); +void CopyIOtoT55x7(uint32_t hi, uint32_t lo); // Clone an ioProx card to T5557/T5567 void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT); // Clone an HID card to T5557/T5567 +void CopyVikingtoT55xx(uint32_t block1, uint32_t block2, uint8_t Q5); void WriteEM410x(uint32_t card, uint32_t id_hi, uint32_t id_lo); -void CopyIndala64toT55x7(int hi, int lo); // Clone Indala 64-bit tag by UID to T55x7 -void CopyIndala224toT55x7(int uid1, int uid2, int uid3, int uid4, int uid5, int uid6, int uid7); // Clone Indala 224-bit tag by UID to T55x7 +void CopyIndala64toT55x7(uint32_t hi, uint32_t lo); // Clone Indala 64-bit tag by UID to T55x7 +void CopyIndala224toT55x7(uint32_t uid1, uint32_t uid2, uint32_t uid3, uint32_t uid4, uint32_t uid5, uint32_t uid6, uint32_t uid7); // Clone Indala 224-bit tag by UID to T55x7 +void T55xxResetRead(void); void T55xxWriteBlock(uint32_t Data, uint32_t Block, uint32_t Pwd, uint8_t PwdMode); -void T55xxReadBlock(uint32_t Block, uint32_t Pwd, uint8_t PwdMode ); -void T55xxReadTrace(void); -int DemodPCF7931(uint8_t **outBlocks); -int IsBlock0PCF7931(uint8_t *Block); -int IsBlock1PCF7931(uint8_t *Block); -void ReadPCF7931(); +void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd); +void T55xxWakeUp(uint32_t Pwd); +void TurnReadLFOn(); +//void T55xxReadTrace(void); void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode); void EM4xWriteWord(uint32_t Data, uint8_t Address, uint32_t Pwd, uint8_t PwdMode); /// iso14443.h -void SimulateIso14443Tag(void); -void AcquireRawAdcSamplesIso14443(uint32_t parameter); -void ReadSTMemoryIso14443(uint32_t); -void RAMFUNC SnoopIso14443(void); +void SimulateIso14443bTag(void); +void AcquireRawAdcSamplesIso14443b(uint32_t parameter); +void ReadSTMemoryIso14443b(uint32_t); +void RAMFUNC SnoopIso14443b(void); void SendRawCommand14443B(uint32_t, uint32_t, uint8_t, uint8_t[]); /// iso14443a.h @@ -160,6 +109,7 @@ void RAMFUNC SniffMifare(uint8_t param); /// epa.h void EPA_PACE_Collect_Nonce(UsbCommand * c); +void EPA_PACE_Replay(UsbCommand *c); // mifarecmd.h void ReaderMifare(bool first_try); @@ -170,10 +120,10 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *datain); void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain); void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); -void MifareUWriteBlock(uint8_t arg0,uint8_t *datain); -void MifareUWriteBlock_Special(uint8_t arg0,uint8_t *datain); +//void MifareUWriteBlockCompat(uint8_t arg0,uint8_t *datain); +void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain); void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); -void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain); +void 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); void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain); @@ -201,9 +151,6 @@ void OnSuccess(); void OnError(uint8_t reason); - - - /// iso15693.h void RecordRawAdcSamplesIso15693(void); void AcquireRawAdcSamplesIso15693(void); @@ -219,6 +166,13 @@ 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); void IClass_iso14443A_GetPublic(uint8_t arg0); +void iClass_Authentication(uint8_t *MAC); +void iClass_WriteBlock(uint8_t blockNo, uint8_t *data); +void iClass_ReadBlk(uint8_t blockNo); +bool iClass_ReadBlock(uint8_t blockNo, uint8_t *readdata); +void iClass_Dump(uint8_t blockno, uint8_t numblks); +void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t *data); +void iClass_ReadCheck(uint8_t blockNo, uint8_t keyType); // hitag2.h void SnoopHitag(uint32_t type); @@ -230,5 +184,6 @@ bool cmd_receive(UsbCommand* cmd); bool cmd_send(uint32_t cmd, uint32_t arg0, uint32_t arg1, uint32_t arg2, void* data, size_t len); /// util.h +void HfSnoop(int , int); #endif diff --git a/armsrc/des.c b/armsrc/des.c index a81df9c8..f1aa80da 100644 --- a/armsrc/des.c +++ b/armsrc/des.c @@ -274,7 +274,7 @@ uint32_t des_f(uint32_t r, uint8_t* kr){ uint64_t data; uint8_t *sbp; /* sboxpointer */ permute((uint8_t*)e_permtab, (uint8_t*)&r, (uint8_t*)&data); - for(i=0; i<7; ++i) + for(i=0; i<6; ++i) ((uint8_t*)&data)[i] ^= kr[i]; /* Sbox substitution */ diff --git a/armsrc/epa.c b/armsrc/epa.c index 0006d59d..50c7d878 100644 --- a/armsrc/epa.c +++ b/armsrc/epa.c @@ -5,17 +5,18 @@ // at your option, any later version. See the LICENSE.txt file for the text of // the license. //----------------------------------------------------------------------------- -// Routines to support the German eletronic "Personalausweis" (ID card) +// Routines to support the German electronic "Personalausweis" (ID card) // Note that the functions which do not implement USB commands do NOT initialize // the card (with iso14443a_select_card etc.). If You want to use these // functions, You need to do the setup before calling them! //----------------------------------------------------------------------------- #include "iso14443a.h" +#include "iso14443b.h" #include "epa.h" #include "cmd.h" -// Protocol and Parameter Selection Request +// Protocol and Parameter Selection Request for ISO 14443 type A cards // use regular (1x) speed in both directions // CRC is already included static const uint8_t pps[] = {0xD0, 0x11, 0x00, 0x52, 0xA6}; @@ -74,6 +75,54 @@ static const uint8_t oid_pace_start[] = { 0x04 // id-PACE }; +// APDUs for replaying: +// MSE: Set AT (initiate PACE) +static uint8_t apdu_replay_mse_set_at_pace[41]; +// General Authenticate (Get Nonce) +static uint8_t apdu_replay_general_authenticate_pace_get_nonce[8]; +// General Authenticate (Map Nonce) +static uint8_t apdu_replay_general_authenticate_pace_map_nonce[75]; +// General Authenticate (Mutual Authenticate) +static uint8_t apdu_replay_general_authenticate_pace_mutual_authenticate[75]; +// General Authenticate (Perform Key Agreement) +static uint8_t apdu_replay_general_authenticate_pace_perform_key_agreement[18]; +// pointers to the APDUs (for iterations) +static struct { + uint8_t len; + uint8_t *data; +} const apdus_replay[] = { + {sizeof(apdu_replay_mse_set_at_pace), apdu_replay_mse_set_at_pace}, + {sizeof(apdu_replay_general_authenticate_pace_get_nonce), apdu_replay_general_authenticate_pace_get_nonce}, + {sizeof(apdu_replay_general_authenticate_pace_map_nonce), apdu_replay_general_authenticate_pace_map_nonce}, + {sizeof(apdu_replay_general_authenticate_pace_mutual_authenticate), apdu_replay_general_authenticate_pace_mutual_authenticate}, + {sizeof(apdu_replay_general_authenticate_pace_perform_key_agreement), apdu_replay_general_authenticate_pace_perform_key_agreement} +}; + +// lengths of the replay APDUs +static uint8_t apdu_lengths_replay[5]; + +// type of card (ISO 14443 A or B) +static char iso_type = 0; + +//----------------------------------------------------------------------------- +// Wrapper for sending APDUs to type A and B cards +//----------------------------------------------------------------------------- +int EPA_APDU(uint8_t *apdu, size_t length, uint8_t *response) +{ + switch(iso_type) + { + case 'a': + return iso14_apdu(apdu, (uint16_t) length, response); + break; + case 'b': + return iso14443b_apdu(apdu, length, response); + break; + default: + return 0; + break; + } +} + //----------------------------------------------------------------------------- // Closes the communication channel and turns off the field //----------------------------------------------------------------------------- @@ -81,6 +130,7 @@ void EPA_Finish() { FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); + iso_type = 0; } //----------------------------------------------------------------------------- @@ -101,7 +151,7 @@ size_t EPA_Parse_CardAccess(uint8_t *data, pace_version_info_t *pace_info) { size_t index = 0; - + while (index <= length - 2) { // determine type of element // SET or SEQUENCE @@ -158,7 +208,7 @@ size_t EPA_Parse_CardAccess(uint8_t *data, index += 2 + data[index + 1]; } } - + // TODO: We should check whether we reached the end in error, but for that // we need a better parser (e.g. with states like IN_SET or IN_PACE_INFO) return 0; @@ -176,31 +226,31 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) // we reserve 262 bytes here just to be safe (256-byte APDU + SW + ISO frame) uint8_t response_apdu[262]; int rapdu_length = 0; - + // select the file EF.CardAccess - rapdu_length = iso14_apdu((uint8_t *)apdu_select_binary_cardaccess, + rapdu_length = EPA_APDU((uint8_t *)apdu_select_binary_cardaccess, sizeof(apdu_select_binary_cardaccess), response_apdu); - if (rapdu_length != 6 + if (rapdu_length < 6 || response_apdu[rapdu_length - 4] != 0x90 || response_apdu[rapdu_length - 3] != 0x00) { - Dbprintf("epa - no select cardaccess"); + DbpString("Failed to select EF.CardAccess!"); return -1; } - + // read the file - rapdu_length = iso14_apdu((uint8_t *)apdu_read_binary, + rapdu_length = EPA_APDU((uint8_t *)apdu_read_binary, sizeof(apdu_read_binary), response_apdu); if (rapdu_length <= 6 || response_apdu[rapdu_length - 4] != 0x90 || response_apdu[rapdu_length - 3] != 0x00) { - Dbprintf("epa - no read cardaccess"); + Dbprintf("Failed to read EF.CardAccess!"); return -1; } - + // copy the content into the buffer // length of data available: apdu_length - 4 (ISO frame) - 2 (SW) size_t to_copy = rapdu_length - 6; @@ -215,16 +265,11 @@ int EPA_Read_CardAccess(uint8_t *buffer, size_t max_length) //----------------------------------------------------------------------------- static void EPA_PACE_Collect_Nonce_Abort(uint8_t step, int func_return) { -// // step in which the failure occured -// ack->arg[0] = step; -// // last return code -// ack->arg[1] = func_return; - // power down the field EPA_Finish(); - + // send the USB packet - cmd_send(CMD_ACK,step,func_return,0,0,0); + cmd_send(CMD_ACK,step,func_return,0,0,0); } //----------------------------------------------------------------------------- @@ -246,10 +291,6 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) // return value of a function int func_return = 0; -// // initialize ack with 0s -// memset(ack->arg, 0, 12); -// memset(ack->d.asBytes, 0, 48); - // set up communication func_return = EPA_Setup(); if (func_return != 0) { @@ -277,11 +318,11 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) EPA_PACE_Collect_Nonce_Abort(3, func_return); return; } - + // initiate the PACE protocol // use the CAN for the password since that doesn't change func_return = EPA_PACE_MSE_Set_AT(pace_version_info, 2); - + // now get the nonce uint8_t nonce[256] = {0}; uint8_t requested_size = (uint8_t)c->arg[0]; @@ -292,14 +333,12 @@ void EPA_PACE_Collect_Nonce(UsbCommand *c) EPA_PACE_Collect_Nonce_Abort(4, func_return); return; } - - // all done, return + + // all done, return EPA_Finish(); - + // save received information -// ack->arg[1] = func_return; -// memcpy(ack->d.asBytes, nonce, func_return); - cmd_send(CMD_ACK,0,func_return,0,nonce,func_return); + cmd_send(CMD_ACK,0,func_return,0,nonce,func_return); } //----------------------------------------------------------------------------- @@ -320,10 +359,10 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) sizeof(apdu_general_authenticate_pace_get_nonce)); // append Le (requested length + 2 due to tag/length taking 2 bytes) in RAPDU apdu[sizeof(apdu_general_authenticate_pace_get_nonce)] = requested_length + 4; - + // send it uint8_t response_apdu[262]; - int send_return = iso14_apdu(apdu, + int send_return = EPA_APDU(apdu, sizeof(apdu), response_apdu); // check if the command succeeded @@ -333,7 +372,7 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) { return -1; } - + // if there is no nonce in the RAPDU, return here if (send_return < 10) { @@ -348,7 +387,7 @@ int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce) } // copy the nonce memcpy(nonce, response_apdu + 6, nonce_length); - + return nonce_length; } @@ -394,7 +433,7 @@ int EPA_PACE_MSE_Set_AT(pace_version_info_t pace_version_info, uint8_t password) apdu[4] = apdu_length - 5; // send it uint8_t response_apdu[6]; - int send_return = iso14_apdu(apdu, + int send_return = EPA_APDU(apdu, apdu_length, response_apdu); // check if the command succeeded @@ -407,35 +446,109 @@ int EPA_PACE_MSE_Set_AT(pace_version_info_t pace_version_info, uint8_t password) return 0; } +//----------------------------------------------------------------------------- +// Perform the PACE protocol by replaying given APDUs +//----------------------------------------------------------------------------- +void EPA_PACE_Replay(UsbCommand *c) +{ + uint32_t timings[sizeof(apdu_lengths_replay) / sizeof(apdu_lengths_replay[0])] = {0}; + + // if an APDU has been passed, save it + if (c->arg[0] != 0) { + // make sure it's not too big + if(c->arg[2] > apdus_replay[c->arg[0] - 1].len) + { + cmd_send(CMD_ACK, 1, 0, 0, NULL, 0); + } + memcpy(apdus_replay[c->arg[0] - 1].data + c->arg[1], + c->d.asBytes, + c->arg[2]); + // save/update APDU length + if (c->arg[1] == 0) { + apdu_lengths_replay[c->arg[0] - 1] = c->arg[2]; + } else { + apdu_lengths_replay[c->arg[0] - 1] += c->arg[2]; + } + cmd_send(CMD_ACK, 0, 0, 0, NULL, 0); + return; + } + + // return value of a function + int func_return; + + // set up communication + func_return = EPA_Setup(); + if (func_return != 0) { + EPA_Finish(); + cmd_send(CMD_ACK, 2, func_return, 0, NULL, 0); + return; + } + + // response APDU + uint8_t response_apdu[300] = {0}; + + // now replay the data and measure the timings + for (int i = 0; i < sizeof(apdu_lengths_replay); i++) { + StartCountUS(); + func_return = EPA_APDU(apdus_replay[i].data, + apdu_lengths_replay[i], + response_apdu); + timings[i] = GetCountUS(); + // every step but the last one should succeed + if (i < sizeof(apdu_lengths_replay) - 1 + && (func_return < 6 + || response_apdu[func_return - 4] != 0x90 + || response_apdu[func_return - 3] != 0x00)) + { + EPA_Finish(); + cmd_send(CMD_ACK, 3 + i, func_return, 0, timings, 20); + return; + } + } + EPA_Finish(); + cmd_send(CMD_ACK,0,0,0,timings,20); + return; +} + //----------------------------------------------------------------------------- // Set up a communication channel (Card Select, PPS) // Returns 0 on success or a non-zero error code on failure //----------------------------------------------------------------------------- int EPA_Setup() { - int return_code = 0; uint8_t uid[10]; uint8_t pps_response[3]; uint8_t pps_response_par[1]; iso14a_card_select_t card_select_info; + // first, look for type A cards // power up the field iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); - // select the card return_code = iso14443a_select_card(uid, &card_select_info, NULL); - if (return_code != 1) { - Dbprintf("Epa: Can't select card"); - return 1; + if (return_code == 1) { + // send the PPS request + ReaderTransmit((uint8_t *)pps, sizeof(pps), NULL); + return_code = ReaderReceive(pps_response, pps_response_par); + if (return_code != 3 || pps_response[0] != 0xD0) { + return return_code == 0 ? 2 : return_code; + } + Dbprintf("ISO 14443 Type A"); + iso_type = 'a'; + return 0; } - // send the PPS request - ReaderTransmit((uint8_t *)pps, sizeof(pps), NULL); - return_code = ReaderReceive(pps_response, pps_response_par); - if (return_code != 3 || pps_response[0] != 0xD0) { - return return_code == 0 ? 2 : return_code; + // if we're here, there is no type A card, so we look for type B + // power up the field + iso14443b_setup(); + // select the card + return_code = iso14443b_select_card(); + if (return_code == 1) { + Dbprintf("ISO 14443 Type B"); + iso_type = 'b'; + return 0; } - - return 0; -} \ No newline at end of file + Dbprintf("No card found."); + return 1; +} diff --git a/armsrc/epa.h b/armsrc/epa.h index 730652b7..d2ebed57 100644 --- a/armsrc/epa.h +++ b/armsrc/epa.h @@ -19,7 +19,7 @@ typedef struct { uint8_t parameter_id; } pace_version_info_t; -// note: EPA_PACE_GetNonce is declared in apps.h +// note: EPA_PACE_Collect_Nonce and EPA_PACE_Replay are declared in apps.h // general functions void EPA_Finish(); @@ -33,4 +33,4 @@ int EPA_Setup(); int EPA_PACE_MSE_Set_AT(pace_version_info_t pace_version_info, uint8_t password); int EPA_PACE_Get_Nonce(uint8_t requested_length, uint8_t *nonce); -#endif /* __EPA_H */ \ No newline at end of file +#endif /* __EPA_H */ diff --git a/armsrc/fpgaloader.c b/armsrc/fpgaloader.c index 077b378a..308dda8c 100644 --- a/armsrc/fpgaloader.c +++ b/armsrc/fpgaloader.c @@ -9,10 +9,32 @@ // Routines to load the FPGA image, and then to configure the FPGA's major // mode once it is configured. //----------------------------------------------------------------------------- + +#include +#include +#include +#include "fpgaloader.h" #include "proxmark3.h" -#include "apps.h" #include "util.h" #include "string.h" +#include "BigBuf.h" +#include "zlib.h" + +extern void Dbprintf(const char *fmt, ...); + +// remember which version of the bitstream we have already downloaded to the FPGA +static int downloaded_bitstream = FPGA_BITSTREAM_ERR; + +// this is where the bitstreams are located in memory: +extern uint8_t _binary_obj_fpga_all_bit_z_start, _binary_obj_fpga_all_bit_z_end; + +static uint8_t *fpga_image_ptr = NULL; +static uint32_t uncompressed_bytes_cnt; + +static const uint8_t _bitparse_fixed_header[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x00, 0x00, 0x01}; +#define FPGA_BITSTREAM_FIXED_HEADER_SIZE sizeof(_bitparse_fixed_header) +#define OUTPUT_BUFFER_LEN 80 +#define FPGA_INTERLEAVE_SIZE 288 //----------------------------------------------------------------------------- // Set up the Serial Peripheral Interface as master @@ -150,6 +172,94 @@ 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) +{ + if (fpga_image_ptr == compressed_fpga_stream->next_out) { // need more data + compressed_fpga_stream->next_out = output_buffer; + compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; + fpga_image_ptr = output_buffer; + int res = inflate(compressed_fpga_stream, Z_SYNC_FLUSH); + if (res != Z_OK) { + Dbprintf("inflate returned: %d, %s", res, compressed_fpga_stream->msg); + } + if (res < 0) { + return res; + } + } + + uncompressed_bytes_cnt++; + + return *fpga_image_ptr++; +} + +//---------------------------------------------------------------------------- +// Undo the interleaving of several FPGA config files. FPGA config files +// are combined into one big file: +// 288 bytes from FPGA file 1, followed by 288 bytes from FGPA file 2, etc. +//---------------------------------------------------------------------------- +static int get_from_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +{ + while((uncompressed_bytes_cnt / FPGA_INTERLEAVE_SIZE) % FPGA_BITSTREAM_MAX != (bitstream_version - 1)) { + // skip undesired data belonging to other bitstream_versions + get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer); + } + + return get_from_fpga_combined_stream(compressed_fpga_stream, output_buffer); + +} + + +static voidpf fpga_inflate_malloc(voidpf opaque, uInt items, uInt size) +{ + return BigBuf_malloc(items*size); +} + + +static void fpga_inflate_free(voidpf opaque, voidpf address) +{ + BigBuf_free(); +} + + +//---------------------------------------------------------------------------- +// Initialize decompression of the respective (HF or LF) FPGA stream +//---------------------------------------------------------------------------- +static bool reset_fpga_stream(int bitstream_version, z_streamp compressed_fpga_stream, uint8_t *output_buffer) +{ + uint8_t header[FPGA_BITSTREAM_FIXED_HEADER_SIZE]; + + uncompressed_bytes_cnt = 0; + + // initialize z_stream structure for inflate: + compressed_fpga_stream->next_in = &_binary_obj_fpga_all_bit_z_start; + compressed_fpga_stream->avail_in = &_binary_obj_fpga_all_bit_z_start - &_binary_obj_fpga_all_bit_z_end; + compressed_fpga_stream->next_out = output_buffer; + compressed_fpga_stream->avail_out = OUTPUT_BUFFER_LEN; + compressed_fpga_stream->zalloc = &fpga_inflate_malloc; + compressed_fpga_stream->zfree = &fpga_inflate_free; + + inflateInit2(compressed_fpga_stream, 0); + + fpga_image_ptr = output_buffer; + + for (uint16_t i = 0; i < FPGA_BITSTREAM_FIXED_HEADER_SIZE; i++) { + header[i] = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); + } + + // Check for a valid .bit file (starts with _bitparse_fixed_header) + if(memcmp(_bitparse_fixed_header, header, FPGA_BITSTREAM_FIXED_HEADER_SIZE) == 0) { + return true; + } else { + return false; + } +} + + static void DownloadFPGA_byte(unsigned char w) { #define SEND_BIT(x) { if(w & (1<PIO_OER = GPIO_FPGA_ON; @@ -218,23 +330,15 @@ static void DownloadFPGA(const char *FpgaImage, int FpgaImageLen, int byterevers return; } - if(bytereversal) { - /* This is only supported for uint32_t aligned images */ - if( ((int)FpgaImage % sizeof(uint32_t)) == 0 ) { - i=0; - while(FpgaImageLen-->0) - DownloadFPGA_byte(FpgaImage[(i++)^0x3]); - /* Explanation of the magic in the above line: - * i^0x3 inverts the lower two bits of the integer i, counting backwards - * for each 4 byte increment. The generated sequence of (i++)^3 is - * 3 2 1 0 7 6 5 4 11 10 9 8 15 14 13 12 etc. pp. - */ + for(i = 0; i < FpgaImageLen; i++) { + int b = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); + if (b < 0) { + Dbprintf("Error %d during FpgaDownload", b); + break; } - } else { - while(FpgaImageLen-->0) - DownloadFPGA_byte(*FpgaImage++); + DownloadFPGA_byte(b); } - + // continue to clock FPGA until ready signal goes high i=100000; while ( (i--) && ( !(AT91C_BASE_PIOA->PIO_PDSR & GPIO_FPGA_DONE ) ) ) { @@ -250,39 +354,21 @@ static void DownloadFPGA(const char *FpgaImage, int FpgaImageLen, int byterevers LED_D_OFF(); } -static char *bitparse_headers_start; -static char *bitparse_bitstream_end; -static int bitparse_initialized = 0; + /* Simple Xilinx .bit parser. The file starts with the fixed opaque byte sequence * 00 09 0f f0 0f f0 0f f0 0f f0 00 00 01 * After that the format is 1 byte section type (ASCII character), 2 byte length * (big endian), bytes content. Except for section 'e' which has 4 bytes * length. */ -static const char _bitparse_fixed_header[] = {0x00, 0x09, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x0f, 0xf0, 0x00, 0x00, 0x01}; -static int bitparse_init(void * start_address, void *end_address) -{ - bitparse_initialized = 0; - - if(memcmp(_bitparse_fixed_header, start_address, sizeof(_bitparse_fixed_header)) != 0) { - return 0; /* Not matched */ - } else { - bitparse_headers_start= ((char*)start_address) + sizeof(_bitparse_fixed_header); - bitparse_bitstream_end= (char*)end_address; - bitparse_initialized = 1; - return 1; - } -} - -int bitparse_find_section(char section_name, char **section_start, unsigned int *section_length) +static int bitparse_find_section(int bitstream_version, char section_name, unsigned int *section_length, z_streamp compressed_fpga_stream, uint8_t *output_buffer) { - char *pos = bitparse_headers_start; int result = 0; - - if(!bitparse_initialized) return 0; - - while(pos < bitparse_bitstream_end) { - char current_name = *pos++; + #define MAX_FPGA_BIT_STREAM_HEADER_SEARCH 100 // maximum number of bytes to search for the requested section + uint16_t numbytes = 0; + while(numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH) { + char current_name = get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); + numbytes++; unsigned int current_length = 0; if(current_name < 'a' || current_name > 'e') { /* Strange section name, abort */ @@ -292,11 +378,13 @@ int bitparse_find_section(char section_name, char **section_start, unsigned int switch(current_name) { case 'e': /* Four byte length field */ - current_length += (*pos++) << 24; - current_length += (*pos++) << 16; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 24; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 16; + numbytes += 2; default: /* Fall through, two byte length field */ - current_length += (*pos++) << 8; - current_length += (*pos++) << 0; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 8; + current_length += get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer) << 0; + numbytes += 2; } if(current_name != 'e' && current_length > 255) { @@ -306,111 +394,123 @@ int bitparse_find_section(char section_name, char **section_start, unsigned int if(current_name == section_name) { /* Found it */ - *section_start = pos; *section_length = current_length; result = 1; break; } - pos += current_length; /* Skip section */ + for (uint16_t i = 0; i < current_length && numbytes < MAX_FPGA_BIT_STREAM_HEADER_SEARCH; i++) { + get_from_fpga_stream(bitstream_version, compressed_fpga_stream, output_buffer); + numbytes++; + } } return result; } -//----------------------------------------------------------------------------- -// Find out which FPGA image format is stored in flash, then call DownloadFPGA -// with the right parameters to download the image -//----------------------------------------------------------------------------- -extern char _binary_fpga_lf_bit_start, _binary_fpga_lf_bit_end; -extern char _binary_fpga_hf_bit_start, _binary_fpga_hf_bit_end; + +//---------------------------------------------------------------------------- +// 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) { - void *bit_start; - void *bit_end; - + z_stream compressed_fpga_stream; + uint8_t output_buffer[OUTPUT_BUFFER_LEN]; + // check whether or not the bitstream is already loaded - if (FpgaGatherBitstreamVersion() == bitstream_version) + if (downloaded_bitstream == bitstream_version) return; - if (bitstream_version == FPGA_BITSTREAM_LF) { - bit_start = &_binary_fpga_lf_bit_start; - bit_end = &_binary_fpga_lf_bit_end; - } else if (bitstream_version == FPGA_BITSTREAM_HF) { - bit_start = &_binary_fpga_hf_bit_start; - bit_end = &_binary_fpga_hf_bit_end; - } else + // make sure that we have enough memory to decompress + BigBuf_free(); + + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { return; - /* Check for the new flash image format: Should have the .bit file at &_binary_fpga_bit_start - */ - if(bitparse_init(bit_start, bit_end)) { - /* Successfully initialized the .bit parser. Find the 'e' section and - * send its contents to the FPGA. - */ - char *bitstream_start; - unsigned int bitstream_length; - if(bitparse_find_section('e', &bitstream_start, &bitstream_length)) { - DownloadFPGA(bitstream_start, bitstream_length, 0); - - return; /* All done */ - } } - /* Fallback for the old flash image format: Check for the magic marker 0xFFFFFFFF - * 0xAA995566 at address 0x102000. This is raw bitstream with a size of 336,768 bits - * = 10,524 uint32_t, stored as uint32_t e.g. little-endian in memory, but each DWORD - * is still to be transmitted in MSBit first order. Set the invert flag to indicate - * that the DownloadFPGA function should invert every 4 byte sequence when doing - * the bytewise download. - */ - if( *(uint32_t*)0x102000 == 0xFFFFFFFF && *(uint32_t*)0x102004 == 0xAA995566 ) - DownloadFPGA((char*)0x102000, 10524*4, 1); -} + unsigned int 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; + } + + inflateEnd(&compressed_fpga_stream); +} -int FpgaGatherBitstreamVersion() -{ - char temp[256]; - FpgaGatherVersion(temp, sizeof (temp)); - if (!memcmp("LF", temp, 2)) - return FPGA_BITSTREAM_LF; - else if (!memcmp("HF", temp, 2)) - return FPGA_BITSTREAM_HF; - return FPGA_BITSTREAM_ERR; -} -void FpgaGatherVersion(char *dst, int len) +//----------------------------------------------------------------------------- +// 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) { - char *fpga_info; unsigned int fpga_info_len; - dst[0] = 0; - if(!bitparse_find_section('e', &fpga_info, &fpga_info_len)) { - strncat(dst, "FPGA image: legacy image without version information", len-1); - } else { - /* USB packets only have 48 bytes data payload, so be terse */ - if(bitparse_find_section('a', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - if (!memcmp("fpga_lf", fpga_info, 7)) - strncat(dst, "LF ", len-1); - else if (!memcmp("fpga_hf", fpga_info, 7)) - strncat(dst, "HF ", len-1); + char tempstr[40]; + z_stream compressed_fpga_stream; + uint8_t output_buffer[OUTPUT_BUFFER_LEN]; + + dst[0] = '\0'; + + // ensure that we can allocate enough memory for decompression: + BigBuf_free(); + + if (!reset_fpga_stream(bitstream_version, &compressed_fpga_stream, output_buffer)) { + return; + } + + 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)) { + tempstr[i] = c; + } } - strncat(dst, "FPGA image built", len-1); -#if 0 - if(bitparse_find_section('b', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - strncat(dst, " for ", len-1); - strncat(dst, fpga_info, len-1); + if (!memcmp("fpga_lf", tempstr, 7)) + strncat(dst, "LF ", len-1); + else if (!memcmp("fpga_hf", tempstr, 7)) + strncat(dst, "HF ", len-1); + } + strncat(dst, "FPGA image built", len-1); + if(bitparse_find_section(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); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } -#endif - if(bitparse_find_section('c', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - strncat(dst, " on ", len-1); - strncat(dst, fpga_info, len-1); + strncat(dst, tempstr, len-1); + } + if(bitparse_find_section(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); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } - if(bitparse_find_section('d', &fpga_info, &fpga_info_len) && fpga_info[fpga_info_len-1] == 0 ) { - strncat(dst, " at ", len-1); - strncat(dst, fpga_info, len-1); + strncat(dst, tempstr, len-1); + } + if(bitparse_find_section(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); + if (i < sizeof(tempstr)) { + tempstr[i] = c; + } } + strncat(dst, tempstr, len-1); } + + strncat(dst, "\n", len-1); + + 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 @@ -458,3 +558,11 @@ void SetAdcMuxFor(uint32_t whichGpio) HIGH(whichGpio); } + +void Fpga_print_status(void) +{ + Dbprintf("Fgpa"); + if(downloaded_bitstream == FPGA_BITSTREAM_HF) Dbprintf(" mode.............HF"); + else if(downloaded_bitstream == FPGA_BITSTREAM_LF) Dbprintf(" mode.............LF"); + else Dbprintf(" mode.............%d", downloaded_bitstream); +} diff --git a/armsrc/fpgaloader.h b/armsrc/fpgaloader.h new file mode 100644 index 00000000..38724cdb --- /dev/null +++ b/armsrc/fpgaloader.h @@ -0,0 +1,73 @@ +//----------------------------------------------------------------------------- +// Jonathan Westhues, April 2006 +// iZsh , 2014 +// +// This code is licensed to you under the terms of the GNU GPL, version 2 or, +// at your option, any later version. See the LICENSE.txt file for the text of +// the license. +//----------------------------------------------------------------------------- +// Routines to load the FPGA image, and then to configure the FPGA's major +// mode once it is configured. +//----------------------------------------------------------------------------- + +void FpgaSendCommand(uint16_t cmd, uint16_t v); +void FpgaWriteConfWord(uint8_t v); +void FpgaDownloadAndGo(int bitstream_version); +void FpgaGatherVersion(int bitstream_version, char *dst, int len); +void FpgaSetupSsc(void); +void SetupSpi(int mode); +bool FpgaSetupSscDma(uint8_t *buf, int len); +void Fpga_print_status(); +#define FpgaDisableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; +#define FpgaEnableSscDma(void) AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTEN; +void SetAdcMuxFor(uint32_t whichGpio); + +// definitions for multiple FPGA config files support +#define FPGA_BITSTREAM_MAX 2 // the total number of FPGA bitstreams (configs) +#define FPGA_BITSTREAM_ERR 0 +#define FPGA_BITSTREAM_LF 1 +#define FPGA_BITSTREAM_HF 2 + + +// Definitions for the FPGA commands. +#define FPGA_CMD_SET_CONFREG (1<<12) +#define FPGA_CMD_SET_DIVISOR (2<<12) +#define FPGA_CMD_SET_USER_BYTE1 (3<<12) +// Definitions for the FPGA configuration word. +// LF +#define FPGA_MAJOR_MODE_LF_ADC (0<<5) +#define FPGA_MAJOR_MODE_LF_EDGE_DETECT (1<<5) +#define FPGA_MAJOR_MODE_LF_PASSTHRU (2<<5) +// HF +#define FPGA_MAJOR_MODE_HF_READER_TX (0<<5) +#define FPGA_MAJOR_MODE_HF_READER_RX_XCORR (1<<5) +#define FPGA_MAJOR_MODE_HF_SIMULATOR (2<<5) +#define FPGA_MAJOR_MODE_HF_ISO14443A (3<<5) +#define FPGA_MAJOR_MODE_HF_SNOOP (4<<5) +// BOTH +#define FPGA_MAJOR_MODE_OFF (7<<5) +// Options for LF_ADC +#define FPGA_LF_ADC_READER_FIELD (1<<0) +// Options for LF_EDGE_DETECT +#define FPGA_CMD_SET_EDGE_DETECT_THRESHOLD FPGA_CMD_SET_USER_BYTE1 +#define FPGA_LF_EDGE_DETECT_READER_FIELD (1<<0) +#define FPGA_LF_EDGE_DETECT_TOGGLE_MODE (1<<1) +// Options for the HF reader, tx to tag +#define FPGA_HF_READER_TX_SHALLOW_MOD (1<<0) +// Options for the HF reader, correlating against rx from tag +#define FPGA_HF_READER_RX_XCORR_848_KHZ (1<<0) +#define FPGA_HF_READER_RX_XCORR_SNOOP (1<<1) +#define FPGA_HF_READER_RX_XCORR_QUARTER_FREQ (1<<2) +// Options for the HF simulated tag, how to modulate +#define FPGA_HF_SIMULATOR_NO_MODULATION (0<<0) +#define FPGA_HF_SIMULATOR_MODULATE_BPSK (1<<0) +#define FPGA_HF_SIMULATOR_MODULATE_212K (2<<0) +#define FPGA_HF_SIMULATOR_MODULATE_424K (4<<0) +#define FPGA_HF_SIMULATOR_MODULATE_424K_8BIT 0x5//101 + +// Options for ISO14443A +#define FPGA_HF_ISO14443A_SNIFFER (0<<0) +#define FPGA_HF_ISO14443A_TAGSIM_LISTEN (1<<0) +#define FPGA_HF_ISO14443A_TAGSIM_MOD (2<<0) +#define FPGA_HF_ISO14443A_READER_LISTEN (3<<0) +#define FPGA_HF_ISO14443A_READER_MOD (4<<0) diff --git a/armsrc/hfsnoop.c b/armsrc/hfsnoop.c new file mode 100644 index 00000000..56774bd0 --- /dev/null +++ b/armsrc/hfsnoop.c @@ -0,0 +1,79 @@ +#include "proxmark3.h" +#include "apps.h" +#include "BigBuf.h" +#include "util.h" + +static void RAMFUNC optimizedSnoop(void); + +static void RAMFUNC optimizedSnoop(void) +{ + int n = BigBuf_max_traceLen() / sizeof(uint16_t); // take all memory + + uint16_t *dest = (uint16_t *)BigBuf_get_addr(); + uint16_t *destend = dest + n; + + AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(16); // Setting Frame mode, 16 bits per word + // Reading data loop + while(dest <= destend) + { + if(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) + { + *dest = (uint16_t)(AT91C_BASE_SSC->SSC_RHR); + dest = dest + 1; + } + } + //Resetting Frame mode (First set in fpgaloader.c) + AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(8) | AT91C_SSC_MSBF | SSC_FRAME_MODE_WORDS_PER_TRANSFER(0); +} + +void HfSnoop(int samplesToSkip, int triggersToSkip) +{ + Dbprintf("Skipping first %d sample pairs, Skipping %d triggers.", samplesToSkip, triggersToSkip); + bool trigger_cnt; + LED_D_ON(); + // Select correct configs + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // Set up the synchronous serial port + FpgaSetupSsc(); + // connect Demodulated Signal to ADC: + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SNOOP); + SpinDelay(100); + + BigBuf_free(); + BigBuf_Clear(); + + AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(16); // Setting Frame Mode For better performance on high speed data transfer. + + trigger_cnt = 0; + uint16_t r = 0; + while(!BUTTON_PRESS()) { + WDT_HIT(); + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + r = (uint16_t)AT91C_BASE_SSC->SSC_RHR; + r = MAX(r & 0xff, r >> 8); + if (r >= 240) + { + if (++trigger_cnt > triggersToSkip) { + break; + } + } + } + } + + if(!BUTTON_PRESS()) { + int waitcount = samplesToSkip; // lets wait 40000 ticks of pck0 + while(waitcount != 0) { + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + waitcount--; + } + } + optimizedSnoop(); + Dbprintf("Trigger kicked! Value: %d, Dumping Samples Hispeed now.", r); + } + + DbpString("HF Snoop end"); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LED_D_OFF(); +} + diff --git a/armsrc/hitag2.c b/armsrc/hitag2.c index 4b173d6f..508157de 100644 --- a/armsrc/hitag2.c +++ b/armsrc/hitag2.c @@ -411,7 +411,7 @@ static void hitag_reader_send_bit(int bit) { // Binary puls length modulation (BPLM) is used to encode the data stream // This means that a transmission of a one takes longer than that of a zero - // Enable modulation, which means, drop the the field + // Enable modulation, which means, drop the field HIGH(GPIO_SSC_DOUT); // Wait for 4-10 times the carrier period @@ -442,7 +442,7 @@ static void hitag_reader_send_frame(const byte_t* frame, size_t frame_len) } // Send EOF AT91C_BASE_TC0->TC_CCR = AT91C_TC_SWTRG; - // Enable modulation, which means, drop the the field + // Enable modulation, which means, drop the field HIGH(GPIO_SSC_DOUT); // Wait for 4-10 times the carrier period while(AT91C_BASE_TC0->TC_CV < T0*6); @@ -710,22 +710,24 @@ void SnoopHitag(uint32_t type) { byte_t rx[HITAG_FRAME_LEN]; size_t rxlen=0; + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + // Clean up trace and prepare it for storing frames + set_tracing(TRUE); + clear_trace(); + auth_table_len = 0; auth_table_pos = 0; + BigBuf_free(); auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); memset(auth_table, 0x00, AUTH_TABLE_LENGTH); - // Clean up trace and prepare it for storing frames - set_tracing(TRUE); - clear_trace(); - DbpString("Starting Hitag2 snoop"); LED_D_ON(); // Set up eavesdropping mode, frequency divisor which will drive the FPGA // and analog mux selection. - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_TOGGLE_MODE); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); @@ -922,6 +924,12 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { bool bQuitTraceFull = false; bQuiet = false; + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + // Clean up trace and prepare it for storing frames + set_tracing(TRUE); + clear_trace(); + auth_table_len = 0; auth_table_pos = 0; byte_t* auth_table; @@ -929,10 +937,6 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { auth_table = (byte_t *)BigBuf_malloc(AUTH_TABLE_LENGTH); memset(auth_table, 0x00, AUTH_TABLE_LENGTH); - // Clean up trace and prepare it for storing frames - set_tracing(TRUE); - clear_trace(); - DbpString("Starting Hitag2 simulation"); LED_D_ON(); hitag2_init(); @@ -953,7 +957,6 @@ void SimulateHitagTag(bool tag_mem_supplied, byte_t* data) { // Set up simulator mode, frequency divisor which will drive the FPGA // and analog mux selection. - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_EDGE_DETECT | FPGA_LF_EDGE_DETECT_READER_FIELD); FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz SetAdcMuxFor(GPIO_MUXSEL_LOPKD); diff --git a/armsrc/iclass.c b/armsrc/iclass.c index 9139d3bd..f99d0eca 100644 --- a/armsrc/iclass.c +++ b/armsrc/iclass.c @@ -1125,7 +1125,6 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) int resp_cc_len; uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - memset(receivedCmd, 0x44, MAX_FRAME_SIZE); int len; // Prepare card messages @@ -1336,7 +1335,6 @@ int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf) } } - memset(receivedCmd, 0x44, MAX_FRAME_SIZE); } //Dbprintf("%x", cmdsRecvd); @@ -1449,7 +1447,7 @@ static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int } WDT_HIT(); } - if (samples) *samples = (c + *wait) << 3; + if (samples && wait) *samples = (c + *wait) << 3; } @@ -1603,16 +1601,16 @@ void setupIclassReader() } -size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries) +bool sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries) { while(retries-- > 0) { ReaderTransmitIClass(command, cmdsize); if(expected_size == ReaderReceiveIClass(resp)){ - return 0; + return true; } } - return 1;//Error + return false;//Error } /** @@ -1622,14 +1620,17 @@ size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* * 1 = Got CSN * 2 = Got CSN and CC */ -uint8_t handshakeIclassTag(uint8_t *card_data) +uint8_t handshakeIclassTag_ext(uint8_t *card_data, bool use_credit_key) { static uint8_t act_all[] = { 0x0a }; - static uint8_t identify[] = { 0x0c }; + //static uint8_t identify[] = { 0x0c }; + static uint8_t identify[] = { 0x0c, 0x00, 0x73, 0x33 }; static uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - - - static uint8_t readcheck_cc[]= { 0x88, 0x02,}; + static uint8_t readcheck_cc[]= { 0x88, 0x02 }; + if (use_credit_key) + readcheck_cc[0] = 0x18; + else + readcheck_cc[0] = 0x88; uint8_t resp[ICLASS_BUFFER_SIZE]; @@ -1670,6 +1671,9 @@ uint8_t handshakeIclassTag(uint8_t *card_data) return read_status; } +uint8_t handshakeIclassTag(uint8_t *card_data){ + return handshakeIclassTag_ext(card_data, false); +} // Reader iClass Anticollission @@ -1689,6 +1693,9 @@ void ReaderIClass(uint8_t arg0) { uint8_t result_status = 0; bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE; bool try_once = arg0 & FLAG_ICLASS_READER_ONE_TRY; + bool use_credit_key = false; + if (arg0 & FLAG_ICLASS_READER_CEDITKEY) + use_credit_key = true; set_tracing(TRUE); setupIclassReader(); @@ -1703,7 +1710,7 @@ void ReaderIClass(uint8_t arg0) { } WDT_HIT(); - read_status = handshakeIclassTag(card_data); + read_status = handshakeIclassTag_ext(card_data, use_credit_key); if(read_status == 0) continue; if(read_status == 1) result_status = FLAG_ICLASS_READER_CSN; @@ -1717,11 +1724,10 @@ void ReaderIClass(uint8_t arg0) { if(arg0 & FLAG_ICLASS_READER_CONF) { if(sendCmdGetResponseWithRetries(readConf, sizeof(readConf),card_data+8, 10, 10)) - { - Dbprintf("Failed to dump config block"); - }else { result_status |= FLAG_ICLASS_READER_CONF; + } else { + Dbprintf("Failed to dump config block"); } } @@ -1729,10 +1735,9 @@ void ReaderIClass(uint8_t arg0) { if(arg0 & FLAG_ICLASS_READER_AA){ if(sendCmdGetResponseWithRetries(readAA, sizeof(readAA),card_data+(8*4), 10, 10)) { -// Dbprintf("Failed to dump AA block"); - }else - { result_status |= FLAG_ICLASS_READER_AA; + } else { + //Dbprintf("Failed to dump AA block"); } } @@ -1764,8 +1769,8 @@ void ReaderIClass(uint8_t arg0) { } LED_B_OFF(); } - cmd_send(CMD_ACK,0,0,0,card_data, 0); - LED_A_OFF(); + cmd_send(CMD_ACK,0,0,0,card_data, 0); + LED_A_OFF(); } void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { @@ -1816,7 +1821,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { //for now replay captured auth (as cc not updated) memcpy(check+5,MAC,4); - if(sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5)) + if(!sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5)) { Dbprintf("Error: Authentication Fail!"); continue; @@ -1828,7 +1833,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { read[2] = crc >> 8; read[3] = crc & 0xff; - if(sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10)) + if(!sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10)) { Dbprintf("Dump config (block 1) failed"); continue; @@ -1855,7 +1860,7 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { read[2] = crc >> 8; read[3] = crc & 0xff; - if(!sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10)) + if(sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10)) { Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x", block, resp[0], resp[1], resp[2], @@ -1906,130 +1911,129 @@ void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) { LED_A_OFF(); } -//2. Create Read method (cut-down from above) based off responses from 1. -// Since we have the MAC could continue to use replay function. -//3. Create Write method -/* -void IClass_iso14443A_write(uint8_t arg0, uint8_t blockNo, uint8_t *data, uint8_t *MAC) { - uint8_t act_all[] = { 0x0a }; - uint8_t identify[] = { 0x0c }; - uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - uint8_t readcheck_cc[]= { 0x88, 0x02 }; - uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 }; - uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; - - uint16_t crc = 0; - - uint8_t* resp = (((uint8_t *)BigBuf) + 3560); - - // Reset trace buffer - memset(trace, 0x44, RECV_CMD_OFFSET); - traceLen = 0; +void iClass_ReadCheck(uint8_t blockNo, uint8_t keyType) { + uint8_t readcheck[] = { keyType, blockNo }; + uint8_t resp[] = {0,0,0,0,0,0,0,0}; + size_t isOK = 0; + isOK = sendCmdGetResponseWithRetries(readcheck, sizeof(readcheck), resp, sizeof(resp), 6); + cmd_send(CMD_ACK,isOK,0,0,0,0); +} - // Setup SSC - FpgaSetupSsc(); - // Start from off (no field generated) - // Signal field is off with the appropriate LED - LED_D_OFF(); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); +void iClass_Authentication(uint8_t *MAC) { + uint8_t check[] = { ICLASS_CMD_CHECK, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + uint8_t resp[ICLASS_BUFFER_SIZE]; + memcpy(check+5,MAC,4); + bool isOK; + isOK = sendCmdGetResponseWithRetries(check, sizeof(check), resp, 4, 6); + cmd_send(CMD_ACK,isOK,0,0,0,0); +} +bool iClass_ReadBlock(uint8_t blockNo, uint8_t *readdata) { + uint8_t readcmd[] = {ICLASS_CMD_READ_OR_IDENTIFY, blockNo, 0x00, 0x00}; //0x88, 0x00 // can i use 0C? + char bl = blockNo; + uint16_t rdCrc = iclass_crc16(&bl, 1); + readcmd[2] = rdCrc >> 8; + readcmd[3] = rdCrc & 0xff; + uint8_t resp[] = {0,0,0,0,0,0,0,0,0,0}; + bool isOK = false; + + //readcmd[1] = blockNo; + isOK = sendCmdGetResponseWithRetries(readcmd, sizeof(readcmd), resp, 10, 10); + memcpy(readdata, resp, sizeof(resp)); + + return isOK; +} - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); +void iClass_ReadBlk(uint8_t blockno) { + uint8_t readblockdata[] = {0,0,0,0,0,0,0,0,0,0}; + bool isOK = false; + isOK = iClass_ReadBlock(blockno, readblockdata); + cmd_send(CMD_ACK, isOK, 0, 0, readblockdata, 8); +} - // Now give it time to spin up. - // Signal field is on with the appropriate LED - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD); - SpinDelay(200); +void iClass_Dump(uint8_t blockno, uint8_t numblks) { + uint8_t readblockdata[] = {0,0,0,0,0,0,0,0,0,0}; + bool isOK = false; + uint8_t blkCnt = 0; - LED_A_ON(); + BigBuf_free(); + uint8_t *dataout = BigBuf_malloc(255*8); + if (dataout == NULL){ + Dbprintf("out of memory"); + OnError(1); + return; + } + memset(dataout,0xFF,255*8); + + for (;blkCnt < numblks; blkCnt++) { + isOK = iClass_ReadBlock(blockno+blkCnt, readblockdata); + if (!isOK || (readblockdata[0] == 0xBB || readblockdata[7] == 0xBB || readblockdata[2] == 0xBB)) { //try again + isOK = iClass_ReadBlock(blockno+blkCnt, readblockdata); + if (!isOK) { + Dbprintf("Block %02X failed to read", blkCnt+blockno); + break; + } + } + memcpy(dataout+(blkCnt*8),readblockdata,8); + } + //return pointer to dump memory in arg3 + cmd_send(CMD_ACK,isOK,blkCnt,BigBuf_max_traceLen(),0,0); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); + BigBuf_free(); +} - for(int i=0;i<1;i++) { - - if(traceLen > TRACE_SIZE) { - DbpString("Trace full"); - break; +bool iClass_WriteBlock_ext(uint8_t blockNo, uint8_t *data) { + uint8_t write[] = { ICLASS_CMD_UPDATE, blockNo, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + //uint8_t readblockdata[10]; + //write[1] = blockNo; + memcpy(write+2, data, 12); // data + mac + uint8_t resp[] = {0,0,0,0,0,0,0,0,0,0}; + bool isOK; + isOK = sendCmdGetResponseWithRetries(write,sizeof(write),resp,sizeof(resp),10); + if (isOK) { + //Dbprintf("WriteResp: %02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",resp[0],resp[1],resp[2],resp[3],resp[4],resp[5],resp[6],resp[7],resp[8],resp[9]); + if (memcmp(write+2,resp,8)) { + //error try again + isOK = sendCmdGetResponseWithRetries(write,sizeof(write),resp,sizeof(resp),10); } - - if (BUTTON_PRESS()) break; - - // Send act_all - ReaderTransmitIClass(act_all, 1); - // Card present? - if(ReaderReceiveIClass(resp)) { - ReaderTransmitIClass(identify, 1); - if(ReaderReceiveIClass(resp) == 10) { - // Select card - memcpy(&select[1],resp,8); - ReaderTransmitIClass(select, sizeof(select)); - - if(ReaderReceiveIClass(resp) == 10) { - Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x", - resp[0], resp[1], resp[2], - resp[3], resp[4], resp[5], - resp[6], resp[7]); - } - // Card selected - Dbprintf("Readcheck on Sector 2"); - ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc)); - if(ReaderReceiveIClass(resp) == 8) { - Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x", - resp[0], resp[1], resp[2], - resp[3], resp[4], resp[5], - resp[6], resp[7]); - }else return; - Dbprintf("Authenticate"); - //for now replay captured auth (as cc not updated) - memcpy(check+5,MAC,4); - Dbprintf(" AA: %02x %02x %02x %02x", - check[5], check[6], check[7],check[8]); - ReaderTransmitIClass(check, sizeof(check)); - if(ReaderReceiveIClass(resp) == 4) { - Dbprintf(" AR: %02x %02x %02x %02x", - resp[0], resp[1], resp[2],resp[3]); - }else { - Dbprintf("Error: Authentication Fail!"); - return; - } - Dbprintf("Write Block"); - - //read configuration for max block number - read_success=false; - read[1]=1; - uint8_t *blockno=&read[1]; - crc = iclass_crc16((char *)blockno,1); - read[2] = crc >> 8; - read[3] = crc & 0xff; - while(!read_success){ - ReaderTransmitIClass(read, sizeof(read)); - if(ReaderReceiveIClass(resp) == 10) { - read_success=true; - mem=resp[5]; - memory.k16= (mem & 0x80); - memory.book= (mem & 0x20); - memory.k2= (mem & 0x8); - memory.lockauth= (mem & 0x2); - memory.keyaccess= (mem & 0x1); - - } - } - if (memory.k16){ - cardsize=255; - }else cardsize=32; - //check card_size - - memcpy(write+1,blockNo,1); - memcpy(write+2,data,8); - memcpy(write+10,mac,4); - while(!send_success){ - ReaderTransmitIClass(write, sizeof(write)); - if(ReaderReceiveIClass(resp) == 10) { - write_success=true; - } - }// + } + return isOK; +} + +void iClass_WriteBlock(uint8_t blockNo, uint8_t *data) { + bool isOK = iClass_WriteBlock_ext(blockNo, data); + if (isOK){ + Dbprintf("Write block [%02x] successful",blockNo); + } else { + Dbprintf("Write block [%02x] failed",blockNo); + } + cmd_send(CMD_ACK,isOK,0,0,0,0); +} + +void iClass_Clone(uint8_t startblock, uint8_t endblock, uint8_t *data) { + int i; + int written = 0; + int total_block = (endblock - startblock) + 1; + for (i = 0; i < total_block;i++){ + // block number + if (iClass_WriteBlock_ext(i+startblock, data+(i*12))){ + Dbprintf("Write block [%02x] successful",i + startblock); + written++; + } else { + if (iClass_WriteBlock_ext(i+startblock, data+(i*12))){ + Dbprintf("Write block [%02x] successful",i + startblock); + written++; + } else { + Dbprintf("Write block [%02x] failed",i + startblock); + } } - WDT_HIT(); } - - LED_A_OFF(); -}*/ + if (written == total_block) + Dbprintf("Clone complete"); + else + Dbprintf("Clone incomplete"); + + cmd_send(CMD_ACK,1,0,0,0,0); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LEDsoff(); +} diff --git a/armsrc/iso14443.c b/armsrc/iso14443.c deleted file mode 100644 index c7f49f14..00000000 --- a/armsrc/iso14443.c +++ /dev/null @@ -1,1250 +0,0 @@ -//----------------------------------------------------------------------------- -// Jonathan Westhues, split Nov 2006 -// -// This code is licensed to you under the terms of the GNU GPL, version 2 or, -// at your option, any later version. See the LICENSE.txt file for the text of -// the license. -//----------------------------------------------------------------------------- -// Routines to support ISO 14443. This includes both the reader software and -// the `fake tag' modes. At the moment only the Type B modulation is -// supported. -//----------------------------------------------------------------------------- - -#include "proxmark3.h" -#include "apps.h" -#include "util.h" -#include "string.h" - -#include "iso14443crc.h" - -//static void GetSamplesFor14443(int weTx, int n); - -/*#define DEMOD_TRACE_SIZE 4096 -#define READER_TAG_BUFFER_SIZE 2048 -#define TAG_READER_BUFFER_SIZE 2048 -#define DEMOD_DMA_BUFFER_SIZE 1024 -*/ -//============================================================================= -// 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 -// frame (i.e., a group of bytes between SOF and EOF), we check the CRC. -// If it's good, then we can do something appropriate with it, and send -// a response. -//============================================================================= - -//----------------------------------------------------------------------------- -// Code up a string of octets at layer 2 (including CRC, we don't generate -// that here) so that they can be transmitted to the reader. Doesn't transmit -// them yet, just leaves them ready to send in ToSend[]. -//----------------------------------------------------------------------------- -static void CodeIso14443bAsTag(const uint8_t *cmd, int len) -{ - int i; - - ToSendReset(); - - // Transmit a burst of ones, as the initial thing that lets the - // reader get phase sync. This (TR1) must be > 80/fs, per spec, - // but tag that I've tried (a Paypass) exceeds that by a fair bit, - // so I will too. - for(i = 0; i < 20; i++) { - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - } - - // Send SOF. - for(i = 0; i < 10; i++) { - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - } - for(i = 0; i < 2; i++) { - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - } - - for(i = 0; i < len; i++) { - int j; - uint8_t b = cmd[i]; - - // Start bit - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - - // Data bits - for(j = 0; j < 8; j++) { - if(b & 1) { - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - } else { - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - } - b >>= 1; - } - - // Stop bit - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - } - - // Send SOF. - for(i = 0; i < 10; i++) { - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - ToSendStuffBit(0); - } - for(i = 0; i < 10; i++) { - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - ToSendStuffBit(1); - } - - // Convert from last byte pos to length - ToSendMax++; - - // Add a few more for slop - ToSendMax += 2; -} - -//----------------------------------------------------------------------------- -// The software UART that receives commands from the reader, and its state -// variables. -//----------------------------------------------------------------------------- -static struct { - enum { - STATE_UNSYNCD, - STATE_GOT_FALLING_EDGE_OF_SOF, - STATE_AWAITING_START_BIT, - STATE_RECEIVING_DATA, - STATE_ERROR_WAIT - } state; - uint16_t shiftReg; - int bitCnt; - int byteCnt; - int byteCntMax; - int posCnt; - uint8_t *output; -} Uart; - -/* Receive & handle a bit coming from the reader. - * - * LED handling: - * LED A -> ON once we have received the SOF and are expecting the rest. - * LED A -> OFF once we have received EOF or are in error state or unsynced - * - * Returns: true if we received a EOF - * false if we are still waiting for some more - */ -static int Handle14443UartBit(int bit) -{ - switch(Uart.state) { - case STATE_UNSYNCD: - LED_A_OFF(); - if(!bit) { - // we went low, so this could be the beginning - // of an SOF - Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF; - Uart.posCnt = 0; - Uart.bitCnt = 0; - } - break; - - case STATE_GOT_FALLING_EDGE_OF_SOF: - Uart.posCnt++; - if(Uart.posCnt == 2) { - if(bit) { - if(Uart.bitCnt >= 10) { - // we've seen enough consecutive - // zeros that it's a valid SOF - Uart.posCnt = 0; - Uart.byteCnt = 0; - Uart.state = STATE_AWAITING_START_BIT; - LED_A_ON(); // Indicate we got a valid SOF - } else { - // didn't stay down long enough - // before going high, error - Uart.state = STATE_ERROR_WAIT; - } - } else { - // do nothing, keep waiting - } - Uart.bitCnt++; - } - if(Uart.posCnt >= 4) Uart.posCnt = 0; - if(Uart.bitCnt > 14) { - // Give up if we see too many zeros without - // a one, too. - Uart.state = STATE_ERROR_WAIT; - } - break; - - case STATE_AWAITING_START_BIT: - Uart.posCnt++; - if(bit) { - if(Uart.posCnt > 25) { - // stayed high for too long between - // characters, error - Uart.state = STATE_ERROR_WAIT; - } - } else { - // falling edge, this starts the data byte - Uart.posCnt = 0; - Uart.bitCnt = 0; - Uart.shiftReg = 0; - Uart.state = STATE_RECEIVING_DATA; - LED_A_ON(); // Indicate we're receiving - } - break; - - case STATE_RECEIVING_DATA: - Uart.posCnt++; - if(Uart.posCnt == 2) { - // time to sample a bit - Uart.shiftReg >>= 1; - if(bit) { - Uart.shiftReg |= 0x200; - } - Uart.bitCnt++; - } - if(Uart.posCnt >= 4) { - Uart.posCnt = 0; - } - if(Uart.bitCnt == 10) { - if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001)) - { - // this is a data byte, with correct - // start and stop bits - Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff; - Uart.byteCnt++; - - if(Uart.byteCnt >= Uart.byteCntMax) { - // Buffer overflowed, give up - Uart.posCnt = 0; - Uart.state = STATE_ERROR_WAIT; - } else { - // so get the next byte now - Uart.posCnt = 0; - Uart.state = STATE_AWAITING_START_BIT; - } - } else if(Uart.shiftReg == 0x000) { - // this is an EOF byte - LED_A_OFF(); // Finished receiving - return TRUE; - } else { - // this is an error - Uart.posCnt = 0; - Uart.state = STATE_ERROR_WAIT; - } - } - break; - - case STATE_ERROR_WAIT: - // We're all screwed up, so wait a little while - // for whatever went wrong to finish, and then - // start over. - Uart.posCnt++; - if(Uart.posCnt > 10) { - Uart.state = STATE_UNSYNCD; - } - break; - - default: - Uart.state = STATE_UNSYNCD; - break; - } - - // This row make the error blew circular buffer in hf 14b snoop - //if (Uart.state == STATE_ERROR_WAIT) LED_A_OFF(); // Error - - return FALSE; -} - -//----------------------------------------------------------------------------- -// Receive a command (from the reader to us, where we are the simulated tag), -// and store it in the given buffer, up to the given maximum length. Keeps -// spinning, waiting for a well-framed command, until either we get one -// (returns TRUE) or someone presses the pushbutton on the board (FALSE). -// -// Assume that we're called with the SSC (to the FPGA) and ADC path set -// correctly. -//----------------------------------------------------------------------------- -static int GetIso14443CommandFromReader(uint8_t *received, int *len, int maxLen) -{ - uint8_t mask; - int i, bit; - - // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen - // only, since we are receiving, not transmitting). - // Signal field is off with the appropriate LED - LED_D_OFF(); - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION); - - - // Now run a `software UART' on the stream of incoming samples. - Uart.output = received; - Uart.byteCntMax = maxLen; - Uart.state = STATE_UNSYNCD; - - for(;;) { - WDT_HIT(); - - if(BUTTON_PRESS()) return FALSE; - - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0x00; - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - - mask = 0x80; - for(i = 0; i < 8; i++, mask >>= 1) { - bit = (b & mask); - if(Handle14443UartBit(bit)) { - *len = Uart.byteCnt; - return TRUE; - } - } - } - } -} - -//----------------------------------------------------------------------------- -// Main loop of simulated tag: receive commands from reader, decide what -// response to send, and send it. -//----------------------------------------------------------------------------- -void SimulateIso14443Tag(void) -{ - static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; - static const uint8_t response1[] = { - 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22, - 0x00, 0x21, 0x85, 0x5e, 0xd7 - }; - - uint8_t *resp; - int respLen; - - uint8_t *resp1 = BigBuf_get_addr() + 800; - int resp1Len; - - uint8_t *receivedCmd = BigBuf_get_addr(); - int len; - - int i; - - int cmdsRecvd = 0; - - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - memset(receivedCmd, 0x44, 400); - - CodeIso14443bAsTag(response1, sizeof(response1)); - memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax; - - // We need to listen to the high-frequency, peak-detected path. - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); - - cmdsRecvd = 0; - - for(;;) { - uint8_t b1, b2; - - if(!GetIso14443CommandFromReader(receivedCmd, &len, 100)) { - Dbprintf("button pressed, received %d commands", cmdsRecvd); - break; - } - - // Good, look at the command now. - - if(len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len)==0) { - resp = resp1; respLen = resp1Len; - } else { - Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); - // And print whether the CRC fails, just for good measure - ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2); - if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) { - // Not so good, try again. - DbpString("+++CRC fail"); - } else { - DbpString("CRC passes"); - } - break; - } - - memset(receivedCmd, 0x44, 32); - - cmdsRecvd++; - - if(cmdsRecvd > 0x30) { - DbpString("many commands later..."); - break; - } - - if(respLen <= 0) continue; - - // Modulate BPSK - // Signal field is off with the appropriate LED - LED_D_OFF(); - FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK); - AT91C_BASE_SSC->SSC_THR = 0xff; - FpgaSetupSsc(); - - // Transmit the response. - i = 0; - for(;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - uint8_t b = resp[i]; - - AT91C_BASE_SSC->SSC_THR = b; - - i++; - if(i > respLen) { - break; - } - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - (void)b; - } - } - } -} - -//============================================================================= -// An ISO 14443 Type B reader. We take layer two commands, code them -// appropriately, and then send them to the tag. We then listen for the -// tag's response, which we leave in the buffer to be demodulated on the -// PC side. -//============================================================================= - -static struct { - enum { - DEMOD_UNSYNCD, - DEMOD_PHASE_REF_TRAINING, - DEMOD_AWAITING_FALLING_EDGE_OF_SOF, - DEMOD_GOT_FALLING_EDGE_OF_SOF, - DEMOD_AWAITING_START_BIT, - DEMOD_RECEIVING_DATA, - DEMOD_ERROR_WAIT - } state; - int bitCount; - int posCount; - int thisBit; - int metric; - int metricN; - uint16_t shiftReg; - uint8_t *output; - int len; - int sumI; - int sumQ; -} Demod; - -/* - * Handles reception of a bit from the tag - * - * LED handling: - * LED C -> ON once we have received the SOF and are expecting the rest. - * LED C -> OFF once we have received EOF or are unsynced - * - * Returns: true if we received a EOF - * false if we are still waiting for some more - * - */ -static RAMFUNC int Handle14443SamplesDemod(int ci, int cq) -{ - int v; - - // The soft decision on the bit uses an estimate of just the - // quadrant of the reference angle, not the exact angle. -#define MAKE_SOFT_DECISION() { \ - if(Demod.sumI > 0) { \ - v = ci; \ - } else { \ - v = -ci; \ - } \ - if(Demod.sumQ > 0) { \ - v += cq; \ - } else { \ - v -= cq; \ - } \ - } - - switch(Demod.state) { - case DEMOD_UNSYNCD: - v = ci; - if(v < 0) v = -v; - if(cq > 0) { - v += cq; - } else { - v -= cq; - } - if(v > 40) { - Demod.posCount = 0; - Demod.state = DEMOD_PHASE_REF_TRAINING; - Demod.sumI = 0; - Demod.sumQ = 0; - } - break; - - case DEMOD_PHASE_REF_TRAINING: - if(Demod.posCount < 8) { - Demod.sumI += ci; - Demod.sumQ += cq; - } else if(Demod.posCount > 100) { - // error, waited too long - Demod.state = DEMOD_UNSYNCD; - } else { - MAKE_SOFT_DECISION(); - if(v < 0) { - Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF; - Demod.posCount = 0; - } - } - Demod.posCount++; - break; - - case DEMOD_AWAITING_FALLING_EDGE_OF_SOF: - MAKE_SOFT_DECISION(); - if(v < 0) { - Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF; - Demod.posCount = 0; - } else { - if(Demod.posCount > 100) { - Demod.state = DEMOD_UNSYNCD; - } - } - Demod.posCount++; - break; - - case DEMOD_GOT_FALLING_EDGE_OF_SOF: - MAKE_SOFT_DECISION(); - if(v > 0) { - if(Demod.posCount < 12) { - Demod.state = DEMOD_UNSYNCD; - } else { - LED_C_ON(); // Got SOF - Demod.state = DEMOD_AWAITING_START_BIT; - Demod.posCount = 0; - Demod.len = 0; - Demod.metricN = 0; - Demod.metric = 0; - } - } else { - if(Demod.posCount > 100) { - Demod.state = DEMOD_UNSYNCD; - } - } - Demod.posCount++; - break; - - case DEMOD_AWAITING_START_BIT: - MAKE_SOFT_DECISION(); - if(v > 0) { - if(Demod.posCount > 10) { - Demod.state = DEMOD_UNSYNCD; - } - } else { - Demod.bitCount = 0; - Demod.posCount = 1; - Demod.thisBit = v; - Demod.shiftReg = 0; - Demod.state = DEMOD_RECEIVING_DATA; - } - break; - - case DEMOD_RECEIVING_DATA: - MAKE_SOFT_DECISION(); - if(Demod.posCount == 0) { - Demod.thisBit = v; - Demod.posCount = 1; - } else { - Demod.thisBit += v; - - if(Demod.thisBit > 0) { - Demod.metric += Demod.thisBit; - } else { - Demod.metric -= Demod.thisBit; - } - (Demod.metricN)++; - - Demod.shiftReg >>= 1; - if(Demod.thisBit > 0) { - Demod.shiftReg |= 0x200; - } - - Demod.bitCount++; - if(Demod.bitCount == 10) { - uint16_t s = Demod.shiftReg; - if((s & 0x200) && !(s & 0x001)) { - uint8_t b = (s >> 1); - Demod.output[Demod.len] = b; - Demod.len++; - Demod.state = DEMOD_AWAITING_START_BIT; - } else if(s == 0x000) { - // This is EOF - LED_C_OFF(); - Demod.state = DEMOD_UNSYNCD; - return TRUE; - } else { - Demod.state = DEMOD_UNSYNCD; - } - } - Demod.posCount = 0; - } - break; - - default: - Demod.state = DEMOD_UNSYNCD; - break; - } - - if (Demod.state == DEMOD_UNSYNCD) LED_C_OFF(); // Not synchronized... - return FALSE; -} -static void DemodReset() -{ - // Clear out the state of the "UART" that receives from the tag. - Demod.len = 0; - Demod.state = DEMOD_UNSYNCD; - memset(Demod.output, 0x00, MAX_FRAME_SIZE); -} -static void DemodInit(uint8_t *data) -{ - Demod.output = data; - DemodReset(); -} - -static void UartReset() -{ - Uart.byteCntMax = MAX_FRAME_SIZE; - Uart.state = STATE_UNSYNCD; - Uart.byteCnt = 0; - Uart.bitCnt = 0; -} -static void UartInit(uint8_t *data) -{ - Uart.output = data; - UartReset(); -} - -/* - * Demodulate the samples we received from the tag, also log to tracebuffer - * weTx: set to 'TRUE' if we behave like a reader - * set to 'FALSE' if we behave like a snooper - * quiet: set to 'TRUE' to disable debug output - */ -static void GetSamplesFor14443Demod(int weTx, int n, int quiet) -{ - int max = 0; - int gotFrame = FALSE; - int lastRxCounter, ci, cq, samples = 0; - - // Allocate memory from BigBuf for some buffers - // free all previous allocations first - BigBuf_free(); - - // The command (reader -> tag) that we're receiving. - uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); - - // The response (tag -> reader) that we're receiving. - uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); - - // The DMA buffer, used to stream samples from the FPGA - uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); - - // Set up the demodulator for tag -> reader responses. - DemodInit(receivedResponse); - // Set up the demodulator for the reader -> tag commands - UartInit(receivedCmd); - - // Setup and start DMA. - FpgaSetupSscDma(dmaBuf, DMA_BUFFER_SIZE); - - uint8_t *upTo= dmaBuf; - lastRxCounter = DMA_BUFFER_SIZE; - - // Signal field is ON with the appropriate LED: - if (weTx) LED_D_ON(); else LED_D_OFF(); - // And put the FPGA in the appropriate mode - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | - (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP)); - - for(;;) { - int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; - if(behindBy > max) max = behindBy; - - while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (DMA_BUFFER_SIZE-1)) - > 2) - { - ci = upTo[0]; - cq = upTo[1]; - upTo += 2; - if(upTo - dmaBuf > DMA_BUFFER_SIZE) { - upTo -= DMA_BUFFER_SIZE; - AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; - AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; - } - lastRxCounter -= 2; - if(lastRxCounter <= 0) { - lastRxCounter += DMA_BUFFER_SIZE; - } - - samples += 2; - - Handle14443UartBit(1); - Handle14443UartBit(1); - - if(Handle14443SamplesDemod(ci, cq)) { - gotFrame = 1; - } - } - - if(samples > 2000) { - break; - } - } - AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; - if (!quiet) Dbprintf("%x %x %x", max, gotFrame, Demod.len); - //Tracing - if (tracing && Demod.len > 0) { - uint8_t parity[MAX_PARITY_SIZE]; - GetParity(Demod.output , Demod.len, parity); - LogTrace(Demod.output,Demod.len, 0, 0, parity, FALSE); - } -} - -//----------------------------------------------------------------------------- -// Read the tag's response. We just receive a stream of slightly-processed -// samples from the FPGA, which we will later do some signal processing on, -// to get the bits. -//----------------------------------------------------------------------------- -/*static void GetSamplesFor14443(int weTx, int n) -{ - uint8_t *dest = (uint8_t *)BigBuf; - int c; - - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | - (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP)); - - c = 0; - for(;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0x43; - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - int8_t b; - b = (int8_t)AT91C_BASE_SSC->SSC_RHR; - - dest[c++] = (uint8_t)b; - - if(c >= n) { - break; - } - } - } -}*/ - -//----------------------------------------------------------------------------- -// Transmit the command (to the tag) that was placed in ToSend[]. -//----------------------------------------------------------------------------- -static void TransmitFor14443(void) -{ - int c; - - FpgaSetupSsc(); - - while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0xff; - } - - // Signal field is ON with the appropriate Red LED - LED_D_ON(); - // Signal we are transmitting with the Green LED - LED_B_ON(); - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); - - for(c = 0; c < 10;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = 0xff; - c++; - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; - (void)r; - } - WDT_HIT(); - } - - c = 0; - for(;;) { - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { - AT91C_BASE_SSC->SSC_THR = ToSend[c]; - c++; - if(c >= ToSendMax) { - break; - } - } - if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { - volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; - (void)r; - } - WDT_HIT(); - } - LED_B_OFF(); // Finished sending -} - -//----------------------------------------------------------------------------- -// Code a layer 2 command (string of octets, including CRC) into ToSend[], -// so that it is ready to transmit to the tag using TransmitFor14443(). -//----------------------------------------------------------------------------- -static void CodeIso14443bAsReader(const uint8_t *cmd, int len) -{ - int i, j; - uint8_t b; - - ToSendReset(); - - // Establish initial reference level - for(i = 0; i < 40; i++) { - ToSendStuffBit(1); - } - // Send SOF - for(i = 0; i < 10; i++) { - ToSendStuffBit(0); - } - - for(i = 0; i < len; i++) { - // Stop bits/EGT - ToSendStuffBit(1); - ToSendStuffBit(1); - // Start bit - ToSendStuffBit(0); - // Data bits - b = cmd[i]; - for(j = 0; j < 8; j++) { - if(b & 1) { - ToSendStuffBit(1); - } else { - ToSendStuffBit(0); - } - b >>= 1; - } - } - // Send EOF - ToSendStuffBit(1); - for(i = 0; i < 10; i++) { - ToSendStuffBit(0); - } - for(i = 0; i < 8; i++) { - ToSendStuffBit(1); - } - - // And then a little more, to make sure that the last character makes - // it out before we switch to rx mode. - for(i = 0; i < 24; i++) { - ToSendStuffBit(1); - } - - // Convert from last character reference to length - ToSendMax++; -} - -//----------------------------------------------------------------------------- -// Read an ISO 14443 tag. We send it some set of commands, and record the -// responses. -// The command name is misleading, it actually decodes the reponse in HEX -// into the output buffer (read the result using hexsamples, not hisamples) -// -// obsolete function only for test -//----------------------------------------------------------------------------- -void AcquireRawAdcSamplesIso14443(uint32_t parameter) -{ - uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; - - SendRawCommand14443B(sizeof(cmd1),1,1,cmd1); -} - -/** - Convenience function to encode, transmit and trace iso 14443b comms - **/ -static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) -{ - CodeIso14443bAsReader(cmd, len); - TransmitFor14443(); - if (tracing) { - uint8_t parity[MAX_PARITY_SIZE]; - GetParity(cmd, len, parity); - LogTrace(cmd,len, 0, 0, parity, TRUE); - } -} - -//----------------------------------------------------------------------------- -// Read a SRI512 ISO 14443 tag. -// -// SRI512 tags are just simple memory tags, here we're looking at making a dump -// of the contents of the memory. No anticollision algorithm is done, we assume -// we have a single tag in the field. -// -// I tried to be systematic and check every answer of the tag, every CRC, etc... -//----------------------------------------------------------------------------- -void ReadSTMemoryIso14443(uint32_t dwLast) -{ - clear_trace(); - set_tracing(TRUE); - - uint8_t i = 0x00; - - 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. - LED_D_OFF(); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); - - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); - - // Now give it time to spin up. - // Signal field is on with the appropriate LED - LED_D_ON(); - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); - SpinDelay(200); - - // First command: wake up the tag using the INITIATE command - uint8_t cmd1[] = { 0x06, 0x00, 0x97, 0x5b}; - - CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); -// LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); -// LED_A_OFF(); - - if (Demod.len == 0) { - DbpString("No response from tag"); - return; - } else { - Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %x %x %x", - Demod.output[0], Demod.output[1],Demod.output[2]); - } - // There is a response, SELECT the uid - DbpString("Now SELECT tag:"); - cmd1[0] = 0x0E; // 0x0E is SELECT - cmd1[1] = Demod.output[0]; - ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]); - CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); - -// LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); -// LED_A_OFF(); - if (Demod.len != 3) { - Dbprintf("Expected 3 bytes from tag, got %d", Demod.len); - return; - } - // Check the CRC of the answer: - ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]); - if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) { - DbpString("CRC Error reading select response."); - return; - } - // Check response from the tag: should be the same UID as the command we just sent: - if (cmd1[1] != Demod.output[0]) { - Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1[1], Demod.output[0]); - return; - } - // Tag is now selected, - // First get the tag's UID: - cmd1[0] = 0x0B; - ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]); - CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one - -// LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); -// LED_A_OFF(); - if (Demod.len != 10) { - Dbprintf("Expected 10 bytes from tag, got %d", Demod.len); - return; - } - // The check the CRC of the answer (use cmd1 as temporary variable): - ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]); - if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) { - Dbprintf("CRC Error reading block! - Below: expected, got %x %x", - (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); - // Do not return;, let's go on... (we should retry, maybe ?) - } - Dbprintf("Tag UID (64 bits): %08x %08x", - (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], - (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); - - // Now loop to read all 16 blocks, address from 0 to last block - Dbprintf("Tag memory dump, block 0 to %d",dwLast); - cmd1[0] = 0x08; - i = 0x00; - dwLast++; - for (;;) { - if (i == dwLast) { - DbpString("System area block (0xff):"); - i = 0xff; - } - cmd1[1] = i; - ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]); - CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); - -// LED_A_ON(); - GetSamplesFor14443Demod(TRUE, 2000,TRUE); -// LED_A_OFF(); - if (Demod.len != 6) { // Check if we got an answer from the tag - DbpString("Expected 6 bytes from tag, got less..."); - return; - } - // The check the CRC of the answer (use cmd1 as temporary variable): - ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]); - if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) { - Dbprintf("CRC Error reading block! - Below: expected, got %x %x", - (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); - // Do not return;, let's go on... (we should retry, maybe ?) - } - // Now print out the memory location: - Dbprintf("Address=%x, Contents=%x, CRC=%x", i, - (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], - (Demod.output[4]<<8)+Demod.output[5]); - if (i == 0xff) { - break; - } - i++; - } -} - - -//============================================================================= -// Finally, the `sniffer' combines elements from both the reader and -// simulated tag, to show both sides of the conversation. -//============================================================================= - -//----------------------------------------------------------------------------- -// Record the sequence of commands sent by the reader to the tag, with -// triggering so that we start recording at the point that the tag is moved -// near the reader. -//----------------------------------------------------------------------------- -/* - * Memory usage for this function, (within BigBuf) - * 0-4095 : Demodulated samples receive (4096 bytes) - DEMOD_TRACE_SIZE - * 4096-6143 : Last Received command, 2048 bytes (reader->tag) - READER_TAG_BUFFER_SIZE - * 6144-8191 : Last Received command, 2048 bytes(tag->reader) - TAG_READER_BUFFER_SIZE - * 8192-9215 : DMA Buffer, 1024 bytes (samples) - DEMOD_DMA_BUFFER_SIZE - */ -void RAMFUNC SnoopIso14443(void) -{ - // We won't start recording the frames that we acquire until we trigger; - // a good trigger condition to get started is probably when we see a - // response from the tag. - int triggered = TRUE; - - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - BigBuf_free(); - - clear_trace(); - set_tracing(TRUE); - - // The DMA buffer, used to stream samples from the FPGA - uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE); - int lastRxCounter; - uint8_t *upTo; - int ci, cq; - int maxBehindBy = 0; - - // Count of samples received so far, so that we can include timing - // information in the trace buffer. - int samples = 0; - - DemodInit(BigBuf_malloc(MAX_FRAME_SIZE)); - UartInit(BigBuf_malloc(MAX_FRAME_SIZE)); - - // Print some debug information about the buffer sizes - Dbprintf("Snooping buffers initialized:"); - Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen()); - Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE); - Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE); - Dbprintf(" DMA: %i bytes", DMA_BUFFER_SIZE); - - // Signal field is off with the appropriate LED - LED_D_OFF(); - - // And put the FPGA in the appropriate mode - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | - FPGA_HF_READER_RX_XCORR_SNOOP); - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - - // Setup for the DMA. - FpgaSetupSsc(); - upTo = dmaBuf; - lastRxCounter = DMA_BUFFER_SIZE; - FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); - uint8_t parity[MAX_PARITY_SIZE]; - LED_A_ON(); - - // And now we loop, receiving samples. - for(;;) { - int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & - (DMA_BUFFER_SIZE-1); - if(behindBy > maxBehindBy) { - maxBehindBy = behindBy; - if(behindBy > (9*DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? - Dbprintf("blew circular buffer! behindBy=0x%x", behindBy); - break; - } - } - if(behindBy < 2) continue; - - ci = upTo[0]; - cq = upTo[1]; - upTo += 2; - lastRxCounter -= 2; - if(upTo - dmaBuf > DMA_BUFFER_SIZE) { - upTo -= DMA_BUFFER_SIZE; - lastRxCounter += DMA_BUFFER_SIZE; - AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; - AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE; - } - - samples += 2; - - if(Handle14443UartBit(ci & 1)) { - if(triggered && tracing) { - GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE); - } - if(Uart.byteCnt==0) Dbprintf("[1] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); - - /* And ready to receive another command. */ - UartReset(); - /* And also reset the demod code, which might have been */ - /* false-triggered by the commands from the reader. */ - DemodReset(); - } - if(Handle14443UartBit(cq & 1)) { - if(triggered && tracing) { - GetParity(Uart.output, Uart.byteCnt, parity); - LogTrace(Uart.output,Uart.byteCnt,samples, samples,parity,TRUE); - } - if(Uart.byteCnt==0) Dbprintf("[2] Error, Uart.byteCnt==0, Uart.bitCnt=%d", Uart.bitCnt); - - /* And ready to receive another command. */ - UartReset(); - /* And also reset the demod code, which might have been */ - /* false-triggered by the commands from the reader. */ - DemodReset(); - } - - if(Handle14443SamplesDemod(ci, cq)) { - - //Use samples as a time measurement - if(tracing) - { - uint8_t parity[MAX_PARITY_SIZE]; - GetParity(Demod.output, Demod.len, parity); - LogTrace(Demod.output,Demod.len,samples, samples,parity,FALSE); - } - triggered = TRUE; - LED_A_OFF(); - LED_B_ON(); - - // And ready to receive another response. - DemodReset(); - } - WDT_HIT(); - - if(!tracing) { - DbpString("Reached trace limit"); - break; - } - - if(BUTTON_PRESS()) { - DbpString("cancelled"); - break; - } - } - FpgaDisableSscDma(); - LED_A_OFF(); - LED_B_OFF(); - LED_C_OFF(); - AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; - DbpString("Snoop statistics:"); - Dbprintf(" Max behind by: %i", maxBehindBy); - Dbprintf(" Uart State: %x", Uart.state); - Dbprintf(" Uart ByteCnt: %i", Uart.byteCnt); - Dbprintf(" Uart ByteCntMax: %i", Uart.byteCntMax); - Dbprintf(" Trace length: %i", BigBuf_get_traceLen()); -} - -/* - * Send raw command to tag ISO14443B - * @Input - * datalen len of buffer data - * recv bool when true wait for data from tag and send to client - * powerfield bool leave the field on when true - * data buffer with byte to send - * - * @Output - * none - * - */ - -void SendRawCommand14443B(uint32_t datalen, uint32_t recv,uint8_t powerfield, uint8_t data[]) -{ - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - if(!powerfield) - { - // Make sure that we start from off, since the tags are stateful; - // confusing things will happen if we don't reset them between reads. - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - LED_D_OFF(); - SpinDelay(200); - } - - if(!GETBIT(GPIO_LED_D)) - { - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); - - // Now give it time to spin up. - // Signal field is on with the appropriate LED - LED_D_ON(); - FpgaWriteConfWord( - FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); - SpinDelay(200); - } - - CodeAndTransmit14443bAsReader(data, datalen); - - if(recv) - { - uint16_t iLen = MIN(Demod.len,USB_CMD_DATA_SIZE); - GetSamplesFor14443Demod(TRUE, 2000, TRUE); - cmd_send(CMD_ACK,iLen,0,0,Demod.output,iLen); - } - if(!powerfield) - { - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - LED_D_OFF(); - } -} - diff --git a/armsrc/iso14443a.c b/armsrc/iso14443a.c index 64bbcbf5..27574dad 100644 --- a/armsrc/iso14443a.c +++ b/armsrc/iso14443a.c @@ -213,6 +213,12 @@ void AppendCrc14443a(uint8_t* data, int len) ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1); } +void AppendCrc14443b(uint8_t* data, int len) +{ + ComputeCrc14443(CRC_14443_B,data,len,data+len,data+len+1); +} + + //============================================================================= // ISO 14443 Type A - Miller decoder //============================================================================= @@ -232,13 +238,17 @@ void AppendCrc14443a(uint8_t* data, int len) static tUart Uart; // Lookup-Table to decide if 4 raw bits are a modulation. -// We accept two or three consecutive "0" in any position with the rest "1" +// We accept the following: +// 0001 - a 3 tick wide pause +// 0011 - a 2 tick wide pause, or a three tick wide pause shifted left +// 0111 - a 2 tick wide pause shifted left +// 1001 - a 2 tick wide pause shifted right const bool Mod_Miller_LUT[] = { - TRUE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, - TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE + FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE, + FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE }; -#define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x00F0) >> 4]) -#define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x000F)]) +#define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4]) +#define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)]) void UartReset() { @@ -248,8 +258,6 @@ void UartReset() Uart.parityLen = 0; // number of decoded parity bytes Uart.shiftReg = 0; // shiftreg to hold decoded data bits Uart.parityBits = 0; // holds 8 parity bits - Uart.twoBits = 0x0000; // buffer for 2 Bits - Uart.highCnt = 0; Uart.startTime = 0; Uart.endTime = 0; } @@ -258,6 +266,7 @@ void UartInit(uint8_t *data, uint8_t *parity) { Uart.output = data; Uart.parity = parity; + Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits UartReset(); } @@ -265,40 +274,37 @@ void UartInit(uint8_t *data, uint8_t *parity) static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) { - Uart.twoBits = (Uart.twoBits << 8) | bit; + Uart.fourBits = (Uart.fourBits << 8) | bit; if (Uart.state == STATE_UNSYNCD) { // not yet synced - if (Uart.highCnt < 2) { // wait for a stable unmodulated signal - if (Uart.twoBits == 0xffff) { - Uart.highCnt++; - } else { - Uart.highCnt = 0; - } - } else { - Uart.syncBit = 0xFFFF; // not set - // we look for a ...1111111100x11111xxxxxx pattern (the start bit) - if ((Uart.twoBits & 0xDF00) == 0x1F00) Uart.syncBit = 8; // mask is 11x11111 xxxxxxxx, - // check for 00x11111 xxxxxxxx - else if ((Uart.twoBits & 0xEF80) == 0x8F80) Uart.syncBit = 7; // both masks shifted right one bit, left padded with '1' - else if ((Uart.twoBits & 0xF7C0) == 0xC7C0) Uart.syncBit = 6; // ... - else if ((Uart.twoBits & 0xFBE0) == 0xE3E0) Uart.syncBit = 5; - else if ((Uart.twoBits & 0xFDF0) == 0xF1F0) Uart.syncBit = 4; - else if ((Uart.twoBits & 0xFEF8) == 0xF8F8) Uart.syncBit = 3; - else if ((Uart.twoBits & 0xFF7C) == 0xFC7C) Uart.syncBit = 2; - else if ((Uart.twoBits & 0xFFBE) == 0xFE3E) Uart.syncBit = 1; - if (Uart.syncBit != 0xFFFF) { // found a sync bit - Uart.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8); - Uart.startTime -= Uart.syncBit; - Uart.endTime = Uart.startTime; - Uart.state = STATE_START_OF_COMMUNICATION; - } + Uart.syncBit = 9999; // not set + // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from + // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111) + // we therefore look for a ...xx11111111111100x11111xxxxxx... pattern + // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's) + #define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00000111 11111111 11101111 10000000 + #define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00000111 11111111 10001111 10000000 + if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 0)) == ISO14443A_STARTBIT_PATTERN >> 0) Uart.syncBit = 7; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 1)) == ISO14443A_STARTBIT_PATTERN >> 1) Uart.syncBit = 6; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 2)) == ISO14443A_STARTBIT_PATTERN >> 2) Uart.syncBit = 5; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 3)) == ISO14443A_STARTBIT_PATTERN >> 3) Uart.syncBit = 4; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 4)) == ISO14443A_STARTBIT_PATTERN >> 4) Uart.syncBit = 3; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 5)) == ISO14443A_STARTBIT_PATTERN >> 5) Uart.syncBit = 2; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 6)) == ISO14443A_STARTBIT_PATTERN >> 6) Uart.syncBit = 1; + else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 7)) == ISO14443A_STARTBIT_PATTERN >> 7) Uart.syncBit = 0; + + if (Uart.syncBit != 9999) { // found a sync bit + Uart.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8); + Uart.startTime -= Uart.syncBit; + Uart.endTime = Uart.startTime; + Uart.state = STATE_START_OF_COMMUNICATION; } } else { - if (IsMillerModulationNibble1(Uart.twoBits >> Uart.syncBit)) { - if (IsMillerModulationNibble2(Uart.twoBits >> Uart.syncBit)) { // Modulation in both halves - error + if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) { + if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation in both halves - error UartReset(); } else { // Modulation in first half = Sequence Z = logic "0" if (Uart.state == STATE_MILLER_X) { // error - must not follow after X @@ -322,7 +328,7 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) } } } else { - if (IsMillerModulationNibble2(Uart.twoBits >> Uart.syncBit)) { // Modulation second half = Sequence X = logic "1" + if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation second half = Sequence X = logic "1" Uart.bitCount++; Uart.shiftReg = (Uart.shiftReg >> 1) | 0x100; // add a 1 to the shiftreg Uart.state = STATE_MILLER_X; @@ -358,12 +364,10 @@ static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time) return TRUE; // we are finished with decoding the raw data sequence } else { UartReset(); // Nothing received - start over - Uart.highCnt = 1; } } if (Uart.state == STATE_START_OF_COMMUNICATION) { // error - must not follow directly after SOC UartReset(); - Uart.highCnt = 1; } else { // a logic "0" Uart.bitCount++; Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg @@ -551,12 +555,8 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { LEDsoff(); - // We won't start recording the frames that we acquire until we trigger; - // a good trigger condition to get started is probably when we see a - // response from the tag. - // triggered == FALSE -- to wait first for card - bool triggered = !(param & 0x03); - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + // Allocate memory from BigBuf for some buffers // free all previous allocations first BigBuf_free(); @@ -583,8 +583,6 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { bool TagIsActive = FALSE; bool ReaderIsActive = FALSE; - iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse, receivedResponsePar); @@ -594,6 +592,12 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { // Setup and start DMA. FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); + // We won't start recording the frames that we acquire until we trigger; + // a good trigger condition to get started is probably when we see a + // response from the tag. + // triggered == FALSE -- to wait first for card + bool triggered = !(param & 0x03); + // And now we loop, receiving samples. for(uint32_t rsamples = 0; TRUE; ) { @@ -680,6 +684,9 @@ void RAMFUNC SnoopIso14443a(uint8_t param) { // And ready to receive another response. DemodReset(); + // And reset the Miller decoder including itS (now outdated) input buffer + UartInit(receivedCmd, receivedCmdPar); + LED_C_OFF(); } TagIsActive = (Demod.state != DEMOD_UNSYNCD); @@ -1026,6 +1033,9 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) .modulation_n = 0 }; + // We need to listen to the high-frequency, peak-detected path. + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + BigBuf_free_keep_EM(); // allocate buffers: @@ -1054,16 +1064,12 @@ void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data) int happened2 = 0; int cmdsRecvd = 0; - // We need to listen to the high-frequency, peak-detected path. - iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - cmdsRecvd = 0; tag_response_info_t* p_response; LED_A_ON(); for(;;) { // Clean receive command buffer - if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) { DbpString("Button press"); break; @@ -1337,7 +1343,7 @@ void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8 } // Only transmit parity bit if we transmitted a complete byte - if (j == 8) { + if (j == 8 && parity != NULL) { // Get the parity bit if (parity[i>>3] & (0x80 >> (i&0x0007))) { // Sequence X @@ -1631,6 +1637,7 @@ static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receive } } + void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t *timing) { CodeIso14443aBitsAsReaderPar(frame, bits, par); @@ -1646,11 +1653,13 @@ void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t } } + void ReaderTransmitPar(uint8_t* frame, uint16_t len, uint8_t *par, uint32_t *timing) { ReaderTransmitBitsPar(frame, len*8, par, timing); } + void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect @@ -1659,6 +1668,7 @@ void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing) ReaderTransmitBitsPar(frame, len, par, timing); } + void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing) { // Generate parity and redirect @@ -1719,6 +1729,11 @@ int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, u memset(uid_ptr,0,10); } + // check for proprietary anticollision: + if ((resp[0] & 0x1F) == 0) { + return 3; + } + // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in // which case we need to make a cascade 2 request and select - this is a long UID // While the UID is not complete, the 3nd bit (from the right) is set in the SAK. @@ -1927,15 +1942,38 @@ void ReaderIso14443a(UsbCommand *c) if(param & ISO14A_RAW) { if(param & ISO14A_APPEND_CRC) { - AppendCrc14443a(cmd,len); + if(param & ISO14A_TOPAZMODE) { + AppendCrc14443b(cmd,len); + } else { + AppendCrc14443a(cmd,len); + } len += 2; if (lenbits) lenbits += 16; } - if(lenbits>0) { - GetParity(cmd, lenbits/8, par); - ReaderTransmitBitsPar(cmd, lenbits, par, NULL); - } else { - ReaderTransmit(cmd,len, NULL); + if(lenbits>0) { // want to send a specific number of bits (e.g. short commands) + if(param & ISO14A_TOPAZMODE) { + int bits_to_send = lenbits; + uint16_t i = 0; + ReaderTransmitBitsPar(&cmd[i++], MIN(bits_to_send, 7), NULL, NULL); // first byte is always short (7bits) and no parity + bits_to_send -= 7; + while (bits_to_send > 0) { + ReaderTransmitBitsPar(&cmd[i++], MIN(bits_to_send, 8), NULL, NULL); // following bytes are 8 bit and no parity + bits_to_send -= 8; + } + } else { + GetParity(cmd, lenbits/8, par); + ReaderTransmitBitsPar(cmd, lenbits, par, NULL); // bytes are 8 bit with odd parity + } + } else { // want to send complete bytes only + if(param & ISO14A_TOPAZMODE) { + uint16_t i = 0; + ReaderTransmitBitsPar(&cmd[i++], 7, NULL, NULL); // first byte: 7 bits, no paritiy + while (i < len) { + ReaderTransmitBitsPar(&cmd[i++], 8, NULL, NULL); // following bytes: 8 bits, no paritiy + } + } else { + ReaderTransmit(cmd,len, NULL); // 8 bits, odd parity + } } arg0 = ReaderReceive(buf, par); cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf)); @@ -1971,7 +2009,7 @@ int32_t dist_nt(uint32_t nt1, uint32_t nt2) { nttmp1 = prng_successor(nttmp1, 1); if (nttmp1 == nt2) return i; nttmp2 = prng_successor(nttmp2, 1); - if (nttmp2 == nt1) return -i; + if (nttmp2 == nt1) return -i; } return(-99999); // either nt1 or nt2 are invalid nonces @@ -1994,6 +2032,10 @@ void ReaderMifare(bool first_try) uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; + if (first_try) { + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + } + // free eventually allocated BigBuf memory. We want all for tracing. BigBuf_free(); @@ -2013,20 +2055,20 @@ void ReaderMifare(bool first_try) byte_t par_list[8] = {0x00}; byte_t ks_list[8] = {0x00}; + #define PRNG_SEQUENCE_LENGTH (1 << 16); static uint32_t sync_time; - static uint32_t sync_cycles; + static int32_t sync_cycles; int catch_up_cycles = 0; int last_catch_up = 0; + uint16_t elapsed_prng_sequences; uint16_t consecutive_resyncs = 0; int isOK = 0; if (first_try) { mf_nr_ar3 = 0; - iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); sync_time = GetCountSspClk() & 0xfffffff8; - sync_cycles = 65536; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces). + sync_cycles = PRNG_SEQUENCE_LENGTH; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the tag nonces). nt_attacked = 0; - nt = 0; par[0] = 0; } else { @@ -2040,33 +2082,84 @@ void ReaderMifare(bool first_try) LED_B_OFF(); LED_C_OFF(); - + + #define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up. + #define MAX_SYNC_TRIES 32 + #define NUM_DEBUG_INFOS 8 // per strategy + #define MAX_STRATEGY 3 + uint16_t unexpected_random = 0; + uint16_t sync_tries = 0; + int16_t debug_info_nr = -1; + uint16_t strategy = 0; + int32_t debug_info[MAX_STRATEGY][NUM_DEBUG_INFOS]; + uint32_t select_time; + uint32_t halt_time; + for(uint16_t i = 0; TRUE; i++) { + LED_C_ON(); WDT_HIT(); // Test if the action was cancelled if(BUTTON_PRESS()) { + isOK = -1; break; } - LED_C_ON(); + if (strategy == 2) { + // test with additional hlt command + halt_time = 0; + int len = mifare_sendcmd_short(NULL, false, 0x50, 0x00, receivedAnswer, receivedAnswerPar, &halt_time); + if (len && MF_DBGLEVEL >= 3) { + Dbprintf("Unexpected response of %d bytes to hlt command (additional debugging).", len); + } + } + if (strategy == 3) { + // test with FPGA power off/on + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); + iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD); + SpinDelay(100); + } + if(!iso14443a_select_card(uid, NULL, &cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card"); continue; } + select_time = GetCountSspClk(); - sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles; - catch_up_cycles = 0; + elapsed_prng_sequences = 1; + if (debug_info_nr == -1) { + sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles; + catch_up_cycles = 0; - // if we missed the sync time already, advance to the next nonce repeat - while(GetCountSspClk() > sync_time) { - sync_time = (sync_time & 0xfffffff8) + sync_cycles; - } + // if we missed the sync time already, advance to the next nonce repeat + while(GetCountSspClk() > sync_time) { + elapsed_prng_sequences++; + sync_time = (sync_time & 0xfffffff8) + sync_cycles; + } - // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked) - ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time); + // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked) + ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time); + } else { + // collect some information on tag nonces for debugging: + #define DEBUG_FIXED_SYNC_CYCLES PRNG_SEQUENCE_LENGTH + if (strategy == 0) { + // nonce distances at fixed time after card select: + sync_time = select_time + DEBUG_FIXED_SYNC_CYCLES; + } else if (strategy == 1) { + // nonce distances at fixed time between authentications: + sync_time = sync_time + DEBUG_FIXED_SYNC_CYCLES; + } else if (strategy == 2) { + // nonce distances at fixed time after halt: + sync_time = halt_time + DEBUG_FIXED_SYNC_CYCLES; + } else { + // nonce_distances at fixed time after power on + sync_time = DEBUG_FIXED_SYNC_CYCLES; + } + ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time); + } // Receive the (4 Byte) "random" nonce if (!ReaderReceive(receivedAnswer, receivedAnswerPar)) { @@ -2084,13 +2177,37 @@ void ReaderMifare(bool first_try) int nt_distance = dist_nt(previous_nt, nt); if (nt_distance == 0) { nt_attacked = nt; - } - else { - if (nt_distance == -99999) { // invalid nonce received, try again - continue; + } else { + if (nt_distance == -99999) { // invalid nonce received + unexpected_random++; + if (unexpected_random > MAX_UNEXPECTED_RANDOM) { + isOK = -3; // Card has an unpredictable PRNG. Give up + break; + } else { + continue; // continue trying... + } + } + if (++sync_tries > MAX_SYNC_TRIES) { + if (strategy > MAX_STRATEGY || MF_DBGLEVEL < 3) { + isOK = -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly + break; + } else { // continue for a while, just to collect some debug info + debug_info[strategy][debug_info_nr] = nt_distance; + debug_info_nr++; + if (debug_info_nr == NUM_DEBUG_INFOS) { + strategy++; + debug_info_nr = 0; + } + continue; + } + } + sync_cycles = (sync_cycles - nt_distance/elapsed_prng_sequences); + if (sync_cycles <= 0) { + sync_cycles += PRNG_SEQUENCE_LENGTH; + } + if (MF_DBGLEVEL >= 3) { + Dbprintf("calibrating in cycle %d. nt_distance=%d, elapsed_prng_sequences=%d, new sync_cycles: %d\n", i, nt_distance, elapsed_prng_sequences, sync_cycles); } - sync_cycles = (sync_cycles - nt_distance); - if (MF_DBGLEVEL >= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i, nt_distance, sync_cycles); continue; } } @@ -2101,6 +2218,7 @@ void ReaderMifare(bool first_try) catch_up_cycles = 0; continue; } + catch_up_cycles /= elapsed_prng_sequences; if (catch_up_cycles == last_catch_up) { consecutive_resyncs++; } @@ -2114,6 +2232,9 @@ void ReaderMifare(bool first_try) else { sync_cycles = sync_cycles + catch_up_cycles; if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i, -catch_up_cycles, sync_cycles); + last_catch_up = 0; + catch_up_cycles = 0; + consecutive_resyncs = 0; } continue; } @@ -2121,12 +2242,10 @@ void ReaderMifare(bool first_try) consecutive_resyncs = 0; // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding - if (ReaderReceive(receivedAnswer, receivedAnswerPar)) - { + if (ReaderReceive(receivedAnswer, receivedAnswerPar)) { catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer - if (nt_diff == 0) - { + if (nt_diff == 0) { par_low = par[0] & 0xE0; // there is no need to check all parities for other nt_diff. Parity Bits for mf_nr_ar[0..2] won't change } @@ -2149,6 +2268,10 @@ void ReaderMifare(bool first_try) if (nt_diff == 0 && first_try) { par[0]++; + if (par[0] == 0x00) { // tried all 256 possible parities without success. Card doesn't send NACK. + isOK = -2; + break; + } } else { par[0] = ((par[0] & 0x1F) + 1) | par_low; } @@ -2157,6 +2280,16 @@ void ReaderMifare(bool first_try) mf_nr_ar[3] &= 0x1F; + + if (isOK == -4) { + if (MF_DBGLEVEL >= 3) { + for (uint16_t i = 0; i <= MAX_STRATEGY; i++) { + for(uint16_t j = 0; j < NUM_DEBUG_INFOS; j++) { + Dbprintf("collected debug info[%d][%d] = %d", i, j, debug_info[i][j]); + } + } + } + } byte_t buf[28]; memcpy(buf + 0, uid, 4); @@ -2165,7 +2298,7 @@ void ReaderMifare(bool first_try) memcpy(buf + 16, ks_list, 8); memcpy(buf + 24, mf_nr_ar, 4); - cmd_send(CMD_ACK,isOK,0,0,buf,28); + cmd_send(CMD_ACK, isOK, 0, 0, buf, 28); // Thats it... FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); @@ -2226,13 +2359,6 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * uint32_t ar_nr_responses[] = {0,0,0,0,0,0,0,0}; uint8_t ar_nr_collected = 0; - // free eventually allocated BigBuf memory but keep Emulator Memory - BigBuf_free_keep_EM(); - - // clear trace - clear_trace(); - set_tracing(TRUE); - // Authenticate response - nonce uint32_t nonce = bytes_to_num(rAUTH_NT, 4); @@ -2274,10 +2400,6 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3]; } - // We need to listen to the high-frequency, peak-detected path. - iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); - - if (MF_DBGLEVEL >= 1) { if (!_7BUID) { Dbprintf("4B UID: %02x%02x%02x%02x", @@ -2289,6 +2411,17 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * } } + // We need to listen to the high-frequency, peak-detected path. + iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN); + + // free eventually allocated BigBuf memory but keep Emulator Memory + BigBuf_free_keep_EM(); + + // clear trace + clear_trace(); + set_tracing(TRUE); + + bool finished = FALSE; while (!BUTTON_PRESS() && !finished) { WDT_HIT(); @@ -2510,13 +2643,13 @@ void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t * || receivedCmd[0] == 0xB0) { // transfer if (receivedCmd[1] >= 16 * 4) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); - if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking",receivedCmd[0],receivedCmd[1],receivedCmd[1]); + if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02x) on out of range block: %d (0x%02x), nacking",receivedCmd[0],receivedCmd[1],receivedCmd[1]); break; } if (receivedCmd[1] / 4 != cardAUTHSC) { EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA)); - if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd[0],receivedCmd[1],cardAUTHSC); + if (MF_DBGLEVEL >= 2) Dbprintf("Reader tried to operate (0x%02x) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd[0],receivedCmd[1],cardAUTHSC); break; } } @@ -2707,10 +2840,8 @@ void RAMFUNC SniffMifare(uint8_t param) { uint8_t receivedResponse[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedResponsePar[MAX_MIFARE_PARITY_SIZE]; - // As we receive stuff, we copy it from receivedCmd or receivedResponse - // into trace, along with its length and other annotations. - //uint8_t *trace = (uint8_t *)BigBuf; - + iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); + // free eventually allocated BigBuf memory BigBuf_free(); // allocate the DMA buffer, used to stream samples from the FPGA @@ -2722,8 +2853,6 @@ void RAMFUNC SniffMifare(uint8_t param) { bool ReaderIsActive = FALSE; bool TagIsActive = FALSE; - iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER); - // Set up the demodulator for tag -> reader responses. DemodInit(receivedResponse, receivedResponsePar); @@ -2803,7 +2932,7 @@ void RAMFUNC SniffMifare(uint8_t param) { if (MfSniffLogic(receivedCmd, Uart.len, Uart.parity, Uart.bitCount, TRUE)) break; /* And ready to receive another command. */ - UartReset(); + UartInit(receivedCmd, receivedCmdPar); /* And also reset the demod code */ DemodReset(); @@ -2820,6 +2949,8 @@ void RAMFUNC SniffMifare(uint8_t param) { // And ready to receive another response. DemodReset(); + // And reset the Miller decoder including its (now outdated) input buffer + UartInit(receivedCmd, receivedCmdPar); } TagIsActive = (Demod.state != DEMOD_UNSYNCD); } diff --git a/armsrc/iso14443a.h b/armsrc/iso14443a.h index 1e978e88..ec99ab99 100644 --- a/armsrc/iso14443a.h +++ b/armsrc/iso14443a.h @@ -56,15 +56,14 @@ typedef struct { // DROP_FIRST_HALF, } state; uint16_t shiftReg; - uint16_t bitCount; + int16_t bitCount; uint16_t len; uint16_t byteCntMax; uint16_t posCnt; uint16_t syncBit; uint8_t parityBits; uint8_t parityLen; - uint16_t highCnt; - uint16_t twoBits; + uint32_t fourBits; uint32_t startTime, endTime; uint8_t *output; uint8_t *parity; diff --git a/armsrc/iso14443b.c b/armsrc/iso14443b.c new file mode 100644 index 00000000..82e5dd6a --- /dev/null +++ b/armsrc/iso14443b.c @@ -0,0 +1,1343 @@ +//----------------------------------------------------------------------------- +// Jonathan Westhues, split Nov 2006 +// +// This code is licensed to you under the terms of the GNU GPL, version 2 or, +// at your option, any later version. See the LICENSE.txt file for the text of +// the license. +//----------------------------------------------------------------------------- +// Routines to support ISO 14443B. This includes both the reader software and +// the `fake tag' modes. +//----------------------------------------------------------------------------- + +#include "proxmark3.h" +#include "apps.h" +#include "util.h" +#include "string.h" + +#include "iso14443crc.h" + +#define RECEIVE_SAMPLES_TIMEOUT 2000 +#define ISO14443B_DMA_BUFFER_SIZE 256 + +// PCB Block number for APDUs +static uint8_t pcb_blocknum = 0; + +//============================================================================= +// 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 +// frame (i.e., a group of bytes between SOF and EOF), we check the CRC. +// If it's good, then we can do something appropriate with it, and send +// a response. +//============================================================================= + +//----------------------------------------------------------------------------- +// Code up a string of octets at layer 2 (including CRC, we don't generate +// that here) so that they can be transmitted to the reader. Doesn't transmit +// them yet, just leaves them ready to send in ToSend[]. +//----------------------------------------------------------------------------- +static void CodeIso14443bAsTag(const uint8_t *cmd, int len) +{ + int i; + + ToSendReset(); + + // Transmit a burst of ones, as the initial thing that lets the + // reader get phase sync. This (TR1) must be > 80/fs, per spec, + // but tag that I've tried (a Paypass) exceeds that by a fair bit, + // so I will too. + for(i = 0; i < 20; i++) { + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + } + + // Send SOF. + for(i = 0; i < 10; i++) { + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + } + for(i = 0; i < 2; i++) { + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + } + + for(i = 0; i < len; i++) { + int j; + uint8_t b = cmd[i]; + + // Start bit + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + + // Data bits + for(j = 0; j < 8; j++) { + if(b & 1) { + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + } else { + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + } + b >>= 1; + } + + // Stop bit + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + } + + // Send EOF. + for(i = 0; i < 10; i++) { + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + ToSendStuffBit(0); + } + for(i = 0; i < 2; i++) { + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + ToSendStuffBit(1); + } + + // Convert from last byte pos to length + ToSendMax++; +} + +//----------------------------------------------------------------------------- +// The software UART that receives commands from the reader, and its state +// variables. +//----------------------------------------------------------------------------- +static struct { + enum { + STATE_UNSYNCD, + STATE_GOT_FALLING_EDGE_OF_SOF, + STATE_AWAITING_START_BIT, + STATE_RECEIVING_DATA + } state; + uint16_t shiftReg; + int bitCnt; + int byteCnt; + int byteCntMax; + int posCnt; + uint8_t *output; +} Uart; + +/* Receive & handle a bit coming from the reader. + * + * This function is called 4 times per bit (every 2 subcarrier cycles). + * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us + * + * LED handling: + * LED A -> ON once we have received the SOF and are expecting the rest. + * LED A -> OFF once we have received EOF or are in error state or unsynced + * + * Returns: true if we received a EOF + * false if we are still waiting for some more + */ +static RAMFUNC int Handle14443bUartBit(uint8_t bit) +{ + switch(Uart.state) { + case STATE_UNSYNCD: + if(!bit) { + // we went low, so this could be the beginning + // of an SOF + Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF; + Uart.posCnt = 0; + Uart.bitCnt = 0; + } + break; + + case STATE_GOT_FALLING_EDGE_OF_SOF: + Uart.posCnt++; + if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit + if(bit) { + if(Uart.bitCnt > 9) { + // we've seen enough consecutive + // zeros that it's a valid SOF + Uart.posCnt = 0; + Uart.byteCnt = 0; + Uart.state = STATE_AWAITING_START_BIT; + LED_A_ON(); // Indicate we got a valid SOF + } else { + // didn't stay down long enough + // before going high, error + Uart.state = STATE_UNSYNCD; + } + } else { + // do nothing, keep waiting + } + Uart.bitCnt++; + } + if(Uart.posCnt >= 4) Uart.posCnt = 0; + if(Uart.bitCnt > 12) { + // Give up if we see too many zeros without + // a one, too. + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; + } + break; + + case STATE_AWAITING_START_BIT: + Uart.posCnt++; + if(bit) { + if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs + // stayed high for too long between + // characters, error + Uart.state = STATE_UNSYNCD; + } + } else { + // falling edge, this starts the data byte + Uart.posCnt = 0; + Uart.bitCnt = 0; + Uart.shiftReg = 0; + Uart.state = STATE_RECEIVING_DATA; + } + break; + + case STATE_RECEIVING_DATA: + Uart.posCnt++; + if(Uart.posCnt == 2) { + // time to sample a bit + Uart.shiftReg >>= 1; + if(bit) { + Uart.shiftReg |= 0x200; + } + Uart.bitCnt++; + } + if(Uart.posCnt >= 4) { + Uart.posCnt = 0; + } + if(Uart.bitCnt == 10) { + if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001)) + { + // this is a data byte, with correct + // start and stop bits + Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff; + Uart.byteCnt++; + + if(Uart.byteCnt >= Uart.byteCntMax) { + // Buffer overflowed, give up + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; + } else { + // so get the next byte now + Uart.posCnt = 0; + Uart.state = STATE_AWAITING_START_BIT; + } + } else if (Uart.shiftReg == 0x000) { + // this is an EOF byte + LED_A_OFF(); // Finished receiving + Uart.state = STATE_UNSYNCD; + if (Uart.byteCnt != 0) { + return TRUE; + } + } else { + // this is an error + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; + } + } + break; + + default: + LED_A_OFF(); + Uart.state = STATE_UNSYNCD; + break; + } + + return FALSE; +} + + +static void UartReset() +{ + Uart.byteCntMax = MAX_FRAME_SIZE; + Uart.state = STATE_UNSYNCD; + Uart.byteCnt = 0; + Uart.bitCnt = 0; +} + + +static void UartInit(uint8_t *data) +{ + Uart.output = data; + UartReset(); +} + + +//----------------------------------------------------------------------------- +// Receive a command (from the reader to us, where we are the simulated tag), +// and store it in the given buffer, up to the given maximum length. Keeps +// spinning, waiting for a well-framed command, until either we get one +// (returns TRUE) or someone presses the pushbutton on the board (FALSE). +// +// Assume that we're called with the SSC (to the FPGA) and ADC path set +// correctly. +//----------------------------------------------------------------------------- +static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) +{ + // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen + // only, since we are receiving, not transmitting). + // Signal field is off with the appropriate LED + LED_D_OFF(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION); + + // Now run a `software UART' on the stream of incoming samples. + UartInit(received); + + for(;;) { + WDT_HIT(); + + if(BUTTON_PRESS()) return FALSE; + + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; + for(uint8_t mask = 0x80; mask != 0x00; mask >>= 1) { + if(Handle14443bUartBit(b & mask)) { + *len = Uart.byteCnt; + return TRUE; + } + } + } + } + + return FALSE; +} + +//----------------------------------------------------------------------------- +// Main loop of simulated tag: receive commands from reader, decide what +// response to send, and send it. +//----------------------------------------------------------------------------- +void SimulateIso14443bTag(void) +{ + // the only commands we understand is WUPB, AFI=0, Select All, N=1: + static const uint8_t cmd1[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // WUPB + // ... and REQB, AFI=0, Normal Request, N=1: + static const uint8_t cmd2[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; // REQB + // ... and HLTB + static const uint8_t cmd3[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB + // ... and ATTRIB + static const uint8_t cmd4[] = { 0x1D, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB + + // ... and we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922, + // supports only 106kBit/s in both directions, max frame size = 32Bytes, + // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported: + static const uint8_t response1[] = { + 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22, + 0x00, 0x21, 0x85, 0x5e, 0xd7 + }; + // response to HLTB and ATTRIB + static const uint8_t response2[] = {0x00, 0x78, 0xF0}; + + + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + + clear_trace(); + set_tracing(TRUE); + + const uint8_t *resp; + uint8_t *respCode; + uint16_t respLen, respCodeLen; + + // allocate command receive buffer + BigBuf_free(); + uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE); + + uint16_t len; + uint16_t cmdsRecvd = 0; + + // prepare the (only one) tag answer: + CodeIso14443bAsTag(response1, sizeof(response1)); + uint8_t *resp1Code = BigBuf_malloc(ToSendMax); + memcpy(resp1Code, ToSend, ToSendMax); + uint16_t resp1CodeLen = ToSendMax; + + // prepare the (other) tag answer: + CodeIso14443bAsTag(response2, sizeof(response2)); + uint8_t *resp2Code = BigBuf_malloc(ToSendMax); + memcpy(resp2Code, ToSend, ToSendMax); + uint16_t resp2CodeLen = ToSendMax; + + // We need to listen to the high-frequency, peak-detected path. + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + FpgaSetupSsc(); + + cmdsRecvd = 0; + + for(;;) { + + if(!GetIso14443bCommandFromReader(receivedCmd, &len)) { + Dbprintf("button pressed, received %d commands", cmdsRecvd); + break; + } + + if (tracing) { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(receivedCmd, len, 0, 0, parity, TRUE); + } + + // Good, look at the command now. + if ( (len == sizeof(cmd1) && memcmp(receivedCmd, cmd1, len) == 0) + || (len == sizeof(cmd2) && memcmp(receivedCmd, cmd2, len) == 0) ) { + resp = response1; + respLen = sizeof(response1); + respCode = resp1Code; + respCodeLen = resp1CodeLen; + } else if ( (len == sizeof(cmd3) && receivedCmd[0] == cmd3[0]) + || (len == sizeof(cmd4) && receivedCmd[0] == cmd4[0]) ) { + resp = response2; + respLen = sizeof(response2); + respCode = resp2Code; + respCodeLen = resp2CodeLen; + } else { + Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsRecvd); + // And print whether the CRC fails, just for good measure + uint8_t b1, b2; + if (len >= 3){ // if crc exists + ComputeCrc14443(CRC_14443_B, receivedCmd, len-2, &b1, &b2); + if(b1 != receivedCmd[len-2] || b2 != receivedCmd[len-1]) { + // Not so good, try again. + DbpString("+++CRC fail"); + + } else { + DbpString("CRC passes"); + } + } + //get rid of compiler warning + respCodeLen = 0; + resp = response1; + respLen = 0; + respCode = resp1Code; + //don't crash at new command just wait and see if reader will send other new cmds. + //break; + } + + cmdsRecvd++; + + if(cmdsRecvd > 0x30) { + DbpString("many commands later..."); + break; + } + + if(respCodeLen <= 0) continue; + + // Modulate BPSK + // Signal field is off with the appropriate LED + LED_D_OFF(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK); + AT91C_BASE_SSC->SSC_THR = 0xff; + FpgaSetupSsc(); + + // Transmit the response. + uint16_t i = 0; + for(;;) { + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { + uint8_t b = respCode[i]; + + AT91C_BASE_SSC->SSC_THR = b; + + i++; + if(i > respCodeLen) { + break; + } + } + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR; + (void)b; + } + } + + // trace the response: + if (tracing) { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(resp, respLen, 0, 0, parity, FALSE); + } + + } +} + +//============================================================================= +// An ISO 14443 Type B reader. We take layer two commands, code them +// appropriately, and then send them to the tag. We then listen for the +// tag's response, which we leave in the buffer to be demodulated on the +// PC side. +//============================================================================= + +static struct { + enum { + DEMOD_UNSYNCD, + DEMOD_PHASE_REF_TRAINING, + DEMOD_AWAITING_FALLING_EDGE_OF_SOF, + DEMOD_GOT_FALLING_EDGE_OF_SOF, + DEMOD_AWAITING_START_BIT, + DEMOD_RECEIVING_DATA + } state; + int bitCount; + int posCount; + int thisBit; +/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented. + int metric; + int metricN; +*/ + uint16_t shiftReg; + uint8_t *output; + int len; + int sumI; + int sumQ; +} Demod; + +/* + * Handles reception of a bit from the tag + * + * This function is called 2 times per bit (every 4 subcarrier cycles). + * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us + * + * LED handling: + * LED C -> ON once we have received the SOF and are expecting the rest. + * LED C -> OFF once we have received EOF or are unsynced + * + * Returns: true if we received a EOF + * false if we are still waiting for some more + * + */ +static RAMFUNC int Handle14443bSamplesDemod(int ci, int cq) +{ + int v; + +// The soft decision on the bit uses an estimate of just the +// quadrant of the reference angle, not the exact angle. +#define MAKE_SOFT_DECISION() { \ + if(Demod.sumI > 0) { \ + v = ci; \ + } else { \ + v = -ci; \ + } \ + if(Demod.sumQ > 0) { \ + v += cq; \ + } else { \ + v -= cq; \ + } \ + } + +#define SUBCARRIER_DETECT_THRESHOLD 8 + +// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq) +/* #define CHECK_FOR_SUBCARRIER() { \ + v = ci; \ + if(v < 0) v = -v; \ + if(cq > 0) { \ + v += cq; \ + } else { \ + v -= cq; \ + } \ + } + */ +// Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq))) +#define CHECK_FOR_SUBCARRIER() { \ + if(ci < 0) { \ + if(cq < 0) { /* ci < 0, cq < 0 */ \ + if (cq < ci) { \ + v = -cq - (ci >> 1); \ + } else { \ + v = -ci - (cq >> 1); \ + } \ + } else { /* ci < 0, cq >= 0 */ \ + if (cq < -ci) { \ + v = -ci + (cq >> 1); \ + } else { \ + v = cq - (ci >> 1); \ + } \ + } \ + } else { \ + if(cq < 0) { /* ci >= 0, cq < 0 */ \ + if (-cq < ci) { \ + v = ci - (cq >> 1); \ + } else { \ + v = -cq + (ci >> 1); \ + } \ + } else { /* ci >= 0, cq >= 0 */ \ + if (cq < ci) { \ + v = ci + (cq >> 1); \ + } else { \ + v = cq + (ci >> 1); \ + } \ + } \ + } \ + } + + switch(Demod.state) { + case DEMOD_UNSYNCD: + CHECK_FOR_SUBCARRIER(); + if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected + Demod.state = DEMOD_PHASE_REF_TRAINING; + Demod.sumI = ci; + Demod.sumQ = cq; + Demod.posCount = 1; + } + break; + + case DEMOD_PHASE_REF_TRAINING: + if(Demod.posCount < 8) { + CHECK_FOR_SUBCARRIER(); + if (v > SUBCARRIER_DETECT_THRESHOLD) { + // set the reference phase (will code a logic '1') by averaging over 32 1/fs. + // note: synchronization time > 80 1/fs + Demod.sumI += ci; + Demod.sumQ += cq; + Demod.posCount++; + } else { // subcarrier lost + Demod.state = DEMOD_UNSYNCD; + } + } else { + Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF; + } + break; + + case DEMOD_AWAITING_FALLING_EDGE_OF_SOF: + MAKE_SOFT_DECISION(); + if(v < 0) { // logic '0' detected + Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF; + Demod.posCount = 0; // start of SOF sequence + } else { + if(Demod.posCount > 200/4) { // maximum length of TR1 = 200 1/fs + Demod.state = DEMOD_UNSYNCD; + } + } + Demod.posCount++; + break; + + case DEMOD_GOT_FALLING_EDGE_OF_SOF: + Demod.posCount++; + MAKE_SOFT_DECISION(); + if(v > 0) { + if(Demod.posCount < 9*2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges + Demod.state = DEMOD_UNSYNCD; + } else { + LED_C_ON(); // Got SOF + Demod.state = DEMOD_AWAITING_START_BIT; + Demod.posCount = 0; + Demod.len = 0; +/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented. + Demod.metricN = 0; + Demod.metric = 0; +*/ + } + } else { + if(Demod.posCount > 12*2) { // low phase of SOF too long (> 12 etu) + Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); + } + } + break; + + case DEMOD_AWAITING_START_BIT: + Demod.posCount++; + MAKE_SOFT_DECISION(); + if(v > 0) { + if(Demod.posCount > 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs + Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); + } + } else { // start bit detected + Demod.bitCount = 0; + Demod.posCount = 1; // this was the first half + Demod.thisBit = v; + Demod.shiftReg = 0; + Demod.state = DEMOD_RECEIVING_DATA; + } + break; + + case DEMOD_RECEIVING_DATA: + MAKE_SOFT_DECISION(); + if(Demod.posCount == 0) { // first half of bit + Demod.thisBit = v; + Demod.posCount = 1; + } else { // second half of bit + Demod.thisBit += v; + +/* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented. + if(Demod.thisBit > 0) { + Demod.metric += Demod.thisBit; + } else { + Demod.metric -= Demod.thisBit; + } + (Demod.metricN)++; +*/ + + Demod.shiftReg >>= 1; + if(Demod.thisBit > 0) { // logic '1' + Demod.shiftReg |= 0x200; + } + + Demod.bitCount++; + if(Demod.bitCount == 10) { + uint16_t s = Demod.shiftReg; + if((s & 0x200) && !(s & 0x001)) { // stop bit == '1', start bit == '0' + uint8_t b = (s >> 1); + Demod.output[Demod.len] = b; + Demod.len++; + Demod.state = DEMOD_AWAITING_START_BIT; + } else { + Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); + if(s == 0x000) { + // This is EOF (start, stop and all data bits == '0' + return TRUE; + } + } + } + Demod.posCount = 0; + } + break; + + default: + Demod.state = DEMOD_UNSYNCD; + LED_C_OFF(); + break; + } + + return FALSE; +} + + +static void DemodReset() +{ + // Clear out the state of the "UART" that receives from the tag. + Demod.len = 0; + Demod.state = DEMOD_UNSYNCD; + Demod.posCount = 0; + memset(Demod.output, 0x00, MAX_FRAME_SIZE); +} + + +static void DemodInit(uint8_t *data) +{ + Demod.output = data; + DemodReset(); +} + + +/* + * Demodulate the samples we received from the tag, also log to tracebuffer + * quiet: set to 'TRUE' to disable debug output + */ +static void GetSamplesFor14443bDemod(int n, bool quiet) +{ + int max = 0; + bool gotFrame = FALSE; + int lastRxCounter, ci, cq, samples = 0; + + // Allocate memory from BigBuf for some buffers + // free all previous allocations first + BigBuf_free(); + + // The response (tag -> reader) that we're receiving. + uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE); + + // The DMA buffer, used to stream samples from the FPGA + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); + + // Set up the demodulator for tag -> reader responses. + DemodInit(receivedResponse); + + // Setup and start DMA. + FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); + + int8_t *upTo = dmaBuf; + lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; + + // Signal field is ON with the appropriate LED: + LED_D_ON(); + // And put the FPGA in the appropriate mode + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); + + for(;;) { + int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR; + if(behindBy > max) max = behindBy; + + while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (ISO14443B_DMA_BUFFER_SIZE-1)) > 2) { + ci = upTo[0]; + cq = upTo[1]; + upTo += 2; + if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { + upTo = dmaBuf; + AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; + } + lastRxCounter -= 2; + if(lastRxCounter <= 0) { + lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; + } + + samples += 2; + + if(Handle14443bSamplesDemod(ci, cq)) { + gotFrame = TRUE; + break; + } + } + + if(samples > n || gotFrame) { + break; + } + } + + AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; + + if (!quiet) Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", max, samples, gotFrame, Demod.len, Demod.sumI, Demod.sumQ); + //Tracing + if (tracing && Demod.len > 0) { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE); + } +} + + +//----------------------------------------------------------------------------- +// Transmit the command (to the tag) that was placed in ToSend[]. +//----------------------------------------------------------------------------- +static void TransmitFor14443b(void) +{ + int c; + + FpgaSetupSsc(); + + while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { + AT91C_BASE_SSC->SSC_THR = 0xff; + } + + // Signal field is ON with the appropriate Red LED + LED_D_ON(); + // Signal we are transmitting with the Green LED + LED_B_ON(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); + + for(c = 0; c < 10;) { + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { + AT91C_BASE_SSC->SSC_THR = 0xff; + c++; + } + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; + (void)r; + } + WDT_HIT(); + } + + c = 0; + for(;;) { + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) { + AT91C_BASE_SSC->SSC_THR = ToSend[c]; + c++; + if(c >= ToSendMax) { + break; + } + } + if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) { + volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR; + (void)r; + } + WDT_HIT(); + } + LED_B_OFF(); // Finished sending +} + + +//----------------------------------------------------------------------------- +// Code a layer 2 command (string of octets, including CRC) into ToSend[], +// so that it is ready to transmit to the tag using TransmitFor14443b(). +//----------------------------------------------------------------------------- +static void CodeIso14443bAsReader(const uint8_t *cmd, int len) +{ + int i, j; + uint8_t b; + + ToSendReset(); + + // Establish initial reference level + for(i = 0; i < 40; i++) { + ToSendStuffBit(1); + } + // Send SOF + for(i = 0; i < 10; i++) { + ToSendStuffBit(0); + } + + for(i = 0; i < len; i++) { + // Stop bits/EGT + ToSendStuffBit(1); + ToSendStuffBit(1); + // Start bit + ToSendStuffBit(0); + // Data bits + b = cmd[i]; + for(j = 0; j < 8; j++) { + if(b & 1) { + ToSendStuffBit(1); + } else { + ToSendStuffBit(0); + } + b >>= 1; + } + } + // Send EOF + ToSendStuffBit(1); + for(i = 0; i < 10; i++) { + ToSendStuffBit(0); + } + for(i = 0; i < 8; i++) { + ToSendStuffBit(1); + } + + // And then a little more, to make sure that the last character makes + // it out before we switch to rx mode. + for(i = 0; i < 24; i++) { + ToSendStuffBit(1); + } + + // Convert from last character reference to length + ToSendMax++; +} + + +/** + Convenience function to encode, transmit and trace iso 14443b comms + **/ +static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len) +{ + CodeIso14443bAsReader(cmd, len); + TransmitFor14443b(); + if (tracing) { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(cmd,len, 0, 0, parity, TRUE); + } +} + +/* Sends an APDU to the tag + * TODO: check CRC and preamble + */ +int iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response) +{ + uint8_t message_frame[message_length + 4]; + // PCB + message_frame[0] = 0x0A | pcb_blocknum; + pcb_blocknum ^= 1; + // CID + message_frame[1] = 0; + // INF + memcpy(message_frame + 2, message, message_length); + // EDC (CRC) + ComputeCrc14443(CRC_14443_B, message_frame, message_length + 2, &message_frame[message_length + 2], &message_frame[message_length + 3]); + // send + CodeAndTransmit14443bAsReader(message_frame, message_length + 4); + // get response + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT*100, TRUE); + if(Demod.len < 3) + { + return 0; + } + // TODO: Check CRC + // copy response contents + if(response != NULL) + { + memcpy(response, Demod.output, Demod.len); + } + return Demod.len; +} + +/* Perform the ISO 14443 B Card Selection procedure + * Currently does NOT do any collision handling. + * It expects 0-1 cards in the device's range. + * TODO: Support multiple cards (perform anticollision) + * TODO: Verify CRC checksums + */ +int iso14443b_select_card() +{ + // WUPB command (including CRC) + // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state + static const uint8_t wupb[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; + // ATTRIB command (with space for CRC) + uint8_t attrib[] = { 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00}; + + // first, wake up the tag + CodeAndTransmit14443bAsReader(wupb, sizeof(wupb)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + // ATQB too short? + if (Demod.len < 14) + { + return 2; + } + + // select the tag + // copy the PUPI to ATTRIB + memcpy(attrib + 1, Demod.output + 1, 4); + /* copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into + ATTRIB (Param 3) */ + attrib[7] = Demod.output[10] & 0x0F; + ComputeCrc14443(CRC_14443_B, attrib, 9, attrib + 9, attrib + 10); + CodeAndTransmit14443bAsReader(attrib, sizeof(attrib)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + // Answer to ATTRIB too short? + if(Demod.len < 3) + { + return 2; + } + // reset PCB block number + pcb_blocknum = 0; + return 1; +} + +// Set up ISO 14443 Type B communication (similar to iso14443a_setup) +void iso14443b_setup() { + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + // Set up the synchronous serial port + FpgaSetupSsc(); + // connect Demodulated Signal to ADC: + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + + // Signal field is on with the appropriate LED + LED_D_ON(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD); + + // Start the timer + StartCountSspClk(); + + DemodReset(); + UartReset(); +} + +//----------------------------------------------------------------------------- +// Read a SRI512 ISO 14443B tag. +// +// SRI512 tags are just simple memory tags, here we're looking at making a dump +// of the contents of the memory. No anticollision algorithm is done, we assume +// we have a single tag in the field. +// +// I tried to be systematic and check every answer of the tag, every CRC, etc... +//----------------------------------------------------------------------------- +void ReadSTMemoryIso14443b(uint32_t dwLast) +{ + uint8_t i = 0x00; + + 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. + LED_D_OFF(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); + + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + FpgaSetupSsc(); + + // Now give it time to spin up. + // Signal field is on with the appropriate LED + LED_D_ON(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ); + SpinDelay(200); + + clear_trace(); + set_tracing(TRUE); + + // First command: wake up the tag using the INITIATE command + uint8_t cmd1[] = {0x06, 0x00, 0x97, 0x5b}; + CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + + if (Demod.len == 0) { + DbpString("No response from tag"); + return; + } else { + Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x", + Demod.output[0], Demod.output[1], Demod.output[2]); + } + + // There is a response, SELECT the uid + DbpString("Now SELECT tag:"); + cmd1[0] = 0x0E; // 0x0E is SELECT + cmd1[1] = Demod.output[0]; + ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]); + CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + if (Demod.len != 3) { + Dbprintf("Expected 3 bytes from tag, got %d", Demod.len); + return; + } + // Check the CRC of the answer: + ComputeCrc14443(CRC_14443_B, Demod.output, 1 , &cmd1[2], &cmd1[3]); + if(cmd1[2] != Demod.output[1] || cmd1[3] != Demod.output[2]) { + DbpString("CRC Error reading select response."); + return; + } + // Check response from the tag: should be the same UID as the command we just sent: + if (cmd1[1] != Demod.output[0]) { + Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1[1], Demod.output[0]); + return; + } + + // Tag is now selected, + // First get the tag's UID: + cmd1[0] = 0x0B; + ComputeCrc14443(CRC_14443_B, cmd1, 1 , &cmd1[1], &cmd1[2]); + CodeAndTransmit14443bAsReader(cmd1, 3); // Only first three bytes for this one + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + if (Demod.len != 10) { + Dbprintf("Expected 10 bytes from tag, got %d", Demod.len); + return; + } + // The check the CRC of the answer (use cmd1 as temporary variable): + ComputeCrc14443(CRC_14443_B, Demod.output, 8, &cmd1[2], &cmd1[3]); + if(cmd1[2] != Demod.output[8] || cmd1[3] != Demod.output[9]) { + Dbprintf("CRC Error reading block! Expected: %04x got: %04x", + (cmd1[2]<<8)+cmd1[3], (Demod.output[8]<<8)+Demod.output[9]); + // Do not return;, let's go on... (we should retry, maybe ?) + } + Dbprintf("Tag UID (64 bits): %08x %08x", + (Demod.output[7]<<24) + (Demod.output[6]<<16) + (Demod.output[5]<<8) + Demod.output[4], + (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0]); + + // Now loop to read all 16 blocks, address from 0 to last block + Dbprintf("Tag memory dump, block 0 to %d", dwLast); + cmd1[0] = 0x08; + i = 0x00; + dwLast++; + for (;;) { + if (i == dwLast) { + DbpString("System area block (0xff):"); + i = 0xff; + } + cmd1[1] = i; + ComputeCrc14443(CRC_14443_B, cmd1, 2, &cmd1[2], &cmd1[3]); + CodeAndTransmit14443bAsReader(cmd1, sizeof(cmd1)); + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + if (Demod.len != 6) { // Check if we got an answer from the tag + DbpString("Expected 6 bytes from tag, got less..."); + return; + } + // The check the CRC of the answer (use cmd1 as temporary variable): + ComputeCrc14443(CRC_14443_B, Demod.output, 4, &cmd1[2], &cmd1[3]); + if(cmd1[2] != Demod.output[4] || cmd1[3] != Demod.output[5]) { + Dbprintf("CRC Error reading block! Expected: %04x got: %04x", + (cmd1[2]<<8)+cmd1[3], (Demod.output[4]<<8)+Demod.output[5]); + // Do not return;, let's go on... (we should retry, maybe ?) + } + // Now print out the memory location: + Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i, + (Demod.output[3]<<24) + (Demod.output[2]<<16) + (Demod.output[1]<<8) + Demod.output[0], + (Demod.output[4]<<8)+Demod.output[5]); + if (i == 0xff) { + break; + } + i++; + } +} + + +//============================================================================= +// Finally, the `sniffer' combines elements from both the reader and +// simulated tag, to show both sides of the conversation. +//============================================================================= + +//----------------------------------------------------------------------------- +// Record the sequence of commands sent by the reader to the tag, with +// triggering so that we start recording at the point that the tag is moved +// near the reader. +//----------------------------------------------------------------------------- +/* + * Memory usage for this function, (within BigBuf) + * Last Received command (reader->tag) - MAX_FRAME_SIZE + * Last Received command (tag->reader) - MAX_FRAME_SIZE + * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE + * Demodulated samples received - all the rest + */ +void RAMFUNC SnoopIso14443b(void) +{ + // We won't start recording the frames that we acquire until we trigger; + // a good trigger condition to get started is probably when we see a + // response from the tag. + int triggered = TRUE; // TODO: set and evaluate trigger condition + + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + BigBuf_free(); + + clear_trace(); + set_tracing(TRUE); + + // The DMA buffer, used to stream samples from the FPGA + int8_t *dmaBuf = (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE); + int lastRxCounter; + int8_t *upTo; + int ci, cq; + int maxBehindBy = 0; + + // Count of samples received so far, so that we can include timing + // information in the trace buffer. + int samples = 0; + + DemodInit(BigBuf_malloc(MAX_FRAME_SIZE)); + UartInit(BigBuf_malloc(MAX_FRAME_SIZE)); + + // Print some debug information about the buffer sizes + Dbprintf("Snooping buffers initialized:"); + Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen()); + Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE); + Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE); + Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE); + + // Signal field is off, no reader signal, no tag signal + LEDsoff(); + + // And put the FPGA in the appropriate mode + FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ | FPGA_HF_READER_RX_XCORR_SNOOP); + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + + // Setup for the DMA. + FpgaSetupSsc(); + upTo = dmaBuf; + lastRxCounter = ISO14443B_DMA_BUFFER_SIZE; + FpgaSetupSscDma((uint8_t*) dmaBuf, ISO14443B_DMA_BUFFER_SIZE); + uint8_t parity[MAX_PARITY_SIZE]; + + bool TagIsActive = FALSE; + bool ReaderIsActive = FALSE; + + // And now we loop, receiving samples. + for(;;) { + int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) & + (ISO14443B_DMA_BUFFER_SIZE-1); + if(behindBy > maxBehindBy) { + maxBehindBy = behindBy; + } + + if(behindBy < 2) continue; + + ci = upTo[0]; + cq = upTo[1]; + upTo += 2; + lastRxCounter -= 2; + if(upTo >= dmaBuf + ISO14443B_DMA_BUFFER_SIZE) { + upTo = dmaBuf; + lastRxCounter += ISO14443B_DMA_BUFFER_SIZE; + AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; + AT91C_BASE_PDC_SSC->PDC_RNCR = ISO14443B_DMA_BUFFER_SIZE; + WDT_HIT(); + if(behindBy > (9*ISO14443B_DMA_BUFFER_SIZE/10)) { // TODO: understand whether we can increase/decrease as we want or not? + Dbprintf("blew circular buffer! behindBy=%d", behindBy); + break; + } + if(!tracing) { + DbpString("Reached trace limit"); + break; + } + if(BUTTON_PRESS()) { + DbpString("cancelled"); + break; + } + } + + samples += 2; + + if (!TagIsActive) { // no need to try decoding reader data if the tag is sending + if(Handle14443bUartBit(ci & 0x01)) { + if(triggered && tracing) { + LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); + } + /* And ready to receive another command. */ + UartReset(); + /* And also reset the demod code, which might have been */ + /* false-triggered by the commands from the reader. */ + DemodReset(); + } + if(Handle14443bUartBit(cq & 0x01)) { + if(triggered && tracing) { + LogTrace(Uart.output, Uart.byteCnt, samples, samples, parity, TRUE); + } + /* And ready to receive another command. */ + UartReset(); + /* And also reset the demod code, which might have been */ + /* false-triggered by the commands from the reader. */ + DemodReset(); + } + ReaderIsActive = (Uart.state > STATE_GOT_FALLING_EDGE_OF_SOF); + } + + if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time + if(Handle14443bSamplesDemod(ci | 0x01, cq | 0x01)) { + + //Use samples as a time measurement + if(tracing) + { + uint8_t parity[MAX_PARITY_SIZE]; + LogTrace(Demod.output, Demod.len, samples, samples, parity, FALSE); + } + triggered = TRUE; + + // And ready to receive another response. + DemodReset(); + } + TagIsActive = (Demod.state > DEMOD_GOT_FALLING_EDGE_OF_SOF); + } + + } + + FpgaDisableSscDma(); + LEDsoff(); + AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS; + DbpString("Snoop statistics:"); + Dbprintf(" Max behind by: %i", maxBehindBy); + Dbprintf(" Uart State: %x", Uart.state); + Dbprintf(" Uart ByteCnt: %i", Uart.byteCnt); + Dbprintf(" Uart ByteCntMax: %i", Uart.byteCntMax); + Dbprintf(" Trace length: %i", BigBuf_get_traceLen()); +} + + +/* + * Send raw command to tag ISO14443B + * @Input + * datalen len of buffer data + * recv bool when true wait for data from tag and send to client + * powerfield bool leave the field on when true + * data buffer with byte to send + * + * @Output + * none + * + */ +void SendRawCommand14443B(uint32_t datalen, uint32_t recv, uint8_t powerfield, uint8_t data[]) +{ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); + FpgaSetupSsc(); + + if (datalen){ + set_tracing(TRUE); + + CodeAndTransmit14443bAsReader(data, datalen); + + if(recv) { + GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT, TRUE); + uint16_t iLen = MIN(Demod.len, USB_CMD_DATA_SIZE); + cmd_send(CMD_ACK, iLen, 0, 0, Demod.output, iLen); + } + } + + if(!powerfield) { + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LED_D_OFF(); + } +} + diff --git a/armsrc/iso14443b.h b/armsrc/iso14443b.h new file mode 100644 index 00000000..f90c54f3 --- /dev/null +++ b/armsrc/iso14443b.h @@ -0,0 +1,21 @@ +//----------------------------------------------------------------------------- +// Merlok - June 2011 +// Gerhard de Koning Gans - May 2008 +// Hagen Fritsch - June 2010 +// +// This code is licensed to you under the terms of the GNU GPL, version 2 or, +// at your option, any later version. See the LICENSE.txt file for the text of +// the license. +//----------------------------------------------------------------------------- +// Routines to support ISO 14443 type A. +//----------------------------------------------------------------------------- + +#ifndef __ISO14443B_H +#define __ISO14443B_H +#include "common.h" + +int iso14443b_apdu(uint8_t const *message, size_t message_length, uint8_t *response); +void iso14443b_setup(); +int iso14443b_select_card(); + +#endif /* __ISO14443B_H */ diff --git a/armsrc/iso15693.c b/armsrc/iso15693.c index 94040a85..e7145c5c 100644 --- a/armsrc/iso15693.c +++ b/armsrc/iso15693.c @@ -877,12 +877,12 @@ int SendDataTag(uint8_t *send, int sendlen, int init, int speed, uint8_t **recv) LED_C_OFF(); LED_D_OFF(); + if (init) Iso15693InitReader(); + int answerLen=0; uint8_t *answer = BigBuf_get_addr() + 3660; if (recv != NULL) memset(answer, 0, 100); - if (init) Iso15693InitReader(); - if (!speed) { // low speed (1 out of 256) CodeIso15693AsReader256(send, sendlen); @@ -999,10 +999,6 @@ void ReaderIso15693(uint32_t parameter) LED_C_OFF(); LED_D_OFF(); - uint8_t *answer1 = BigBuf_get_addr() + 3660; - uint8_t *answer2 = BigBuf_get_addr() + 3760; - uint8_t *answer3 = BigBuf_get_addr() + 3860; - int answerLen1 = 0; int answerLen2 = 0; int answerLen3 = 0; @@ -1013,19 +1009,21 @@ void ReaderIso15693(uint32_t parameter) int elapsed = 0; uint8_t TagUID[8] = {0x00}; + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + uint8_t *answer1 = BigBuf_get_addr() + 3660; + uint8_t *answer2 = BigBuf_get_addr() + 3760; + uint8_t *answer3 = BigBuf_get_addr() + 3860; // Blank arrays memset(answer1, 0x00, 300); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); - SetAdcMuxFor(GPIO_MUXSEL_HIPKD); // Setup SSC FpgaSetupSsc(); // Start from off (no field generated) - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); - SpinDelay(200); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); // Give the tags time to energize FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR); @@ -1111,24 +1109,22 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) LED_C_OFF(); LED_D_OFF(); - uint8_t *buf = BigBuf_get_addr() + 3660; - int answerLen1 = 0; int samples = 0; int tsamples = 0; int wait = 0; int elapsed = 0; - memset(buf, 0x00, 100); - FpgaDownloadAndGo(FPGA_BITSTREAM_HF); + uint8_t *buf = BigBuf_get_addr() + 3660; + memset(buf, 0x00, 100); + SetAdcMuxFor(GPIO_MUXSEL_HIPKD); - FpgaSetupSsc(); // Start from off (no field generated) - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelay(200); LED_A_OFF(); diff --git a/armsrc/ldscript b/armsrc/ldscript index 840b8196..34da26bc 100644 --- a/armsrc/ldscript +++ b/armsrc/ldscript @@ -24,6 +24,7 @@ SECTIONS } >osimage :text .text : { + KEEP(*(stage1_image)) *(.text) *(.text.*) *(.eh_frame) @@ -34,14 +35,13 @@ SECTIONS .rodata : { *(.rodata) *(.rodata.*) - *(fpga_lf_bit.data) - *(fpga_hf_bit.data) + *(fpga_all_bit.data) KEEP(*(.version_information)) + . = ALIGN(8); } >osimage :text - . = ALIGN(4); - .data : { + KEEP(*(compressed_data)) *(.data) *(.data.*) *(.ramfunc) @@ -51,6 +51,7 @@ SECTIONS __data_src_start__ = LOADADDR(.data); __data_start__ = ADDR(.data); __data_end__ = __data_start__ + SIZEOF(.data); + __os_size__ = SIZEOF(.text) + SIZEOF(.data) + SIZEOF(.rodata); .bss : { __bss_start__ = .; diff --git a/armsrc/lfops.c b/armsrc/lfops.c index c3fa8a0e..14b62673 100644 --- a/armsrc/lfops.c +++ b/armsrc/lfops.c @@ -16,8 +16,8 @@ #include "string.h" #include "lfdemod.h" #include "lfsampling.h" -#include "usb_cdc.h" - +#include "protocols.h" +#include "usb_cdc.h" // for usb_poll_validate_length /** * Function to do a modulation and then get samples. @@ -26,7 +26,7 @@ * @param period_1 * @param command */ -void ModThenAcquireRawAdcSamples125k(int delay_off, int period_0, int period_1, uint8_t *command) +void ModThenAcquireRawAdcSamples125k(uint32_t delay_off, uint32_t period_0, uint32_t period_1, uint8_t *command) { int divisor_used = 95; // 125 KHz @@ -37,6 +37,8 @@ void ModThenAcquireRawAdcSamples125k(int delay_off, int period_0, int period_1, sample_config sc = { 0,0,1, divisor_used, 0}; setSamplingConfig(&sc); + //clear read buffer + BigBuf_Clear_keep_EM(); /* Make sure the tag is reset */ FpgaDownloadAndGo(FPGA_BITSTREAM_LF); @@ -73,8 +75,6 @@ void ModThenAcquireRawAdcSamples125k(int delay_off, int period_0, int period_1, DoAcquisition_config(false); } - - /* blank r/w tag data stream ...0000000000000000 01111111 1010101010101010101010101010101010101010101010101010101010101010 @@ -248,7 +248,7 @@ void AcquireTiType(void) // clear buffer uint32_t *BigBuf = (uint32_t *)BigBuf_get_addr(); - memset(BigBuf,0,BigBuf_max_traceLen()/sizeof(uint32_t)); + BigBuf_Clear_ext(false); // Set up the synchronous serial port AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DIN; @@ -395,14 +395,14 @@ void SimulateTagLowFrequency(int period, int gap, int ledcontrol) AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK; - #define SHORT_COIL() LOW(GPIO_SSC_DOUT) - #define OPEN_COIL() HIGH(GPIO_SSC_DOUT) + #define SHORT_COIL() LOW(GPIO_SSC_DOUT) + #define OPEN_COIL() HIGH(GPIO_SSC_DOUT) i = 0; for(;;) { //wait until SSC_CLK goes HIGH while(!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)) { - if(BUTTON_PRESS() || usb_poll()) { + if(BUTTON_PRESS() || (usb_poll_validate_length() )) { DbpString("Stopped"); return; } @@ -642,7 +642,6 @@ static void biphaseSimBit(uint8_t c, int *n, uint8_t clock, uint8_t *phase) memset(dest+(*n), c ^ *phase, clock); *phase ^= 1; } - } // args clock, ask/man or askraw, invert, transmission separator @@ -687,13 +686,9 @@ void CmdASKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream) //i+=16; //Dbprintf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", dest[i],dest[i+1],dest[i+2],dest[i+3],dest[i+4],dest[i+5],dest[i+6],dest[i+7],dest[i+8],dest[i+9],dest[i+10],dest[i+11],dest[i+12],dest[i+13],dest[i+14],dest[i+15]); - if (ledcontrol) - LED_A_ON(); - + if (ledcontrol) LED_A_ON(); SimulateTagLowFrequency(n, 0, ledcontrol); - - if (ledcontrol) - LED_A_OFF(); + if (ledcontrol) LED_A_OFF(); } //carrier can be 2,4 or 8 @@ -743,12 +738,9 @@ void CmdPSKsimTag(uint16_t arg1, uint16_t arg2, size_t size, uint8_t *BitStream) //i+=16; //Dbprintf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d", dest[i],dest[i+1],dest[i+2],dest[i+3],dest[i+4],dest[i+5],dest[i+6],dest[i+7],dest[i+8],dest[i+9],dest[i+10],dest[i+11],dest[i+12],dest[i+13],dest[i+14],dest[i+15]); - if (ledcontrol) - LED_A_ON(); + if (ledcontrol) LED_A_ON(); SimulateTagLowFrequency(n, 0, ledcontrol); - - if (ledcontrol) - LED_A_OFF(); + if (ledcontrol) LED_A_OFF(); } // loop to get raw HID waveform then FSK demodulate the TAG ID from it @@ -762,7 +754,10 @@ void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol) // Configure to go in 125Khz listen mode LFSetupFPGAForADC(95, true); - while(!BUTTON_PRESS()) { + //clear read buffer + BigBuf_Clear_keep_EM(); + + while(!BUTTON_PRESS() && !usb_poll_validate_length()) { WDT_HIT(); if (ledcontrol) LED_A_ON(); @@ -841,6 +836,96 @@ void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol) if (ledcontrol) LED_A_OFF(); } +// loop to get raw HID waveform then FSK demodulate the TAG ID from it +void CmdAWIDdemodFSK(int findone, int *high, int *low, int ledcontrol) +{ + uint8_t *dest = BigBuf_get_addr(); + size_t size; + int idx=0; + //clear read buffer + BigBuf_Clear_keep_EM(); + // Configure to go in 125Khz listen mode + LFSetupFPGAForADC(95, true); + + while(!BUTTON_PRESS() && !usb_poll_validate_length()) { + + WDT_HIT(); + if (ledcontrol) LED_A_ON(); + + DoAcquisition_default(-1,true); + // FSK demodulator + size = 50*128*2; //big enough to catch 2 sequences of largest format + idx = AWIDdemodFSK(dest, &size); + + if (idx<=0 || size!=96) continue; + // Index map + // 0 10 20 30 40 50 60 + // | | | | | | | + // 01234567 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 456 7 890 1 234 5 678 9 012 3 - to 96 + // ----------------------------------------------------------------------------- + // 00000001 000 1 110 1 101 1 011 1 101 1 010 0 000 1 000 1 010 0 001 0 110 1 100 0 000 1 000 1 + // premable bbb o bbb o bbw o fff o fff o ffc o ccc o ccc o ccc o ccc o ccc o wxx o xxx o xxx o - to 96 + // |---26 bit---| |-----117----||-------------142-------------| + // b = format bit len, o = odd parity of last 3 bits + // f = facility code, c = card number + // w = wiegand parity + // (26 bit format shown) + + //get raw ID before removing parities + uint32_t rawLo = bytebits_to_byte(dest+idx+64,32); + uint32_t rawHi = bytebits_to_byte(dest+idx+32,32); + uint32_t rawHi2 = bytebits_to_byte(dest+idx,32); + + size = removeParity(dest, idx+8, 4, 1, 88); + if (size != 66) continue; + // ok valid card found! + + // Index map + // 0 10 20 30 40 50 60 + // | | | | | | | + // 01234567 8 90123456 7890123456789012 3 456789012345678901234567890123456 + // ----------------------------------------------------------------------------- + // 00011010 1 01110101 0000000010001110 1 000000000000000000000000000000000 + // bbbbbbbb w ffffffff cccccccccccccccc w xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx + // |26 bit| |-117--| |-----142------| + // b = format bit len, o = odd parity of last 3 bits + // f = facility code, c = card number + // w = wiegand parity + // (26 bit format shown) + + uint32_t fc = 0; + uint32_t cardnum = 0; + uint32_t code1 = 0; + uint32_t code2 = 0; + uint8_t fmtLen = bytebits_to_byte(dest,8); + if (fmtLen==26){ + fc = bytebits_to_byte(dest+9, 8); + cardnum = bytebits_to_byte(dest+17, 16); + code1 = bytebits_to_byte(dest+8,fmtLen); + Dbprintf("AWID Found - BitLength: %d, FC: %d, Card: %d - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, fc, cardnum, code1, rawHi2, rawHi, rawLo); + } else { + cardnum = bytebits_to_byte(dest+8+(fmtLen-17), 16); + if (fmtLen>32){ + code1 = bytebits_to_byte(dest+8,fmtLen-32); + code2 = bytebits_to_byte(dest+8+(fmtLen-32),32); + Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x%08x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, code2, rawHi2, rawHi, rawLo); + } else{ + code1 = bytebits_to_byte(dest+8,fmtLen); + Dbprintf("AWID Found - BitLength: %d -unknown BitLength- (%d) - Wiegand: %x, Raw: %08x%08x%08x", fmtLen, cardnum, code1, rawHi2, rawHi, rawLo); + } + } + if (findone){ + if (ledcontrol) LED_A_OFF(); + return; + } + // reset + idx = 0; + WDT_HIT(); + } + DbpString("Stopped"); + if (ledcontrol) LED_A_OFF(); +} + void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol) { uint8_t *dest = BigBuf_get_addr(); @@ -849,10 +934,12 @@ void CmdEM410xdemod(int findone, int *high, int *low, int ledcontrol) int clk=0, invert=0, errCnt=0, maxErr=20; uint32_t hi=0; uint64_t lo=0; + //clear read buffer + BigBuf_Clear_keep_EM(); // Configure to go in 125Khz listen mode LFSetupFPGAForADC(95, true); - while(!BUTTON_PRESS()) { + while(!BUTTON_PRESS() && !usb_poll_validate_length()) { WDT_HIT(); if (ledcontrol) LED_A_ON(); @@ -908,10 +995,12 @@ void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol) uint8_t version=0; uint8_t facilitycode=0; uint16_t number=0; + //clear read buffer + BigBuf_Clear_keep_EM(); // Configure to go in 125Khz listen mode LFSetupFPGAForADC(95, true); - while(!BUTTON_PRESS()) { + while(!BUTTON_PRESS() && !usb_poll_validate_length()) { WDT_HIT(); if (ledcontrol) LED_A_ON(); DoAcquisition_default(-1,true); @@ -966,237 +1055,206 @@ void CmdIOdemodFSK(int findone, int *high, int *low, int ledcontrol) } /*------------------------------ - * T5555/T5557/T5567 routines + * T5555/T5557/T5567/T5577 routines *------------------------------ - */ - -/* T55x7 configuration register definitions */ -#define T55x7_POR_DELAY 0x00000001 -#define T55x7_ST_TERMINATOR 0x00000008 -#define T55x7_PWD 0x00000010 -#define T55x7_MAXBLOCK_SHIFT 5 -#define T55x7_AOR 0x00000200 -#define T55x7_PSKCF_RF_2 0 -#define T55x7_PSKCF_RF_4 0x00000400 -#define T55x7_PSKCF_RF_8 0x00000800 -#define T55x7_MODULATION_DIRECT 0 -#define T55x7_MODULATION_PSK1 0x00001000 -#define T55x7_MODULATION_PSK2 0x00002000 -#define T55x7_MODULATION_PSK3 0x00003000 -#define T55x7_MODULATION_FSK1 0x00004000 -#define T55x7_MODULATION_FSK2 0x00005000 -#define T55x7_MODULATION_FSK1a 0x00006000 -#define T55x7_MODULATION_FSK2a 0x00007000 -#define T55x7_MODULATION_MANCHESTER 0x00008000 -#define T55x7_MODULATION_BIPHASE 0x00010000 -#define T55x7_BITRATE_RF_8 0 -#define T55x7_BITRATE_RF_16 0x00040000 -#define T55x7_BITRATE_RF_32 0x00080000 -#define T55x7_BITRATE_RF_40 0x000C0000 -#define T55x7_BITRATE_RF_50 0x00100000 -#define T55x7_BITRATE_RF_64 0x00140000 -#define T55x7_BITRATE_RF_100 0x00180000 -#define T55x7_BITRATE_RF_128 0x001C0000 - -/* T5555 (Q5) configuration register definitions */ -#define T5555_ST_TERMINATOR 0x00000001 -#define T5555_MAXBLOCK_SHIFT 0x00000001 -#define T5555_MODULATION_MANCHESTER 0 -#define T5555_MODULATION_PSK1 0x00000010 -#define T5555_MODULATION_PSK2 0x00000020 -#define T5555_MODULATION_PSK3 0x00000030 -#define T5555_MODULATION_FSK1 0x00000040 -#define T5555_MODULATION_FSK2 0x00000050 -#define T5555_MODULATION_BIPHASE 0x00000060 -#define T5555_MODULATION_DIRECT 0x00000070 -#define T5555_INVERT_OUTPUT 0x00000080 -#define T5555_PSK_RF_2 0 -#define T5555_PSK_RF_4 0x00000100 -#define T5555_PSK_RF_8 0x00000200 -#define T5555_USE_PWD 0x00000400 -#define T5555_USE_AOR 0x00000800 -#define T5555_BITRATE_SHIFT 12 -#define T5555_FAST_WRITE 0x00004000 -#define T5555_PAGE_SELECT 0x00008000 - -/* - * Relevant times in microsecond + * NOTE: T55x7/T5555 configuration register definitions moved to protocols.h + * + * Relevant communication times in microsecond * To compensate antenna falling times shorten the write times * and enlarge the gap ones. + * Q5 tags seems to have issues when these values changes. */ -#define START_GAP 50*8 // 10 - 50fc 250 -#define WRITE_GAP 20*8 // - 30fc 160 -#define WRITE_0 24*8 // 16 - 63fc 54fc 144 -#define WRITE_1 54*8 // 48 - 63fc 54fc 432 for T55x7; 448 for E5550 //400 +#define START_GAP 31*8 // was 250 // SPEC: 1*8 to 50*8 - typ 15*8 (or 15fc) +#define WRITE_GAP 20*8 // was 160 // SPEC: 1*8 to 20*8 - typ 10*8 (or 10fc) +#define WRITE_0 18*8 // was 144 // SPEC: 16*8 to 32*8 - typ 24*8 (or 24fc) +#define WRITE_1 50*8 // was 400 // SPEC: 48*8 to 64*8 - typ 56*8 (or 56fc) 432 for T55x7; 448 for E5550 +#define READ_GAP 15*8 -#define T55xx_SAMPLES_SIZE 12000 // 32 x 32 x 10 (32 bit times numofblock (7), times clock skip..) +void TurnReadLFOn(int delay) { + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); + // Give it a bit of time for the resonant antenna to settle. + SpinDelayUs(delay); //155*8 //50*8 +} // Write one bit to card -void T55xxWriteBit(int bit) -{ - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz - FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); - if (bit == 0) - SpinDelayUs(WRITE_0); +void T55xxWriteBit(int bit) { + if (!bit) + TurnReadLFOn(WRITE_0); else - SpinDelayUs(WRITE_1); + TurnReadLFOn(WRITE_1); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelayUs(WRITE_GAP); } +// Send T5577 reset command then read stream (see if we can identify the start of the stream) +void T55xxResetRead(void) { + LED_A_ON(); + //clear buffer now so it does not interfere with timing later + BigBuf_Clear_keep_EM(); + + // Set up FPGA, 125kHz + LFSetupFPGAForADC(95, true); + + // Trigger T55x7 in mode. + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelayUs(START_GAP); + + // reset tag - op code 00 + T55xxWriteBit(0); + T55xxWriteBit(0); + + // Turn field on to read the response + TurnReadLFOn(READ_GAP); + + // Acquisition + doT55x7Acquisition(BigBuf_max_traceLen()); + + // Turn the field off + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off + cmd_send(CMD_ACK,0,0,0,0,0); + LED_A_OFF(); +} + // Write one card block in page 0, no lock -void T55xxWriteBlock(uint32_t Data, uint32_t Block, uint32_t Pwd, uint8_t PwdMode) -{ +void T55xxWriteBlockExt(uint32_t Data, uint32_t Block, uint32_t Pwd, uint8_t arg) { + LED_A_ON(); + bool PwdMode = arg & 0x1; + uint8_t Page = (arg & 0x2)>>1; uint32_t i = 0; // Set up FPGA, 125kHz - // Wait for config.. (192+8190xPOW)x8 == 67ms - LFSetupFPGAForADC(0, true); + LFSetupFPGAForADC(95, true); - // Now start writting + // Trigger T55x7 in mode. FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelayUs(START_GAP); - // Opcode + // Opcode 10 T55xxWriteBit(1); - T55xxWriteBit(0); //Page 0 - if (PwdMode == 1){ - // Pwd + T55xxWriteBit(Page); //Page 0 + if (PwdMode){ + // Send Pwd for (i = 0x80000000; i != 0; i >>= 1) T55xxWriteBit(Pwd & i); } - // Lock bit + // Send Lock bit T55xxWriteBit(0); - // Data + // Send Data for (i = 0x80000000; i != 0; i >>= 1) T55xxWriteBit(Data & i); - // Block + // Send Block number for (i = 0x04; i != 0; i >>= 1) T55xxWriteBit(Block & i); - // Now perform write (nominal is 5.6 ms for T55x7 and 18ms for E5550, + // Perform write (nominal is 5.6 ms for T55x7 and 18ms for E5550, // so wait a little more) - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz - FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); - SpinDelay(20); + TurnReadLFOn(20 * 1000); + //could attempt to do a read to confirm write took + // as the tag should repeat back the new block + // until it is reset, but to confirm it we would + // need to know the current block 0 config mode + + // turn field off FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + LED_A_OFF(); } -void TurnReadLFOn(){ - FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); - // Give it a bit of time for the resonant antenna to settle. - SpinDelayUs(8*150); +// Write one card block in page 0, no lock +void T55xxWriteBlock(uint32_t Data, uint32_t Block, uint32_t Pwd, uint8_t arg) { + T55xxWriteBlockExt(Data, Block, Pwd, arg); + cmd_send(CMD_ACK,0,0,0,0,0); } - -// Read one card block in page 0 -void T55xxReadBlock(uint32_t Block, uint32_t Pwd, uint8_t PwdMode) -{ +// Read one card block in page [page] +void T55xxReadBlock(uint16_t arg0, uint8_t Block, uint32_t Pwd) { + LED_A_ON(); + bool PwdMode = arg0 & 0x1; + uint8_t Page = (arg0 & 0x2) >> 1; uint32_t i = 0; - uint8_t *dest = BigBuf_get_addr(); - uint16_t bufferlength = BigBuf_max_traceLen(); - if ( bufferlength > T55xx_SAMPLES_SIZE ) - bufferlength = T55xx_SAMPLES_SIZE; + bool RegReadMode = (Block == 0xFF); - // Clear destination buffer before sending the command - memset(dest, 0x80, bufferlength); + //clear buffer now so it does not interfere with timing later + BigBuf_Clear_ext(false); - // Set up FPGA, 125kHz - // Wait for config.. (192+8190xPOW)x8 == 67ms - LFSetupFPGAForADC(0, true); + //make sure block is at max 7 + Block &= 0x7; + + // Set up FPGA, 125kHz to power up the tag + LFSetupFPGAForADC(95, true); + + // Trigger T55x7 Direct Access Mode with start gap FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelayUs(START_GAP); - // Opcode + // Opcode 1[page] T55xxWriteBit(1); - T55xxWriteBit(0); //Page 0 - if (PwdMode == 1){ - // Pwd + T55xxWriteBit(Page); //Page 0 + + if (PwdMode){ + // Send Pwd for (i = 0x80000000; i != 0; i >>= 1) T55xxWriteBit(Pwd & i); } - // Lock bit + // Send a zero bit separation T55xxWriteBit(0); - // Block - for (i = 0x04; i != 0; i >>= 1) - T55xxWriteBit(Block & i); + + // Send Block number (if direct access mode) + if (!RegReadMode) + for (i = 0x04; i != 0; i >>= 1) + T55xxWriteBit(Block & i); // Turn field on to read the response - TurnReadLFOn(); - // Now do the acquisition - i = 0; - for(;;) { - if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) { - AT91C_BASE_SSC->SSC_THR = 0x43; - LED_D_ON(); - } - if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { - dest[i] = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - i++; - LED_D_OFF(); - if (i >= bufferlength) break; - } - } + TurnReadLFOn(READ_GAP); - cmd_send(CMD_ACK,0,0,0,0,0); + // Acquisition + doT55x7Acquisition(12000); + + // Turn the field off FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off - LED_D_OFF(); + cmd_send(CMD_ACK,0,0,0,0,0); + LED_A_OFF(); } -// Read card traceability data (page 1) -void T55xxReadTrace(void){ - +void T55xxWakeUp(uint32_t Pwd){ + LED_B_ON(); uint32_t i = 0; - uint8_t *dest = BigBuf_get_addr(); - uint16_t bufferlength = BigBuf_max_traceLen(); - if ( bufferlength > T55xx_SAMPLES_SIZE ) - bufferlength= T55xx_SAMPLES_SIZE; - - // Clear destination buffer before sending the command - memset(dest, 0x80, bufferlength); - - LFSetupFPGAForADC(0, true); + + // Set up FPGA, 125kHz + LFSetupFPGAForADC(95, true); + + // Trigger T55x7 Direct Access Mode FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); SpinDelayUs(START_GAP); - - // Opcode + + // Opcode 10 T55xxWriteBit(1); - T55xxWriteBit(1); //Page 1 + T55xxWriteBit(0); //Page 0 - // Turn field on to read the response - TurnReadLFOn(); + // Send Pwd + for (i = 0x80000000; i != 0; i >>= 1) + T55xxWriteBit(Pwd & i); - // Now do the acquisition - for(;;) { - if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) { - AT91C_BASE_SSC->SSC_THR = 0x43; - LED_D_ON(); - } - if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { - dest[i] = (uint8_t)AT91C_BASE_SSC->SSC_RHR; - i++; - LED_D_OFF(); + // Turn and leave field on to let the begin repeating transmission + TurnReadLFOn(20*1000); +} - if (i >= bufferlength) break; - } - } +/*-------------- Cloning routines -----------*/ - cmd_send(CMD_ACK,0,0,0,0,0); - FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off - LED_D_OFF(); +void WriteT55xx(uint32_t *blockdata, uint8_t startblock, uint8_t numblocks) { + // write last block first and config block last (if included) + for (uint8_t i = numblocks+startblock; i > startblock; i--) { + T55xxWriteBlockExt(blockdata[i-1],i-1,0,0); + } } -/*-------------- Cloning routines -----------*/ // Copy HID id to card and setup block 0 config -void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT) -{ - int data1=0, data2=0, data3=0, data4=0, data5=0, data6=0; //up to six blocks for long format - int last_block = 0; +void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT) { + uint32_t data[] = {0,0,0,0,0,0,0}; + uint8_t last_block = 0; - if (longFMT){ + if (longFMT) { // Ensure no more than 84 bits supplied if (hi2>0xFFFFF) { DbpString("Tags can only have 84 bits."); @@ -1204,140 +1262,100 @@ void CopyHIDtoT55x7(uint32_t hi2, uint32_t hi, uint32_t lo, uint8_t longFMT) } // Build the 6 data blocks for supplied 84bit ID last_block = 6; - data1 = 0x1D96A900; // load preamble (1D) & long format identifier (9E manchester encoded) - for (int i=0;i<4;i++) { - if (hi2 & (1<<(19-i))) - data1 |= (1<<(((3-i)*2)+1)); // 1 -> 10 - else - data1 |= (1<<((3-i)*2)); // 0 -> 01 - } - - data2 = 0; - for (int i=0;i<16;i++) { - if (hi2 & (1<<(15-i))) - data2 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data2 |= (1<<((15-i)*2)); // 0 -> 01 - } - - data3 = 0; - for (int i=0;i<16;i++) { - if (hi & (1<<(31-i))) - data3 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data3 |= (1<<((15-i)*2)); // 0 -> 01 - } - - data4 = 0; - for (int i=0;i<16;i++) { - if (hi & (1<<(15-i))) - data4 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data4 |= (1<<((15-i)*2)); // 0 -> 01 - } - - data5 = 0; - for (int i=0;i<16;i++) { - if (lo & (1<<(31-i))) - data5 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data5 |= (1<<((15-i)*2)); // 0 -> 01 - } - - data6 = 0; - for (int i=0;i<16;i++) { - if (lo & (1<<(15-i))) - data6 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data6 |= (1<<((15-i)*2)); // 0 -> 01 - } - } - else { + // load preamble (1D) & long format identifier (9E manchester encoded) + data[1] = 0x1D96A900 | (manchesterEncode2Bytes((hi2 >> 16) & 0xF) & 0xFF); + // load raw id from hi2, hi, lo to data blocks (manchester encoded) + data[2] = manchesterEncode2Bytes(hi2 & 0xFFFF); + data[3] = manchesterEncode2Bytes(hi >> 16); + data[4] = manchesterEncode2Bytes(hi & 0xFFFF); + data[5] = manchesterEncode2Bytes(lo >> 16); + data[6] = manchesterEncode2Bytes(lo & 0xFFFF); + } else { // Ensure no more than 44 bits supplied if (hi>0xFFF) { DbpString("Tags can only have 44 bits."); return; } - // Build the 3 data blocks for supplied 44bit ID last_block = 3; - - data1 = 0x1D000000; // load preamble - - for (int i=0;i<12;i++) { - if (hi & (1<<(11-i))) - data1 |= (1<<(((11-i)*2)+1)); // 1 -> 10 - else - data1 |= (1<<((11-i)*2)); // 0 -> 01 - } - - data2 = 0; - for (int i=0;i<16;i++) { - if (lo & (1<<(31-i))) - data2 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data2 |= (1<<((15-i)*2)); // 0 -> 01 - } - - data3 = 0; - for (int i=0;i<16;i++) { - if (lo & (1<<(15-i))) - data3 |= (1<<(((15-i)*2)+1)); // 1 -> 10 - else - data3 |= (1<<((15-i)*2)); // 0 -> 01 - } + // load preamble + data[1] = 0x1D000000 | (manchesterEncode2Bytes(hi) & 0xFFFFFF); + data[2] = manchesterEncode2Bytes(lo >> 16); + data[3] = manchesterEncode2Bytes(lo & 0xFFFF); } + // load chip config block + data[0] = T55x7_BITRATE_RF_50 | T55x7_MODULATION_FSK2a | last_block << T55x7_MAXBLOCK_SHIFT; + + //TODO add selection of chip for Q5 or T55x7 + // data[0] = (((50-2)/2)<> 32), 1, 0, 0); - T55xxWriteBlock((uint32_t)id, 2, 0, 0); - - // Config for EM410x (RF/64, Manchester, Maxblock=2) - if (card) { - // Clock rate is stored in bits 8-15 of the card value - clock = (card & 0xFF00) >> 8; - Dbprintf("Clock rate: %d", clock); - switch (clock) - { - case 32: - clock = T55x7_BITRATE_RF_32; - break; - case 16: - clock = T55x7_BITRATE_RF_16; - break; - case 0: - // A value of 0 is assumed to be 64 for backwards-compatibility - // Fall through... - case 64: - clock = T55x7_BITRATE_RF_64; - break; - default: + uint32_t data[] = {0, id>>32, id & 0xFFFFFFFF}; + + clock = (card & 0xFF00) >> 8; + clock = (clock == 0) ? 64 : clock; + Dbprintf("Clock rate: %d", clock); + if (card & 0xFF) { //t55x7 + clock = GetT55xxClockBit(clock); + if (clock == 0) { Dbprintf("Invalid clock rate: %d", clock); return; } - - // Writing configuration for T55x7 tag - T55xxWriteBlock(clock | - T55x7_MODULATION_MANCHESTER | - 2 << T55x7_MAXBLOCK_SHIFT, - 0, 0, 0); + data[0] = clock | T55x7_MODULATION_MANCHESTER | (2 << T55x7_MAXBLOCK_SHIFT); + } else { //t5555 (Q5) + clock = (clock-2)>>1; //n = (RF-2)/2 + data[0] = (clock << T5555_BITRATE_SHIFT) | T5555_MODULATION_MANCHESTER | (2 << T5555_MAXBLOCK_SHIFT); } - else - // Writing configuration for T5555(Q5) tag - T55xxWriteBlock(0x1F << T5555_BITRATE_SHIFT | - T5555_MODULATION_MANCHESTER | - 2 << T5555_MAXBLOCK_SHIFT, - 0, 0, 0); + + WriteT55xx(data, 0, 3); LED_D_OFF(); Dbprintf("Tag %s written with 0x%08x%08x\n", card ? "T55x7":"T5555", (uint32_t)(id >> 32), (uint32_t)id); } -// Clone Indala 64-bit tag by UID to T55x7 -void CopyIndala64toT55x7(int hi, int lo) -{ - - //Program the 2 data blocks for supplied 64bit UID - // and the block 0 for Indala64 format - T55xxWriteBlock(hi,1,0,0); - T55xxWriteBlock(lo,2,0,0); - //Config for Indala (RF/32;PSK1 with RF/2;Maxblock=2) - T55xxWriteBlock(T55x7_BITRATE_RF_32 | - T55x7_MODULATION_PSK1 | - 2 << T55x7_MAXBLOCK_SHIFT, - 0, 0, 0); - //Alternative config for Indala (Extended mode;RF/32;PSK1 with RF/2;Maxblock=2;Inverse data) - // T5567WriteBlock(0x603E1042,0); - - DbpString("DONE!"); - -} - -void CopyIndala224toT55x7(int uid1, int uid2, int uid3, int uid4, int uid5, int uid6, int uid7) -{ - - //Program the 7 data blocks for supplied 224bit UID - // and the block 0 for Indala224 format - T55xxWriteBlock(uid1,1,0,0); - T55xxWriteBlock(uid2,2,0,0); - T55xxWriteBlock(uid3,3,0,0); - T55xxWriteBlock(uid4,4,0,0); - T55xxWriteBlock(uid5,5,0,0); - T55xxWriteBlock(uid6,6,0,0); - T55xxWriteBlock(uid7,7,0,0); - //Config for Indala (RF/32;PSK1 with RF/2;Maxblock=7) - T55xxWriteBlock(T55x7_BITRATE_RF_32 | - T55x7_MODULATION_PSK1 | - 7 << T55x7_MAXBLOCK_SHIFT, - 0,0,0); - //Alternative config for Indala (Extended mode;RF/32;PSK1 with RF/2;Maxblock=7;Inverse data) - // T5567WriteBlock(0x603E10E2,0); - - DbpString("DONE!"); - -} - - -#define abs(x) ( ((x)<0) ? -(x) : (x) ) -#define max(x,y) ( x GraphBuffer[0]) { - while(i < GraphTraceLen) { - if( !(GraphBuffer[i] > GraphBuffer[i-1]) && GraphBuffer[i] > lmax) - break; - i++; - } - dir = 0; - } - else { - while(i < GraphTraceLen) { - if( !(GraphBuffer[i] < GraphBuffer[i-1]) && GraphBuffer[i] < lmin) - break; - i++; - } - dir = 1; - } - - lastval = i++; - half_switch = 0; - pmc = 0; - block_done = 0; - - for (bitidx = 0; i < GraphTraceLen; i++) - { - if ( (GraphBuffer[i-1] > GraphBuffer[i] && dir == 1 && GraphBuffer[i] > lmax) || (GraphBuffer[i-1] < GraphBuffer[i] && dir == 0 && GraphBuffer[i] < lmin)) - { - lc = i - lastval; - lastval = i; - - // Switch depending on lc length: - // Tolerance is 1/8 of clock rate (arbitrary) - if (abs(lc-clock/4) < tolerance) { - // 16T0 - if((i - pmc) == lc) { /* 16T0 was previous one */ - /* It's a PMC ! */ - i += (128+127+16+32+33+16)-1; - lastval = i; - pmc = 0; - block_done = 1; - } - else { - pmc = i; - } - } else if (abs(lc-clock/2) < tolerance) { - // 32TO - if((i - pmc) == lc) { /* 16T0 was previous one */ - /* It's a PMC ! */ - i += (128+127+16+32+33)-1; - lastval = i; - pmc = 0; - block_done = 1; - } - else if(half_switch == 1) { - BitStream[bitidx++] = 0; - half_switch = 0; - } - else - half_switch++; - } else if (abs(lc-clock) < tolerance) { - // 64TO - BitStream[bitidx++] = 1; - } else { - // Error - warnings++; - if (warnings > 10) - { - Dbprintf("Error: too many detection errors, aborting."); - return 0; - } - } - - if(block_done == 1) { - if(bitidx == 128) { - for(j=0; j<16; j++) { - Blocks[num_blocks][j] = 128*BitStream[j*8+7]+ - 64*BitStream[j*8+6]+ - 32*BitStream[j*8+5]+ - 16*BitStream[j*8+4]+ - 8*BitStream[j*8+3]+ - 4*BitStream[j*8+2]+ - 2*BitStream[j*8+1]+ - BitStream[j*8]; - } - num_blocks++; - } - bitidx = 0; - block_done = 0; - half_switch = 0; - } - if(i < GraphTraceLen) - { - if (GraphBuffer[i-1] > GraphBuffer[i]) dir=0; - else dir = 1; - } - } - if(bitidx==255) - bitidx=0; - warnings = 0; - if(num_blocks == 4) break; - } - memcpy(outBlocks, Blocks, 16*num_blocks); - return num_blocks; -} - -int IsBlock0PCF7931(uint8_t *Block) { - // Assume RFU means 0 :) - if((memcmp(Block, "\x00\x00\x00\x00\x00\x00\x00\x01", 8) == 0) && memcmp(Block+9, "\x00\x00\x00\x00\x00\x00\x00", 7) == 0) // PAC enabled - return 1; - if((memcmp(Block+9, "\x00\x00\x00\x00\x00\x00\x00", 7) == 0) && Block[7] == 0) // PAC disabled, can it *really* happen ? - return 1; - return 0; -} - -int IsBlock1PCF7931(uint8_t *Block) { - // Assume RFU means 0 :) - if(Block[10] == 0 && Block[11] == 0 && Block[12] == 0 && Block[13] == 0) - if((Block[14] & 0x7f) <= 9 && Block[15] <= 9) - return 1; - - return 0; -} - -#define ALLOC 16 - -void ReadPCF7931() { - uint8_t Blocks[8][17]; - uint8_t tmpBlocks[4][16]; - int i, j, ind, ind2, n; - int num_blocks = 0; - int max_blocks = 8; - int ident = 0; - int error = 0; - int tries = 0; - - memset(Blocks, 0, 8*17*sizeof(uint8_t)); - - do { - memset(tmpBlocks, 0, 4*16*sizeof(uint8_t)); - n = DemodPCF7931((uint8_t**)tmpBlocks); - if(!n) - error++; - if(error==10 && num_blocks == 0) { - Dbprintf("Error, no tag or bad tag"); - return; - } - else if (tries==20 || error==10) { - Dbprintf("Error reading the tag"); - Dbprintf("Here is the partial content"); - goto end; - } - - for(i=0; i= 0; ind--,ind2--) { - if(ind2 < 0) - ind2 = max_blocks; - if(!Blocks[ind2][ALLOC]) { // Block ind2 not already found - // Dbprintf("Tmp %d -> Block %d", ind, ind2); - memcpy(Blocks[ind2], tmpBlocks[ind], 16); - Blocks[ind2][ALLOC] = 1; - num_blocks++; - if(num_blocks == max_blocks) goto end; - } - } - for(ind=i+1,ind2=j+1; ind < n; ind++,ind2++) { - if(ind2 > max_blocks) - ind2 = 0; - if(!Blocks[ind2][ALLOC]) { // Block ind2 not already found - // Dbprintf("Tmp %d -> Block %d", ind, ind2); - memcpy(Blocks[ind2], tmpBlocks[ind], 16); - Blocks[ind2][ALLOC] = 1; - num_blocks++; - if(num_blocks == max_blocks) goto end; - } - } - } - } - } - } - } - tries++; - if (BUTTON_PRESS()) return; - } while (num_blocks != max_blocks); - end: - Dbprintf("-----------------------------------------"); - Dbprintf("Memory content:"); - Dbprintf("-----------------------------------------"); - for(i=0; i", i); - } - Dbprintf("-----------------------------------------"); - - return ; -} - - //----------------------------------- // EM4469 / EM4305 routines //----------------------------------- @@ -1759,7 +1447,6 @@ void ReadPCF7931() { #define FWD_CMD_READ 0x9 #define FWD_CMD_DISABLE 0x5 - uint8_t forwardLink_data[64]; //array of forwarded bits uint8_t * forward_ptr; //ptr for forward message preparation uint8_t fwd_bit_sz; //forwardlink bit counter @@ -1770,8 +1457,15 @@ uint8_t * fwd_write_ptr; //forwardlink bit pointer // see EM4469 spec //==================================================================== //-------------------------------------------------------------------- +// VALUES TAKEN FROM EM4x function: SendForward +// START_GAP = 440; (55*8) cycles at 125Khz (8us = 1cycle) +// WRITE_GAP = 128; (16*8) +// WRITE_1 = 256 32*8; (32*8) + +// These timings work for 4469/4269/4305 (with the 55*8 above) +// WRITE_0 = 23*8 , 9*8 SpinDelayUs(23*8); + uint8_t Prepare_Cmd( uint8_t cmd ) { - //-------------------------------------------------------------------- *forward_ptr++ = 0; //start bit *forward_ptr++ = 0; //second pause for 4050 code @@ -1791,10 +1485,7 @@ uint8_t Prepare_Cmd( uint8_t cmd ) { // prepares address bits // see EM4469 spec //==================================================================== - -//-------------------------------------------------------------------- uint8_t Prepare_Addr( uint8_t addr ) { - //-------------------------------------------------------------------- register uint8_t line_parity; @@ -1815,10 +1506,7 @@ uint8_t Prepare_Addr( uint8_t addr ) { // prepares data bits intreleaved with parity bits // see EM4469 spec //==================================================================== - -//-------------------------------------------------------------------- uint8_t Prepare_Data( uint16_t data_low, uint16_t data_hi) { - //-------------------------------------------------------------------- register uint8_t line_parity; register uint8_t column_parity; @@ -1862,21 +1550,14 @@ void SendForward(uint8_t fwd_bit_count) { LED_D_ON(); - //Field on - FpgaDownloadAndGo(FPGA_BITSTREAM_LF); - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz - FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD); - - // Give it a bit of time for the resonant antenna to settle. - // And for the tag to fully power up - SpinDelay(150); + // Set up FPGA, 125kHz + LFSetupFPGAForADC(95, true); // force 1st mod pulse (start gap must be longer for 4305) fwd_bit_sz--; //prepare next bit modulation fwd_write_ptr++; FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off SpinDelayUs(55*8); //55 cycles off (8us each)for 4305 - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);//field on SpinDelayUs(16*8); //16 cycles on (8us each) @@ -1888,7 +1569,6 @@ void SendForward(uint8_t fwd_bit_count) { //These timings work for 4469/4269/4305 (with the 55*8 above) FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off SpinDelayUs(23*8); //16-4 cycles off (8us each) - FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_ADC | FPGA_LF_ADC_READER_FIELD);//field on SpinDelayUs(9*8); //16 cycles on (8us each) } @@ -1907,14 +1587,17 @@ void EM4xLogin(uint32_t Password) { //Wait for command to complete SpinDelay(20); - } void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode) { uint8_t fwd_bit_count; uint8_t *dest = BigBuf_get_addr(); - int m=0, i=0; + uint16_t bufferlength = BigBuf_max_traceLen(); + uint32_t i = 0; + + // Clear destination buffer before sending the command + BigBuf_Clear_ext(false); //If password mode do login if (PwdMode == 1) EM4xLogin(Pwd); @@ -1923,9 +1606,6 @@ void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode) { fwd_bit_count = Prepare_Cmd( FWD_CMD_READ ); fwd_bit_count += Prepare_Addr( Address ); - m = BigBuf_max_traceLen(); - // Clear destination buffer before sending the command - memset(dest, 128, m); // Connect the A/D to the peak-detected low-frequency path. SetAdcMuxFor(GPIO_MUXSEL_LOPKD); // Now set up the SSC to get the ADC samples that are now streaming at us. @@ -1942,10 +1622,11 @@ void EM4xReadWord(uint8_t Address, uint32_t Pwd, uint8_t PwdMode) { if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { dest[i] = (uint8_t)AT91C_BASE_SSC->SSC_RHR; i++; - if (i >= m) break; + if (i >= bufferlength) break; } } FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); // field off + cmd_send(CMD_ACK,0,0,0,0,0); LED_D_OFF(); } diff --git a/armsrc/lfsampling.c b/armsrc/lfsampling.c index 120c0801..88df543f 100644 --- a/armsrc/lfsampling.c +++ b/armsrc/lfsampling.c @@ -10,14 +10,14 @@ #include "apps.h" #include "util.h" #include "string.h" - +#include "usb_cdc.h" // for usb_poll_validate_length #include "lfsampling.h" sample_config config = { 1, 8, 1, 95, 0 } ; void printConfig() { - Dbprintf("Sampling config: "); + Dbprintf("LF Sampling config: "); Dbprintf(" [q] divisor: %d ", config.divisor); Dbprintf(" [b] bps: %d ", config.bits_per_sample); Dbprintf(" [d] decimation: %d ", config.decimation); @@ -103,7 +103,6 @@ void LFSetupFPGAForADC(int divisor, bool lf_field) FpgaSetupSsc(); } - /** * Does the sample acquisition. If threshold is specified, the actual sampling * is not commenced until the threshold has been reached. @@ -119,14 +118,13 @@ void LFSetupFPGAForADC(int divisor, bool lf_field) * @param silent - is true, now outputs are made. If false, dbprints the status * @return the number of bits occupied by the samples. */ - -uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averaging, int trigger_threshold,bool silent) +uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averaging, int trigger_threshold, bool silent) { //. uint8_t *dest = BigBuf_get_addr(); int bufsize = BigBuf_max_traceLen(); - memset(dest, 0, bufsize); + //memset(dest, 0, bufsize); //creates issues with cmdread (marshmellow) if(bits_per_sample < 1) bits_per_sample = 1; if(bits_per_sample > 8) bits_per_sample = 8; @@ -151,9 +149,10 @@ uint32_t DoAcquisition(uint8_t decimation, uint32_t bits_per_sample, bool averag if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { sample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; LED_D_OFF(); - if (trigger_threshold > 0 && sample < trigger_threshold) + // threshold either high or low values 128 = center 0. if trigger = 178 + if ((trigger_threshold > 0) && (sample < (trigger_threshold+128)) && (sample > (128-trigger_threshold))) // continue; - + trigger_threshold = 0; sample_total_numbers++; @@ -249,3 +248,70 @@ uint32_t SnoopLF() { return ReadLF(false, true); } + +/** +* acquisition of T55x7 LF signal. Similart to other LF, but adjusted with @marshmellows thresholds +* the data is collected in BigBuf. +**/ +void doT55x7Acquisition(size_t sample_size) { + + #define T55xx_READ_UPPER_THRESHOLD 128+60 // 60 grph + #define T55xx_READ_LOWER_THRESHOLD 128-60 // -60 grph + #define T55xx_READ_TOL 5 + + uint8_t *dest = BigBuf_get_addr(); + uint16_t bufsize = BigBuf_max_traceLen(); + + if ( bufsize > sample_size ) + bufsize = sample_size; + + uint16_t i = 0; + bool startFound = false; + bool highFound = false; + bool lowFound = false; + uint8_t curSample = 0; + uint8_t lastSample = 0; + uint16_t skipCnt = 0; + while(!BUTTON_PRESS() && !usb_poll_validate_length() && skipCnt<1000 && iSSC_SR & AT91C_SSC_TXRDY) { + AT91C_BASE_SSC->SSC_THR = 0x43; + LED_D_ON(); + } + if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) { + curSample = (uint8_t)AT91C_BASE_SSC->SSC_RHR; + LED_D_OFF(); + + // skip until the first high sample above threshold + if (!startFound && curSample > T55xx_READ_UPPER_THRESHOLD) { + //if (curSample > lastSample) + // lastSample = curSample; + highFound = true; + } else if (!highFound) { + skipCnt++; + continue; + } + // skip until the first Low sample below threshold + if (!startFound && curSample < T55xx_READ_LOWER_THRESHOLD) { + //if (curSample > lastSample) + lastSample = curSample; + lowFound = true; + } else if (!lowFound) { + skipCnt++; + continue; + } + + + // skip until first high samples begin to change + if (startFound || curSample > T55xx_READ_LOWER_THRESHOLD+T55xx_READ_TOL){ + // if just found start - recover last sample + if (!startFound) { + dest[i++] = lastSample; + startFound = true; + } + // collect samples + dest[i++] = curSample; + } + } + } +} diff --git a/armsrc/lfsampling.h b/armsrc/lfsampling.h index 6c671ec8..bd8ad1d0 100644 --- a/armsrc/lfsampling.h +++ b/armsrc/lfsampling.h @@ -1,6 +1,12 @@ #ifndef LFSAMPLING_H #define LFSAMPLING_H +/** +* acquisition of T55x7 LF signal. Similart to other LF, but adjusted with @marshmellows thresholds +* the data is collected in BigBuf. +**/ +void doT55x7Acquisition(size_t sample_size); + /** * Initializes the FPGA for reader-mode (field on), and acquires the samples. * @return number of bits sampled @@ -41,7 +47,6 @@ uint32_t DoAcquisition_config( bool silent); **/ void LFSetupFPGAForADC(int divisor, bool lf_field); - /** * Called from the USB-handler to set the sampling configuration * The sampling config is used for std reading and snooping. @@ -56,4 +61,8 @@ void LFSetupFPGAForADC(int divisor, bool lf_field); void setSamplingConfig(sample_config *sc); sample_config * getSamplingConfig(); + +void printConfig(); + + #endif // LFSAMPLING_H diff --git a/armsrc/mifarecmd.c b/armsrc/mifarecmd.c index 8355cd19..a3d6609d 100644 --- a/armsrc/mifarecmd.c +++ b/armsrc/mifarecmd.c @@ -16,7 +16,6 @@ #include "mifarecmd.h" #include "apps.h" #include "util.h" - #include "crc.h" // the block number for the ISO14443-4 PCB @@ -24,7 +23,6 @@ uint8_t pcb_blocknum = 0; // Deselect card by sending a s-block. the crc is precalced for speed static uint8_t deselect_cmd[] = {0xc2,0xe0,0xb4}; - //----------------------------------------------------------------------------- // Select, Authenticate, Read a MIFARE tag. // read block @@ -46,10 +44,10 @@ void MifareReadBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -97,9 +95,11 @@ void MifareUC_Auth(uint8_t arg0, uint8_t *keybytes){ bool turnOffField = (arg0 == 1); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card"); OnError(0); @@ -131,9 +131,10 @@ void MifareUReadBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + int len = iso14443a_select_card(NULL, NULL, NULL); if(!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%02X)",len); @@ -201,11 +202,10 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -248,11 +248,18 @@ void MifareReadSector(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } +// arg0 = blockNo (start) +// arg1 = Pages (number of blocks) +// arg2 = useKey +// datain = KEY bytes void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) { + LEDsoff(); + LED_A_ON(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + // free eventually allocated BigBuf memory BigBuf_free(); - // clear trace clear_trace(); // params @@ -268,10 +275,6 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) return; } - LEDsoff(); - LED_A_ON(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - int len = iso14443a_select_card(NULL, NULL, NULL); if (!len) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Can't select card (RC:%d)",len); @@ -303,7 +306,7 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) } for (int i = 0; i < blocks; i++){ - if ((i*4) + 4 > CARD_MEMORY_SIZE) { + if ((i*4) + 4 >= CARD_MEMORY_SIZE) { Dbprintf("Data exceeds buffer!!"); break; } @@ -335,9 +338,11 @@ void MifareUReadCard(uint8_t arg0, uint16_t arg1, uint8_t arg2, uint8_t *datain) if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Blocks read %d", countblocks); countblocks *= 4; + cmd_send(CMD_ACK, 1, countblocks, BigBuf_max_traceLen(), 0, 0); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); + BigBuf_free(); } //----------------------------------------------------------------------------- @@ -363,11 +368,10 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) struct Crypto1State *pcs; pcs = &mpcs; - // clear trace - clear_trace(); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + LED_A_ON(); LED_B_OFF(); LED_C_OFF(); @@ -412,7 +416,8 @@ void MifareWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) LEDsoff(); } -void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) +/* // Command not needed but left for future testing +void MifareUWriteBlockCompat(uint8_t arg0, uint8_t *datain) { uint8_t blockNo = arg0; byte_t blockdata[16] = {0x00}; @@ -432,7 +437,7 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) return; }; - if(mifare_ultra_writeblock(blockNo, blockdata)) { + if(mifare_ultra_writeblock_compat(blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(0); return; }; @@ -449,26 +454,58 @@ void MifareUWriteBlock(uint8_t arg0, uint8_t *datain) FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); } - -void MifareUWriteBlock_Special(uint8_t arg0, uint8_t *datain) +*/ + +// Arg0 : Block to write to. +// Arg1 : 0 = use no authentication. +// 1 = use 0x1A authentication. +// 2 = use 0x1B authentication. +// datain : 4 first bytes is data to be written. +// : 4/16 next bytes is authentication key. +void MifareUWriteBlock(uint8_t arg0, uint8_t arg1, uint8_t *datain) { uint8_t blockNo = arg0; + bool useKey = (arg1 == 1); //UL_C + bool usePwd = (arg1 == 2); //UL_EV1/NTAG byte_t blockdata[4] = {0x00}; memcpy(blockdata, datain,4); LEDsoff(); LED_A_ON(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); return; }; - if(mifare_ultra_special_writeblock(blockNo, blockdata)) { + // UL-C authentication + if ( useKey ) { + uint8_t key[16] = {0x00}; + memcpy(key, datain+4, sizeof(key) ); + + if ( !mifare_ultra_auth(key) ) { + OnError(1); + return; + } + } + + // UL-EV1 / NTAG authentication + if (usePwd) { + uint8_t pwd[4] = {0x00}; + memcpy(pwd, datain+4, 4); + uint8_t pack[4] = {0,0,0,0}; + if (!mifare_ul_ev1_auth(pwd, pack)) { + OnError(1); + return; + } + } + + if(mifare_ultra_writeblock(blockNo, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(0); return; @@ -495,9 +532,10 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ memcpy(pwd, datain, 16); LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); + if(!iso14443a_select_card(NULL, NULL, NULL)) { if (MF_DBGLEVEL >= 1) Dbprintf("Can't select card"); OnError(0); @@ -508,7 +546,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[6]; blockdata[2] = pwd[5]; blockdata[3] = pwd[4]; - if(mifare_ultra_special_writeblock( 44, blockdata)) { + if(mifare_ultra_writeblock( 44, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(44); return; @@ -518,7 +556,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[2]; blockdata[2] = pwd[1]; blockdata[3] = pwd[0]; - if(mifare_ultra_special_writeblock( 45, blockdata)) { + if(mifare_ultra_writeblock( 45, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(45); return; @@ -528,7 +566,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[14]; blockdata[2] = pwd[13]; blockdata[3] = pwd[12]; - if(mifare_ultra_special_writeblock( 46, blockdata)) { + if(mifare_ultra_writeblock( 46, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(46); return; @@ -538,7 +576,7 @@ void MifareUSetPwd(uint8_t arg0, uint8_t *datain){ blockdata[1] = pwd[10]; blockdata[2] = pwd[9]; blockdata[3] = pwd[8]; - if(mifare_ultra_special_writeblock( 47, blockdata)) { + if(mifare_ultra_writeblock( 47, blockdata)) { if (MF_DBGLEVEL >= 1) Dbprintf("Write block error"); OnError(47); return; @@ -597,19 +635,20 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat uint32_t auth1_time, auth2_time; static uint16_t delta_time; - // free eventually allocated BigBuf memory - BigBuf_free(); - // clear trace - clear_trace(); - set_tracing(false); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + // free eventually allocated BigBuf memory + BigBuf_free(); + if (calibrate) clear_trace(); + set_tracing(true); + // statistics on nonce distance + int16_t isOK = 0; + #define NESTED_MAX_TRIES 12 + uint16_t unsuccessfull_tries = 0; if (calibrate) { // for first call only. Otherwise reuse previous calibration LED_B_ON(); WDT_HIT(); @@ -620,6 +659,12 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat for (rtr = 0; rtr < 17; rtr++) { + // Test if the action was cancelled + if(BUTTON_PRESS()) { + isOK = -2; + break; + } + // prepare next select. No need to power down the card. if(mifare_classic_halt(pcs, cuid)) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Halt error"); @@ -667,14 +712,17 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat delta_time = auth2_time - auth1_time + 32; // allow some slack for proper timing } if (MF_DBGLEVEL >= 3) Dbprintf("Nested: calibrating... ntdist=%d", i); + } else { + unsuccessfull_tries++; + if (unsuccessfull_tries > NESTED_MAX_TRIES) { // card isn't vulnerable to nested attack (random numbers are not predictable) + isOK = -3; + } } } - - if (rtr <= 1) return; davg = (davg + (rtr - 1)/2) / (rtr - 1); - if (MF_DBGLEVEL >= 3) Dbprintf("min=%d max=%d avg=%d, delta_time=%d", dmin, dmax, davg, delta_time); + if (MF_DBGLEVEL >= 3) Dbprintf("rtr=%d isOK=%d min=%d max=%d avg=%d, delta_time=%d", rtr, isOK, dmin, dmax, davg, delta_time); dmin = davg - 2; dmax = davg + 2; @@ -682,12 +730,12 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat LED_B_OFF(); } -// ------------------------------------------------------------------------------------------------- + // ------------------------------------------------------------------------------------------------- LED_C_ON(); // get crypted nonces for target sector - for(i=0; i < 2; i++) { // look for exactly two different nonces + for(i=0; i < 2 && !isOK; i++) { // look for exactly two different nonces target_nt[i] = 0; while(target_nt[i] == 0) { // continue until we have an unambiguous nonce @@ -711,7 +759,7 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat // nested authentication auth2_time = auth1_time + delta_time; - len = mifare_sendcmd_shortex(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time); + len = mifare_sendcmd_short(pcs, AUTH_NESTED, 0x60 + (targetKeyType & 0x01), targetBlockNo, receivedAnswer, par, &auth2_time); if (len != 4) { if (MF_DBGLEVEL >= 1) Dbprintf("Nested: Auth2 error len=%d", len); continue; @@ -765,25 +813,25 @@ void MifareNested(uint32_t arg0, uint32_t arg1, uint32_t calibrate, uint8_t *dat memcpy(buf+16, &target_ks[1], 4); LED_B_ON(); - cmd_send(CMD_ACK, 0, 2, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); + cmd_send(CMD_ACK, isOK, 0, targetBlockNo + (targetKeyType * 0x100), buf, sizeof(buf)); LED_B_OFF(); if (MF_DBGLEVEL >= 3) DbpString("NESTED FINISHED"); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); LEDsoff(); - set_tracing(TRUE); } //----------------------------------------------------------------------------- // MIFARE check keys. key count up to 85. // //----------------------------------------------------------------------------- -void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) +void MifareChkKeys(uint16_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) { // params - uint8_t blockNo = arg0; - uint8_t keyType = arg1; + uint8_t blockNo = arg0 & 0xff; + uint8_t keyType = (arg0 >> 8) & 0xff; + bool clearTrace = arg1; uint8_t keyCount = arg2; uint64_t ui64Key = 0; @@ -800,15 +848,13 @@ void MifareChkKeys(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain) int OLD_MF_DBGLEVEL = MF_DBGLEVEL; MF_DBGLEVEL = MF_DBG_NONE; - // clear trace - clear_trace(); - set_tracing(TRUE); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + if (clearTrace) clear_trace(); + set_tracing(TRUE); for (i = 0; i < keyCount; i++) { if(mifare_classic_halt(pcs, cuid)) { @@ -855,16 +901,23 @@ void MifareSetDbgLvl(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai //----------------------------------------------------------------------------- // Work with emulator memory // +// Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not +// involved in dealing with emulator memory. But if it is called later, it might +// destroy the Emulator Memory. //----------------------------------------------------------------------------- + void MifareEMemClr(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); emlClearMem(); } void MifareEMemSet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); emlSetMem(datain, arg0, arg1); // data, block num, blocks count } void MifareEMemGet(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain){ + FpgaDownloadAndGo(FPGA_BITSTREAM_HF); byte_t buf[USB_CMD_DATA_SIZE]; emlGetMem(buf, arg0, arg1); // data, block num, blocks count (max 4) @@ -891,15 +944,13 @@ void MifareECardLoad(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai byte_t dataoutbuf2[16]; uint8_t uid[10]; - // clear trace - clear_trace(); - set_tracing(false); - - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); - LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + + clear_trace(); + set_tracing(false); bool isOK = true; @@ -993,10 +1044,10 @@ void MifareCSetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_A_ON(); LED_B_OFF(); LED_C_OFF(); + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); clear_trace(); set_tracing(TRUE); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } while (true) { @@ -1092,6 +1143,7 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai // bit 2 - need HALT after sequence // bit 3 - need init FPGA and field before sequence // bit 4 - need reset FPGA and LED + // bit 5 - need to set datain instead of issuing USB reply (called via ARM for StandAloneMode14a) uint8_t workFlags = arg0; uint8_t blockNo = arg2; @@ -1111,10 +1163,10 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai LED_A_ON(); LED_B_OFF(); LED_C_OFF(); - + iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); set_tracing(TRUE); - iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); } while (true) { @@ -1151,7 +1203,12 @@ void MifareCGetBlock(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datai } LED_B_ON(); - cmd_send(CMD_ACK,isOK,0,0,data,18); + if (workFlags & 0x20) { + if (isOK) + memcpy(datain, data, 18); + } + else + cmd_send(CMD_ACK,isOK,0,0,data,18); LED_B_OFF(); if ((workFlags & 0x10) || (!isOK)) { @@ -1189,7 +1246,7 @@ void MifareCIdent(){ cmd_send(CMD_ACK,isOK,0,0,0,0); } - // +// // DESFIRE // @@ -1199,8 +1256,8 @@ void Mifare_DES_Auth1(uint8_t arg0, uint8_t *datain){ uint8_t uid[10] = {0x00}; uint32_t cuid; - clear_trace(); iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN); + clear_trace(); int len = iso14443a_select_card(uid, NULL, &cuid); if(!len) { @@ -1231,14 +1288,12 @@ void Mifare_DES_Auth2(uint32_t arg0, uint8_t *datain){ isOK = mifare_desfire_des_auth2(cuid, key, dataout); if( isOK) { - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) - Dbprintf("Authentication part2: Failed"); - //OnError(4); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) Dbprintf("Authentication part2: Failed"); + OnError(4); return; } - if (MF_DBGLEVEL >= MF_DBG_EXTENDED) - DbpString("AUTH 2 FINISHED"); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) DbpString("AUTH 2 FINISHED"); cmd_send(CMD_ACK, isOK, 0, 0, dataout, sizeof(dataout)); FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); diff --git a/armsrc/mifareutil.c b/armsrc/mifareutil.c index 2f84797b..8ef364c2 100644 --- a/armsrc/mifareutil.c +++ b/armsrc/mifareutil.c @@ -65,74 +65,25 @@ uint8_t mf_crypto1_encrypt4bit(struct Crypto1State *pcs, uint8_t data) { return bt; } -// send commands -int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) +// send X byte basic commands +int mifare_sendcmd(uint8_t cmd, uint8_t* data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) { - return mifare_sendcmd_shortex(pcs, crypted, cmd, data, answer, answer_parity, timing); -} - -int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t* data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing) -{ - uint8_t dcmd[8]; - dcmd[0] = cmd; - dcmd[1] = data[0]; - dcmd[2] = data[1]; - dcmd[3] = data[2]; - dcmd[4] = data[3]; - dcmd[5] = data[4]; - AppendCrc14443a(dcmd, 6); - ReaderTransmit(dcmd, sizeof(dcmd), NULL); - int len = ReaderReceive(answer, answer_parity); - if(!len) { - if (MF_DBGLEVEL >= 1) Dbprintf("Authentication failed. Card timeout."); - return 2; - } - return len; -} - -int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) -{ - uint8_t dcmd[19]; - int len; - dcmd[0] = cmd; - memcpy(dcmd+1,data,16); - AppendCrc14443a(dcmd, 17); - - ReaderTransmit(dcmd, sizeof(dcmd), timing); - len = ReaderReceive(answer, answer_parity); - if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); - len = ReaderReceive(answer,answer_parity); - } - if(len==1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); - return 1; - } - return len; -} - -int mifare_sendcmd_short_mfuev1auth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) -{ - uint8_t dcmd[7]; - int len; - dcmd[0] = cmd; - memcpy(dcmd+1,data,4); - AppendCrc14443a(dcmd, 5); - + uint8_t dcmd[data_size+3]; + dcmd[0] = cmd; + memcpy(dcmd+1,data,data_size); + AppendCrc14443a(dcmd, data_size+1); ReaderTransmit(dcmd, sizeof(dcmd), timing); - len = ReaderReceive(answer, answer_parity); + int len = ReaderReceive(answer, answer_parity); if(!len) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Authentication failed. Card timeout."); - len = ReaderReceive(answer,answer_parity); - } - if(len==1) { - if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("NAK - Authentication failed."); - return 1; - } + if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("%02X Cmd failed. Card timeout.", cmd); + len = ReaderReceive(answer,answer_parity); + //return 0; + } return len; } -int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) +// send 2 byte commands +int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing) { uint8_t dcmd[4], ecmd[4]; uint16_t pos, res; @@ -318,8 +269,10 @@ int mifare_ul_ev1_auth(uint8_t *keybytes, uint8_t *pack){ uint8_t key[4] = {0x00}; memcpy(key, keybytes, 4); - Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); - len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); + if (MF_DBGLEVEL >= MF_DBG_EXTENDED) + Dbprintf("EV1 Auth : %02x%02x%02x%02x", key[0], key[1], key[2], key[3]); + len = mifare_sendcmd(0x1B, key, sizeof(key), resp, respPar, NULL); + //len = mifare_sendcmd_short_mfuev1auth(NULL, 0, 0x1B, key, resp, respPar, NULL); if (len != 4) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x %u", resp[0], len); return 0; @@ -380,8 +333,8 @@ int mifare_ultra_auth(uint8_t *keybytes){ // encrypt out, in, length, key, iv tdes_2key_enc(rnd_ab, rnd_ab, sizeof(rnd_ab), key, enc_random_b); - - len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL); + //len = mifare_sendcmd_short_mfucauth(NULL, 1, 0xAF, rnd_ab, resp, respPar, NULL); + len = mifare_sendcmd(0xAF, rnd_ab, sizeof(rnd_ab), resp, respPar, NULL); if (len != 11) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", resp[0]); return 0; @@ -425,6 +378,7 @@ int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData) uint8_t receivedAnswer[MAX_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; + len = mifare_sendcmd_short(NULL, 1, 0x30, blockNo, receivedAnswer, receivedAnswerPar, NULL); if (len == 1) { if (MF_DBGLEVEL >= MF_DBG_ERROR) Dbprintf("Cmd Error: %02x", receivedAnswer[0]); @@ -493,7 +447,8 @@ int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t bl return 0; } -int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) +/* // command not needed, but left for future testing +int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData) { uint16_t len; uint8_t par[3] = {0}; // enough for 18 parity bits @@ -501,7 +456,6 @@ int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) uint8_t receivedAnswer[MAX_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_PARITY_SIZE]; - // command MIFARE_CLASSIC_WRITEBLOCK len = mifare_sendcmd_short(NULL, true, 0xA0, blockNo, receivedAnswer, receivedAnswerPar, NULL); if ((len != 1) || (receivedAnswer[0] != 0x0A)) { // 0x0a - ACK @@ -524,20 +478,21 @@ int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) } return 0; } +*/ -int mifare_ultra_special_writeblock(uint8_t blockNo, uint8_t *blockData) +int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData) { uint16_t len; - uint8_t d_block[8] = {0x00}; + uint8_t d_block[5] = {0x00}; uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE]; uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE]; // command MIFARE_CLASSIC_WRITEBLOCK d_block[0]= blockNo; memcpy(d_block+1,blockData,4); - AppendCrc14443a(d_block, 6); + //AppendCrc14443a(d_block, 6); - len = mifare_sendcmd_short_special(NULL, 1, 0xA2, d_block, receivedAnswer, receivedAnswerPar, NULL); + len = mifare_sendcmd(0xA2, d_block, sizeof(d_block), receivedAnswer, receivedAnswerPar, NULL); if (receivedAnswer[0] != 0x0A) { // 0x0a - ACK if (MF_DBGLEVEL >= MF_DBG_ERROR) diff --git a/armsrc/mifareutil.h b/armsrc/mifareutil.h index d4fcd818..7a09ce64 100644 --- a/armsrc/mifareutil.h +++ b/armsrc/mifareutil.h @@ -8,6 +8,7 @@ //----------------------------------------------------------------------------- // code for work with mifare cards. //----------------------------------------------------------------------------- +#include "crapto1.h" #ifndef __MIFAREUTIL_H #define __MIFAREUTIL_H @@ -53,23 +54,22 @@ extern int MF_DBGLEVEL; #define cardSTATE_TO_IDLE() cardSTATE = MFEMUL_IDLE; LED_B_OFF(); LED_C_OFF(); //functions +int mifare_sendcmd(uint8_t cmd, uint8_t *data, uint8_t data_size, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); int mifare_sendcmd_short(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_short_special(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); - -int mifare_sendcmd_short_mfucauth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_short_mfuev1auth(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t *data, uint8_t *answer, uint8_t *answer_parity, uint32_t *timing); -int mifare_sendcmd_shortex(struct Crypto1State *pcs, uint8_t crypted, uint8_t cmd, uint8_t data, uint8_t* answer, uint8_t *answer_parity, uint32_t *timing); +// mifare classic int mifare_classic_auth(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested); int mifare_classic_authex(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t keyType, uint64_t ui64Key, uint8_t isNested, uint32_t * ntptr, uint32_t *timing); int mifare_classic_readblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); +int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); +int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); + +// Ultralight/NTAG... int mifare_ul_ev1_auth(uint8_t *key, uint8_t *pack); int mifare_ultra_auth(uint8_t *key); int mifare_ultra_readblock(uint8_t blockNo, uint8_t *blockData); -int mifare_classic_writeblock(struct Crypto1State *pcs, uint32_t uid, uint8_t blockNo, uint8_t *blockData); +//int mifare_ultra_writeblock_compat(uint8_t blockNo, uint8_t *blockData); int mifare_ultra_writeblock(uint8_t blockNo, uint8_t *blockData); -int mifare_ultra_special_writeblock(uint8_t blockNo, uint8_t *blockData); -int mifare_classic_halt(struct Crypto1State *pcs, uint32_t uid); int mifare_ultra_halt(); // desfire diff --git a/armsrc/optimized_cipher.c b/armsrc/optimized_cipher.c index 444b93d0..bfaf5088 100644 --- a/armsrc/optimized_cipher.c +++ b/armsrc/optimized_cipher.c @@ -61,12 +61,10 @@ **/ #include "optimized_cipher.h" -#include #include #include #include #include -#include #define opt_T(s) (0x1 & ((s->t >> 15) ^ (s->t >> 14)^ (s->t >> 10)^ (s->t >> 8)^ (s->t >> 5)^ (s->t >> 4)^ (s->t >> 1)^ s->t)) diff --git a/armsrc/pcf7931.c b/armsrc/pcf7931.c new file mode 100644 index 00000000..165319ca --- /dev/null +++ b/armsrc/pcf7931.c @@ -0,0 +1,528 @@ +#include "proxmark3.h" +#include "apps.h" +#include "lfsampling.h" +#include "pcf7931.h" +#include "string.h" + +#define T0_PCF 8 //period for the pcf7931 in us +#define ALLOC 16 + +#define abs(x) ( ((x)<0) ? -(x) : (x) ) +#define max(x,y) ( x 18000 ) + GraphTraceLen = 18000; + + + int i, j, lastval, bitidx, half_switch; + int clock = 64; + int tolerance = clock / 8; + int pmc, block_done; + int lc, warnings = 0; + int num_blocks = 0; + int lmin=128, lmax=128; + uint8_t dir; + //clear read buffer + BigBuf_Clear_keep_EM(); + + LFSetupFPGAForADC(95, true); + DoAcquisition_default(0, true); + + lmin = 64; + lmax = 192; + + i = 2; + + /* Find first local max/min */ + if(dest[1] > dest[0]) { + while(i < GraphTraceLen) { + if( !(dest[i] > dest[i-1]) && dest[i] > lmax) + break; + i++; + } + dir = 0; + } + else { + while(i < GraphTraceLen) { + if( !(dest[i] < dest[i-1]) && dest[i] < lmin) + break; + i++; + } + dir = 1; + } + + lastval = i++; + half_switch = 0; + pmc = 0; + block_done = 0; + + for (bitidx = 0; i < GraphTraceLen; i++) + { + if ( (dest[i-1] > dest[i] && dir == 1 && dest[i] > lmax) || (dest[i-1] < dest[i] && dir == 0 && dest[i] < lmin)) + { + lc = i - lastval; + lastval = i; + + // Switch depending on lc length: + // Tolerance is 1/8 of clock rate (arbitrary) + if (abs(lc-clock/4) < tolerance) { + // 16T0 + if((i - pmc) == lc) { /* 16T0 was previous one */ + /* It's a PMC ! */ + i += (128+127+16+32+33+16)-1; + lastval = i; + pmc = 0; + block_done = 1; + } + else { + pmc = i; + } + } else if (abs(lc-clock/2) < tolerance) { + // 32TO + if((i - pmc) == lc) { /* 16T0 was previous one */ + /* It's a PMC ! */ + i += (128+127+16+32+33)-1; + lastval = i; + pmc = 0; + block_done = 1; + } + else if(half_switch == 1) { + bits[bitidx++] = 0; + half_switch = 0; + } + else + half_switch++; + } else if (abs(lc-clock) < tolerance) { + // 64TO + bits[bitidx++] = 1; + } else { + // Error + warnings++; + if (warnings > 10) + { + Dbprintf("Error: too many detection errors, aborting."); + return 0; + } + } + + if(block_done == 1) { + if(bitidx == 128) { + for(j=0; j<16; j++) { + blocks[num_blocks][j] = 128*bits[j*8+7]+ + 64*bits[j*8+6]+ + 32*bits[j*8+5]+ + 16*bits[j*8+4]+ + 8*bits[j*8+3]+ + 4*bits[j*8+2]+ + 2*bits[j*8+1]+ + bits[j*8]; + + } + num_blocks++; + } + bitidx = 0; + block_done = 0; + half_switch = 0; + } + if(i < GraphTraceLen) + dir =(dest[i-1] > dest[i]) ? 0 : 1; + } + if(bitidx==255) + bitidx=0; + warnings = 0; + if(num_blocks == 4) break; + } + memcpy(outBlocks, blocks, 16*num_blocks); + return num_blocks; +} + +int IsBlock0PCF7931(uint8_t *Block) { + // Assume RFU means 0 :) + if((memcmp(Block, "\x00\x00\x00\x00\x00\x00\x00\x01", 8) == 0) && memcmp(Block+9, "\x00\x00\x00\x00\x00\x00\x00", 7) == 0) // PAC enabled + return 1; + if((memcmp(Block+9, "\x00\x00\x00\x00\x00\x00\x00", 7) == 0) && Block[7] == 0) // PAC disabled, can it *really* happen ? + return 1; + return 0; +} + +int IsBlock1PCF7931(uint8_t *Block) { + // Assume RFU means 0 :) + if(Block[10] == 0 && Block[11] == 0 && Block[12] == 0 && Block[13] == 0) + if((Block[14] & 0x7f) <= 9 && Block[15] <= 9) + return 1; + + return 0; +} + +void ReadPCF7931() { + uint8_t Blocks[8][17]; + uint8_t tmpBlocks[4][16]; + int i, j, ind, ind2, n; + int num_blocks = 0; + int max_blocks = 8; + int ident = 0; + int error = 0; + int tries = 0; + + memset(Blocks, 0, 8*17*sizeof(uint8_t)); + + do { + memset(tmpBlocks, 0, 4*16*sizeof(uint8_t)); + n = DemodPCF7931((uint8_t**)tmpBlocks); + if(!n) + error++; + if(error==10 && num_blocks == 0) { + Dbprintf("Error, no tag or bad tag"); + return; + } + else if (tries==20 || error==10) { + Dbprintf("Error reading the tag"); + Dbprintf("Here is the partial content"); + goto end; + } + + for(i=0; i= 0; ind--,ind2--) { + if(ind2 < 0) + ind2 = max_blocks; + if(!Blocks[ind2][ALLOC]) { // Block ind2 not already found + // Dbprintf("Tmp %d -> Block %d", ind, ind2); + memcpy(Blocks[ind2], tmpBlocks[ind], 16); + Blocks[ind2][ALLOC] = 1; + num_blocks++; + if(num_blocks == max_blocks) goto end; + } + } + for(ind=i+1,ind2=j+1; ind < n; ind++,ind2++) { + if(ind2 > max_blocks) + ind2 = 0; + if(!Blocks[ind2][ALLOC]) { // Block ind2 not already found + // Dbprintf("Tmp %d -> Block %d", ind, ind2); + memcpy(Blocks[ind2], tmpBlocks[ind], 16); + Blocks[ind2][ALLOC] = 1; + num_blocks++; + if(num_blocks == max_blocks) goto end; + } + } + } + } + } + } + } + tries++; + if (BUTTON_PRESS()) return; + } while (num_blocks != max_blocks); + end: + Dbprintf("-----------------------------------------"); + Dbprintf("Memory content:"); + Dbprintf("-----------------------------------------"); + for(i=0; i", i); + } + Dbprintf("-----------------------------------------"); + + cmd_send(CMD_ACK,0,0,0,0,0); +} + + +/* Write on a byte of a PCF7931 tag + * @param address : address of the block to write + @param byte : address of the byte to write + @param data : data to write + */ +void WritePCF7931(uint8_t pass1, uint8_t pass2, uint8_t pass3, uint8_t pass4, uint8_t pass5, uint8_t pass6, uint8_t pass7, uint16_t init_delay, int32_t l, int32_t p, uint8_t address, uint8_t byte, uint8_t data) +{ + + uint32_t tab[1024]={0}; // data times frame + uint32_t u = 0; + uint8_t parity = 0; + bool comp = 0; + + //BUILD OF THE DATA FRAME + + //alimentation of the tag (time for initializing) + AddPatternPCF7931(init_delay, 0, 8192/2*T0_PCF, tab); + + //PMC + Dbprintf("Initialization delay : %d us", init_delay); + AddPatternPCF7931(8192/2*T0_PCF + 319*T0_PCF+70, 3*T0_PCF, 29*T0_PCF, tab); + + Dbprintf("Offsets : %d us on the low pulses width, %d us on the low pulses positions", l, p); + + //password indication bit + AddBitPCF7931(1, tab, l, p); + + + //password (on 56 bits) + Dbprintf("Password (LSB first on each byte) : %02x %02x %02x %02x %02x %02x %02x", pass1,pass2,pass3,pass4,pass5,pass6,pass7); + AddBytePCF7931(pass1, tab, l, p); + AddBytePCF7931(pass2, tab, l, p); + AddBytePCF7931(pass3, tab, l, p); + AddBytePCF7931(pass4, tab, l, p); + AddBytePCF7931(pass5, tab, l, p); + AddBytePCF7931(pass6, tab, l, p); + AddBytePCF7931(pass7, tab, l, p); + + //programming mode (0 or 1) + AddBitPCF7931(0, tab, l, p); + + //block adress on 6 bits + Dbprintf("Block address : %02x", address); + for (u=0; u<6; u++) + { + if (address&(1< 0xFFFF){ + tab[u] -= 0xFFFF; + comp = 0; + } + } + } + + SendCmdPCF7931(tab); +} + + + +/* Send a trame to a PCF7931 tags + * @param tab : array of the data frame + */ + +void SendCmdPCF7931(uint32_t * tab){ + uint16_t u=0; + uint16_t tempo=0; + + Dbprintf("SENDING DATA FRAME..."); + + FpgaDownloadAndGo(FPGA_BITSTREAM_LF); + + FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz + + FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU ); + + LED_A_ON(); + + // steal this pin from the SSP and use it to control the modulation + AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT; + AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT; + + //initialization of the timer + AT91C_BASE_PMC->PMC_PCER |= (0x1 << 12) | (0x1 << 13) | (0x1 << 14); + AT91C_BASE_TCB->TCB_BMR = AT91C_TCB_TC0XC0S_NONE | AT91C_TCB_TC1XC1S_TIOA0 | AT91C_TCB_TC2XC2S_NONE; + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable + AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK; //clock at 48/32 MHz + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKEN; + AT91C_BASE_TCB->TCB_BCR = 1; + + + tempo = AT91C_BASE_TC0->TC_CV; + for(u=0;tab[u]!= 0;u+=3){ + + + // modulate antenna + HIGH(GPIO_SSC_DOUT); + while(tempo != tab[u]){ + tempo = AT91C_BASE_TC0->TC_CV; + } + + // stop modulating antenna + LOW(GPIO_SSC_DOUT); + while(tempo != tab[u+1]){ + tempo = AT91C_BASE_TC0->TC_CV; + } + + + // modulate antenna + HIGH(GPIO_SSC_DOUT); + while(tempo != tab[u+2]){ + tempo = AT91C_BASE_TC0->TC_CV; + } + + + } + + LED_A_OFF(); + FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF); + SpinDelay(200); + + + AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable + DbpString("FINISH !"); + DbpString("(Could be usefull to send the same trame many times)"); + LED(0xFFFF, 1000); +} + + +/* Add a byte for building the data frame of PCF7931 tags + * @param b : byte to add + * @param tab : array of the data frame + * @param l : offset on low pulse width + * @param p : offset on low pulse positioning + */ + +bool AddBytePCF7931(uint8_t byte, uint32_t * tab, int32_t l, int32_t p){ + + uint32_t u; + for (u=0; u<8; u++) + { + if (byte&(1<magic != VERSION_INFORMATION_MAGIC) { - strncat(dst, "Missing/Invalid version information", len - strlen(dst) - 1); + strncat(dst, "Missing/Invalid version information\n", len - strlen(dst) - 1); return; } if(v->versionversion != 1) { - strncat(dst, "Version information not understood", len - strlen(dst) - 1); + strncat(dst, "Version information not understood\n", len - strlen(dst) - 1); return; } if(!v->present) { - strncat(dst, "Version information not available", len - strlen(dst) - 1); + strncat(dst, "Version information not available\n", len - strlen(dst) - 1); return; } @@ -289,6 +289,7 @@ void FormatVersionInformation(char *dst, int len, const char *prefix, void *vers strncat(dst, " ", len - strlen(dst) - 1); strncat(dst, v->buildtime, len - strlen(dst) - 1); + strncat(dst, "\n", len - strlen(dst) - 1); } // ------------------------------------------------------------------------- @@ -303,11 +304,12 @@ void FormatVersionInformation(char *dst, int len, const char *prefix, void *vers void StartTickCount() { -// must be 0x40, but on my cpu - included divider is optimal -// 0x20 - 1 ms / bit -// 0x40 - 2 ms / bit - - AT91C_BASE_RTTC->RTTC_RTMR = AT91C_RTTC_RTTRST + 0x001D; // was 0x003B + // This timer is based on the slow clock. The slow clock frequency is between 22kHz and 40kHz. + // We can determine the actual slow clock frequency by looking at the Main Clock Frequency Register. + uint16_t mainf = AT91C_BASE_PMC->PMC_MCFR & 0xffff; // = 16 * main clock frequency (16MHz) / slow clock frequency + // set RealTimeCounter divider to count at 1kHz: + AT91C_BASE_RTTC->RTTC_RTMR = AT91C_RTTC_RTTRST | ((256000 + (mainf/2)) / mainf); + // note: worst case precision is approx 2.5% } /* diff --git a/client/Makefile b/client/Makefile index 7954d1ea..0972f441 100644 --- a/client/Makefile +++ b/client/Makefile @@ -9,12 +9,13 @@ include ../common/Makefile.common CC=gcc CXX=g++ #COMMON_FLAGS = -m32 -VPATH = ../common +VPATH = ../common ../zlib OBJDIR = obj -LDLIBS = -L/opt/local/lib -L/usr/local/lib ../liblua/liblua.a -lreadline -lpthread -lm +LDLIBS = -L/opt/local/lib -L/usr/local/lib -lreadline -lpthread -lm +LUALIB = ../liblua/liblua.a LDFLAGS = $(COMMON_FLAGS) -CFLAGS = -std=c99 -I. -I../include -I../common -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -g -O4 +CFLAGS = -std=c99 -I. -I../include -I../common -I../zlib -I/opt/local/include -I../liblua -Wall $(COMMON_FLAGS) -g -O4 LUAPLATFORM = generic ifneq (,$(findstring MINGW,$(platform))) @@ -35,14 +36,13 @@ else ifeq ($(platform),Darwin) else CXXFLAGS = $(shell pkg-config --cflags QtCore QtGui 2>/dev/null) -Wall -O4 QTLDLIBS = $(shell pkg-config --libs QtCore QtGui 2>/dev/null) + LUALIB += -ldl MOC = $(shell pkg-config --variable=moc_location QtCore) - LDLIBS += -ldl # Below is a variant you can use if you have problems compiling with QT5 on ubuntu. see http://www.proxmark.org/forum/viewtopic.php?id=1661 for more info. #MOC = /usr/lib/x86_64-linux-gnu/qt4/bin/moc LUAPLATFORM = linux endif - ifneq ($(QTLDLIBS),) QTGUI = $(OBJDIR)/proxgui.o $(OBJDIR)/proxguiqt.o $(OBJDIR)/proxguiqt.moc.o CFLAGS += -DHAVE_GUI @@ -57,14 +57,14 @@ CORESRCS = uart.c \ CMDSRCS = nonce2key/crapto1.c\ - nonce2key/crypto1.c\ - nonce2key/nonce2key.c\ - loclass/cipher.c \ - loclass/cipherutils.c \ - loclass/des.c \ - loclass/ikeys.c \ - loclass/elite_crack.c\ - loclass/fileutils.c\ + nonce2key/crypto1.c\ + nonce2key/nonce2key.c\ + loclass/cipher.c \ + loclass/cipherutils.c \ + loclass/des.c \ + loclass/ikeys.c \ + loclass/elite_crack.c\ + loclass/fileutils.c\ mifarehost.c\ crc.c \ crc16.c \ @@ -85,10 +85,12 @@ CMDSRCS = nonce2key/crapto1.c\ cmdhficlass.c \ cmdhfmf.c \ cmdhfmfu.c \ + cmdhftopaz.c \ cmdhw.c \ cmdlf.c \ cmdlfio.c \ cmdlfhid.c \ + cmdlfawid.c \ cmdlfem4x.c \ cmdlfhitag.c \ cmdlfti.c \ @@ -96,27 +98,34 @@ CMDSRCS = nonce2key/crapto1.c\ cmdmain.c \ cmdlft55xx.c \ cmdlfpcf7931.c\ + cmdlfviking.c\ pm3_binlib.c\ scripting.c\ cmdscript.c\ pm3_bitlib.c\ aes.c\ protocols.c\ + sha1.c\ + +ZLIBSRCS = deflate.c adler32.c trees.c zutil.c inflate.c inffast.c inftrees.c +ZLIB_FLAGS = -DZ_SOLO -DZ_PREFIX -DNO_GZIP -DZLIB_PM3_TUNED +#-DDEBUG -Dverbose=1 COREOBJS = $(CORESRCS:%.c=$(OBJDIR)/%.o) CMDOBJS = $(CMDSRCS:%.c=$(OBJDIR)/%.o) +ZLIBOBJS = $(ZLIBSRCS:%.c=$(OBJDIR)/%.o) RM = rm -f -BINS = proxmark3 flasher #snooper cli -CLEAN = cli cli.exe flasher flasher.exe proxmark3 proxmark3.exe snooper snooper.exe $(CMDOBJS) $(OBJDIR)/*.o *.o *.moc.cpp +BINS = proxmark3 flasher fpga_compress #snooper cli +CLEAN = cli cli.exe flasher flasher.exe proxmark3 proxmark3.exe fpga_compress fpga_compress.exe snooper snooper.exe $(CMDOBJS) $(OBJDIR)/*.o *.o *.moc.cpp all: lua_build $(BINS) all-static: LDLIBS:=-static $(LDLIBS) -all-static: snooper cli flasher - -proxmark3: LDLIBS+=$(QTLDLIBS) +all-static: snooper cli flasher fpga_compress + +proxmark3: LDLIBS+=$(LUALIB) $(QTLDLIBS) proxmark3: $(OBJDIR)/proxmark3.o $(COREOBJS) $(CMDOBJS) $(QTGUI) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ @@ -129,8 +138,11 @@ cli: $(OBJDIR)/cli.o $(COREOBJS) $(CMDOBJS) $(OBJDIR)/guidummy.o flasher: $(OBJDIR)/flash.o $(OBJDIR)/flasher.o $(COREOBJS) $(CXX) $(CXXFLAGS) $^ $(LDLIBS) -o $@ +fpga_compress: $(OBJDIR)/fpga_compress.o $(ZLIBOBJS) + $(CXX) $(CXXFLAGS) $(ZLIB_FLAGS) $^ $(LDLIBS) -o $@ + $(OBJDIR)/%.o: %.c - $(CC) $(CFLAGS) -c -o $@ $< + $(CC) $(CFLAGS) $(ZLIB_FLAGS) -c -o $@ $< $(OBJDIR)/%.o: %.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< diff --git a/client/cmddata.c b/client/cmddata.c index b9069bc1..c7fdc91e 100644 --- a/client/cmddata.c +++ b/client/cmddata.c @@ -23,10 +23,12 @@ #include "lfdemod.h" #include "usb_cmd.h" #include "crc.h" +#include "crc16.h" +#include "loclass/cipherutils.h" uint8_t DemodBuffer[MAX_DEMOD_BUF_LEN]; -uint8_t g_debugMode; -size_t DemodBufferLen; +uint8_t g_debugMode=0; +size_t DemodBufferLen=0; static int CmdHelp(const char *Cmd); //set the demod buffer with given array of binary (one bit per byte) @@ -55,6 +57,16 @@ int CmdSetDebugMode(const char *Cmd) return 1; } +int usage_data_printdemodbuf(){ + PrintAndLog("Usage: data printdemodbuffer x o l "); + PrintAndLog("Options: "); + PrintAndLog(" h This help"); + PrintAndLog(" x output in hex (omit for binary output)"); + PrintAndLog(" o enter offset in # of bits"); + PrintAndLog(" l enter length to print in # of bits or hex characters respectively"); + return 0; +} + //by marshmellow void printDemodBuff(void) { @@ -73,23 +85,56 @@ void printDemodBuff(void) int CmdPrintDemodBuff(const char *Cmd) { - char hex; - char printBuff[512]={0x00}; - uint8_t numBits = DemodBufferLen & 0xFFFC; - sscanf(Cmd, "%c", &hex); - if (hex == 'h'){ - PrintAndLog("Usage: data printdemodbuffer [x]"); - PrintAndLog("Options: "); - PrintAndLog(" h This help"); - PrintAndLog(" x output in hex (omit for binary output)"); - return 0; + char hex[512]={0x00}; + bool hexMode = false; + bool errors = false; + uint32_t offset = 0; //could be size_t but no param_get16... + uint32_t length = 512; + char cmdp = 0; + while(param_getchar(Cmd, cmdp) != 0x00) + { + switch(param_getchar(Cmd, cmdp)) + { + case 'h': + case 'H': + return usage_data_printdemodbuf(); + case 'x': + case 'X': + hexMode = true; + cmdp++; + break; + case 'o': + case 'O': + offset = param_get32ex(Cmd, cmdp+1, 0, 10); + if (!offset) errors = true; + cmdp += 2; + break; + case 'l': + case 'L': + length = param_get32ex(Cmd, cmdp+1, 512, 10); + if (!length) errors = true; + cmdp += 2; + break; + default: + PrintAndLog("Unknown parameter '%c'", param_getchar(Cmd, cmdp)); + errors = true; + break; + } + if(errors) break; } - if (hex == 'x'){ - numBits = binarraytohex(printBuff, (char *)DemodBuffer, numBits); + //Validations + if(errors) return usage_data_printdemodbuf(); + length = (length > (DemodBufferLen-offset)) ? DemodBufferLen-offset : length; + int numBits = (length) & 0x00FFC; //make sure we don't exceed our string + + if (hexMode){ + char *buf = (char *) (DemodBuffer + offset); + numBits = (numBits > sizeof(hex)) ? sizeof(hex) : numBits; + numBits = binarraytohex(hex, buf, numBits); if (numBits==0) return 0; - PrintAndLog("DemodBuffer: %s",printBuff); + PrintAndLog("DemodBuffer: %s",hex); } else { - printDemodBuff(); + PrintAndLog("DemodBuffer:\n%s", sprint_bin_break(DemodBuffer+offset,numBits,16)); } return 1; } @@ -232,7 +277,8 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ) int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose) { - if (!ASKDemod(Cmd, FALSE, FALSE, 1)) return 0; + bool st = TRUE; + if (!ASKDemod_ext(Cmd, FALSE, FALSE, 1, &st)) return 0; return AskEm410xDecode(verbose, hi, lo); } @@ -267,8 +313,7 @@ int CmdAskEM410xDemod(const char *Cmd) //verbose will print results and demoding messages //emSearch will auto search for EM410x format in bitstream //askType switches decode: ask/raw = 0, ask/manchester = 1 -int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) -{ +int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck) { int invert=0; int clk=0; int maxErr=100; @@ -277,7 +322,7 @@ int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) char amp = param_getchar(Cmd, 0); uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; sscanf(Cmd, "%i %i %i %i %c", &clk, &invert, &maxErr, &maxLen, &); - if (!maxLen) maxLen = 512*64; + if (!maxLen) maxLen = BIGBUF_SIZE; if (invert != 0 && invert != 1) { PrintAndLog("Invalid argument: %s", Cmd); return 0; @@ -289,15 +334,22 @@ int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) if (amp == 'a' || amp == 'A') askAmp=1; size_t BitLen = getFromGraphBuf(BitStream); if (g_debugMode) PrintAndLog("DEBUG: Bitlen from grphbuff: %d",BitLen); - if (BitLen<255) return 0; - if (maxLenmaxErr){ + if (errCnt > maxErr){ if (g_debugMode) PrintAndLog("DEBUG: Too many errors found, errors:%d, bits:%d, clock:%d",errCnt, BitLen, clk); return 0; } @@ -307,8 +359,8 @@ int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) setDemodBuf(BitStream,BitLen,0); if (verbose || g_debugMode){ if (errCnt>0) PrintAndLog("# Errors during Demoding (shown as 7 in bit stream): %d",errCnt); - if (askType) PrintAndLog("ASK/Manchester decoded bitstream:"); - else PrintAndLog("ASK/Raw decoded bitstream:"); + if (askType) PrintAndLog("ASK/Manchester - Clock: %d - Decoded bitstream:",clk); + else PrintAndLog("ASK/Raw - Clock: %d - Decoded bitstream:",clk); // Now output the bitstream to the scrollback by line of 16 bits printDemodBuff(); @@ -320,6 +372,10 @@ int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) } return 1; } +int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType) { + bool st = false; + return ASKDemod_ext(Cmd, verbose, emSearch, askType, &st); +} //by marshmellow //takes 5 arguments - clock, invert, maxErr, maxLen as integers and amplify as char == 'a' @@ -329,7 +385,8 @@ int Cmdaskmandemod(const char *Cmd) { char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 25 || cmdp == 'h' || cmdp == 'H') { - PrintAndLog("Usage: data rawdemod am [clock] [maxError] [maxLen] [amplify]"); + PrintAndLog("Usage: data rawdemod am [clock] [maxError] [maxLen] [amplify]"); + PrintAndLog(" ['s'] optional, check for Sequence Terminator"); PrintAndLog(" [set clock as integer] optional, if not set, autodetect"); PrintAndLog(" , 1 to invert output"); PrintAndLog(" [set maximum allowed errors], default = 100"); @@ -343,7 +400,13 @@ int Cmdaskmandemod(const char *Cmd) PrintAndLog(" : data rawdemod am 64 1 0 = demod an ask/manchester tag from GraphBuffer using a clock of RF/64, inverting data and allowing 0 demod errors"); return 0; } - return ASKDemod(Cmd, TRUE, TRUE, 1); + bool st = TRUE; + if (Cmd[0]=='s') + return ASKDemod_ext(Cmd++, TRUE, TRUE, 1, &st); + else if (Cmd[1] == 's') + return ASKDemod_ext(Cmd+=2, TRUE, TRUE, 1, &st); + else + return ASKDemod(Cmd, TRUE, TRUE, 1); } //by marshmellow @@ -355,7 +418,7 @@ int Cmdmandecoderaw(const char *Cmd) int errCnt=0; size_t size=0; int invert=0; - size_t maxErr = 20; + int maxErr = 20; char cmdp = param_getchar(Cmd, 0); if (strlen(Cmd) > 5 || cmdp == 'h' || cmdp == 'H') { PrintAndLog("Usage: data manrawdecode [invert] [maxErr]"); @@ -461,22 +524,20 @@ int CmdBiphaseDecodeRaw(const char *Cmd) int ASKbiphaseDemod(const char *Cmd, bool verbose) { //ask raw demod GraphBuffer first - int offset=0, clk=0, invert=0, maxErr=0, ans=0; - ans = sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); - if (ans>0) - ans = ASKDemod(Cmd+1, FALSE, FALSE, 0); - else - ans = ASKDemod(Cmd, FALSE, FALSE, 0); - if (!ans) { - if (g_debugMode || verbose) PrintAndLog("Error AskDemod: %d", ans); - return 0; - } + int offset=0, clk=0, invert=0, maxErr=0; + sscanf(Cmd, "%i %i %i %i", &offset, &clk, &invert, &maxErr); + + uint8_t BitStream[MAX_DEMOD_BUF_LEN]; + size_t size = getFromGraphBuf(BitStream); + //invert here inverts the ask raw demoded bits which has no effect on the demod, but we need the pointer + int errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0); + if ( errCnt < 0 || errCnt > maxErr ) { + if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: %d", errCnt, clk); + return 0; + } - //attempt to Biphase decode DemodBuffer - size_t size = DemodBufferLen; - uint8_t BitStream[MAX_DEMOD_BUF_LEN]; - memcpy(BitStream, DemodBuffer, DemodBufferLen); - int errCnt = BiphaseRawDecode(BitStream, &size, offset, 0); + //attempt to Biphase decode BitStream + errCnt = BiphaseRawDecode(BitStream, &size, offset, invert); if (errCnt < 0){ if (g_debugMode || verbose) PrintAndLog("Error BiphaseRawDecode: %d", errCnt); return 0; @@ -488,7 +549,7 @@ int ASKbiphaseDemod(const char *Cmd, bool verbose) //success set DemodBuffer and return setDemodBuf(BitStream, size, 0); if (g_debugMode || verbose){ - PrintAndLog("Biphase Decoded using offset: %d - # errors:%d - data:",offset,errCnt); + PrintAndLog("Biphase Decoded using offset: %d - clock: %d - # errors:%d - data:",offset,clk,errCnt); printDemodBuff(); } return 1; @@ -552,7 +613,7 @@ int CmdG_Prox_II_Demod(const char *Cmd) if ((idx+1) % 5 == 0){ //spacer bit - should be 0 if (DemodBuffer[startIdx+idx] != 0) { - if (g_debugMode) PrintAndLog("Error spacer not 0: %d, pos: %d",DemodBuffer[startIdx+idx],startIdx+idx); + if (g_debugMode) PrintAndLog("Error spacer not 0: %u, pos: %u", (unsigned int)DemodBuffer[startIdx+idx],(unsigned int)(startIdx+idx)); return 0; } continue; @@ -560,21 +621,21 @@ int CmdG_Prox_II_Demod(const char *Cmd) if (keyCnt<8){ //lsb first xorKey = xorKey | (DemodBuffer[startIdx+idx]<>1); Card = ((ByteStream[4]&1)<<19) | (ByteStream[5]<<11) | (ByteStream[6]<<3) | (ByteStream[7]>>5); - PrintAndLog("G-Prox-II Found: FmtLen %d, FC %d, Card %d",fmtLen,FC,Card); + PrintAndLog("G-Prox-II Found: FmtLen %d, FC %d, Card %d", fmtLen, FC, Card); } else if(fmtLen==26){ FC = ((ByteStream[3] & 0x7F)<<1) | (ByteStream[4]>>7); Card = ((ByteStream[4]&0x7F)<<9) | (ByteStream[5]<<1) | (ByteStream[6]>>7); - PrintAndLog("G-Prox-II Found: FmtLen %d, FC %d, Card %d",fmtLen,FC,Card); + PrintAndLog("G-Prox-II Found: FmtLen %d, FC %d, Card %d",(unsigned int)fmtLen,FC,Card); } else { - PrintAndLog("Unknown G-Prox-II Fmt Found: FmtLen %d",fmtLen); + PrintAndLog("Unknown G-Prox-II Fmt Found: FmtLen %d",(int)fmtLen); } PrintAndLog("Raw: %08x%08x%08x", raw1,raw2,raw3); setDemodBuf(DemodBuffer+ans, 96, 0); return 1; } +//by marshmellow +//see ASKDemod for what args are accepted +int CmdVikingDemod(const char *Cmd) +{ + if (!ASKDemod(Cmd, false, false, 1)) { + if (g_debugMode) PrintAndLog("ASKDemod failed"); + return 0; + } + size_t size = DemodBufferLen; + //call lfdemod.c demod for Viking + int ans = VikingDemod_AM(DemodBuffer, &size); + if (ans < 0) { + if (g_debugMode) PrintAndLog("Error Viking_Demod %d", ans); + return 0; + } + //got a good demod + uint32_t raw1 = bytebits_to_byte(DemodBuffer+ans, 32); + uint32_t raw2 = bytebits_to_byte(DemodBuffer+ans+32, 32); + uint32_t cardid = bytebits_to_byte(DemodBuffer+ans+24, 32); + uint8_t checksum = bytebits_to_byte(DemodBuffer+ans+32+24, 8); + PrintAndLog("Viking Tag Found: Card ID %08X, Checksum: %02X", cardid, (unsigned int) checksum); + PrintAndLog("Raw: %08X%08X", raw1,raw2); + setDemodBuf(DemodBuffer+ans, 64, 0); + return 1; +} + //by marshmellow - see ASKDemod int Cmdaskrawdemod(const char *Cmd) { @@ -850,19 +937,21 @@ int CmdDetectClockRate(const char *Cmd) char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert) { - char *fskType; + static char fType[8]; + memset(fType, 0x00, 8); + char *fskType = fType; if (fchigh==10 && fclow==8){ if (invert) //fsk2a - fskType = "FSK2a"; + memcpy(fskType, "FSK2a", 5); else //fsk2 - fskType = "FSK2"; + memcpy(fskType, "FSK2", 4); } else if (fchigh == 8 && fclow == 5) { if (invert) - fskType = "FSK1"; + memcpy(fskType, "FSK1", 4); else - fskType = "FSK1a"; + memcpy(fskType, "FSK1a", 5); } else { - fskType = "FSK??"; + memcpy(fskType, "FSK??", 5); } return fskType; } @@ -874,55 +963,53 @@ char *GetFSKType(uint8_t fchigh, uint8_t fclow, uint8_t invert) int FSKrawDemod(const char *Cmd, bool verbose) { //raw fsk demod no manchester decoding no start bit finding just get binary from wave + uint8_t rfLen, invert, fchigh, fclow; //set defaults - int rfLen = 0; - int invert = 0; - int fchigh = 0; - int fclow = 0; - //set options from parameters entered with the command - sscanf(Cmd, "%i %i %i %i", &rfLen, &invert, &fchigh, &fclow); + rfLen = param_get8(Cmd, 0); + invert = param_get8(Cmd, 1); + fchigh = param_get8(Cmd, 2); + fclow = param_get8(Cmd, 3); if (strlen(Cmd)>0 && strlen(Cmd)<=2) { - if (rfLen==1){ + if (rfLen==1) { invert = 1; //if invert option only is used rfLen = 0; - } + } } - uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; size_t BitLen = getFromGraphBuf(BitStream); if (BitLen==0) return 0; //get field clock lengths uint16_t fcs=0; - if (fchigh==0 || fclow == 0){ + if (!fchigh || !fclow) { fcs = countFC(BitStream, BitLen, 1); - if (fcs==0){ - fchigh=10; - fclow=8; - }else{ - fchigh = (fcs >> 8) & 0xFF; - fclow = fcs & 0xFF; + if (!fcs) { + fchigh = 10; + fclow = 8; + } else { + fchigh = (fcs >> 8) & 0x00FF; + fclow = fcs & 0x00FF; } } //get bit clock length - if (rfLen==0){ + if (!rfLen) { rfLen = detectFSKClk(BitStream, BitLen, fchigh, fclow); - if (rfLen == 0) rfLen = 50; + if (!rfLen) rfLen = 50; } - int size = fskdemod(BitStream,BitLen,(uint8_t)rfLen,(uint8_t)invert,(uint8_t)fchigh,(uint8_t)fclow); - if (size>0){ + int size = fskdemod(BitStream, BitLen, rfLen, invert, fchigh, fclow); + if (size > 0) { setDemodBuf(BitStream,size,0); // Now output the bitstream to the scrollback by line of 16 bits if (verbose || g_debugMode) { - PrintAndLog("\nUsing Clock:%d, invert:%d, fchigh:%d, fclow:%d", rfLen, invert, fchigh, fclow); + PrintAndLog("\nUsing Clock:%u, invert:%u, fchigh:%u, fclow:%u", (unsigned int)rfLen, (unsigned int)invert, (unsigned int)fchigh, (unsigned int)fclow); PrintAndLog("%s decoded bitstream:",GetFSKType(fchigh,fclow,invert)); printDemodBuff(); } return 1; - } else{ + } else { if (g_debugMode) PrintAndLog("no FSK data found"); } return 0; @@ -1094,8 +1181,6 @@ int CmdFSKdemodParadox(const char *Cmd) //print ioprox ID and some format details int CmdFSKdemodIO(const char *Cmd) { - //raw fsk demod no manchester decoding no start bit finding just get binary from wave - //set defaults int idx=0; //something in graphbuffer? if (GraphTraceLen < 65) { @@ -1184,11 +1269,6 @@ int CmdFSKdemodIO(const char *Cmd) //print full AWID Prox ID and some bit format details if found int CmdFSKdemodAWID(const char *Cmd) { - - //int verbose=1; - //sscanf(Cmd, "%i", &verbose); - - //raw fsk demod no manchester decoding no start bit finding just get binary from wave uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; size_t size = getFromGraphBuf(BitStream); if (size==0) return 0; @@ -1387,7 +1467,6 @@ int CmdFSKdemodPyramid(const char *Cmd) uint32_t fc = 0; uint32_t cardnum = 0; uint32_t code1 = 0; - //uint32_t code2 = 0; if (fmtLen==26){ fc = bytebits_to_byte(BitStream+73, 8); cardnum = bytebits_to_byte(BitStream+81, 16); @@ -1421,6 +1500,98 @@ int CmdFSKdemodPyramid(const char *Cmd) return 1; } +// FDX-B ISO11784/85 demod (aka animal tag) BIPHASE, inverted, rf/32, with preamble of 00000000001 (128bits) +// 8 databits + 1 parity (1) +// CIITT 16 chksum +// NATIONAL CODE, ICAR database +// COUNTRY CODE (ISO3166) or http://cms.abvma.ca/uploads/ManufacturersISOsandCountryCodes.pdf +// FLAG (animal/non-animal) +/* +38 IDbits +10 country code +1 extra app bit +14 reserved bits +1 animal bit +16 ccitt CRC chksum over 64bit ID CODE. +24 appli bits. + +-- sample: 985121004515220 [ 37FF65B88EF94 ] +*/ +int CmdFDXBdemodBI(const char *Cmd){ + + int invert = 1; + int clk = 32; + int errCnt = 0; + int maxErr = 0; + uint8_t BitStream[MAX_DEMOD_BUF_LEN]; + size_t size = getFromGraphBuf(BitStream); + + errCnt = askdemod(BitStream, &size, &clk, &invert, maxErr, 0, 0); + if ( errCnt < 0 || errCnt > maxErr ) { + if (g_debugMode) PrintAndLog("DEBUG: no data or error found %d, clock: %d", errCnt, clk); + return 0; + } + + errCnt = BiphaseRawDecode(BitStream, &size, maxErr, 1); + if (errCnt < 0 || errCnt > maxErr ) { + if (g_debugMode) PrintAndLog("Error BiphaseRawDecode: %d", errCnt); + return 0; + } + + int preambleIndex = FDXBdemodBI(BitStream, &size); + if (preambleIndex < 0){ + if (g_debugMode) PrintAndLog("Error FDXBDemod , no startmarker found :: %d",preambleIndex); + return 0; + } + if (size != 128) { + if (g_debugMode) PrintAndLog("Error incorrect data length found"); + return 0; + } + + setDemodBuf(BitStream, 128, preambleIndex); + + // remove marker bits (1's every 9th digit after preamble) (pType = 2) + size = removeParity(BitStream, preambleIndex + 11, 9, 2, 117); + if ( size != 104 ) { + if (g_debugMode) PrintAndLog("Error removeParity:: %d", size); + return 0; + } + if (g_debugMode) { + char *bin = sprint_bin_break(BitStream,size,16); + PrintAndLog("DEBUG BinStream:\n%s",bin); + } + PrintAndLog("\nFDX-B / ISO 11784/5 Animal Tag ID Found:"); + if (g_debugMode) PrintAndLog("Start marker %d; Size %d", preambleIndex, size); + + //got a good demod + uint64_t NationalCode = ((uint64_t)(bytebits_to_byteLSBF(BitStream+32,6)) << 32) | bytebits_to_byteLSBF(BitStream,32); + uint32_t countryCode = bytebits_to_byteLSBF(BitStream+38,10); + uint8_t dataBlockBit = BitStream[48]; + uint32_t reservedCode = bytebits_to_byteLSBF(BitStream+49,14); + uint8_t animalBit = BitStream[63]; + uint32_t crc16 = bytebits_to_byteLSBF(BitStream+64,16); + uint32_t extended = bytebits_to_byteLSBF(BitStream+80,24); + + uint64_t rawid = ((uint64_t)bytebits_to_byte(BitStream,32)<<32) | bytebits_to_byte(BitStream+32,32); + uint8_t raw[8]; + num_to_bytes(rawid, 8, raw); + + if (g_debugMode) PrintAndLog("Raw ID Hex: %s", sprint_hex(raw,8)); + + uint16_t calcCrc = crc16_ccitt_kermit(raw, 8); + PrintAndLog("Animal ID: %04u-%012llu", countryCode, NationalCode); + PrintAndLog("National Code: %012llu", NationalCode); + PrintAndLog("CountryCode: %04u", countryCode); + PrintAndLog("Extended Data: %s", dataBlockBit ? "True" : "False"); + PrintAndLog("reserved Code: %u", reservedCode); + PrintAndLog("Animal Tag: %s", animalBit ? "True" : "False"); + PrintAndLog("CRC: 0x%04X - [%04X] - %s", crc16, calcCrc, (calcCrc == crc16) ? "Passed" : "Failed"); + PrintAndLog("Extended: 0x%X\n", extended); + + return 1; +} + + //by marshmellow //attempt to psk1 demod graph buffer int PSKDemod(const char *Cmd, bool verbose) @@ -1434,17 +1605,20 @@ int PSKDemod(const char *Cmd, bool verbose) clk=0; } if (invert != 0 && invert != 1) { - if (verbose) PrintAndLog("Invalid argument: %s", Cmd); + if (g_debugMode || verbose) PrintAndLog("Invalid argument: %s", Cmd); return 0; } uint8_t BitStream[MAX_GRAPH_TRACE_LEN]={0}; size_t BitLen = getFromGraphBuf(BitStream); - if (BitLen==0) return -1; + if (BitLen==0) return 0; uint8_t carrier=countFC(BitStream, BitLen, 0); if (carrier!=2 && carrier!=4 && carrier!=8){ //invalid carrier return 0; } + if (g_debugMode){ + PrintAndLog("Carrier: rf/%d",carrier); + } int errCnt=0; errCnt = pskRawDemod(BitStream, &BitLen, &clk, &invert); if (errCnt > maxErr){ @@ -1484,61 +1658,33 @@ int CmdIndalaDecode(const char *Cmd) return 0; } uint8_t invert=0; - ans = indala26decode(DemodBuffer, &DemodBufferLen, &invert); - if (ans < 1) { + size_t size = DemodBufferLen; + size_t startIdx = indala26decode(DemodBuffer, &size, &invert); + if (startIdx < 1 || size > 224) { if (g_debugMode==1) PrintAndLog("Error2: %d",ans); return -1; } - char showbits[251]={0x00}; + setDemodBuf(DemodBuffer, size, startIdx); if (invert) if (g_debugMode==1) PrintAndLog("Had to invert bits"); + PrintAndLog("BitLen: %d",DemodBufferLen); //convert UID to HEX uint32_t uid1, uid2, uid3, uid4, uid5, uid6, uid7; - int idx; - uid1=0; - uid2=0; - PrintAndLog("BitLen: %d",DemodBufferLen); - if (DemodBufferLen==64){ - for( idx=0; idx<64; idx++) { - uid1=(uid1<<1)|(uid2>>31); - if (DemodBuffer[idx] == 0) { - uid2=(uid2<<1)|0; - showbits[idx]='0'; - } else { - uid2=(uid2<<1)|1; - showbits[idx]='1'; - } - } - showbits[idx]='\0'; - PrintAndLog("Indala UID=%s (%x%08x)", showbits, uid1, uid2); - } - else { - uid3=0; - uid4=0; - uid5=0; - uid6=0; - uid7=0; - for( idx=0; idx>31); - uid2=(uid2<<1)|(uid3>>31); - uid3=(uid3<<1)|(uid4>>31); - uid4=(uid4<<1)|(uid5>>31); - uid5=(uid5<<1)|(uid6>>31); - uid6=(uid6<<1)|(uid7>>31); - if (DemodBuffer[idx] == 0) { - uid7=(uid7<<1)|0; - showbits[idx]='0'; - } - else { - uid7=(uid7<<1)|1; - showbits[idx]='1'; - } - } - showbits[idx]='\0'; - PrintAndLog("Indala UID=%s (%x%08x%08x%08x%08x%08x%08x)", showbits, uid1, uid2, uid3, uid4, uid5, uid6, uid7); + uid1=bytebits_to_byte(DemodBuffer,32); + uid2=bytebits_to_byte(DemodBuffer+32,32); + if (DemodBufferLen==64) { + PrintAndLog("Indala UID=%s (%x%08x)", sprint_bin_break(DemodBuffer,DemodBufferLen,16), uid1, uid2); + } else { + uid3=bytebits_to_byte(DemodBuffer+64,32); + uid4=bytebits_to_byte(DemodBuffer+96,32); + uid5=bytebits_to_byte(DemodBuffer+128,32); + uid6=bytebits_to_byte(DemodBuffer+160,32); + uid7=bytebits_to_byte(DemodBuffer+192,32); + PrintAndLog("Indala UID=%s (%x%08x%08x%08x%08x%08x%08x)", + sprint_bin_break(DemodBuffer,DemodBufferLen,16), uid1, uid2, uid3, uid4, uid5, uid6, uid7); } if (g_debugMode){ PrintAndLog("DEBUG: printing demodbuffer:"); @@ -1608,7 +1754,7 @@ int NRZrawDemod(const char *Cmd, bool verbose) size_t BitLen = getFromGraphBuf(BitStream); if (BitLen==0) return 0; int errCnt=0; - errCnt = nrzRawDemod(BitStream, &BitLen, &clk, &invert, maxErr); + errCnt = nrzRawDemod(BitStream, &BitLen, &clk, &invert); if (errCnt > maxErr){ if (g_debugMode) PrintAndLog("Too many errors found, clk: %d, invert: %d, numbits: %d, errCnt: %d",clk,invert,BitLen,errCnt); return 0; @@ -1831,26 +1977,14 @@ int CmdHpf(const char *Cmd) RepaintGraphWindow(); return 0; } -typedef struct { - uint8_t * buffer; - uint32_t numbits; - uint32_t position; -}BitstreamOut; - -bool _headBit( BitstreamOut *stream) -{ - int bytepos = stream->position >> 3; // divide by 8 - int bitpos = (stream->position++) & 7; // mask out 00000111 - return (*(stream->buffer + bytepos) >> (7-bitpos)) & 1; -} -uint8_t getByte(uint8_t bits_per_sample, BitstreamOut* b) +uint8_t getByte(uint8_t bits_per_sample, BitstreamIn* b) { int i; uint8_t val = 0; for(i =0 ; i < bits_per_sample; i++) { - val |= (_headBit(b) << (7-i)); + val |= (headBit(b) << (7-i)); } return val; } @@ -1866,10 +2000,7 @@ int getSamples(const char *Cmd, bool silent) int n = strtol(Cmd, NULL, 0); - if (n == 0) - n = sizeof(got); - - if (n > sizeof(got)) + if (n == 0 || n > sizeof(got)) n = sizeof(got); PrintAndLog("Reading %d bytes from device memory\n", n); @@ -1890,7 +2021,7 @@ int getSamples(const char *Cmd, bool silent) if(bits_per_sample < 8) { PrintAndLog("Unpacking..."); - BitstreamOut bout = { got, bits_per_sample * n, 0}; + BitstreamIn bout = { got, bits_per_sample * n, 0}; int j =0; for (j = 0; j * bits_per_sample < n * 8 && j < n; j++) { uint8_t sample = getByte(bits_per_sample, &bout); @@ -2153,18 +2284,114 @@ int CmdZerocrossings(const char *Cmd) return 0; } +int usage_data_bin2hex(){ + PrintAndLog("Usage: data bin2hex "); + PrintAndLog(" This function will ignore all characters not 1 or 0 (but stop reading on whitespace)"); + return 0; +} + +/** + * @brief Utility for conversion via cmdline. + * @param Cmd + * @return + */ +int Cmdbin2hex(const char *Cmd) +{ + int bg =0, en =0; + if(param_getptr(Cmd, &bg, &en, 0)) + { + return usage_data_bin2hex(); + } + //Number of digits supplied as argument + size_t length = en - bg +1; + size_t bytelen = (length+7) / 8; + uint8_t* arr = (uint8_t *) malloc(bytelen); + memset(arr, 0, bytelen); + BitstreamOut bout = { arr, 0, 0 }; + + for(; bg <= en ;bg++) + { + char c = Cmd[bg]; + if( c == '1') pushBit(&bout, 1); + else if( c == '0') pushBit(&bout, 0); + else PrintAndLog("Ignoring '%c'", c); + } + + if(bout.numbits % 8 != 0) + { + printf("[padded with %d zeroes]\n", 8-(bout.numbits % 8)); + } + + //Uses printf instead of PrintAndLog since the latter + // adds linebreaks to each printout - this way was more convenient since we don't have to + // allocate a string and write to that first... + for(size_t x = 0; x < bytelen ; x++) + { + printf("%02X", arr[x]); + } + printf("\n"); + free(arr); + return 0; +} + +int usage_data_hex2bin(){ + + PrintAndLog("Usage: data bin2hex "); + PrintAndLog(" This function will ignore all non-hexadecimal characters (but stop reading on whitespace)"); + return 0; + +} + +int Cmdhex2bin(const char *Cmd) +{ + int bg =0, en =0; + if(param_getptr(Cmd, &bg, &en, 0)) + { + return usage_data_hex2bin(); + } + + + while(bg <= en ) + { + char x = Cmd[bg++]; + // capitalize + if (x >= 'a' && x <= 'f') + x -= 32; + // convert to numeric value + if (x >= '0' && x <= '9') + x -= '0'; + else if (x >= 'A' && x <= 'F') + x -= 'A' - 10; + else + continue; + + //Uses printf instead of PrintAndLog since the latter + // adds linebreaks to each printout - this way was more convenient since we don't have to + // allocate a string and write to that first... + + for(int i= 0 ; i < 4 ; ++i) + printf("%d",(x >> (3 - i)) & 1); + } + printf("\n"); + + return 0; +} + static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, {"askedgedetect", CmdAskEdgeDetect, 1, "[threshold] Adjust Graph for manual ask demod using the length of sample differences to detect the edge of a wave (use 20-45, def:25)"}, {"askem410xdemod", CmdAskEM410xDemod, 1, "[clock] [invert<0|1>] [maxErr] -- Demodulate an EM410x tag from GraphBuffer (args optional)"}, {"askgproxiidemod", CmdG_Prox_II_Demod, 1, "Demodulate a G Prox II tag from GraphBuffer"}, + {"askvikingdemod", CmdVikingDemod, 1, "Demodulate a Viking tag from GraphBuffer"}, {"autocorr", CmdAutoCorr, 1, "[window length] [g] -- Autocorrelation over window - g to save back to GraphBuffer (overwrite)"}, {"biphaserawdecode",CmdBiphaseDecodeRaw,1, "[offset] [invert<0|1>] [maxErr] -- Biphase decode bin stream in DemodBuffer (offset = 0|1 bits to shift the decode start)"}, + {"bin2hex", Cmdbin2hex, 1, "bin2hex -- Converts binary to hexadecimal"}, {"bitsamples", CmdBitsamples, 0, "Get raw samples as bitstring"}, {"buffclear", CmdBuffClear, 1, "Clear sample buffer and graph window"}, {"dec", CmdDec, 1, "Decimate samples"}, {"detectclock", CmdDetectClockRate, 1, "[modulation] Detect clock rate of wave in GraphBuffer (options: 'a','f','n','p' for ask, fsk, nrz, psk respectively)"}, + {"fdxbdemod", CmdFDXBdemodBI , 1, "Demodulate a FDX-B ISO11784/85 Biphase tag from GraphBuffer"}, {"fskawiddemod", CmdFSKdemodAWID, 1, "Demodulate an AWID FSK tag from GraphBuffer"}, //{"fskfcdetect", CmdFSKfcDetect, 1, "Try to detect the Field Clock of an FSK wave"}, {"fskhiddemod", CmdFSKdemodHID, 1, "Demodulate a HID FSK tag from GraphBuffer"}, @@ -2174,6 +2401,7 @@ static command_t CommandTable[] = {"getbitstream", CmdGetBitStream, 1, "Convert GraphBuffer's >=1 values to 1 and <1 to 0"}, {"grid", CmdGrid, 1, " -- overlay grid on graph window, use zero value to turn off either"}, {"hexsamples", CmdHexsamples, 0, " [] -- Dump big buffer as hex bytes"}, + {"hex2bin", Cmdhex2bin, 1, "hex2bin -- Converts hexadecimal to binary"}, {"hide", CmdHide, 1, "Hide graph window"}, {"hpf", CmdHpf, 1, "Remove DC offset from trace"}, {"load", CmdLoad, 1, " -- Load trace (to graph window"}, @@ -2182,14 +2410,14 @@ static command_t CommandTable[] = {"manrawdecode", Cmdmandecoderaw, 1, "[invert] [maxErr] -- Manchester decode binary stream in DemodBuffer"}, {"norm", CmdNorm, 1, "Normalize max/min to +/-128"}, {"plot", CmdPlot, 1, "Show graph window (hit 'h' in window for keystroke help)"}, - {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] -- print the data in the DemodBuffer - 'x' for hex output"}, + {"printdemodbuffer",CmdPrintDemodBuff, 1, "[x] [o] [l] -- print the data in the DemodBuffer - 'x' for hex output"}, {"pskindalademod", CmdIndalaDecode, 1, "[clock] [invert<0|1>] -- Demodulate an indala tag (PSK1) from GraphBuffer (args optional)"}, {"psknexwatchdemod",CmdPSKNexWatch, 1, "Demodulate a NexWatch tag (nexkey, quadrakey) (PSK1) from GraphBuffer"}, {"rawdemod", CmdRawDemod, 1, "[modulation] ... -see help (h option) -- Demodulate the data in the GraphBuffer and output binary"}, {"samples", CmdSamples, 0, "[512 - 40000] -- Get raw samples for graph window (GraphBuffer)"}, {"save", CmdSave, 1, " -- Save trace (from graph window)"}, {"scale", CmdScale, 1, " -- Set cursor display scale"}, - {"setdebugmode", CmdSetDebugMode, 1, "<0|1> -- Turn on or off Debugging Mode for demods"}, + {"setdebugmode", CmdSetDebugMode, 1, "<0|1|2> -- Turn on or off Debugging Level for lf demods"}, {"shiftgraphzero", CmdGraphShiftZero, 1, " -- Shift 0 for Graphed wave + or - shift value"}, {"dirthreshold", CmdDirectionalThreshold, 1, " -- Max rising higher up-thres/ Min falling lower down-thres, keep rest as prev."}, {"tune", CmdTuneSamples, 0, "Get hw tune samples for graph window"}, diff --git a/client/cmddata.h b/client/cmddata.h index c6230736..20bdbd2b 100644 --- a/client/cmddata.h +++ b/client/cmddata.h @@ -17,6 +17,7 @@ int CmdData(const char *Cmd); void printDemodBuff(void); void setDemodBuf(uint8_t *buff, size_t size, size_t startIdx); int CmdAskEM410xDemod(const char *Cmd); +int CmdVikingDemod(const char *Cmd); int CmdG_Prox_II_Demod(const char *Cmd); int Cmdaskrawdemod(const char *Cmd); int Cmdaskmandemod(const char *Cmd); @@ -27,6 +28,7 @@ int CmdBitsamples(const char *Cmd); int CmdBuffClear(const char *Cmd); int CmdDec(const char *Cmd); int CmdDetectClockRate(const char *Cmd); +int CmdFDXBdemodBI(const char *Cmd); int CmdFSKdemodAWID(const char *Cmd); int CmdFSKdemodHID(const char *Cmd); int CmdFSKdemodIO(const char *Cmd); @@ -61,6 +63,7 @@ int AskEm410xDecode(bool verbose, uint32_t *hi, uint64_t *lo ); int AskEm410xDemod(const char *Cmd, uint32_t *hi, uint64_t *lo, bool verbose); int ASKbiphaseDemod(const char *Cmd, bool verbose); int ASKDemod(const char *Cmd, bool verbose, bool emSearch, uint8_t askType); +int ASKDemod_ext(const char *Cmd, bool verbose, bool emSearch, uint8_t askType, bool *stCheck); int FSKrawDemod(const char *Cmd, bool verbose); int PSKDemod(const char *Cmd, bool verbose); int NRZrawDemod(const char *Cmd, bool verbose); diff --git a/client/cmdhf.c b/client/cmdhf.c index 16f7bb0f..e3671a42 100644 --- a/client/cmdhf.c +++ b/client/cmdhf.c @@ -23,6 +23,7 @@ #include "cmdhficlass.h" #include "cmdhfmf.h" #include "cmdhfmfu.h" +#include "cmdhftopaz.h" #include "protocols.h" static int CmdHelp(const char *Cmd); @@ -187,6 +188,26 @@ void annotateIso15693(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) } } + +void annotateTopaz(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) +{ + switch(cmd[0]) { + case TOPAZ_REQA :snprintf(exp, size, "REQA");break; + case TOPAZ_WUPA :snprintf(exp, size, "WUPA");break; + case TOPAZ_RID :snprintf(exp, size, "RID");break; + case TOPAZ_RALL :snprintf(exp, size, "RALL");break; + case TOPAZ_READ :snprintf(exp, size, "READ");break; + case TOPAZ_WRITE_E :snprintf(exp, size, "WRITE-E");break; + case TOPAZ_WRITE_NE :snprintf(exp, size, "WRITE-NE");break; + case TOPAZ_RSEG :snprintf(exp, size, "RSEG");break; + case TOPAZ_READ8 :snprintf(exp, size, "READ8");break; + case TOPAZ_WRITE_E8 :snprintf(exp, size, "WRITE-E8");break; + case TOPAZ_WRITE_NE8 :snprintf(exp, size, "WRITE-NE8");break; + default: snprintf(exp,size,"?"); break; + } +} + + /** 06 00 = INITIATE 0E xx = SELECT ID (xx = Chip-ID) @@ -218,7 +239,34 @@ void annotateIso14443b(char *exp, size_t size, uint8_t* cmd, uint8_t cmdsize) } /** - * @brief iso14443B_CRC_Ok Checks CRC in command or response + * @brief iso14443A_CRC_check Checks CRC in command or response + * @param isResponse + * @param data + * @param len + * @return 0 : CRC-command, CRC not ok + * 1 : CRC-command, CRC ok + * 2 : Not crc-command + */ + +uint8_t iso14443A_CRC_check(bool isResponse, uint8_t* data, uint8_t len) +{ + uint8_t b1,b2; + + if(len <= 2) return 2; + + if(isResponse & (len < 6)) return 2; + + ComputeCrc14443(CRC_14443_A, data, len-2, &b1, &b2); + if (b1 != data[len-2] || b2 != data[len-1]) { + return 0; + } else { + return 1; + } +} + + +/** + * @brief iso14443B_CRC_check Checks CRC in command or response * @param isResponse * @param data * @param len @@ -235,9 +283,10 @@ uint8_t iso14443B_CRC_check(bool isResponse, uint8_t* data, uint8_t len) ComputeCrc14443(CRC_14443_B, data, len-2, &b1, &b2); if(b1 != data[len-2] || b2 != data[len-1]) { - return 0; + return 0; + } else { + return 1; } - return 1; } /** @@ -301,11 +350,66 @@ uint8_t iclass_CRC_check(bool isResponse, uint8_t* data, uint8_t len) } } -uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles) + +bool is_last_record(uint16_t tracepos, uint8_t *trace, uint16_t traceLen) +{ + return(tracepos + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) >= traceLen); +} + + +bool next_record_is_response(uint16_t tracepos, uint8_t *trace) { - bool isResponse; - uint16_t duration, data_len, parity_len; + uint16_t next_records_datalen = *((uint16_t *)(trace + tracepos + sizeof(uint32_t) + sizeof(uint16_t))); + + return(next_records_datalen & 0x8000); +} + + +bool merge_topaz_reader_frames(uint32_t timestamp, uint32_t *duration, uint16_t *tracepos, uint16_t traceLen, uint8_t *trace, uint8_t *frame, uint8_t *topaz_reader_command, uint16_t *data_len) +{ + +#define MAX_TOPAZ_READER_CMD_LEN 16 + + uint32_t last_timestamp = timestamp + *duration; + + if ((*data_len != 1) || (frame[0] == TOPAZ_WUPA) || (frame[0] == TOPAZ_REQA)) return false; + + memcpy(topaz_reader_command, frame, *data_len); + + while (!is_last_record(*tracepos, trace, traceLen) && !next_record_is_response(*tracepos, trace)) { + uint32_t next_timestamp = *((uint32_t *)(trace + *tracepos)); + *tracepos += sizeof(uint32_t); + uint16_t next_duration = *((uint16_t *)(trace + *tracepos)); + *tracepos += sizeof(uint16_t); + uint16_t next_data_len = *((uint16_t *)(trace + *tracepos)) & 0x7FFF; + *tracepos += sizeof(uint16_t); + uint8_t *next_frame = (trace + *tracepos); + *tracepos += next_data_len; + if ((next_data_len == 1) && (*data_len + next_data_len <= MAX_TOPAZ_READER_CMD_LEN)) { + memcpy(topaz_reader_command + *data_len, next_frame, next_data_len); + *data_len += next_data_len; + last_timestamp = next_timestamp + next_duration; + } else { + // rewind and exit + *tracepos = *tracepos - next_data_len - sizeof(uint16_t) - sizeof(uint16_t) - sizeof(uint32_t); + break; + } + uint16_t next_parity_len = (next_data_len-1)/8 + 1; + *tracepos += next_parity_len; + } + *duration = last_timestamp - timestamp; + + return true; +} + + +uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, uint8_t protocol, bool showWaitCycles, bool markCRCBytes) +{ + bool isResponse; + uint16_t data_len, parity_len; + uint32_t duration; + uint8_t topaz_reader_command[9]; uint32_t timestamp, first_timestamp, EndOfTransmissionTimestamp; char explanation[30] = {0}; @@ -336,29 +440,31 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui uint8_t *parityBytes = trace + tracepos; tracepos += parity_len; + if (protocol == TOPAZ && !isResponse) { + // topaz reader commands come in 1 or 9 separate frames with 7 or 8 Bits each. + // merge them: + if (merge_topaz_reader_frames(timestamp, &duration, &tracepos, traceLen, trace, frame, topaz_reader_command, &data_len)) { + frame = topaz_reader_command; + } + } + //Check the CRC status uint8_t crcStatus = 2; if (data_len > 2) { - uint8_t b1, b2; - if(protocol == ICLASS) - { - crcStatus = iclass_CRC_check(isResponse, frame, data_len); - - }else if (protocol == ISO_14443B) - { - crcStatus = iso14443B_CRC_check(isResponse, frame, data_len); - } - else if (protocol == ISO_14443A){//Iso 14443a - - ComputeCrc14443(CRC_14443_A, frame, data_len-2, &b1, &b2); - - if (b1 != frame[data_len-2] || b2 != frame[data_len-1]) { - if(!(isResponse & (data_len < 6))) - { - crcStatus = 0; - } - } + switch (protocol) { + case ICLASS: + crcStatus = iclass_CRC_check(isResponse, frame, data_len); + break; + case ISO_14443B: + case TOPAZ: + crcStatus = iso14443B_CRC_check(isResponse, frame, data_len); + break; + case ISO_14443A: + crcStatus = iso14443A_CRC_check(isResponse, frame, data_len); + break; + default: + break; } } //0 CRC-command, CRC not ok @@ -378,21 +484,24 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui oddparity ^= (((frame[j] & 0xFF) >> k) & 0x01); } uint8_t parityBits = parityBytes[j>>3]; - if (isResponse && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { + if (protocol != ISO_14443B && (isResponse || protocol == ISO_14443A) && (oddparity != ((parityBits >> (7-(j&0x0007))) & 0x01))) { snprintf(line[j/16]+(( j % 16) * 4),110, "%02x! ", frame[j]); - } else { - snprintf(line[j/16]+(( j % 16) * 4),110, "%02x ", frame[j]); + snprintf(line[j/16]+(( j % 16) * 4), 110, " %02x ", frame[j]); } } - if(crcStatus == 1) - {//CRC-command - char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4)-1; - (*pos1) = '['; - char *pos2 = line[(data_len)/16]+(((data_len) % 16) * 4)-2; - (*pos2) = ']'; + + if (markCRCBytes) { + if(crcStatus == 0 || crcStatus == 1) + {//CRC-command + char *pos1 = line[(data_len-2)/16]+(((data_len-2) % 16) * 4); + (*pos1) = '['; + char *pos2 = line[(data_len)/16]+(((data_len) % 16) * 4); + sprintf(pos2, "%c", ']'); + } } + if(data_len == 0) { if(data_len == 0){ @@ -407,18 +516,19 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui if(!isResponse) { - if(protocol == ICLASS) - annotateIclass(explanation,sizeof(explanation),frame,data_len); - else if (protocol == ISO_14443A) - annotateIso14443a(explanation,sizeof(explanation),frame,data_len); - else if(protocol == ISO_14443B) - annotateIso14443b(explanation,sizeof(explanation),frame,data_len); + switch(protocol) { + case ICLASS: annotateIclass(explanation,sizeof(explanation),frame,data_len); break; + case ISO_14443A: annotateIso14443a(explanation,sizeof(explanation),frame,data_len); break; + case ISO_14443B: annotateIso14443b(explanation,sizeof(explanation),frame,data_len); break; + case TOPAZ: annotateTopaz(explanation,sizeof(explanation),frame,data_len); break; + default: break; + } } int num_lines = MIN((data_len - 1)/16 + 1, 16); for (int j = 0; j < num_lines ; j++) { if (j == 0) { - PrintAndLog(" %9d | %9d | %s | %-64s| %s| %s", + PrintAndLog(" %10d | %10d | %s |%-64s | %s| %s", (timestamp - first_timestamp), (EndOfTransmissionTimestamp - first_timestamp), (isResponse ? "Tag" : "Rdr"), @@ -426,26 +536,22 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); } else { - PrintAndLog(" | | | %-64s| %s| %s", + PrintAndLog(" | | |%-64s | %s| %s", line[j], - (j == num_lines-1)?crc:" ", + (j == num_lines-1) ? crc : " ", (j == num_lines-1) ? explanation : ""); } } - if (tracepos + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint16_t) > traceLen) return traceLen; + if (is_last_record(tracepos, trace, traceLen)) return traceLen; - bool next_isResponse = *((uint16_t *)(trace + tracepos + 6)) & 0x8000; - - if (showWaitCycles && !isResponse && next_isResponse) { + if (showWaitCycles && !isResponse && next_record_is_response(tracepos, trace)) { uint32_t next_timestamp = *((uint32_t *)(trace + tracepos)); - if (next_timestamp != 0x44444444) { - PrintAndLog(" %9d | %9d | %s | fdt (Frame Delay Time): %d", - (EndOfTransmissionTimestamp - first_timestamp), - (next_timestamp - first_timestamp), - " ", - (next_timestamp - EndOfTransmissionTimestamp)); - } + PrintAndLog(" %9d | %9d | %s | fdt (Frame Delay Time): %d", + (EndOfTransmissionTimestamp - first_timestamp), + (next_timestamp - first_timestamp), + " ", + (next_timestamp - EndOfTransmissionTimestamp)); } return tracepos; @@ -455,49 +561,52 @@ uint16_t printTraceLine(uint16_t tracepos, uint16_t traceLen, uint8_t *trace, ui int CmdHFList(const char *Cmd) { bool showWaitCycles = false; + bool markCRCBytes = false; char type[40] = {0}; int tlen = param_getstr(Cmd,0,type); - char param = param_getchar(Cmd, 1); + char param1 = param_getchar(Cmd, 1); + char param2 = param_getchar(Cmd, 2); bool errors = false; uint8_t protocol = 0; //Validate params - if(tlen == 0) - { + + if(tlen == 0) { errors = true; } - if(param == 'h' || (param !=0 && param != 'f')) - { + + if(param1 == 'h' + || (param1 != 0 && param1 != 'f' && param1 != 'c') + || (param2 != 0 && param2 != 'f' && param2 != 'c')) { errors = true; } - if(!errors) - { - if(strcmp(type, "iclass") == 0) - { + + if(!errors) { + if(strcmp(type, "iclass") == 0) { protocol = ICLASS; - }else if(strcmp(type, "14a") == 0) - { + } else if(strcmp(type, "14a") == 0) { protocol = ISO_14443A; - } - else if(strcmp(type, "14b") == 0) - { + } else if(strcmp(type, "14b") == 0) { protocol = ISO_14443B; - }else if(strcmp(type,"raw")== 0) - { + } else if(strcmp(type,"topaz")== 0) { + protocol = TOPAZ; + } else if(strcmp(type,"raw")== 0) { protocol = -1;//No crc, no annotations - }else{ + } else { errors = true; } } if (errors) { PrintAndLog("List protocol data in trace buffer."); - PrintAndLog("Usage: hf list [f]"); + PrintAndLog("Usage: hf list [f][c]"); PrintAndLog(" f - show frame delay times as well"); + PrintAndLog(" c - mark CRC bytes"); PrintAndLog("Supported values:"); PrintAndLog(" raw - just show raw data without annotations"); PrintAndLog(" 14a - interpret data as iso14443a communications"); PrintAndLog(" 14b - interpret data as iso14443b communications"); PrintAndLog(" iclass - interpret data as iclass communications"); + PrintAndLog(" topaz - interpret data as topaz communications"); PrintAndLog(""); PrintAndLog("example: hf list 14a f"); PrintAndLog("example: hf list iclass"); @@ -505,10 +614,13 @@ int CmdHFList(const char *Cmd) } - if (param == 'f') { + if (param1 == 'f' || param2 == 'f') { showWaitCycles = true; } + if (param1 == 'c' || param2 == 'c') { + markCRCBytes = true; + } uint8_t *trace; uint16_t tracepos = 0; @@ -537,12 +649,12 @@ int CmdHFList(const char *Cmd) PrintAndLog("iso14443a - All times are in carrier periods (1/13.56Mhz)"); PrintAndLog("iClass - Timings are not as accurate"); PrintAndLog(""); - PrintAndLog(" Start | End | Src | Data (! denotes parity error) | CRC | Annotation |"); - PrintAndLog("-----------|-----------|-----|-----------------------------------------------------------------|-----|--------------------|"); + PrintAndLog(" Start | End | Src | Data (! denotes parity error) | CRC | Annotation |"); + PrintAndLog("------------|------------|-----|-----------------------------------------------------------------|-----|--------------------|"); while(tracepos < traceLen) { - tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles); + tracepos = printTraceLine(tracepos, traceLen, trace, protocol, showWaitCycles, markCRCBytes); } free(trace); @@ -556,41 +668,51 @@ int CmdHFSearch(const char *Cmd){ if (ans > 0) { PrintAndLog("\nValid ISO14443A Tag Found - Quiting Search\n"); return ans; - } + } ans = HFiClassReader("", false, false); if (ans) { PrintAndLog("\nValid iClass Tag (or PicoPass Tag) Found - Quiting Search\n"); return ans; } + ans = HF14BInfo(false); + if (ans) { + PrintAndLog("\nValid ISO14443B Tag Found - Quiting Search\n"); + return ans; + } ans = HF15Reader("", false); if (ans) { PrintAndLog("\nValid ISO15693 Tag Found - Quiting Search\n"); return ans; } + PrintAndLog("\nno known/supported 13.56 MHz tags found\n"); + return 0; +} - - //14b has issues currently... - //ans = CmdHF14BRead(Cmd); - //if (ans > 0) return ans; - +int CmdHFSnoop(const char *Cmd) +{ + char * pEnd; + UsbCommand c = {CMD_HF_SNIFFER, {strtol(Cmd, &pEnd,0),strtol(pEnd, &pEnd,0),0}}; + SendCommand(&c); return 0; } static command_t CommandTable[] = { - {"help", CmdHelp, 1, "This help"}, - {"14a", CmdHF14A, 1, "{ ISO14443A RFIDs... }"}, - {"14b", CmdHF14B, 1, "{ ISO14443B RFIDs... }"}, - {"15", CmdHF15, 1, "{ ISO15693 RFIDs... }"}, - {"epa", CmdHFEPA, 1, "{ German Identification Card... }"}, - {"legic", CmdHFLegic, 0, "{ LEGIC RFIDs... }"}, - {"iclass", CmdHFiClass, 1, "{ ICLASS RFIDs... }"}, - {"mf", CmdHFMF, 1, "{ MIFARE RFIDs... }"}, - {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, - {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, - {"list", CmdHFList, 1, "List protocol data in trace buffer"}, - {"search", CmdHFSearch, 1, "Search for known HF tags [preliminary]"}, - {NULL, NULL, 0, NULL} + {"help", CmdHelp, 1, "This help"}, + {"14a", CmdHF14A, 1, "{ ISO14443A RFIDs... }"}, + {"14b", CmdHF14B, 1, "{ ISO14443B RFIDs... }"}, + {"15", CmdHF15, 1, "{ ISO15693 RFIDs... }"}, + {"epa", CmdHFEPA, 1, "{ German Identification Card... }"}, + {"legic", CmdHFLegic, 0, "{ LEGIC RFIDs... }"}, + {"iclass", CmdHFiClass, 1, "{ ICLASS RFIDs... }"}, + {"mf", CmdHFMF, 1, "{ MIFARE RFIDs... }"}, + {"mfu", CmdHFMFUltra, 1, "{ MIFARE Ultralight RFIDs... }"}, + {"topaz", CmdHFTopaz, 1, "{ TOPAZ (NFC Type 1) RFIDs... }"}, + {"tune", CmdHFTune, 0, "Continuously measure HF antenna tuning"}, + {"list", CmdHFList, 1, "List protocol data in trace buffer"}, + {"search", CmdHFSearch, 1, "Search for known HF tags [preliminary]"}, + {"snoop", CmdHFSnoop, 0, " Generic HF Snoop"}, + {NULL, NULL, 0, NULL} }; int CmdHF(const char *Cmd) diff --git a/client/cmdhf14a.c b/client/cmdhf14a.c index 9a761864..81716db3 100644 --- a/client/cmdhf14a.c +++ b/client/cmdhf14a.c @@ -141,7 +141,7 @@ int CmdHF14AReader(const char *Cmd) iso14a_card_select_t card; memcpy(&card, (iso14a_card_select_t *)resp.d.asBytes, sizeof(iso14a_card_select_t)); - uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS + uint64_t select_status = resp.arg[0]; // 0: couldn't read, 1: OK, with ATS, 2: OK, no ATS, 3: proprietary Anticollision if(select_status == 0) { if (Cmd[0] != 's') PrintAndLog("iso14443a card select failed"); @@ -352,16 +352,16 @@ int CmdHF14AReader(const char *Cmd) PrintAndLog(" x0 -> <1 kByte"); break; case 0x01: - PrintAndLog(" x0 -> 1 kByte"); + PrintAndLog(" x1 -> 1 kByte"); break; case 0x02: - PrintAndLog(" x0 -> 2 kByte"); + PrintAndLog(" x2 -> 2 kByte"); break; case 0x03: - PrintAndLog(" x0 -> 4 kByte"); + PrintAndLog(" x3 -> 4 kByte"); break; case 0x04: - PrintAndLog(" x0 -> 8 kByte"); + PrintAndLog(" x4 -> 8 kByte"); break; } switch (card.ats[pos + 3] & 0xf0) { @@ -565,20 +565,22 @@ int CmdHF14ASnoop(const char *Cmd) { return 0; } + int CmdHF14ACmdRaw(const char *cmd) { UsbCommand c = {CMD_READER_ISO_14443a, {0, 0, 0}}; - uint8_t reply=1; - uint8_t crc=0; - uint8_t power=0; - uint8_t active=0; - uint8_t active_select=0; - uint16_t numbits=0; - uint32_t timeout=0; - uint8_t bTimeout=0; + bool reply=1; + bool crc = FALSE; + bool power = FALSE; + bool active = FALSE; + bool active_select = FALSE; + uint16_t numbits = 0; + bool bTimeout = FALSE; + uint32_t timeout = 0; + bool topazmode = FALSE; char buf[5]=""; - int i=0; + int i = 0; uint8_t data[USB_CMD_DATA_SIZE]; - uint16_t datalen=0; + uint16_t datalen = 0; uint32_t temp; if (strlen(cmd)<2) { @@ -590,9 +592,11 @@ int CmdHF14ACmdRaw(const char *cmd) { PrintAndLog(" -s active signal field ON with select"); PrintAndLog(" -b number of bits to send. Useful for send partial byte"); PrintAndLog(" -t timeout in ms"); + PrintAndLog(" -T use Topaz protocol to send command"); return 0; } + // strip while (*cmd==' ' || *cmd=='\t') cmd++; @@ -601,19 +605,19 @@ int CmdHF14ACmdRaw(const char *cmd) { if (cmd[i]=='-') { switch (cmd[i+1]) { case 'r': - reply=0; + reply = FALSE; break; case 'c': - crc=1; + crc = TRUE; break; case 'p': - power=1; + power = TRUE; break; case 'a': - active=1; + active = TRUE; break; case 's': - active_select=1; + active_select = TRUE; break; case 'b': sscanf(cmd+i+2,"%d",&temp); @@ -623,13 +627,16 @@ int CmdHF14ACmdRaw(const char *cmd) { i-=2; break; case 't': - bTimeout=1; + bTimeout = TRUE; sscanf(cmd+i+2,"%d",&temp); timeout = temp; i+=3; while(cmd[i]!=' ' && cmd[i]!='\0') { i++; } i-=2; break; + case 'T': + topazmode = TRUE; + break; default: PrintAndLog("Invalid option"); return 0; @@ -659,10 +666,15 @@ int CmdHF14ACmdRaw(const char *cmd) { PrintAndLog("Invalid char on input"); return 0; } + if(crc && datalen>0 && datalen MAX_TIMEOUT) { timeout = MAX_TIMEOUT; @@ -683,11 +695,16 @@ int CmdHF14ACmdRaw(const char *cmd) { } c.arg[2] = 13560000 / 1000 / (8*16) * timeout; // timeout in ETUs (time to transfer 1 bit, approx. 9.4 us) } + if(power) c.arg[0] |= ISO14A_NO_DISCONNECT; - if(datalen>0) + + if(datalen > 0) c.arg[0] |= ISO14A_RAW; + if(topazmode) + c.arg[0] |= ISO14A_TOPAZMODE; + // Max buffer is USB_CMD_DATA_SIZE c.arg[1] = (datalen & 0xFFFF) | (numbits << 16); memcpy(c.d.asBytes,data,datalen); @@ -703,6 +720,7 @@ int CmdHF14ACmdRaw(const char *cmd) { return 0; } + static void waitCmd(uint8_t iSelect) { uint8_t *recv; @@ -712,7 +730,7 @@ static void waitCmd(uint8_t iSelect) if (WaitForResponseTimeout(CMD_ACK,&resp,1500)) { recv = resp.d.asBytes; uint8_t iLen = iSelect ? resp.arg[1] : resp.arg[0]; - PrintAndLog("received %i octets",iLen); + PrintAndLog("received %i octets", iLen); if(!iLen) return; hexout = (char *)malloc(iLen * 3 + 1); diff --git a/client/cmdhf14b.c b/client/cmdhf14b.c index 525ffcc6..36932cbd 100644 --- a/client/cmdhf14b.c +++ b/client/cmdhf14b.c @@ -22,157 +22,29 @@ #include "cmdparser.h" #include "cmdhf14b.h" #include "cmdmain.h" +#include "cmdhf14a.h" static int CmdHelp(const char *Cmd); -int CmdHF14BDemod(const char *Cmd) -{ - int i, j, iold; - int isum, qsum; - int outOfWeakAt; - bool negateI, negateQ; - - uint8_t data[256]; - int dataLen = 0; - - // As received, the samples are pairs, correlations against I and Q - // square waves. So estimate angle of initial carrier (or just - // quadrant, actually), and then do the demod. - - // First, estimate where the tag starts modulating. - for (i = 0; i < GraphTraceLen; i += 2) { - if (abs(GraphBuffer[i]) + abs(GraphBuffer[i + 1]) > 40) { - break; - } - } - if (i >= GraphTraceLen) { - PrintAndLog("too weak to sync"); - return 0; - } - PrintAndLog("out of weak at %d", i); - outOfWeakAt = i; - - // Now, estimate the phase in the initial modulation of the tag - isum = 0; - qsum = 0; - for (; i < (outOfWeakAt + 16); i += 2) { - isum += GraphBuffer[i + 0]; - qsum += GraphBuffer[i + 1]; - } - negateI = (isum < 0); - negateQ = (qsum < 0); - - // Turn the correlation pairs into soft decisions on the bit. - j = 0; - for (i = 0; i < GraphTraceLen / 2; i++) { - int si = GraphBuffer[j]; - int sq = GraphBuffer[j + 1]; - if (negateI) si = -si; - if (negateQ) sq = -sq; - GraphBuffer[i] = si + sq; - j += 2; - } - GraphTraceLen = i; - - i = outOfWeakAt / 2; - while (GraphBuffer[i] > 0 && i < GraphTraceLen) - i++; - if (i >= GraphTraceLen) goto demodError; - - iold = i; - while (GraphBuffer[i] < 0 && i < GraphTraceLen) - i++; - if (i >= GraphTraceLen) goto demodError; - if ((i - iold) > 23) goto demodError; - - PrintAndLog("make it to demod loop"); - - for (;;) { - iold = i; - while (GraphBuffer[i] >= 0 && i < GraphTraceLen) - i++; - if (i >= GraphTraceLen) goto demodError; - if ((i - iold) > 6) goto demodError; - - uint16_t shiftReg = 0; - if (i + 20 >= GraphTraceLen) goto demodError; - - for (j = 0; j < 10; j++) { - int soft = GraphBuffer[i] + GraphBuffer[i + 1]; - - if (abs(soft) < (abs(isum) + abs(qsum)) / 20) { - PrintAndLog("weak bit"); - } - - shiftReg >>= 1; - if(GraphBuffer[i] + GraphBuffer[i+1] >= 0) { - shiftReg |= 0x200; - } - - i+= 2; - } - - if ((shiftReg & 0x200) && !(shiftReg & 0x001)) - { - // valid data byte, start and stop bits okay - PrintAndLog(" %02x", (shiftReg >> 1) & 0xff); - data[dataLen++] = (shiftReg >> 1) & 0xff; - if (dataLen >= sizeof(data)) { - return 0; - } - } else if (shiftReg == 0x000) { - // this is EOF - break; - } else { - goto demodError; - } - } - - uint8_t first, second; - ComputeCrc14443(CRC_14443_B, data, dataLen-2, &first, &second); - PrintAndLog("CRC: %02x %02x (%s)\n", first, second, - (first == data[dataLen-2] && second == data[dataLen-1]) ? - "ok" : "****FAIL****"); - - RepaintGraphWindow(); - return 0; - -demodError: - PrintAndLog("demod error"); - RepaintGraphWindow(); - return 0; -} - int CmdHF14BList(const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list 14b' instead"); return 0; } -int CmdHF14BRead(const char *Cmd) -{ - UsbCommand c = {CMD_ACQUIRE_RAW_ADC_SAMPLES_ISO_14443, {strtol(Cmd, NULL, 0), 0, 0}}; - SendCommand(&c); - return 0; -} -int CmdHF14Sim(const char *Cmd) +int CmdHF14BSim(const char *Cmd) { - UsbCommand c={CMD_SIMULATE_TAG_ISO_14443}; - SendCommand(&c); - return 0; -} - -int CmdHFSimlisten(const char *Cmd) -{ - UsbCommand c = {CMD_SIMULATE_TAG_HF_LISTEN}; + UsbCommand c={CMD_SIMULATE_TAG_ISO_14443B}; + clearCommandBuffer(); SendCommand(&c); return 0; } int CmdHF14BSnoop(const char *Cmd) { - UsbCommand c = {CMD_SNOOP_ISO_14443}; + UsbCommand c = {CMD_SNOOP_ISO_14443B}; + clearCommandBuffer(); SendCommand(&c); return 0; } @@ -184,6 +56,7 @@ int CmdHF14BSnoop(const char *Cmd) int CmdSri512Read(const char *Cmd) { UsbCommand c = {CMD_READ_SRI512_TAG, {strtol(Cmd, NULL, 0), 0, 0}}; + clearCommandBuffer(); SendCommand(&c); return 0; } @@ -195,127 +68,559 @@ int CmdSri512Read(const char *Cmd) int CmdSrix4kRead(const char *Cmd) { UsbCommand c = {CMD_READ_SRIX4K_TAG, {strtol(Cmd, NULL, 0), 0, 0}}; + clearCommandBuffer(); SendCommand(&c); return 0; } -int CmdHF14BCmdRaw (const char *cmd) { - UsbCommand resp; - uint8_t *recv; - UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; // len,recv? - uint8_t reply=1; - uint8_t crc=0; - uint8_t power=0; - char buf[5]=""; - int i=0; - uint8_t data[100] = {0x00}; - unsigned int datalen=0, temp; - char *hexout; - - if (strlen(cmd)<3) { - PrintAndLog("Usage: hf 14b raw [-r] [-c] [-p] <0A 0B 0C ... hex>"); - PrintAndLog(" -r do not read response"); - PrintAndLog(" -c calculate and append CRC"); - PrintAndLog(" -p leave the field on after receive"); - return 0; - } - - // strip - while (*cmd==' ' || *cmd=='\t') cmd++; - - while (cmd[i]!='\0') { - if (cmd[i]==' ' || cmd[i]=='\t') { i++; continue; } - if (cmd[i]=='-') { - switch (cmd[i+1]) { - case 'r': - case 'R': - reply=0; - break; - case 'c': - case 'C': - crc=1; - break; - case 'p': - case 'P': - power=1; - break; - default: - PrintAndLog("Invalid option"); - return 0; - } - i+=2; - continue; - } - if ((cmd[i]>='0' && cmd[i]<='9') || - (cmd[i]>='a' && cmd[i]<='f') || - (cmd[i]>='A' && cmd[i]<='F') ) { - buf[strlen(buf)+1]=0; - buf[strlen(buf)]=cmd[i]; - i++; - - if (strlen(buf)>=2) { - sscanf(buf,"%x",&temp); - data[datalen]=(uint8_t)(temp & 0xff); - datalen++; - *buf=0; - } - continue; - } - PrintAndLog("Invalid char on input"); - return 1; - } - if (datalen == 0) - { - PrintAndLog("Missing data input"); - return 0; - } - if(crc) - { - uint8_t first, second; - ComputeCrc14443(CRC_14443_B, data, datalen, &first, &second); - data[datalen++] = first; - data[datalen++] = second; - } - - c.arg[0] = datalen; - c.arg[1] = reply; - c.arg[2] = power; - memcpy(c.d.asBytes,data,datalen); - - SendCommand(&c); - - if (reply) { - if (WaitForResponseTimeout(CMD_ACK,&resp,1000)) { - recv = resp.d.asBytes; - PrintAndLog("received %i octets",resp.arg[0]); - if(!resp.arg[0]) - return 0; - hexout = (char *)malloc(resp.arg[0] * 3 + 1); - if (hexout != NULL) { - uint8_t first, second; - for (int i = 0; i < resp.arg[0]; i++) { // data in hex - sprintf(&hexout[i * 3], "%02X ", recv[i]); - } - PrintAndLog("%s", hexout); - free(hexout); - ComputeCrc14443(CRC_14443_B, recv, resp.arg[0]-2, &first, &second); - if(recv[resp.arg[0]-2]==first && recv[resp.arg[0]-1]==second) { - PrintAndLog("CRC OK"); - } else { - PrintAndLog("CRC failed"); - } - } else { - PrintAndLog("malloc failed your client has low memory?"); - } - } else { - PrintAndLog("timeout while waiting for reply."); - } - } // if reply - return 0; +int rawClose(void){ + UsbCommand resp; + UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; + clearCommandBuffer(); + SendCommand(&c); + if (!WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + return 0; + } + return 0; } -int CmdHF14BWrite( const char *Cmd){ +int HF14BCmdRaw(bool reply, bool *crc, bool power, uint8_t *data, uint8_t *datalen, bool verbose){ + UsbCommand resp; + UsbCommand c = {CMD_ISO_14443B_COMMAND, {0, 0, 0}}; // len,recv,power + if(*crc) + { + uint8_t first, second; + ComputeCrc14443(CRC_14443_B, data, *datalen, &first, &second); + data[*datalen] = first; + data[*datalen + 1] = second; + *datalen += 2; + } + + c.arg[0] = *datalen; + c.arg[1] = reply; + c.arg[2] = power; + memcpy(c.d.asBytes,data,*datalen); + clearCommandBuffer(); + SendCommand(&c); + + if (!reply) return 1; + + if (!WaitForResponseTimeout(CMD_ACK,&resp,1000)) { + if (verbose) PrintAndLog("timeout while waiting for reply."); + return 0; + } + *datalen = resp.arg[0]; + if (verbose) PrintAndLog("received %u octets", *datalen); + if(*datalen<2) return 0; + + memcpy(data, resp.d.asBytes, *datalen); + if (verbose) PrintAndLog("%s", sprint_hex(data, *datalen)); + + uint8_t first, second; + ComputeCrc14443(CRC_14443_B, data, *datalen-2, &first, &second); + if(data[*datalen-2] == first && data[*datalen-1] == second) { + if (verbose) PrintAndLog("CRC OK"); + *crc = true; + } else { + if (verbose) PrintAndLog("CRC failed"); + *crc = false; + } + return 1; +} + +int CmdHF14BCmdRaw (const char *Cmd) { + bool reply = true; + bool crc = false; + bool power = false; + bool select = false; + bool SRx = false; + char buf[5] = ""; + uint8_t data[100] = {0x00}; + uint8_t datalen = 0; + unsigned int temp; + int i = 0; + if (strlen(Cmd)<3) { + PrintAndLog("Usage: hf 14b raw [-r] [-c] [-p] [-s || -ss] <0A 0B 0C ... hex>"); + PrintAndLog(" -r do not read response"); + PrintAndLog(" -c calculate and append CRC"); + PrintAndLog(" -p leave the field on after receive"); + PrintAndLog(" -s active signal field ON with select"); + PrintAndLog(" -ss active signal field ON with select for SRx ST Microelectronics tags"); + return 0; + } + + // strip + while (*Cmd==' ' || *Cmd=='\t') Cmd++; + + while (Cmd[i]!='\0') { + if (Cmd[i]==' ' || Cmd[i]=='\t') { i++; continue; } + if (Cmd[i]=='-') { + switch (Cmd[i+1]) { + case 'r': + case 'R': + reply = false; + break; + case 'c': + case 'C': + crc = true; + break; + case 'p': + case 'P': + power = true; + break; + case 's': + case 'S': + select = true; + if (Cmd[i+2]=='s' || Cmd[i+2]=='S') { + SRx = true; + i++; + } + break; + default: + PrintAndLog("Invalid option"); + return 0; + } + i+=2; + continue; + } + if ((Cmd[i]>='0' && Cmd[i]<='9') || + (Cmd[i]>='a' && Cmd[i]<='f') || + (Cmd[i]>='A' && Cmd[i]<='F') ) { + buf[strlen(buf)+1]=0; + buf[strlen(buf)]=Cmd[i]; + i++; + + if (strlen(buf)>=2) { + sscanf(buf,"%x",&temp); + data[datalen++]=(uint8_t)(temp & 0xff); + *buf=0; + } + continue; + } + PrintAndLog("Invalid char on input"); + return 0; + } + if (datalen == 0) + { + PrintAndLog("Missing data input"); + return 0; + } + + if (select){ //auto select 14b tag + uint8_t cmd2[16]; + bool crc2 = true; + uint8_t cmdLen; + + if (SRx) { + // REQ SRx + cmdLen = 2; + cmd2[0] = 0x06; + cmd2[1] = 0x00; + } else { + cmdLen = 3; + // REQB + cmd2[0] = 0x05; + cmd2[1] = 0x00; + cmd2[2] = 0x08; + } + + if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + + if ( SRx && (cmdLen != 3 || !crc2) ) return rawClose(); + else if (cmd2[0] != 0x50 || cmdLen != 14 || !crc2) return rawClose(); + + uint8_t chipID = 0; + if (SRx) { + // select + chipID = cmd2[0]; + cmd2[0] = 0x0E; + cmd2[1] = chipID; + cmdLen = 2; + } else { + // attrib + cmd2[0] = 0x1D; + // UID from cmd2[1 - 4] + cmd2[5] = 0x00; + cmd2[6] = 0x08; + cmd2[7] = 0x01; + cmd2[8] = 0x00; + cmdLen = 9; + } + + if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + + if (cmdLen != 3 || !crc2) return rawClose(); + if (SRx && cmd2[0] != chipID) return rawClose(); + } + return HF14BCmdRaw(reply, &crc, power, data, &datalen, true); +} + +// print full atqb info +static void print_atqb_resp(uint8_t *data){ + //PrintAndLog (" UID: %s", sprint_hex(data+1,4)); + PrintAndLog (" App Data: %s", sprint_hex(data+5,4)); + PrintAndLog (" Protocol: %s", sprint_hex(data+9,3)); + uint8_t BitRate = data[9]; + if (!BitRate) + PrintAndLog (" Bit Rate: 106 kbit/s only PICC <-> PCD"); + if (BitRate & 0x10) + PrintAndLog (" Bit Rate: 212 kbit/s PICC -> PCD supported"); + if (BitRate & 0x20) + PrintAndLog (" Bit Rate: 424 kbit/s PICC -> PCD supported"); + if (BitRate & 0x40) + PrintAndLog (" Bit Rate: 847 kbit/s PICC -> PCD supported"); + if (BitRate & 0x01) + PrintAndLog (" Bit Rate: 212 kbit/s PICC <- PCD supported"); + if (BitRate & 0x02) + PrintAndLog (" Bit Rate: 424 kbit/s PICC <- PCD supported"); + if (BitRate & 0x04) + PrintAndLog (" Bit Rate: 847 kbit/s PICC <- PCD supported"); + if (BitRate & 0x80) + PrintAndLog (" Same bit rate <-> required"); + + uint16_t maxFrame = data[10]>>4; + if (maxFrame < 5) + maxFrame = 8*maxFrame + 16; + else if (maxFrame == 5) + maxFrame = 64; + else if (maxFrame == 6) + maxFrame = 96; + else if (maxFrame == 7) + maxFrame = 128; + else if (maxFrame == 8) + maxFrame = 256; + else + maxFrame = 257; + + PrintAndLog ("Max Frame Size: %u%s",maxFrame, (maxFrame == 257) ? "+ RFU" : ""); + + uint8_t protocolT = data[10] & 0xF; + PrintAndLog (" Protocol Type: Protocol is %scompliant with ISO/IEC 14443-4",(protocolT) ? "" : "not " ); + PrintAndLog ("Frame Wait Int: %u", data[11]>>4); + PrintAndLog (" App Data Code: Application is %s",(data[11]&4) ? "Standard" : "Proprietary"); + PrintAndLog (" Frame Options: NAD is %ssupported",(data[11]&2) ? "" : "not "); + PrintAndLog (" Frame Options: CID is %ssupported",(data[11]&1) ? "" : "not "); + PrintAndLog ("Max Buf Length: %u (MBLI) %s",data[14]>>4, (data[14] & 0xF0) ? "" : "not supported"); + + return; +} + +// get SRx chip model (from UID) // from ST Microelectronics +char *get_ST_Chip_Model(uint8_t data){ + static char model[20]; + char *retStr = model; + memset(model,0, sizeof(model)); + + switch (data) { + case 0x0: sprintf(retStr, "SRIX4K (Special)"); break; + case 0x2: sprintf(retStr, "SR176"); break; + case 0x3: sprintf(retStr, "SRIX4K"); break; + case 0x4: sprintf(retStr, "SRIX512"); break; + case 0x6: sprintf(retStr, "SRI512"); break; + case 0x7: sprintf(retStr, "SRI4K"); break; + case 0xC: sprintf(retStr, "SRT512"); break; + default : sprintf(retStr, "Unknown"); break; + } + return retStr; +} + +int print_ST_Lock_info(uint8_t model){ + //assume connection open and tag selected... + uint8_t data[16] = {0x00}; + uint8_t datalen = 2; + bool crc = true; + uint8_t resplen; + uint8_t blk1; + data[0] = 0x08; + + if (model == 0x2) { //SR176 has special command: + data[1] = 0xf; + resplen = 4; + } else { + data[1] = 0xff; + resplen = 6; + } + + //std read cmd + if (HF14BCmdRaw(true, &crc, true, data, &datalen, false)==0) return rawClose(); + + if (datalen != resplen || !crc) return rawClose(); + + PrintAndLog("Chip Write Protection Bits:"); + // now interpret the data + switch (model){ + case 0x0: //fall through (SRIX4K special) + case 0x3: //fall through (SRIx4K) + case 0x7: // (SRI4K) + //only need data[3] + blk1 = 9; + PrintAndLog(" raw: %s",printBits(1,data+3)); + PrintAndLog(" 07/08:%slocked", (data[3] & 1) ? " not " : " " ); + for (uint8_t i = 1; i<8; i++){ + PrintAndLog(" %02u:%slocked", blk1, (data[3] & (1 << i)) ? " not " : " " ); + blk1++; + } + break; + case 0x4: //fall through (SRIX512) + case 0x6: //fall through (SRI512) + case 0xC: // (SRT512) + //need data[2] and data[3] + blk1 = 0; + PrintAndLog(" raw: %s",printBits(2,data+2)); + for (uint8_t b=2; b<4; b++){ + for (uint8_t i=0; i<8; i++){ + PrintAndLog(" %02u:%slocked", blk1, (data[b] & (1 << i)) ? " not " : " " ); + blk1++; + } + } + break; + case 0x2: // (SR176) + //need data[2] + blk1 = 0; + PrintAndLog(" raw: %s",printBits(1,data+2)); + for (uint8_t i = 0; i<8; i++){ + PrintAndLog(" %02u/%02u:%slocked", blk1, blk1+1, (data[2] & (1 << i)) ? " " : " not " ); + blk1+=2; + } + break; + default: + return rawClose(); + } + return 1; +} + +// print UID info from SRx chips (ST Microelectronics) +static void print_st_general_info(uint8_t *data){ + //uid = first 8 bytes in data + PrintAndLog(" UID: %s", sprint_hex(SwapEndian64(data,8,8),8)); + PrintAndLog(" MFG: %02X, %s", data[6], getTagInfo(data[6])); + PrintAndLog(" Chip: %02X, %s", data[5]>>2, get_ST_Chip_Model(data[5]>>2)); + return; +} + +// 14b get and print UID only (general info) +int HF14BStdReader(uint8_t *data, uint8_t *datalen){ + //05 00 00 = find one tag in field + //1d xx xx xx xx 00 08 01 00 = attrib xx=UID (resp 10 [f9 e0]) + //a3 = ? (resp 03 [e2 c2]) + //02 = ? (resp 02 [6a d3]) + // 022b (resp 02 67 00 [29 5b]) + // 0200a40400 (resp 02 67 00 [29 5b]) + // 0200a4040c07a0000002480300 (resp 02 67 00 [29 5b]) + // 0200a4040c07a0000002480200 (resp 02 67 00 [29 5b]) + // 0200a4040006a0000000010100 (resp 02 6a 82 [4b 4c]) + // 0200a4040c09d27600002545500200 (resp 02 67 00 [29 5b]) + // 0200a404000cd2760001354b414e4d30310000 (resp 02 6a 82 [4b 4c]) + // 0200a404000ca000000063504b43532d313500 (resp 02 6a 82 [4b 4c]) + // 0200a4040010a000000018300301000000000000000000 (resp 02 6a 82 [4b 4c]) + //03 = ? (resp 03 [e3 c2]) + //c2 = ? (resp c2 [66 15]) + //b2 = ? (resp a3 [e9 67]) + //a2 = ? (resp 02 [6a d3]) + bool crc = true; + *datalen = 3; + //std read cmd + data[0] = 0x05; + data[1] = 0x00; + data[2] = 0x08; + + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (data[0] != 0x50 || *datalen != 14 || !crc) return rawClose(); + + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog (" UID: %s", sprint_hex(data+1,4)); + + uint8_t cmd2[16]; + uint8_t cmdLen = 3; + bool crc2 = true; + + cmd2[0] = 0x1D; + // UID from data[1 - 4] + cmd2[1] = data[1]; + cmd2[2] = data[2]; + cmd2[3] = data[3]; + cmd2[4] = data[4]; + cmd2[5] = 0x00; + cmd2[6] = 0x08; + cmd2[7] = 0x01; + cmd2[8] = 0x00; + cmdLen = 9; + + // attrib + if (HF14BCmdRaw(true, &crc2, true, cmd2, &cmdLen, false)==0) return rawClose(); + + if (cmdLen != 3 || !crc2) return rawClose(); + // add attrib responce to data + data[14] = cmd2[0]; + rawClose(); + return 1; +} + +// 14b get and print Full Info (as much as we know) +int HF14BStdInfo(uint8_t *data, uint8_t *datalen){ + if (!HF14BStdReader(data,datalen)) return 0; + + //add more info here + print_atqb_resp(data); + + + return 1; +} + +// SRx get and print general info about SRx chip from UID +int HF14B_ST_Reader(uint8_t *data, uint8_t *datalen, bool closeCon){ + bool crc = true; + *datalen = 2; + //wake cmd + data[0] = 0x06; + data[1] = 0x00; + + //leave power on + // verbose on for now for testing - turn off when functional + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (*datalen != 3 || !crc) return rawClose(); + + uint8_t chipID = data[0]; + // select + data[0] = 0x0E; + data[1] = chipID; + *datalen = 2; + + //leave power on + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (*datalen != 3 || !crc || data[0] != chipID) return rawClose(); + + // get uid + data[0] = 0x0B; + *datalen = 1; + + //leave power on + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)==0) return rawClose(); + + if (*datalen != 10 || !crc) return rawClose(); + + //power off ? + if (closeCon) rawClose(); + + PrintAndLog("\n14443-3b ST tag found:"); + print_st_general_info(data); + return 1; +} + +// SRx get and print full info (needs more info...) +int HF14B_ST_Info(uint8_t *data, uint8_t *datalen){ + if (!HF14B_ST_Reader(data, datalen, false)) return 0; + + //add locking bit information here. + if (print_ST_Lock_info(data[5]>>2)) + rawClose(); + + return 1; +} + +// test for other 14b type tags (mimic another reader - don't have tags to identify) +int HF14B_Other_Reader(uint8_t *data, uint8_t *datalen){ + bool crc = true; + *datalen = 4; + //std read cmd + data[0] = 0x00; + data[1] = 0x0b; + data[2] = 0x3f; + data[3] = 0x80; + + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { + if (*datalen > 2 || !crc) { + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog ("Unknown tag type answered to a 0x000b3f80 command ans:"); + PrintAndLog ("%s",sprint_hex(data,*datalen)); + rawClose(); + return 1; + } + } + + crc = false; + *datalen = 1; + data[0] = 0x0a; + + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { + if (*datalen > 0) { + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog ("Unknown tag type answered to a 0x0A command ans:"); + PrintAndLog ("%s",sprint_hex(data,*datalen)); + rawClose(); + return 1; + } + } + + crc = false; + *datalen = 1; + data[0] = 0x0c; + + if (HF14BCmdRaw(true, &crc, true, data, datalen, false)!=0) { + if (*datalen > 0) { + PrintAndLog ("\n14443-3b tag found:"); + PrintAndLog ("Unknown tag type answered to a 0x0C command ans:"); + PrintAndLog ("%s",sprint_hex(data,*datalen)); + rawClose(); + return 1; + } + } + rawClose(); + return 0; +} + +// get and print all info known about any known 14b tag +int HF14BInfo(bool verbose){ + uint8_t data[100]; + uint8_t datalen = 5; + + // try std 14b (atqb) + if (HF14BStdInfo(data, &datalen)) return 1; + + // try st 14b + if (HF14B_ST_Info(data, &datalen)) return 1; + + // try unknown 14b read commands (to be identified later) + // could be read of calypso, CEPAS, moneo, or pico pass. + if (HF14B_Other_Reader(data, &datalen)) return 1; + + if (verbose) PrintAndLog("no 14443B tag found"); + return 0; +} + +// menu command to get and print all info known about any known 14b tag +int CmdHF14Binfo(const char *Cmd){ + return HF14BInfo(true); +} + +// get and print general info about all known 14b chips +int HF14BReader(bool verbose){ + uint8_t data[100]; + uint8_t datalen = 5; + + // try std 14b (atqb) + if (HF14BStdReader(data, &datalen)) return 1; + + // try st 14b + if (HF14B_ST_Reader(data, &datalen, true)) return 1; + + // try unknown 14b read commands (to be identified later) + // could be read of calypso, CEPAS, moneo, or pico pass. + if (HF14B_Other_Reader(data, &datalen)) return 1; + + if (verbose) PrintAndLog("no 14443B tag found"); + return 0; +} + +// menu command to get and print general info about all known 14b chips +int CmdHF14BReader(const char *Cmd){ + return HF14BReader(true); +} +int CmdSriWrite( const char *Cmd){ /* * For SRIX4K blocks 00 - 7F * hf 14b raw -c -p 09 $srix4kwblock $srix4kwdata @@ -385,16 +690,15 @@ int CmdHF14BWrite( const char *Cmd){ static command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, - {"demod", CmdHF14BDemod, 1, "Demodulate ISO14443 Type B from tag"}, - {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443b history"}, - {"read", CmdHF14BRead, 0, "Read HF tag (ISO 14443)"}, - {"sim", CmdHF14Sim, 0, "Fake ISO 14443 tag"}, - {"simlisten", CmdHFSimlisten, 0, "Get HF samples as fake tag"}, - {"snoop", CmdHF14BSnoop, 0, "Eavesdrop ISO 14443"}, + {"info", CmdHF14Binfo, 0, "Find and print details about a 14443B tag"}, + {"list", CmdHF14BList, 0, "[Deprecated] List ISO 14443B history"}, + {"reader", CmdHF14BReader, 0, "Act as a 14443B reader to identify a tag"}, + {"sim", CmdHF14BSim, 0, "Fake ISO 14443B tag"}, + {"snoop", CmdHF14BSnoop, 0, "Eavesdrop ISO 14443B"}, {"sri512read", CmdSri512Read, 0, "Read contents of a SRI512 tag"}, {"srix4kread", CmdSrix4kRead, 0, "Read contents of a SRIX4K tag"}, + {"sriwrite", CmdSriWrite, 0, "Write data to a SRI512 | SRIX4K tag"}, {"raw", CmdHF14BCmdRaw, 0, "Send raw hex data to tag"}, - {"write", CmdHF14BWrite, 0, "Write data to a SRI512 | SRIX4K tag"}, {NULL, NULL, 0, NULL} }; diff --git a/client/cmdhf14b.h b/client/cmdhf14b.h index cc8b9dbd..a45b7434 100644 --- a/client/cmdhf14b.h +++ b/client/cmdhf14b.h @@ -12,15 +12,13 @@ #define CMDHF14B_H__ int CmdHF14B(const char *Cmd); - -int CmdHF14BDemod(const char *Cmd); int CmdHF14BList(const char *Cmd); -int CmdHF14BRead(const char *Cmd); -int CmdHF14Sim(const char *Cmd); -int CmdHFSimlisten(const char *Cmd); +int CmdHF14BInfo(const char *Cmd); +int CmdHF14BSim(const char *Cmd); int CmdHF14BSnoop(const char *Cmd); int CmdSri512Read(const char *Cmd); int CmdSrix4kRead(const char *Cmd); int CmdHF14BWrite( const char *cmd); +int HF14BInfo(bool verbose); #endif diff --git a/client/cmdhfepa.c b/client/cmdhfepa.c index 3286ceb9..f9f69a88 100644 --- a/client/cmdhfepa.c +++ b/client/cmdhfepa.c @@ -9,7 +9,7 @@ //----------------------------------------------------------------------------- #include "util.h" -//#include "proxusb.h" + #include "proxmark3.h" #include "ui.h" #include "cmdparser.h" @@ -29,9 +29,9 @@ int CmdHFEPACollectPACENonces(const char *Cmd) unsigned int n = 0; // delay between requests unsigned int d = 0; - + sscanf(Cmd, "%u %u %u", &m, &n, &d); - + // values are expected to be > 0 m = m > 0 ? m : 1; n = n > 0 ? n : 1; @@ -44,7 +44,7 @@ int CmdHFEPACollectPACENonces(const char *Cmd) UsbCommand c = {CMD_EPA_PACE_COLLECT_NONCE, {(int)m, 0, 0}}; SendCommand(&c); UsbCommand resp; - + WaitForResponse(CMD_ACK,&resp); // check if command failed @@ -58,6 +58,7 @@ int CmdHFEPACollectPACENonces(const char *Cmd) } // print nonce PrintAndLog("Length: %d, Nonce: %s", nonce_length, nonce); + free(nonce); } if (i < n - 1) { sleep(d); @@ -68,13 +69,123 @@ int CmdHFEPACollectPACENonces(const char *Cmd) return 1; } +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +////////////////////////////////The commands lie below here///////////////////////////////////////////////////////////////////////////////////////// + +// perform the PACE protocol by replaying APDUs +int CmdHFEPAPACEReplay(const char *Cmd) +{ + // the 4 APDUs which are replayed + their lengths + uint8_t msesa_apdu[41], gn_apdu[8], map_apdu[75]; + uint8_t pka_apdu[75], ma_apdu[18], apdu_lengths[5] = {0}; + // pointers to the arrays to be able to iterate + uint8_t *apdus[] = {msesa_apdu, gn_apdu, map_apdu, pka_apdu, ma_apdu}; + + // usage message + static const char const *usage_msg = + "Please specify 5 APDUs separated by spaces. " + "Example:\n preplay 0022C1A4 1068000000 1086000002 1234ABCDEF 1A2B3C4D"; + + // Proxmark response + UsbCommand resp; + + int skip = 0, skip_add = 0, scan_return = 0; + // for each APDU + for (int i = 0; i < sizeof(apdu_lengths); i++) { + // scan to next space or end of string + while (Cmd[skip] != ' ' && Cmd[skip] != '\0') { + // convert + scan_return = sscanf(Cmd + skip, "%2X%n", + (unsigned int *) (apdus[i] + apdu_lengths[i]), + &skip_add); + if (scan_return < 1) { + PrintAndLog((char *)usage_msg); + PrintAndLog("Not enough APDUs! Try again!"); + return 0; + } + skip += skip_add; + apdu_lengths[i]++; + } + + // break on EOF + if (Cmd[skip] == '\0') { + if (i < sizeof(apdu_lengths) - 1) { + + PrintAndLog((char *)usage_msg); + return 0; + } + break; + } + // skip the space + skip++; + } + + // transfer the APDUs to the Proxmark + UsbCommand usb_cmd; + usb_cmd.cmd = CMD_EPA_PACE_REPLAY; + for (int i = 0; i < sizeof(apdu_lengths); i++) { + // APDU number + usb_cmd.arg[0] = i + 1; + // transfer the APDU in several parts if necessary + for (int j = 0; j * sizeof(usb_cmd.d.asBytes) < apdu_lengths[i]; j++) { + // offset into the APDU + usb_cmd.arg[1] = j * sizeof(usb_cmd.d.asBytes); + // amount of data in this packet + int packet_length = apdu_lengths[i] - (j * sizeof(usb_cmd.d.asBytes)); + if (packet_length > sizeof(usb_cmd.d.asBytes)) { + packet_length = sizeof(usb_cmd.d.asBytes); + } + usb_cmd.arg[2] = packet_length; + + memcpy(usb_cmd.d.asBytes, // + (j * sizeof(usb_cmd.d.asBytes)), + apdus[i] + (j * sizeof(usb_cmd.d.asBytes)), + packet_length); + SendCommand(&usb_cmd); + WaitForResponse(CMD_ACK, &resp); + if (resp.arg[0] != 0) { + PrintAndLog("Transfer of APDU #%d Part %d failed!", i, j); + return 0; + } + } + } + + // now perform the replay + usb_cmd.arg[0] = 0; + SendCommand(&usb_cmd); + WaitForResponse(CMD_ACK, &resp); + if (resp.arg[0] != 0) { + PrintAndLog("\nPACE replay failed in step %u!", (uint32_t)resp.arg[0]); + PrintAndLog("Measured times:"); + PrintAndLog("MSE Set AT: %u us", resp.d.asDwords[0]); + PrintAndLog("GA Get Nonce: %u us", resp.d.asDwords[1]); + PrintAndLog("GA Map Nonce: %u us", resp.d.asDwords[2]); + PrintAndLog("GA Perform Key Agreement: %u us", resp.d.asDwords[3]); + PrintAndLog("GA Mutual Authenticate: %u us", resp.d.asDwords[4]); + } else { + PrintAndLog("PACE replay successfull!"); + PrintAndLog("MSE Set AT: %u us", resp.d.asDwords[0]); + PrintAndLog("GA Get Nonce: %u us", resp.d.asDwords[1]); + PrintAndLog("GA Map Nonce: %u us", resp.d.asDwords[2]); + PrintAndLog("GA Perform Key Agreement: %u us", resp.d.asDwords[3]); + PrintAndLog("GA Mutual Authenticate: %u us", resp.d.asDwords[4]); + } + + + return 1; +} + +////////////////////////////////The new commands lie above here///////////////////////////////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// + // UI-related stuff -static const command_t CommandTable[] = +static const command_t CommandTable[] = { {"help", CmdHelp, 1, "This help"}, {"cnonces", CmdHFEPACollectPACENonces, 0, " Acquire n>0 encrypted PACE nonces of size m>0 with d sec pauses"}, + {"preplay", CmdHFEPAPACEReplay, 0, + " Perform PACE protocol by replaying given APDUs"}, {NULL, NULL, 0, NULL} }; @@ -92,4 +203,4 @@ int CmdHFEPA(const char *Cmd) // parse CmdsParse(CommandTable, Cmd); return 0; -} \ No newline at end of file +} diff --git a/client/cmdhficlass.c b/client/cmdhficlass.c index 824aaa36..309880d2 100644 --- a/client/cmdhficlass.c +++ b/client/cmdhficlass.c @@ -31,11 +31,27 @@ #include "loclass/fileutils.h" #include "protocols.h" #include "usb_cmd.h" +#include "cmdhfmfu.h" static int CmdHelp(const char *Cmd); -int xorbits_8(uint8_t val) -{ +#define ICLASS_KEYS_MAX 8 +static uint8_t iClass_Key_Table[ICLASS_KEYS_MAX][8] = { + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, + { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 } +}; + +typedef struct iclass_block { + uint8_t d[8]; +} iclass_block_t; + +int xorbits_8(uint8_t val) { uint8_t res = val ^ (val >> 1); //1st pass res = res ^ (res >> 1); // 2nd pass res = res ^ (res >> 2); // 3rd pass @@ -43,20 +59,18 @@ int xorbits_8(uint8_t val) return res & 1; } -int CmdHFiClassList(const char *Cmd) -{ +int CmdHFiClassList(const char *Cmd) { PrintAndLog("Deprecated command, use 'hf list iclass' instead"); return 0; } -int CmdHFiClassSnoop(const char *Cmd) -{ +int CmdHFiClassSnoop(const char *Cmd) { UsbCommand c = {CMD_SNOOP_ICLASS}; SendCommand(&c); return 0; } -int usage_hf_iclass_sim() -{ + +int usage_hf_iclass_sim(void) { PrintAndLog("Usage: hf iclass sim