1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, split Nov 2006
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
7 //-----------------------------------------------------------------------------
8 // Routines to support ISO 14443B. This includes both the reader software and
9 // the `fake tag' modes.
10 //-----------------------------------------------------------------------------
11 #include "iso14443b.h"
13 #define RECEIVE_SAMPLES_TIMEOUT 50000
14 #define ISO14443B_DMA_BUFFER_SIZE 256
16 // Guard Time (per 14443-2)
18 // Synchronization time (per 14443-2)
20 // Frame Delay Time PICC to PCD (per 14443-3 Amendment 1)
24 #define SEND4STUFFBIT(x) ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);
26 static void switch_off(void);
28 // the block number for the ISO14443-4 PCB (used with APDUs)
29 static uint8_t pcb_blocknum
= 0;
31 static uint32_t iso14b_timeout
= RECEIVE_SAMPLES_TIMEOUT
;
32 // param timeout is in ftw_
33 void iso14b_set_timeout(uint32_t timeout
) {
35 // clock is about 1.5 us
36 iso14b_timeout
= timeout
;
37 if(MF_DBGLEVEL
>= 2) Dbprintf("ISO14443B Timeout set to %ld fwt", iso14b_timeout
);
40 static void switch_off(void){
41 if (MF_DBGLEVEL
> 3) Dbprintf("switch_off");
42 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
49 //=============================================================================
50 // An ISO 14443 Type B tag. We listen for commands from the reader, using
51 // a UART kind of thing that's implemented in software. When we get a
52 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
53 // If it's good, then we can do something appropriate with it, and send
55 //=============================================================================
58 //-----------------------------------------------------------------------------
59 // The software UART that receives commands from the reader, and its state variables.
60 //-----------------------------------------------------------------------------
64 STATE_GOT_FALLING_EDGE_OF_SOF
,
65 STATE_AWAITING_START_BIT
,
76 static void UartReset() {
77 Uart
.state
= STATE_UNSYNCD
;
81 Uart
.byteCntMax
= MAX_FRAME_SIZE
;
85 static void UartInit(uint8_t *data
) {
88 // memset(Uart.output, 0x00, MAX_FRAME_SIZE);
91 //-----------------------------------------------------------------------------
92 // The software Demod that receives commands from the tag, and its state variables.
93 //-----------------------------------------------------------------------------
97 DEMOD_PHASE_REF_TRAINING
,
98 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
,
99 DEMOD_GOT_FALLING_EDGE_OF_SOF
,
100 DEMOD_AWAITING_START_BIT
,
106 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
115 uint32_t startTime
, endTime
;
118 // Clear out the state of the "UART" that receives from the tag.
119 static void DemodReset() {
120 Demod
.state
= DEMOD_UNSYNCD
;
132 static void DemodInit(uint8_t *data
) {
135 // memset(Demod.output, 0x00, MAX_FRAME_SIZE);
138 void AppendCrc14443b(uint8_t* data
, int len
) {
139 ComputeCrc14443(CRC_14443_B
, data
, len
, data
+len
, data
+len
+1);
142 //-----------------------------------------------------------------------------
143 // Code up a string of octets at layer 2 (including CRC, we don't generate
144 // that here) so that they can be transmitted to the reader. Doesn't transmit
145 // them yet, just leaves them ready to send in ToSend[].
146 //-----------------------------------------------------------------------------
147 static void CodeIso14443bAsTag(const uint8_t *cmd
, int len
) {
150 * Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
151 * Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
153 * fc - carrier frequency 13.56mHz
154 * TR0 - Guard Time per 14443-2
155 * TR1 - Synchronization Time per 14443-2
156 * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
158 * Elementary Time Unit (ETU) is
159 * - 128 Carrier Cycles (9.4395 µS) = 8 Subcarrier Units
161 * - 10 ETU = 1 startbit, 8 databits, 1 stopbit (10bits length)
165 * Start of frame (SOF) is
166 * - [10-11] ETU of ZEROS, unmodulated time
167 * - [2-3] ETU of ONES,
169 * End of frame (EOF) is
170 * - [10-11] ETU of ZEROS, unmodulated time
172 * -TO VERIFY THIS BELOW-
173 * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
175 * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (9.44µS)
176 * - A 0-bit input to the FPGA becomes an unmodulated time of 9.44µS
180 * Card sends data ub 847.e kHz subcarrier
181 * 848k = 9.44µS = 128 fc
182 * 424k = 18.88µS = 256 fc
183 * 212k = 37.76µS = 512 fc
184 * 106k = 75.52µS = 1024 fc
186 * Reader data transmission:
187 * - no modulation ONES
189 * - Command, data and CRC_B
191 * - no modulation ONES
193 * Card data transmission
196 * - data (each bytes is: 1startbit,8bits, 1stopbit)
200 * FPGA implementation :
201 * At this point only Type A is implemented. This means that we are using a
202 * bit rate of 106 kbit/s, or fc/128. Oversample by 4, which ought to make
203 * things practical for the ARM (fc/32, 423.8 kbits/s, ~50 kbytes/s)
207 // ToSendStuffBit, 40 calls
208 // 1 ETU = 1startbit, 1stopbit, 8databits == 10bits.
209 // 1 ETU = 10 * 4 == 40 stuffbits ( ETU_TAG_BIT )
215 // Transmit a burst of ones, as the initial thing that lets the
216 // reader get phase sync.
217 // This loop is TR1, per specification
218 // TR1 minimum must be > 80/fs
219 // TR1 maximum 200/fs
220 // 80/fs < TR1 < 200/fs
221 // 10 ETU < TR1 < 24 ETU
224 // 10-11 ETU * 4times samples ZEROS
225 for(i
= 0; i
< 10; i
++) { SEND4STUFFBIT(0); }
227 // 2-3 ETU * 4times samples ONES
228 for(i
= 0; i
< 3; i
++) { SEND4STUFFBIT(1); }
231 for(i
= 0; i
< len
; ++i
) {
238 for(j
= 0; j
< 8; ++j
) {
251 // For PICC it ranges 0-18us (1etu = 9us)
256 // 10-11 ETU * 4 sample rate = ZEROS
257 for(i
= 0; i
< 10; i
++) { SEND4STUFFBIT(0); }
260 for(i
= 0; i
< 40; i
++) { SEND4STUFFBIT(1); }
262 // Convert from last byte pos to length
267 /* Receive & handle a bit coming from the reader.
269 * This function is called 4 times per bit (every 2 subcarrier cycles).
270 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
273 * LED A -> ON once we have received the SOF and are expecting the rest.
274 * LED A -> OFF once we have received EOF or are in error state or unsynced
276 * Returns: true if we received a EOF
277 * false if we are still waiting for some more
279 static RAMFUNC
int Handle14443bReaderUartBit(uint8_t bit
) {
283 // we went low, so this could be the beginning of an SOF
284 Uart
.state
= STATE_GOT_FALLING_EDGE_OF_SOF
;
290 case STATE_GOT_FALLING_EDGE_OF_SOF
:
292 if(Uart
.posCnt
== 2) { // sample every 4 1/fs in the middle of a bit
294 if(Uart
.bitCnt
> 9) {
295 // we've seen enough consecutive
296 // zeros that it's a valid SOF
299 Uart
.state
= STATE_AWAITING_START_BIT
;
300 LED_A_ON(); // Indicate we got a valid SOF
302 // didn't stay down long enough
303 // before going high, error
304 Uart
.state
= STATE_UNSYNCD
;
307 // do nothing, keep waiting
311 if(Uart
.posCnt
>= 4) Uart
.posCnt
= 0;
312 if(Uart
.bitCnt
> 12) {
313 // Give up if we see too many zeros without
316 Uart
.state
= STATE_UNSYNCD
;
320 case STATE_AWAITING_START_BIT
:
323 if(Uart
.posCnt
> 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
324 // stayed high for too long between
326 Uart
.state
= STATE_UNSYNCD
;
329 // falling edge, this starts the data byte
333 Uart
.state
= STATE_RECEIVING_DATA
;
337 case STATE_RECEIVING_DATA
:
339 if(Uart
.posCnt
== 2) {
340 // time to sample a bit
343 Uart
.shiftReg
|= 0x200;
347 if(Uart
.posCnt
>= 4) {
350 if(Uart
.bitCnt
== 10) {
351 if((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001))
353 // this is a data byte, with correct
354 // start and stop bits
355 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xff;
358 if(Uart
.byteCnt
>= Uart
.byteCntMax
) {
359 // Buffer overflowed, give up
361 Uart
.state
= STATE_UNSYNCD
;
363 // so get the next byte now
365 Uart
.state
= STATE_AWAITING_START_BIT
;
367 } else if (Uart
.shiftReg
== 0x000) {
368 // this is an EOF byte
369 LED_A_OFF(); // Finished receiving
370 Uart
.state
= STATE_UNSYNCD
;
371 if (Uart
.byteCnt
!= 0) {
377 Uart
.state
= STATE_UNSYNCD
;
384 Uart
.state
= STATE_UNSYNCD
;
391 //-----------------------------------------------------------------------------
392 // Receive a command (from the reader to us, where we are the simulated tag),
393 // and store it in the given buffer, up to the given maximum length. Keeps
394 // spinning, waiting for a well-framed command, until either we get one
395 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
397 // Assume that we're called with the SSC (to the FPGA) and ADC path set
399 //-----------------------------------------------------------------------------
400 static int GetIso14443bCommandFromReader(uint8_t *received
, uint16_t *len
) {
401 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
402 // only, since we are receiving, not transmitting).
403 // Signal field is off with the appropriate LED
405 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
409 // Now run a `software UART' on the stream of incoming samples.
413 while( !BUTTON_PRESS() ) {
416 if ( AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
) {
417 b
= (uint8_t) AT91C_BASE_SSC
->SSC_RHR
;
418 for ( mask
= 0x80; mask
!= 0; mask
>>= 1) {
419 if ( Handle14443bReaderUartBit(b
& mask
)) {
430 static void TransmitFor14443b_AsTag( uint8_t *response
, uint16_t len
) {
432 // Signal field is off with the appropriate LED
436 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
438 // 8 ETU / 8bits. 8/4= 2 etus.
439 AT91C_BASE_SSC
->SSC_THR
= 0XFF;
443 // Transmit the response.
444 for(uint16_t i
= 0; i
< len
;) {
445 if(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_TXRDY
) {
446 AT91C_BASE_SSC
->SSC_THR
= response
[i
];
451 //-----------------------------------------------------------------------------
452 // Main loop of simulated tag: receive commands from reader, decide what
453 // response to send, and send it.
454 //-----------------------------------------------------------------------------
455 void SimulateIso14443bTag(uint32_t pupi
) {
457 ///////////// setup device.
458 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
460 // allocate command receive buffer
462 BigBuf_Clear_ext(false);
466 // connect Demodulated Signal to ADC:
467 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
469 // Set up the synchronous serial port
473 uint16_t len
, cmdsReceived
= 0;
474 int cardSTATE
= SIM_NOFIELD
;
475 int vHf
= 0; // in mV
476 // uint32_t time_0 = 0;
477 // uint32_t t2r_time = 0;
478 // uint32_t r2t_time = 0;
479 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
481 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
482 // static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
483 // ... and REQB, AFI=0, Normal Request, N=1:
484 // static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
486 // static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
488 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
489 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
490 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
491 uint8_t respATQB
[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19,
492 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 };
494 // response to HLTB and ATTRIB
495 static const uint8_t respOK
[] = {0x00, 0x78, 0xF0};
497 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
499 num_to_bytes(pupi
, 4, respATQB
+1);
500 ComputeCrc14443(CRC_14443_B
, respATQB
, 12, respATQB
+13, respATQB
+14);
503 // prepare "ATQB" tag answer (encoded):
504 CodeIso14443bAsTag(respATQB
, sizeof(respATQB
));
505 uint8_t *encodedATQB
= BigBuf_malloc(ToSendMax
);
506 uint16_t encodedATQBLen
= ToSendMax
;
507 memcpy(encodedATQB
, ToSend
, ToSendMax
);
510 // prepare "OK" tag answer (encoded):
511 CodeIso14443bAsTag(respOK
, sizeof(respOK
));
512 uint8_t *encodedOK
= BigBuf_malloc(ToSendMax
);
513 uint16_t encodedOKLen
= ToSendMax
;
514 memcpy(encodedOK
, ToSend
, ToSendMax
);
517 while (!BUTTON_PRESS() && !usb_poll_validate_length()) {
521 if (cardSTATE
== SIM_NOFIELD
) {
522 vHf
= (MAX_ADC_HF_VOLTAGE
* AvgAdc(ADC_CHAN_HF
)) >> 10;
523 if ( vHf
> MF_MINFIELDV
) {
524 cardSTATE
= SIM_IDLE
;
528 if (cardSTATE
== SIM_NOFIELD
) continue;
530 // Get reader command
531 if (!GetIso14443bCommandFromReader(receivedCmd
, &len
)) {
532 Dbprintf("button pressed, received %d commands", cmdsReceived
);
536 // ISO14443-B protocol states:
537 // REQ or WUP request in ANY state
538 // WUP in HALTED state
540 if ( (receivedCmd
[0] == ISO14443B_REQB
&& (receivedCmd
[2] & 0x8)== 0x8 && cardSTATE
!= SIM_HALTED
) ||
541 (receivedCmd
[0] == ISO14443B_REQB
&& (receivedCmd
[2] & 0x8)== 0) ){
543 TransmitFor14443b_AsTag( encodedATQB
, encodedATQBLen
);
544 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, FALSE
);
545 cardSTATE
= SIM_SELECTING
;
551 * How should this flow go?
553 * send response ( waiting for Attrib)
555 * send response ( waiting for commands 7816)
557 send halt response ( waiting for wupb )
564 LogTrace(receivedCmd
, len
, 0, 0, NULL
, TRUE
);
567 case SIM_SELECTING
: {
568 TransmitFor14443b_AsTag( encodedATQB
, encodedATQBLen
);
569 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, FALSE
);
570 cardSTATE
= SIM_IDLE
;
574 TransmitFor14443b_AsTag( encodedOK
, encodedOKLen
);
575 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, FALSE
);
576 cardSTATE
= SIM_HALTED
;
579 case SIM_ACKNOWLEDGE
:{
580 TransmitFor14443b_AsTag( encodedOK
, encodedOKLen
);
581 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, FALSE
);
582 cardSTATE
= SIM_IDLE
;
586 if ( len
== 7 && receivedCmd
[0] == ISO14443B_HALT
) {
587 cardSTATE
= SIM_HALTED
;
588 } else if ( len
== 11 && receivedCmd
[0] == ISO14443B_ATTRIB
) {
589 cardSTATE
= SIM_ACKNOWLEDGE
;
594 // - emulate with a memory dump
595 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len
, cmdsReceived
);
599 if (len
>= 3){ // if crc exists
600 ComputeCrc14443(CRC_14443_B
, receivedCmd
, len
-2, &b1
, &b2
);
601 if(b1
!= receivedCmd
[len
-2] || b2
!= receivedCmd
[len
-1])
602 DbpString("+++CRC fail");
604 DbpString("CRC passes");
606 cardSTATE
= SIM_IDLE
;
614 if(cmdsReceived
> 1000) {
615 DbpString("14B Simulate, 1000 commands later...");
619 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, BigBuf_get_traceLen());
620 switch_off(); //simulate
623 //=============================================================================
624 // An ISO 14443 Type B reader. We take layer two commands, code them
625 // appropriately, and then send them to the tag. We then listen for the
626 // tag's response, which we leave in the buffer to be demodulated on the
628 //=============================================================================
631 * Handles reception of a bit from the tag
633 * This function is called 2 times per bit (every 4 subcarrier cycles).
634 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
637 * LED C -> ON once we have received the SOF and are expecting the rest.
638 * LED C -> OFF once we have received EOF or are unsynced
640 * Returns: true if we received a EOF
641 * false if we are still waiting for some more
644 #ifndef SUBCARRIER_DETECT_THRESHOLD
645 # define SUBCARRIER_DETECT_THRESHOLD 8
648 static RAMFUNC
int Handle14443bTagSamplesDemod(int ci
, int cq
) {
649 int v
=0;// , myI, myQ = 0;
650 // The soft decision on the bit uses an estimate of just the
651 // quadrant of the reference angle, not the exact angle.
652 #define MAKE_SOFT_DECISION() { \
653 if(Demod.sumI > 0) { \
658 if(Demod.sumQ > 0) { \
665 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq)
666 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
667 #define CHECK_FOR_SUBCARRIER() { \
669 if(cq < 0) { /* ci < 0, cq < 0 */ \
671 v = -cq - (ci >> 1); \
673 v = -ci - (cq >> 1); \
675 } else { /* ci < 0, cq >= 0 */ \
677 v = -ci + (cq >> 1); \
679 v = cq - (ci >> 1); \
683 if(cq < 0) { /* ci >= 0, cq < 0 */ \
685 v = ci - (cq >> 1); \
687 v = -cq + (ci >> 1); \
689 } else { /* ci >= 0, cq >= 0 */ \
691 v = ci + (cq >> 1); \
693 v = cq + (ci >> 1); \
699 //note: couldn't we just use MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2) from common.h - marshmellow
700 #define CHECK_FOR_SUBCARRIER_un() { \
703 v = MAX(myI,myQ) + (MIN(myI,myQ) >> 1); \
706 switch(Demod
.state
) {
709 CHECK_FOR_SUBCARRIER();
711 // subcarrier detected
712 if(v
> SUBCARRIER_DETECT_THRESHOLD
) {
713 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
720 case DEMOD_PHASE_REF_TRAINING
:
721 if(Demod
.posCount
< 8) {
723 CHECK_FOR_SUBCARRIER();
725 if (v
> SUBCARRIER_DETECT_THRESHOLD
) {
726 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
727 // note: synchronization time > 80 1/fs
733 Demod
.state
= DEMOD_UNSYNCD
;
736 Demod
.state
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
;
740 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
:
742 MAKE_SOFT_DECISION();
744 if(v
< 0) { // logic '0' detected
745 Demod
.state
= DEMOD_GOT_FALLING_EDGE_OF_SOF
;
746 Demod
.posCount
= 0; // start of SOF sequence
748 // maximum length of TR1 = 200 1/fs
749 if(Demod
.posCount
> 25*2) Demod
.state
= DEMOD_UNSYNCD
;
754 case DEMOD_GOT_FALLING_EDGE_OF_SOF
:
757 MAKE_SOFT_DECISION();
760 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
761 if(Demod
.posCount
< 9*2) {
762 Demod
.state
= DEMOD_UNSYNCD
;
764 LED_C_ON(); // Got SOF
765 Demod
.startTime
= GetCountSspClk();
766 Demod
.state
= DEMOD_AWAITING_START_BIT
;
771 // low phase of SOF too long (> 12 etu)
772 if (Demod
.posCount
> 12*2) {
773 Demod
.state
= DEMOD_UNSYNCD
;
779 case DEMOD_AWAITING_START_BIT
:
782 MAKE_SOFT_DECISION();
785 if(Demod
.posCount
> 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
786 Demod
.state
= DEMOD_UNSYNCD
;
789 } else { // start bit detected
791 Demod
.posCount
= 1; // this was the first half
794 Demod
.state
= DEMOD_RECEIVING_DATA
;
798 case DEMOD_RECEIVING_DATA
:
800 MAKE_SOFT_DECISION();
802 if (Demod
.posCount
== 0) {
807 // second half of bit
809 Demod
.shiftReg
>>= 1;
812 if(Demod
.thisBit
> 0) Demod
.shiftReg
|= 0x200;
816 if(Demod
.bitCount
== 10) {
818 uint16_t s
= Demod
.shiftReg
;
820 // stop bit == '1', start bit == '0'
821 if((s
& 0x200) && !(s
& 0x001)) {
822 uint8_t b
= (s
>> 1);
823 Demod
.output
[Demod
.len
] = b
;
825 Demod
.state
= DEMOD_AWAITING_START_BIT
;
827 Demod
.state
= DEMOD_UNSYNCD
;
828 Demod
.endTime
= GetCountSspClk();
831 // This is EOF (start, stop and all data bits == '0'
832 if(s
== 0) return TRUE
;
840 Demod
.state
= DEMOD_UNSYNCD
;
849 * Demodulate the samples we received from the tag, also log to tracebuffer
850 * quiet: set to 'TRUE' to disable debug output
852 static void GetTagSamplesFor14443bDemod() {
853 bool gotFrame
= FALSE
;
854 int lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
855 int max
= 0, ci
= 0, cq
= 0, samples
= 0;
856 uint32_t time_0
= 0, time_stop
= 0;
860 // Set up the demodulator for tag -> reader responses.
861 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
863 // The DMA buffer, used to stream samples from the FPGA
864 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
865 int8_t *upTo
= dmaBuf
;
867 // Setup and start DMA.
868 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
) ){
869 if (MF_DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
873 time_0
= GetCountSspClk();
875 // And put the FPGA in the appropriate mode
876 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
878 while( !BUTTON_PRESS() ) {
881 int behindBy
= lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
882 if(behindBy
> max
) max
= behindBy
;
884 // rx counter - dma counter? (how much?) & (mod) dma buff / 2. (since 2bytes at the time is read)
885 while(((lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1)) > 2) {
892 // restart DMA buffer to receive again.
893 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
895 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
896 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
900 if(lastRxCounter
<= 0)
901 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
903 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
904 //gotFrame = Handle14443bTagSamplesDemod(ci & 0xfe, cq & 0xfe);
905 gotFrame
= Handle14443bTagSamplesDemod(ci
, cq
);
906 if ( gotFrame
) break;
910 time_stop
= GetCountSspClk() - time_0
;
912 if(time_stop
> iso14b_timeout
|| gotFrame
) break;
917 if (MF_DBGLEVEL
>= 3) {
918 Dbprintf("max behindby = %d, samples = %d, gotFrame = %s, Demod.state = %d, Demod.len = %u",
921 (gotFrame
) ? "true" : "false",
927 LogTrace(Demod
.output
, Demod
.len
, Demod
.startTime
, Demod
.endTime
, NULL
, FALSE
);
931 //-----------------------------------------------------------------------------
932 // Transmit the command (to the tag) that was placed in ToSend[].
933 //-----------------------------------------------------------------------------
934 static void TransmitFor14443b_AsReader(void) {
936 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
940 // we could been in following mode:
941 // FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ
942 // if its second call or more
944 // What does this loop do? Is it TR1?
945 for(c
= 0; c
< 10;) {
946 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
947 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
953 for(c
= 0; c
< ToSendMax
;) {
954 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
955 AT91C_BASE_SSC
->SSC_THR
= ToSend
[c
];
962 //-----------------------------------------------------------------------------
963 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
964 // so that it is ready to transmit to the tag using TransmitFor14443b().
965 //-----------------------------------------------------------------------------
966 static void CodeIso14443bAsReader(const uint8_t *cmd
, int len
)
969 * Reader data transmission:
970 * - no modulation ONES
972 * - Command, data and CRC_B
974 * - no modulation ONES
977 * TR0 - 8 ETUS minimum.
985 // 10-11 ETUs of ZERO
986 for(i
= 0; i
< 10; ++i
) ToSendStuffBit(0);
994 // from here we add BITS
995 for(i
= 0; i
< len
; ++i
) {
1000 if ( b
& 1 ) ToSendStuffBit(1); else ToSendStuffBit(0);
1001 if ( (b
>>1) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1002 if ( (b
>>2) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1003 if ( (b
>>3) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1004 if ( (b
>>4) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1005 if ( (b
>>5) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1006 if ( (b
>>6) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1007 if ( (b
>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1010 // EGT extra guard time
1011 // For PCD it ranges 0-57us (1etu = 9us)
1018 // 10-11 ETUs of ZERO
1019 for(i
= 0; i
< 10; ++i
) ToSendStuffBit(0);
1021 // Transition time. TR0 - guard time
1023 // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF.
1024 for(i
= 0; i
< 40 ; ++i
) ToSendStuffBit(1);
1026 // TR1 - Synchronization time
1027 // Convert from last character reference to length
1033 Convenience function to encode, transmit and trace iso 14443b comms
1035 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd
, int len
) {
1037 CodeIso14443bAsReader(cmd
, len
);
1039 uint32_t time_start
= GetCountSspClk();
1041 TransmitFor14443b_AsReader();
1043 if(trigger
) LED_A_ON();
1045 LogTrace(cmd
, len
, time_start
, GetCountSspClk()-time_start
, NULL
, TRUE
);
1048 /* Sends an APDU to the tag
1049 * TODO: check CRC and preamble
1051 uint8_t iso14443b_apdu(uint8_t const *message
, size_t message_length
, uint8_t *response
)
1053 uint8_t crc
[2] = {0x00, 0x00};
1054 uint8_t message_frame
[message_length
+ 4];
1056 message_frame
[0] = 0x0A | pcb_blocknum
;
1059 message_frame
[1] = 0;
1061 memcpy(message_frame
+ 2, message
, message_length
);
1063 ComputeCrc14443(CRC_14443_B
, message_frame
, message_length
+ 2, &message_frame
[message_length
+ 2], &message_frame
[message_length
+ 3]);
1065 CodeAndTransmit14443bAsReader(message_frame
, message_length
+ 4); //no
1067 GetTagSamplesFor14443bDemod(); //no
1072 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1073 if ( crc
[0] != Demod
.output
[Demod
.len
-2] || crc
[1] != Demod
.output
[Demod
.len
-1] )
1076 // copy response contents
1077 if(response
!= NULL
)
1078 memcpy(response
, Demod
.output
, Demod
.len
);
1086 uint8_t iso14443b_select_srx_card(iso14b_card_select_t
*card
)
1088 // INITIATE command: wake up the tag using the INITIATE
1089 static const uint8_t init_srx
[] = { ISO14443B_INITIATE
, 0x00, 0x97, 0x5b };
1090 // SELECT command (with space for CRC)
1091 uint8_t select_srx
[] = { ISO14443B_SELECT
, 0x00, 0x00, 0x00};
1092 // temp to calc crc.
1093 uint8_t crc
[2] = {0x00, 0x00};
1095 CodeAndTransmit14443bAsReader(init_srx
, sizeof(init_srx
));
1096 GetTagSamplesFor14443bDemod(); //no
1098 if (Demod
.len
== 0) return 2;
1100 // Randomly generated Chip ID
1101 if (card
) card
->chipid
= Demod
.output
[0];
1103 select_srx
[1] = Demod
.output
[0];
1105 ComputeCrc14443(CRC_14443_B
, select_srx
, 2, &select_srx
[2], &select_srx
[3]);
1106 CodeAndTransmit14443bAsReader(select_srx
, sizeof(select_srx
));
1107 GetTagSamplesFor14443bDemod(); //no
1109 if (Demod
.len
!= 3) return 2;
1111 // Check the CRC of the answer:
1112 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2 , &crc
[0], &crc
[1]);
1113 if(crc
[0] != Demod
.output
[1] || crc
[1] != Demod
.output
[2]) return 3;
1115 // Check response from the tag: should be the same UID as the command we just sent:
1116 if (select_srx
[1] != Demod
.output
[0]) return 1;
1118 // First get the tag's UID:
1119 select_srx
[0] = ISO14443B_GET_UID
;
1121 ComputeCrc14443(CRC_14443_B
, select_srx
, 1 , &select_srx
[1], &select_srx
[2]);
1122 CodeAndTransmit14443bAsReader(select_srx
, 3); // Only first three bytes for this one
1123 GetTagSamplesFor14443bDemod(); //no
1125 if (Demod
.len
!= 10) return 2;
1127 // The check the CRC of the answer
1128 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1129 if(crc
[0] != Demod
.output
[8] || crc
[1] != Demod
.output
[9]) return 3;
1133 memcpy(card
->uid
, Demod
.output
, 8);
1138 /* Perform the ISO 14443 B Card Selection procedure
1139 * Currently does NOT do any collision handling.
1140 * It expects 0-1 cards in the device's range.
1141 * TODO: Support multiple cards (perform anticollision)
1142 * TODO: Verify CRC checksums
1144 uint8_t iso14443b_select_card(iso14b_card_select_t
*card
)
1146 // WUPB command (including CRC)
1147 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
1148 static const uint8_t wupb
[] = { ISO14443B_REQB
, 0x00, 0x08, 0x39, 0x73 };
1149 // ATTRIB command (with space for CRC)
1150 uint8_t attrib
[] = { ISO14443B_ATTRIB
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
1152 // temp to calc crc.
1153 uint8_t crc
[2] = {0x00, 0x00};
1155 // first, wake up the tag
1156 CodeAndTransmit14443bAsReader(wupb
, sizeof(wupb
));
1157 GetTagSamplesFor14443bDemod(); //select_card
1160 if (Demod
.len
< 14) return 2;
1163 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1164 if ( crc
[0] != Demod
.output
[12] || crc
[1] != Demod
.output
[13] )
1169 memcpy(card
->uid
, Demod
.output
+1, 4);
1170 memcpy(card
->atqb
, Demod
.output
+5, 7);
1173 // copy the PUPI to ATTRIB ( PUPI == UID )
1174 memcpy(attrib
+ 1, Demod
.output
+ 1, 4);
1176 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
1177 attrib
[7] = Demod
.output
[10] & 0x0F;
1178 ComputeCrc14443(CRC_14443_B
, attrib
, 9, attrib
+ 9, attrib
+ 10);
1180 CodeAndTransmit14443bAsReader(attrib
, sizeof(attrib
));
1181 GetTagSamplesFor14443bDemod();//select_card
1183 // Answer to ATTRIB too short?
1184 if(Demod
.len
< 3) return 2;
1187 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1188 if ( crc
[0] != Demod
.output
[1] || crc
[1] != Demod
.output
[2] )
1192 if (card
) card
->cid
= Demod
.output
[0];
1194 uint8_t fwt
= card
->atqb
[6]>>4;
1196 uint32_t fwt_time
= (302 << fwt
);
1197 iso14b_set_timeout( fwt_time
);
1199 // reset PCB block number
1204 // Set up ISO 14443 Type B communication (similar to iso14443a_setup)
1205 // field is setup for "Sending as Reader"
1206 void iso14443b_setup() {
1207 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup Enter");
1209 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1211 //BigBuf_Clear_ext(false);
1213 // Initialize Demod and Uart structs
1214 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1215 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1217 // connect Demodulated Signal to ADC:
1218 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1220 // Set up the synchronous serial port
1223 // Signal field is on with the appropriate LED
1224 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
1231 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup Exit");
1234 //-----------------------------------------------------------------------------
1235 // Read a SRI512 ISO 14443B tag.
1237 // SRI512 tags are just simple memory tags, here we're looking at making a dump
1238 // of the contents of the memory. No anticollision algorithm is done, we assume
1239 // we have a single tag in the field.
1241 // I tried to be systematic and check every answer of the tag, every CRC, etc...
1242 //-----------------------------------------------------------------------------
1243 void ReadSTMemoryIso14443b(uint8_t numofblocks
)
1245 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1247 // Make sure that we start from off, since the tags are stateful;
1248 // confusing things will happen if we don't reset them between reads.
1249 switch_off(); // before ReadStMemory
1255 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1258 // Now give it time to spin up.
1259 // Signal field is on with the appropriate LED
1261 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
1264 // First command: wake up the tag using the INITIATE command
1265 uint8_t cmd1
[] = {ISO14443B_INITIATE
, 0x00, 0x97, 0x5b};
1266 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1267 GetTagSamplesFor14443bDemod(); // no
1269 if (Demod
.len
== 0) {
1270 DbpString("No response from tag");
1274 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1275 Demod
.output
[0], Demod
.output
[1], Demod
.output
[2]);
1278 // There is a response, SELECT the uid
1279 DbpString("Now SELECT tag:");
1280 cmd1
[0] = ISO14443B_SELECT
; // 0x0E is SELECT
1281 cmd1
[1] = Demod
.output
[0];
1282 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1283 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1284 GetTagSamplesFor14443bDemod(); //no
1285 if (Demod
.len
!= 3) {
1286 Dbprintf("Expected 3 bytes from tag, got %d", Demod
.len
);
1290 // Check the CRC of the answer:
1291 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 1 , &cmd1
[2], &cmd1
[3]);
1292 if(cmd1
[2] != Demod
.output
[1] || cmd1
[3] != Demod
.output
[2]) {
1293 DbpString("CRC Error reading select response.");
1297 // Check response from the tag: should be the same UID as the command we just sent:
1298 if (cmd1
[1] != Demod
.output
[0]) {
1299 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1
[1], Demod
.output
[0]);
1304 // Tag is now selected,
1305 // First get the tag's UID:
1306 cmd1
[0] = ISO14443B_GET_UID
;
1307 ComputeCrc14443(CRC_14443_B
, cmd1
, 1 , &cmd1
[1], &cmd1
[2]);
1308 CodeAndTransmit14443bAsReader(cmd1
, 3); // no -- Only first three bytes for this one
1309 GetTagSamplesFor14443bDemod(); //no
1310 if (Demod
.len
!= 10) {
1311 Dbprintf("Expected 10 bytes from tag, got %d", Demod
.len
);
1315 // The check the CRC of the answer (use cmd1 as temporary variable):
1316 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 8, &cmd1
[2], &cmd1
[3]);
1317 if(cmd1
[2] != Demod
.output
[8] || cmd1
[3] != Demod
.output
[9]) {
1318 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1319 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[8]<<8)+Demod
.output
[9]);
1320 // Do not return;, let's go on... (we should retry, maybe ?)
1322 Dbprintf("Tag UID (64 bits): %08x %08x",
1323 (Demod
.output
[7]<<24) + (Demod
.output
[6]<<16) + (Demod
.output
[5]<<8) + Demod
.output
[4],
1324 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0]);
1326 // Now loop to read all 16 blocks, address from 0 to last block
1327 Dbprintf("Tag memory dump, block 0 to %d", numofblocks
);
1333 if (i
== numofblocks
) {
1334 DbpString("System area block (0xff):");
1338 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1339 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1340 GetTagSamplesFor14443bDemod(); //no
1342 if (Demod
.len
!= 6) { // Check if we got an answer from the tag
1343 DbpString("Expected 6 bytes from tag, got less...");
1346 // The check the CRC of the answer (use cmd1 as temporary variable):
1347 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 4, &cmd1
[2], &cmd1
[3]);
1348 if(cmd1
[2] != Demod
.output
[4] || cmd1
[3] != Demod
.output
[5]) {
1349 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1350 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[4]<<8)+Demod
.output
[5]);
1351 // Do not return;, let's go on... (we should retry, maybe ?)
1353 // Now print out the memory location:
1354 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i
,
1355 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0],
1356 (Demod
.output
[4]<<8)+Demod
.output
[5]);
1358 if (i
== 0xff) break;
1366 static void iso1444b_setup_snoop(void){
1367 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup_snoop Enter");
1369 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1371 BigBuf_Clear_ext(false);
1372 clear_trace();//setup snoop
1375 // Initialize Demod and Uart structs
1376 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1377 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1379 if (MF_DBGLEVEL
> 1) {
1380 // Print debug information about the buffer sizes
1381 Dbprintf("Snooping buffers initialized:");
1382 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1383 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE
);
1384 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE
);
1385 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE
);
1388 // connect Demodulated Signal to ADC:
1389 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1391 // Setup for the DMA.
1394 // Set FPGA in the appropriate mode
1395 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
| FPGA_HF_READER_RX_XCORR_SNOOP
);
1398 // Start the SSP timer
1400 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup_snoop Exit");
1403 //=============================================================================
1404 // Finally, the `sniffer' combines elements from both the reader and
1405 // simulated tag, to show both sides of the conversation.
1406 //=============================================================================
1408 //-----------------------------------------------------------------------------
1409 // Record the sequence of commands sent by the reader to the tag, with
1410 // triggering so that we start recording at the point that the tag is moved
1412 //-----------------------------------------------------------------------------
1414 * Memory usage for this function, (within BigBuf)
1415 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1416 * Last Received command (tag->reader) - MAX_FRAME_SIZE
1417 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
1418 * Demodulated samples received - all the rest
1420 void RAMFUNC
SnoopIso14443b(void) {
1422 uint32_t time_0
= 0, time_start
= 0, time_stop
= 0;
1424 // We won't start recording the frames that we acquire until we trigger;
1425 // a good trigger condition to get started is probably when we see a
1426 // response from the tag.
1427 int triggered
= TRUE
; // TODO: set and evaluate trigger condition
1429 int maxBehindBy
= 0;
1431 int lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
1433 bool TagIsActive
= FALSE
;
1434 bool ReaderIsActive
= FALSE
;
1436 iso1444b_setup_snoop();
1438 // The DMA buffer, used to stream samples from the FPGA
1439 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
1440 int8_t *upTo
= dmaBuf
;
1442 // Setup and start DMA.
1443 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
) ){
1444 if (MF_DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1449 time_0
= GetCountSspClk();
1451 // And now we loop, receiving samples.
1456 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1);
1458 if ( behindBy
> maxBehindBy
)
1459 maxBehindBy
= behindBy
;
1461 if ( behindBy
< 2 ) continue;
1469 if (upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
1471 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
1472 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
1473 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
1476 // TODO: understand whether we can increase/decrease as we want or not?
1477 if ( behindBy
> ( 9 * ISO14443B_DMA_BUFFER_SIZE
/10) ) {
1478 Dbprintf("blew circular buffer! behindBy=%d", behindBy
);
1483 DbpString("Trace full");
1487 if(BUTTON_PRESS()) {
1488 DbpString("cancelled");
1497 // no need to try decoding reader data if the tag is sending
1498 if (Handle14443bReaderUartBit(ci
& 0x01)) {
1500 time_stop
= (GetCountSspClk()-time_0
);
1503 LogTrace(Uart
.output
, Uart
.byteCnt
, time_start
, time_stop
, NULL
, TRUE
);
1505 /* And ready to receive another command. */
1507 /* And also reset the demod code, which might have been */
1508 /* false-triggered by the commands from the reader. */
1511 time_start
= (GetCountSspClk()-time_0
);
1514 if (Handle14443bReaderUartBit(cq
& 0x01)) {
1516 time_stop
= (GetCountSspClk()-time_0
);
1519 LogTrace(Uart
.output
, Uart
.byteCnt
, time_start
, time_stop
, NULL
, TRUE
);
1521 /* And ready to receive another command. */
1523 /* And also reset the demod code, which might have been */
1524 /* false-triggered by the commands from the reader. */
1527 time_start
= (GetCountSspClk()-time_0
);
1529 ReaderIsActive
= (Uart
.state
> STATE_GOT_FALLING_EDGE_OF_SOF
);
1533 if(!ReaderIsActive
) {
1534 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
1535 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
1536 if(Handle14443bTagSamplesDemod(ci
& 0xFE, cq
& 0xFE)) {
1538 time_stop
= (GetCountSspClk()-time_0
);
1540 LogTrace(Demod
.output
, Demod
.len
, time_start
, time_stop
, NULL
, FALSE
);
1544 // And ready to receive another response.
1547 time_start
= (GetCountSspClk()-time_0
);
1549 TagIsActive
= (Demod
.state
> DEMOD_GOT_FALLING_EDGE_OF_SOF
);
1553 switch_off(); // Snoop
1555 DbpString("Snoop statistics:");
1556 Dbprintf(" Max behind by: %i", maxBehindBy
);
1557 Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);
1558 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
1561 if ( dmaBuf
) dmaBuf
= NULL
;
1562 if ( upTo
) upTo
= NULL
;
1563 // Uart.byteCntMax should be set with ATQB value..
1566 void iso14b_set_trigger(bool enable
) {
1571 * Send raw command to tag ISO14443B
1573 * param flags enum ISO14B_COMMAND. (mifare.h)
1574 * len len of buffer data
1575 * data buffer with bytes to send
1581 void SendRawCommand14443B_Ex(UsbCommand
*c
)
1583 iso14b_command_t param
= c
->arg
[0];
1584 size_t len
= c
->arg
[1] & 0xffff;
1585 uint8_t *cmd
= c
->d
.asBytes
;
1587 uint32_t sendlen
= sizeof(iso14b_card_select_t
);
1588 uint8_t buf
[USB_CMD_DATA_SIZE
] = {0x00};
1590 if (MF_DBGLEVEL
> 3) Dbprintf("14b raw: param, %04x", param
);
1592 // turn on trigger (LED_A)
1593 if ((param
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
)
1594 iso14b_set_trigger(TRUE
);
1596 if ((param
& ISO14B_CONNECT
) == ISO14B_CONNECT
) {
1597 // Make sure that we start from off, since the tags are stateful;
1598 // confusing things will happen if we don't reset them between reads.
1599 //switch_off(); // before connect in raw
1605 if ((param
& ISO14B_SELECT_STD
) == ISO14B_SELECT_STD
) {
1606 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
1607 status
= iso14443b_select_card(card
);
1608 cmd_send(CMD_ACK
, status
, sendlen
, 0, buf
, sendlen
);
1609 // 0: OK 2: attrib fail, 3:crc fail,
1610 if ( status
> 0 ) return;
1613 if ((param
& ISO14B_SELECT_SR
) == ISO14B_SELECT_SR
) {
1614 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
1615 status
= iso14443b_select_srx_card(card
);
1616 cmd_send(CMD_ACK
, status
, sendlen
, 0, buf
, sendlen
);
1617 // 0: OK 2: attrib fail, 3:crc fail,
1618 if ( status
> 0 ) return;
1621 if ((param
& ISO14B_APDU
) == ISO14B_APDU
) {
1622 status
= iso14443b_apdu(cmd
, len
, buf
);
1623 cmd_send(CMD_ACK
, status
, status
, 0, buf
, status
);
1626 if ((param
& ISO14B_RAW
) == ISO14B_RAW
) {
1627 if((param
& ISO14B_APPEND_CRC
) == ISO14B_APPEND_CRC
) {
1628 AppendCrc14443b(cmd
, len
);
1632 CodeAndTransmit14443bAsReader(cmd
, len
); // raw
1633 GetTagSamplesFor14443bDemod(); // raw
1635 sendlen
= MIN(Demod
.len
, USB_CMD_DATA_SIZE
);
1636 status
= (Demod
.len
> 0) ? 0 : 1;
1637 cmd_send(CMD_ACK
, status
, sendlen
, 0, Demod
.output
, sendlen
);
1640 // turn off trigger (LED_A)
1641 if ((param
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
)
1642 iso14b_set_trigger(FALSE
);
1644 // turn off antenna et al
1645 // we don't send a HALT command.
1646 if ((param
& ISO14B_DISCONNECT
) == ISO14B_DISCONNECT
) {
1647 if (MF_DBGLEVEL
> 3) Dbprintf("disconnect");
1648 switch_off(); // disconnect raw
1650 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);