1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, split Nov 2006
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
8 //-----------------------------------------------------------------------------
9 // Routines to support ISO 14443B. This includes both the reader software and
10 // the `fake tag' modes.
11 //-----------------------------------------------------------------------------
13 #include "iso14443b.h"
15 #include "proxmark3.h"
20 #include "iso14443crc.h"
21 #include "fpgaloader.h"
24 #define RECEIVE_SAMPLES_TIMEOUT 64 // TR0 max is 256/fs = 256/(848kHz) = 302us or 64 samples from FPGA
25 #define ISO14443B_DMA_BUFFER_SIZE 128
27 // PCB Block number for APDUs
28 static uint8_t pcb_blocknum
= 0;
30 //=============================================================================
31 // An ISO 14443 Type B tag. We listen for commands from the reader, using
32 // a UART kind of thing that's implemented in software. When we get a
33 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
34 // If it's good, then we can do something appropriate with it, and send
36 //=============================================================================
38 //-----------------------------------------------------------------------------
39 // Code up a string of octets at layer 2 (including CRC, we don't generate
40 // that here) so that they can be transmitted to the reader. Doesn't transmit
41 // them yet, just leaves them ready to send in ToSend[].
42 //-----------------------------------------------------------------------------
43 static void CodeIso14443bAsTag(const uint8_t *cmd
, int len
)
49 // Transmit a burst of ones, as the initial thing that lets the
50 // reader get phase sync. This (TR1) must be > 80/fs, per spec,
51 // but tag that I've tried (a Paypass) exceeds that by a fair bit,
53 for(i
= 0; i
< 20; i
++) {
61 for(i
= 0; i
< 10; i
++) {
67 for(i
= 0; i
< 2; i
++) {
74 for(i
= 0; i
< len
; i
++) {
85 for(j
= 0; j
< 8; j
++) {
108 for(i
= 0; i
< 10; i
++) {
114 for(i
= 0; i
< 2; i
++) {
121 // Convert from last byte pos to length
125 //-----------------------------------------------------------------------------
126 // The software UART that receives commands from the reader, and its state
128 //-----------------------------------------------------------------------------
132 STATE_GOT_FALLING_EDGE_OF_SOF
,
133 STATE_AWAITING_START_BIT
,
144 /* Receive & handle a bit coming from the reader.
146 * This function is called 4 times per bit (every 2 subcarrier cycles).
147 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
150 * LED A -> ON once we have received the SOF and are expecting the rest.
151 * LED A -> OFF once we have received EOF or are in error state or unsynced
153 * Returns: true if we received a EOF
154 * false if we are still waiting for some more
156 static RAMFUNC
int Handle14443bUartBit(uint8_t bit
)
161 // we went low, so this could be the beginning
163 Uart
.state
= STATE_GOT_FALLING_EDGE_OF_SOF
;
169 case STATE_GOT_FALLING_EDGE_OF_SOF
:
171 if(Uart
.posCnt
== 2) { // sample every 4 1/fs in the middle of a bit
173 if(Uart
.bitCnt
> 9) {
174 // we've seen enough consecutive
175 // zeros that it's a valid SOF
178 Uart
.state
= STATE_AWAITING_START_BIT
;
179 LED_A_ON(); // Indicate we got a valid SOF
181 // didn't stay down long enough
182 // before going high, error
183 Uart
.state
= STATE_UNSYNCD
;
186 // do nothing, keep waiting
190 if(Uart
.posCnt
>= 4) Uart
.posCnt
= 0;
191 if(Uart
.bitCnt
> 12) {
192 // Give up if we see too many zeros without
195 Uart
.state
= STATE_UNSYNCD
;
199 case STATE_AWAITING_START_BIT
:
202 if(Uart
.posCnt
> 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
203 // stayed high for too long between
205 Uart
.state
= STATE_UNSYNCD
;
208 // falling edge, this starts the data byte
212 Uart
.state
= STATE_RECEIVING_DATA
;
216 case STATE_RECEIVING_DATA
:
218 if(Uart
.posCnt
== 2) {
219 // time to sample a bit
222 Uart
.shiftReg
|= 0x200;
226 if(Uart
.posCnt
>= 4) {
229 if(Uart
.bitCnt
== 10) {
230 if((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001))
232 // this is a data byte, with correct
233 // start and stop bits
234 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xff;
237 if(Uart
.byteCnt
>= Uart
.byteCntMax
) {
238 // Buffer overflowed, give up
240 Uart
.state
= STATE_UNSYNCD
;
242 // so get the next byte now
244 Uart
.state
= STATE_AWAITING_START_BIT
;
246 } else if (Uart
.shiftReg
== 0x000) {
247 // this is an EOF byte
248 LED_A_OFF(); // Finished receiving
249 Uart
.state
= STATE_UNSYNCD
;
250 if (Uart
.byteCnt
!= 0) {
256 Uart
.state
= STATE_UNSYNCD
;
263 Uart
.state
= STATE_UNSYNCD
;
271 static void UartReset()
273 Uart
.byteCntMax
= MAX_FRAME_SIZE
;
274 Uart
.state
= STATE_UNSYNCD
;
280 static void UartInit(uint8_t *data
)
287 //-----------------------------------------------------------------------------
288 // Receive a command (from the reader to us, where we are the simulated tag),
289 // and store it in the given buffer, up to the given maximum length. Keeps
290 // spinning, waiting for a well-framed command, until either we get one
291 // (returns true) or someone presses the pushbutton on the board (false).
293 // Assume that we're called with the SSC (to the FPGA) and ADC path set
295 //-----------------------------------------------------------------------------
296 static int GetIso14443bCommandFromReader(uint8_t *received
, uint16_t *len
)
298 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
299 // only, since we are receiving, not transmitting).
300 // Signal field is off with the appropriate LED
302 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
304 // Now run a `software UART' on the stream of incoming samples.
310 if(BUTTON_PRESS()) return false;
312 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
313 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
314 for(uint8_t mask
= 0x80; mask
!= 0x00; mask
>>= 1) {
315 if(Handle14443bUartBit(b
& mask
)) {
326 //-----------------------------------------------------------------------------
327 // Main loop of simulated tag: receive commands from reader, decide what
328 // response to send, and send it.
329 //-----------------------------------------------------------------------------
330 void SimulateIso14443bTag(void)
333 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
334 static const uint8_t cmd1
[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // WUPB
335 // ... and REQB, AFI=0, Normal Request, N=1:
336 static const uint8_t cmd2
[] = { 0x05, 0x00, 0x00, 0x71, 0xFF }; // REQB
338 static const uint8_t cmd3
[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB
340 static const uint8_t cmd4
[] = { 0x1D, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
342 // ... and we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
343 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
344 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
345 static const uint8_t response1
[] = {
346 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22,
347 0x00, 0x21, 0x85, 0x5e, 0xd7
349 // response to HLTB and ATTRIB
350 static const uint8_t response2
[] = {0x00, 0x78, 0xF0};
353 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
360 uint16_t respLen
, respCodeLen
;
362 // allocate command receive buffer
364 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
367 uint16_t cmdsRecvd
= 0;
369 // prepare the (only one) tag answer:
370 CodeIso14443bAsTag(response1
, sizeof(response1
));
371 uint8_t *resp1Code
= BigBuf_malloc(ToSendMax
);
372 memcpy(resp1Code
, ToSend
, ToSendMax
);
373 uint16_t resp1CodeLen
= ToSendMax
;
375 // prepare the (other) tag answer:
376 CodeIso14443bAsTag(response2
, sizeof(response2
));
377 uint8_t *resp2Code
= BigBuf_malloc(ToSendMax
);
378 memcpy(resp2Code
, ToSend
, ToSendMax
);
379 uint16_t resp2CodeLen
= ToSendMax
;
381 // We need to listen to the high-frequency, peak-detected path.
382 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
383 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
389 if(!GetIso14443bCommandFromReader(receivedCmd
, &len
)) {
390 Dbprintf("button pressed, received %d commands", cmdsRecvd
);
394 LogTrace(receivedCmd
, len
, 0, 0, NULL
, true);
396 // Good, look at the command now.
397 if ( (len
== sizeof(cmd1
) && memcmp(receivedCmd
, cmd1
, len
) == 0)
398 || (len
== sizeof(cmd2
) && memcmp(receivedCmd
, cmd2
, len
) == 0) ) {
400 respLen
= sizeof(response1
);
401 respCode
= resp1Code
;
402 respCodeLen
= resp1CodeLen
;
403 } else if ( (len
== sizeof(cmd3
) && receivedCmd
[0] == cmd3
[0])
404 || (len
== sizeof(cmd4
) && receivedCmd
[0] == cmd4
[0]) ) {
406 respLen
= sizeof(response2
);
407 respCode
= resp2Code
;
408 respCodeLen
= resp2CodeLen
;
410 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len
, cmdsRecvd
);
411 // And print whether the CRC fails, just for good measure
413 if (len
>= 3){ // if crc exists
414 ComputeCrc14443(CRC_14443_B
, receivedCmd
, len
-2, &b1
, &b2
);
415 if(b1
!= receivedCmd
[len
-2] || b2
!= receivedCmd
[len
-1]) {
416 // Not so good, try again.
417 DbpString("+++CRC fail");
420 DbpString("CRC passes");
423 //get rid of compiler warning
427 respCode
= resp1Code
;
428 //don't crash at new command just wait and see if reader will send other new cmds.
434 if(cmdsRecvd
> 0x30) {
435 DbpString("many commands later...");
439 if(respCodeLen
<= 0) continue;
442 // Signal field is off with the appropriate LED
444 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
445 AT91C_BASE_SSC
->SSC_THR
= 0xff;
446 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
448 // Transmit the response.
451 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
452 uint8_t b
= respCode
[i
];
454 AT91C_BASE_SSC
->SSC_THR
= b
;
457 if(i
> respCodeLen
) {
461 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
462 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
467 // trace the response:
468 LogTrace(resp
, respLen
, 0, 0, NULL
, false);
472 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
476 //=============================================================================
477 // An ISO 14443 Type B reader. We take layer two commands, code them
478 // appropriately, and then send them to the tag. We then listen for the
479 // tag's response, which we leave in the buffer to be demodulated on the
481 //=============================================================================
486 DEMOD_PHASE_REF_TRAINING
,
487 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
,
488 DEMOD_GOT_FALLING_EDGE_OF_SOF
,
489 DEMOD_AWAITING_START_BIT
,
495 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
507 * Handles reception of a bit from the tag
509 * This function is called 2 times per bit (every 4 subcarrier cycles).
510 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
513 * LED C -> ON once we have received the SOF and are expecting the rest.
514 * LED C -> OFF once we have received EOF or are unsynced
516 * Returns: true if we received a EOF
517 * false if we are still waiting for some more
520 static RAMFUNC
int Handle14443bSamplesDemod(int ci
, int cq
)
524 // The soft decision on the bit uses an estimate of just the
525 // quadrant of the reference angle, not the exact angle.
526 #define MAKE_SOFT_DECISION() { \
527 if(Demod.sumI > 0) { \
532 if(Demod.sumQ > 0) { \
539 #define SUBCARRIER_DETECT_THRESHOLD 8
541 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
542 #define AMPLITUDE(ci,cq) (MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2))
543 switch(Demod
.state
) {
545 if(AMPLITUDE(ci
,cq
) > SUBCARRIER_DETECT_THRESHOLD
) { // subcarrier detected
546 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
553 case DEMOD_PHASE_REF_TRAINING
:
554 if(Demod
.posCount
< 8) {
555 if (AMPLITUDE(ci
,cq
) > SUBCARRIER_DETECT_THRESHOLD
) {
556 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
557 // note: synchronization time > 80 1/fs
561 } else { // subcarrier lost
562 Demod
.state
= DEMOD_UNSYNCD
;
565 Demod
.state
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
;
569 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
:
570 MAKE_SOFT_DECISION();
571 if(v
< 0) { // logic '0' detected
572 Demod
.state
= DEMOD_GOT_FALLING_EDGE_OF_SOF
;
573 Demod
.posCount
= 0; // start of SOF sequence
575 if(Demod
.posCount
> 200/4) { // maximum length of TR1 = 200 1/fs
576 Demod
.state
= DEMOD_UNSYNCD
;
582 case DEMOD_GOT_FALLING_EDGE_OF_SOF
:
584 MAKE_SOFT_DECISION();
586 if(Demod
.posCount
< 9*2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
587 Demod
.state
= DEMOD_UNSYNCD
;
589 LED_C_ON(); // Got SOF
593 Demod
.state
= DEMOD_AWAITING_START_BIT
;
594 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
600 if(Demod
.posCount
> 12*2) { // low phase of SOF too long (> 12 etu)
601 Demod
.state
= DEMOD_UNSYNCD
;
607 case DEMOD_AWAITING_START_BIT
:
609 MAKE_SOFT_DECISION();
611 if (Demod
.posCount
> 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
613 if (Demod
.bitCount
== 0 && Demod
.len
== 0) { // received SOF only, this is valid for iClass/Picopass
616 Demod
.state
= DEMOD_UNSYNCD
;
619 } else { // start bit detected
620 Demod
.posCount
= 1; // this was the first half
623 Demod
.state
= DEMOD_RECEIVING_DATA
;
627 case DEMOD_RECEIVING_DATA
:
628 MAKE_SOFT_DECISION();
629 if (Demod
.posCount
== 0) { // first half of bit
632 } else { // second half of bit
635 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
636 if(Demod.thisBit > 0) {
637 Demod.metric += Demod.thisBit;
639 Demod.metric -= Demod.thisBit;
644 Demod
.shiftReg
>>= 1;
645 if (Demod
.thisBit
> 0) { // logic '1'
646 Demod
.shiftReg
|= 0x200;
650 if (Demod
.bitCount
== 10) {
651 uint16_t s
= Demod
.shiftReg
;
652 if ((s
& 0x200) && !(s
& 0x001)) { // stop bit == '1', start bit == '0'
653 uint8_t b
= (s
>> 1);
654 Demod
.output
[Demod
.len
] = b
;
657 Demod
.state
= DEMOD_AWAITING_START_BIT
;
659 Demod
.state
= DEMOD_UNSYNCD
;
662 // This is EOF (start, stop and all data bits == '0'
672 Demod
.state
= DEMOD_UNSYNCD
;
681 static void DemodReset()
683 // Clear out the state of the "UART" that receives from the tag.
685 Demod
.state
= DEMOD_UNSYNCD
;
687 memset(Demod
.output
, 0x00, MAX_FRAME_SIZE
);
691 static void DemodInit(uint8_t *data
)
699 * Demodulate the samples we received from the tag, also log to tracebuffer
700 * quiet: set to 'true' to disable debug output
702 static int GetSamplesFor14443bDemod(int timeout
, bool quiet
) {
705 bool gotFrame
= false;
706 int lastRxCounter
, samples
= 0;
709 // Allocate memory from BigBuf for some buffers
710 // free all previous allocations first
713 // The response (tag -> reader) that we're receiving.
714 uint8_t *receivedResponse
= BigBuf_malloc(MAX_FRAME_SIZE
);
716 // The DMA buffer, used to stream samples from the FPGA
717 uint16_t *dmaBuf
= (uint16_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
* sizeof(uint16_t));
719 // Set up the demodulator for tag -> reader responses.
720 DemodInit(receivedResponse
);
722 // wait for last transfer to complete
723 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_TXEMPTY
))
725 // Setup and start DMA.
726 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
727 FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
);
729 uint16_t *upTo
= dmaBuf
;
730 lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
732 // Signal field is ON with the appropriate LED:
734 // And put the FPGA in the appropriate mode
735 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_848_KHZ
| FPGA_HF_READER_MODE_RECEIVE_IQ
);
738 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1);
739 if(behindBy
> maxBehindBy
) {
740 maxBehindBy
= behindBy
;
743 if(behindBy
< 1) continue;
749 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) { // we have read all of the DMA buffer content.
750 upTo
= dmaBuf
; // start reading the circular buffer from the beginning
751 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
753 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_ENDRX
)) { // DMA Counter Register had reached 0, already rotated.
754 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
; // refresh the DMA Next Buffer and
755 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
; // DMA Next Counter registers
759 if (Handle14443bSamplesDemod(ci
, cq
)) {
765 if(samples
> timeout
&& Demod
.state
< DEMOD_PHASE_REF_TRAINING
) {
774 if (!quiet
) Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", maxBehindBy
, samples
, gotFrame
, Demod
.len
, Demod
.sumI
, Demod
.sumQ
);
780 LogTrace(Demod
.output
, Demod
.len
, 0, 0, NULL
, false);
786 //-----------------------------------------------------------------------------
787 // Transmit the command (to the tag) that was placed in ToSend[].
788 //-----------------------------------------------------------------------------
789 static void TransmitFor14443b(void)
791 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD
);
793 for(int c
= 0; c
< ToSendMax
; c
++) {
794 uint8_t data
= ToSend
[c
];
795 for (int i
= 0; i
< 8; i
++) {
796 uint16_t send_word
= (data
& 0x80) ? 0x0000 : 0xffff;
797 while (!(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
))) ;
798 AT91C_BASE_SSC
->SSC_THR
= send_word
;
799 while (!(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
))) ;
800 AT91C_BASE_SSC
->SSC_THR
= send_word
;
809 //-----------------------------------------------------------------------------
810 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
811 // so that it is ready to transmit to the tag using TransmitFor14443b().
812 //-----------------------------------------------------------------------------
813 static void CodeIso14443bAsReader(const uint8_t *cmd
, int len
)
821 for(i
= 0; i
< 10; i
++) {
827 for(i
= 0; i
< len
; i
++) {
832 for(j
= 0; j
< 8; j
++) {
845 for(i
= 0; i
< 10; i
++) {
850 // ensure that last byte is filled up
851 for(i
= 0; i
< 8; i
++) {
855 // Convert from last character reference to length
861 Convenience function to encode, transmit and trace iso 14443b comms
863 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd
, int len
)
865 CodeIso14443bAsReader(cmd
, len
);
867 LogTrace(cmd
,len
, 0, 0, NULL
, true);
870 /* Sends an APDU to the tag
871 * TODO: check CRC and preamble
873 int iso14443b_apdu(uint8_t const *message
, size_t message_length
, uint8_t *response
) {
875 uint8_t message_frame
[message_length
+ 4];
877 message_frame
[0] = 0x0A | pcb_blocknum
;
880 message_frame
[1] = 0;
882 memcpy(message_frame
+ 2, message
, message_length
);
884 ComputeCrc14443(CRC_14443_B
, message_frame
, message_length
+ 2, &message_frame
[message_length
+ 2], &message_frame
[message_length
+ 3]);
886 CodeAndTransmit14443bAsReader(message_frame
, message_length
+ 4);
888 int ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
889 FpgaDisableTracing();
895 // copy response contents
896 if (response
!= NULL
) {
897 memcpy(response
, Demod
.output
, Demod
.len
);
903 /* Perform the ISO 14443 B Card Selection procedure
904 * Currently does NOT do any collision handling.
905 * It expects 0-1 cards in the device's range.
906 * TODO: Support multiple cards (perform anticollision)
907 * TODO: Verify CRC checksums
909 int iso14443b_select_card()
911 // WUPB command (including CRC)
912 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
913 static const uint8_t wupb
[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
914 // ATTRIB command (with space for CRC)
915 uint8_t attrib
[] = { 0x1D, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
917 // first, wake up the tag
918 CodeAndTransmit14443bAsReader(wupb
, sizeof(wupb
));
919 int ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
926 // copy the PUPI to ATTRIB
927 memcpy(attrib
+ 1, Demod
.output
+ 1, 4);
928 /* copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into
930 attrib
[7] = Demod
.output
[10] & 0x0F;
931 ComputeCrc14443(CRC_14443_B
, attrib
, 9, attrib
+ 9, attrib
+ 10);
932 CodeAndTransmit14443bAsReader(attrib
, sizeof(attrib
));
933 ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
934 // Answer to ATTRIB too short?
938 // reset PCB block number
943 // Set up ISO 14443 Type B communication (similar to iso14443a_setup)
944 void iso14443b_setup() {
945 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
946 // Set up the synchronous serial port
947 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
948 // connect Demodulated Signal to ADC:
949 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
951 // Signal field is on with the appropriate LED
953 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD
);
959 //-----------------------------------------------------------------------------
960 // Read a SRI512 ISO 14443B tag.
962 // SRI512 tags are just simple memory tags, here we're looking at making a dump
963 // of the contents of the memory. No anticollision algorithm is done, we assume
964 // we have a single tag in the field.
966 // I tried to be systematic and check every answer of the tag, every CRC, etc...
967 //-----------------------------------------------------------------------------
968 void ReadSTMemoryIso14443b(uint32_t dwLast
)
973 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
974 // Make sure that we start from off, since the tags are stateful;
975 // confusing things will happen if we don't reset them between reads.
977 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
980 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
981 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
983 // Now give it time to spin up.
984 // Signal field is on with the appropriate LED
986 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD
);
992 // First command: wake up the tag using the INITIATE command
993 uint8_t cmd1
[] = {0x06, 0x00, 0x97, 0x5b};
994 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
));
995 int ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
998 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
999 DbpString("No response from tag");
1003 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1004 Demod
.output
[0], Demod
.output
[1], Demod
.output
[2]);
1007 // There is a response, SELECT the uid
1008 DbpString("Now SELECT tag:");
1009 cmd1
[0] = 0x0E; // 0x0E is SELECT
1010 cmd1
[1] = Demod
.output
[0];
1011 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1012 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
));
1013 ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
1014 if (Demod
.len
!= 3) {
1015 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1016 Dbprintf("Expected 3 bytes from tag, got %d", Demod
.len
);
1020 // Check the CRC of the answer:
1021 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 1 , &cmd1
[2], &cmd1
[3]);
1022 if(cmd1
[2] != Demod
.output
[1] || cmd1
[3] != Demod
.output
[2]) {
1023 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1024 DbpString("CRC Error reading select response.");
1028 // Check response from the tag: should be the same UID as the command we just sent:
1029 if (cmd1
[1] != Demod
.output
[0]) {
1030 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1031 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1
[1], Demod
.output
[0]);
1036 // Tag is now selected,
1037 // First get the tag's UID:
1039 ComputeCrc14443(CRC_14443_B
, cmd1
, 1 , &cmd1
[1], &cmd1
[2]);
1040 CodeAndTransmit14443bAsReader(cmd1
, 3); // Only first three bytes for this one
1041 ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
1043 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1044 Dbprintf("Expected 10 bytes from tag, got %d", Demod
.len
);
1048 // The check the CRC of the answer (use cmd1 as temporary variable):
1049 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 8, &cmd1
[2], &cmd1
[3]);
1050 if(cmd1
[2] != Demod
.output
[8] || cmd1
[3] != Demod
.output
[9]) {
1051 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1052 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[8]<<8)+Demod
.output
[9]);
1053 // Do not return;, let's go on... (we should retry, maybe ?)
1055 Dbprintf("Tag UID (64 bits): %08x %08x",
1056 (Demod
.output
[7]<<24) + (Demod
.output
[6]<<16) + (Demod
.output
[5]<<8) + Demod
.output
[4],
1057 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0]);
1059 // Now loop to read all 16 blocks, address from 0 to last block
1060 Dbprintf("Tag memory dump, block 0 to %d", dwLast
);
1066 DbpString("System area block (0xff):");
1070 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1071 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
));
1072 ret
= GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, true);
1073 if (ret
!= 6) { // Check if we got an answer from the tag
1074 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1075 DbpString("Expected 6 bytes from tag, got less...");
1079 // The check the CRC of the answer (use cmd1 as temporary variable):
1080 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 4, &cmd1
[2], &cmd1
[3]);
1081 if (cmd1
[2] != Demod
.output
[4] || cmd1
[3] != Demod
.output
[5]) {
1082 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1083 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[4]<<8)+Demod
.output
[5]);
1084 // Do not return;, let's go on... (we should retry, maybe ?)
1086 // Now print out the memory location:
1087 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i
,
1088 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0],
1089 (Demod
.output
[4]<<8)+Demod
.output
[5]);
1096 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1101 //=============================================================================
1102 // Finally, the `sniffer' combines elements from both the reader and
1103 // simulated tag, to show both sides of the conversation.
1104 //=============================================================================
1106 //-----------------------------------------------------------------------------
1107 // Record the sequence of commands sent by the reader to the tag, with
1108 // triggering so that we start recording at the point that the tag is moved
1110 //-----------------------------------------------------------------------------
1112 * Memory usage for this function, (within BigBuf)
1113 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1114 * Last Received command (tag->reader) - MAX_FRAME_SIZE
1115 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
1116 * Demodulated samples received - all the rest
1118 void RAMFUNC
SnoopIso14443b(void)
1121 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1127 // The DMA buffer, used to stream samples from the FPGA
1128 uint16_t *dmaBuf
= (uint16_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
* sizeof(uint16_t));
1132 int maxBehindBy
= 0;
1134 // Count of samples received so far, so that we can include timing
1135 // information in the trace buffer.
1138 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1139 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1141 // Print some debug information about the buffer sizes
1142 Dbprintf("Snooping buffers initialized:");
1143 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1144 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE
);
1145 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE
);
1146 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE
);
1148 // Signal field is off
1151 // And put the FPGA in the appropriate mode
1152 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_848_KHZ
| FPGA_HF_READER_MODE_SNOOP_IQ
);
1153 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1155 // Setup for the DMA.
1156 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
1158 lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
1159 FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
);
1161 bool TagIsActive
= false;
1162 bool ReaderIsActive
= false;
1163 // We won't start recording the frames that we acquire until we trigger.
1164 // A good trigger condition to get started is probably when we see a
1166 bool triggered
= false;
1168 // And now we loop, receiving samples.
1170 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1);
1171 if(behindBy
> maxBehindBy
) {
1172 maxBehindBy
= behindBy
;
1175 if(behindBy
< 1) continue;
1181 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) { // we have read all of the DMA buffer content.
1182 upTo
= dmaBuf
; // start reading the circular buffer from the beginning again
1183 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
1184 if(behindBy
> (9*ISO14443B_DMA_BUFFER_SIZE
/10)) {
1185 Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy
);
1189 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_ENDRX
)) { // DMA Counter Register had reached 0, already rotated.
1190 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
; // refresh the DMA Next Buffer and
1191 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
; // DMA Next Counter registers
1193 if(BUTTON_PRESS()) {
1194 DbpString("cancelled");
1201 if (!TagIsActive
) { // no need to try decoding reader data if the tag is sending
1202 if(Handle14443bUartBit(ci
& 0x01)) {
1204 LogTrace(Uart
.output
, Uart
.byteCnt
, samples
, samples
, NULL
, true);
1205 /* And ready to receive another command. */
1207 /* And also reset the demod code, which might have been */
1208 /* false-triggered by the commands from the reader. */
1211 if(Handle14443bUartBit(cq
& 0x01)) {
1213 LogTrace(Uart
.output
, Uart
.byteCnt
, samples
, samples
, NULL
, true);
1214 /* And ready to receive another command. */
1216 /* And also reset the demod code, which might have been */
1217 /* false-triggered by the commands from the reader. */
1220 ReaderIsActive
= (Uart
.state
> STATE_GOT_FALLING_EDGE_OF_SOF
);
1223 if (!ReaderIsActive
&& triggered
) { // no need to try decoding tag data if the reader is sending or not yet triggered
1224 if (Handle14443bSamplesDemod(ci
/2, cq
/2) >= 0) {
1225 //Use samples as a time measurement
1226 LogTrace(Demod
.output
, Demod
.len
, samples
, samples
, NULL
, false);
1227 // And ready to receive another response.
1230 TagIsActive
= (Demod
.state
> DEMOD_GOT_FALLING_EDGE_OF_SOF
);
1235 FpgaDisableSscDma();
1236 DbpString("Snoop statistics:");
1237 Dbprintf(" Max behind by: %i", maxBehindBy
);
1238 Dbprintf(" Uart State: %x", Uart
.state
);
1239 Dbprintf(" Uart ByteCnt: %i", Uart
.byteCnt
);
1240 Dbprintf(" Uart ByteCntMax: %i", Uart
.byteCntMax
);
1241 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
1247 * Send raw command to tag ISO14443B
1249 * datalen len of buffer data
1250 * recv bool when true wait for data from tag and send to client
1251 * powerfield bool leave the field on when true
1252 * data buffer with byte to send
1258 void SendRawCommand14443B(uint32_t datalen
, uint32_t recv
, uint8_t powerfield
, uint8_t data
[])
1261 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1262 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1264 // switch field on and give tag some time to power up
1266 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD
);
1267 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
1273 CodeAndTransmit14443bAsReader(data
, datalen
);
1276 int ret
= GetSamplesFor14443bDemod(5*RECEIVE_SAMPLES_TIMEOUT
, true);
1277 FpgaDisableTracing();
1278 uint16_t iLen
= MIN(Demod
.len
, USB_CMD_DATA_SIZE
);
1279 cmd_send(CMD_ACK
, ret
, 0, 0, Demod
.output
, iLen
);
1282 FpgaDisableTracing();
1286 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);