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);
25 #define SEND4STUFFBIT(x) ToSendStuffBit(x);
27 static void switch_off(void);
29 // the block number for the ISO14443-4 PCB (used with APDUs)
30 static uint8_t pcb_blocknum
= 0;
32 static uint32_t iso14b_timeout
= RECEIVE_SAMPLES_TIMEOUT
;
33 // param timeout is in ftw_
34 void iso14b_set_timeout(uint32_t timeout
) {
36 // clock is about 1.5 us
37 iso14b_timeout
= timeout
;
38 if(MF_DBGLEVEL
>= 2) Dbprintf("ISO14443B Timeout set to %ld fwt", iso14b_timeout
);
41 static void switch_off(void){
42 if (MF_DBGLEVEL
> 3) Dbprintf("switch_off");
43 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
50 //=============================================================================
51 // An ISO 14443 Type B tag. We listen for commands from the reader, using
52 // a UART kind of thing that's implemented in software. When we get a
53 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
54 // If it's good, then we can do something appropriate with it, and send
56 //=============================================================================
59 //-----------------------------------------------------------------------------
60 // The software UART that receives commands from the reader, and its state variables.
61 //-----------------------------------------------------------------------------
65 STATE_GOT_FALLING_EDGE_OF_SOF
,
66 STATE_AWAITING_START_BIT
,
77 static void UartReset() {
78 Uart
.state
= STATE_UNSYNCD
;
82 Uart
.byteCntMax
= MAX_FRAME_SIZE
;
86 static void UartInit(uint8_t *data
) {
89 // memset(Uart.output, 0x00, MAX_FRAME_SIZE);
92 //-----------------------------------------------------------------------------
93 // The software Demod that receives commands from the tag, and its state variables.
94 //-----------------------------------------------------------------------------
98 DEMOD_PHASE_REF_TRAINING
,
99 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
,
100 DEMOD_GOT_FALLING_EDGE_OF_SOF
,
101 DEMOD_AWAITING_START_BIT
,
107 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
116 uint32_t startTime
, endTime
;
119 // Clear out the state of the "UART" that receives from the tag.
120 static void DemodReset() {
121 Demod
.state
= DEMOD_UNSYNCD
;
133 static void DemodInit(uint8_t *data
) {
136 // memset(Demod.output, 0x00, MAX_FRAME_SIZE);
139 void AppendCrc14443b(uint8_t* data
, int len
) {
140 ComputeCrc14443(CRC_14443_B
, data
, len
, data
+len
, data
+len
+1);
143 //-----------------------------------------------------------------------------
144 // Code up a string of octets at layer 2 (including CRC, we don't generate
145 // that here) so that they can be transmitted to the reader. Doesn't transmit
146 // them yet, just leaves them ready to send in ToSend[].
147 //-----------------------------------------------------------------------------
148 static void CodeIso14443bAsTag(const uint8_t *cmd
, int len
) {
151 * Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
152 * Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
154 * fc - carrier frequency 13.56mHz
155 * TR0 - Guard Time per 14443-2
156 * TR1 - Synchronization Time per 14443-2
157 * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
159 * Elementary Time Unit (ETU) is
160 * - 128 Carrier Cycles (9.4395 µS) = 8 Subcarrier Units
162 * - 10 ETU = 1 startbit, 8 databits, 1 stopbit (10bits length)
166 * Start of frame (SOF) is
167 * - [10-11] ETU of ZEROS, unmodulated time
168 * - [2-3] ETU of ONES,
170 * End of frame (EOF) is
171 * - [10-11] ETU of ZEROS, unmodulated time
173 * -TO VERIFY THIS BELOW-
174 * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
176 * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (9.44µS)
177 * - A 0-bit input to the FPGA becomes an unmodulated time of 9.44µS
181 * Card sends data ub 847.e kHz subcarrier
182 * 848k = 9.44µS = 128 fc
183 * 424k = 18.88µS = 256 fc
184 * 212k = 37.76µS = 512 fc
185 * 106k = 75.52µS = 1024 fc
187 * Reader data transmission:
188 * - no modulation ONES
190 * - Command, data and CRC_B
192 * - no modulation ONES
194 * Card data transmission
197 * - data (each bytes is: 1startbit,8bits, 1stopbit)
201 * FPGA implementation :
202 * At this point only Type A is implemented. This means that we are using a
203 * bit rate of 106 kbit/s, or fc/128. Oversample by 4, which ought to make
204 * things practical for the ARM (fc/32, 423.8 kbits/s, ~50 kbytes/s)
208 // ToSendStuffBit, 40 calls
209 // 1 ETU = 1startbit, 1stopbit, 8databits == 10bits.
210 // 1 ETU = 10 * 4 == 40 stuffbits ( ETU_TAG_BIT )
216 // Transmit a burst of ones, as the initial thing that lets the
217 // reader get phase sync.
218 // This loop is TR1, per specification
219 // TR1 minimum must be > 80/fs
220 // TR1 maximum 200/fs
221 // 80/fs < TR1 < 200/fs
222 // 10 ETU < TR1 < 24 ETU
225 // 10-11 ETU * 4times samples ZEROS
226 for(i
= 0; i
< 10; i
++) { SEND4STUFFBIT(0); }
228 // 2-3 ETU * 4times samples ONES
229 for(i
= 0; i
< 3; i
++) { SEND4STUFFBIT(1); }
232 for(i
= 0; i
< len
; ++i
) {
239 for(j
= 0; j
< 8; ++j
) {
252 // For PICC it ranges 0-18us (1etu = 9us)
257 // 10-11 ETU * 4 sample rate = ZEROS
258 for(i
= 0; i
< 10; i
++) { SEND4STUFFBIT(0); }
261 for(i
= 0; i
< 40; i
++) { SEND4STUFFBIT(1); }
263 // Convert from last byte pos to length
268 /* Receive & handle a bit coming from the reader.
270 * This function is called 4 times per bit (every 2 subcarrier cycles).
271 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
274 * LED A -> ON once we have received the SOF and are expecting the rest.
275 * LED A -> OFF once we have received EOF or are in error state or unsynced
277 * Returns: true if we received a EOF
278 * false if we are still waiting for some more
280 static RAMFUNC
int Handle14443bReaderUartBit(uint8_t bit
) {
284 // we went low, so this could be the beginning of an SOF
285 Uart
.state
= STATE_GOT_FALLING_EDGE_OF_SOF
;
291 case STATE_GOT_FALLING_EDGE_OF_SOF
:
293 if(Uart
.posCnt
== 2) { // sample every 4 1/fs in the middle of a bit
295 if(Uart
.bitCnt
> 9) {
296 // we've seen enough consecutive
297 // zeros that it's a valid SOF
300 Uart
.state
= STATE_AWAITING_START_BIT
;
301 LED_A_ON(); // Indicate we got a valid SOF
303 // didn't stay down long enough
304 // before going high, error
305 Uart
.state
= STATE_UNSYNCD
;
308 // do nothing, keep waiting
312 if(Uart
.posCnt
>= 4) Uart
.posCnt
= 0;
313 if(Uart
.bitCnt
> 12) {
314 // Give up if we see too many zeros without
317 Uart
.state
= STATE_UNSYNCD
;
321 case STATE_AWAITING_START_BIT
:
324 if(Uart
.posCnt
> 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
325 // stayed high for too long between
327 Uart
.state
= STATE_UNSYNCD
;
330 // falling edge, this starts the data byte
334 Uart
.state
= STATE_RECEIVING_DATA
;
338 case STATE_RECEIVING_DATA
:
340 if(Uart
.posCnt
== 2) {
341 // time to sample a bit
344 Uart
.shiftReg
|= 0x200;
348 if(Uart
.posCnt
>= 4) {
351 if(Uart
.bitCnt
== 10) {
352 if((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001))
354 // this is a data byte, with correct
355 // start and stop bits
356 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xff;
359 if(Uart
.byteCnt
>= Uart
.byteCntMax
) {
360 // Buffer overflowed, give up
362 Uart
.state
= STATE_UNSYNCD
;
364 // so get the next byte now
366 Uart
.state
= STATE_AWAITING_START_BIT
;
368 } else if (Uart
.shiftReg
== 0x000) {
369 // this is an EOF byte
370 LED_A_OFF(); // Finished receiving
371 Uart
.state
= STATE_UNSYNCD
;
372 if (Uart
.byteCnt
!= 0) {
378 Uart
.state
= STATE_UNSYNCD
;
385 Uart
.state
= STATE_UNSYNCD
;
392 //-----------------------------------------------------------------------------
393 // Receive a command (from the reader to us, where we are the simulated tag),
394 // and store it in the given buffer, up to the given maximum length. Keeps
395 // spinning, waiting for a well-framed command, until either we get one
396 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
398 // Assume that we're called with the SSC (to the FPGA) and ADC path set
400 //-----------------------------------------------------------------------------
401 static int GetIso14443bCommandFromReader(uint8_t *received
, uint16_t *len
) {
402 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
403 // only, since we are receiving, not transmitting).
404 // Signal field is off with the appropriate LED
406 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
412 // clear receiving shift register and holding register
413 // What does this loop do? Is it TR1?
414 for(uint8_t c
= 0; c
< 10;) {
415 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
416 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
421 // Now run a `software UART' on the stream of incoming samples.
426 while( !BUTTON_PRESS() ) {
429 if ( AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
) {
430 b
= (uint8_t) AT91C_BASE_SSC
->SSC_RHR
;
431 for ( mask
= 0x80; mask
!= 0; mask
>>= 1) {
432 if ( Handle14443bReaderUartBit(b
& mask
)) {
442 void ClearFpgaShiftingRegisters(void){
446 // clear receiving shift register and holding register
447 while(!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
448 b
= AT91C_BASE_SSC
->SSC_RHR
; (void) b
;
450 while(!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
451 b
= AT91C_BASE_SSC
->SSC_RHR
; (void) b
;
454 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
455 for (uint8_t j
= 0; j
< 5; j
++) { // allow timeout - better late than never
456 while(!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
457 if (AT91C_BASE_SSC
->SSC_RHR
) break;
461 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
464 void WaitForFpgaDelayQueueIsEmpty( uint16_t delay
){
465 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
466 uint8_t fpga_queued_bits
= delay
>> 3; // twich /8 ?? >>3,
467 for (uint8_t i
= 0; i
<= fpga_queued_bits
/8 + 1; ) {
468 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
469 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
475 static void TransmitFor14443b_AsTag( uint8_t *response
, uint16_t len
) {
477 // Signal field is off with the appropriate LED
479 uint16_t fpgasendQueueDelay
= 0;
482 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
484 ClearFpgaShiftingRegisters();
488 // Transmit the response.
489 for(uint16_t i
= 0; i
< len
;) {
490 if(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_TXRDY
) {
491 AT91C_BASE_SSC
->SSC_THR
= response
[++i
];
492 fpgasendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
496 WaitForFpgaDelayQueueIsEmpty(fpgasendQueueDelay
);
498 //-----------------------------------------------------------------------------
499 // Main loop of simulated tag: receive commands from reader, decide what
500 // response to send, and send it.
501 //-----------------------------------------------------------------------------
502 void SimulateIso14443bTag(uint32_t pupi
) {
504 ///////////// setup device.
505 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
507 // allocate command receive buffer
509 BigBuf_Clear_ext(false);
513 // connect Demodulated Signal to ADC:
514 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
516 // Set up the synchronous serial port
520 uint16_t len
, cmdsReceived
= 0;
521 int cardSTATE
= SIM_NOFIELD
;
522 int vHf
= 0; // in mV
523 // uint32_t time_0 = 0;
524 // uint32_t t2r_time = 0;
525 // uint32_t r2t_time = 0;
526 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
528 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
529 // static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
530 // ... and REQB, AFI=0, Normal Request, N=1:
531 // static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
533 // static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
535 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
536 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
537 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
538 uint8_t respATQB
[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19,
539 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 };
541 // response to HLTB and ATTRIB
542 static const uint8_t respOK
[] = {0x00, 0x78, 0xF0};
544 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
546 num_to_bytes(pupi
, 4, respATQB
+1);
547 ComputeCrc14443(CRC_14443_B
, respATQB
, 12, respATQB
+13, respATQB
+14);
550 // prepare "ATQB" tag answer (encoded):
551 CodeIso14443bAsTag(respATQB
, sizeof(respATQB
));
552 uint8_t *encodedATQB
= BigBuf_malloc(ToSendMax
);
553 uint16_t encodedATQBLen
= ToSendMax
;
554 memcpy(encodedATQB
, ToSend
, ToSendMax
);
557 // prepare "OK" tag answer (encoded):
558 CodeIso14443bAsTag(respOK
, sizeof(respOK
));
559 uint8_t *encodedOK
= BigBuf_malloc(ToSendMax
);
560 uint16_t encodedOKLen
= ToSendMax
;
561 memcpy(encodedOK
, ToSend
, ToSendMax
);
564 while (!BUTTON_PRESS() && !usb_poll_validate_length()) {
568 if (cardSTATE
== SIM_NOFIELD
) {
569 vHf
= (MAX_ADC_HF_VOLTAGE
* AvgAdc(ADC_CHAN_HF
)) >> 10;
570 if ( vHf
> MF_MINFIELDV
) {
571 cardSTATE
= SIM_IDLE
;
575 if (cardSTATE
== SIM_NOFIELD
) continue;
577 // Get reader command
578 if (!GetIso14443bCommandFromReader(receivedCmd
, &len
)) {
579 Dbprintf("button pressed, received %d commands", cmdsReceived
);
583 // ISO14443-B protocol states:
584 // REQ or WUP request in ANY state
585 // WUP in HALTED state
587 if ( (receivedCmd
[0] == ISO14443B_REQB
&& (receivedCmd
[2] & 0x8)== 0x8 && cardSTATE
== SIM_HALTED
) ||
588 receivedCmd
[0] == ISO14443B_REQB
){
589 LogTrace(receivedCmd
, len
, 0, 0, NULL
, TRUE
);
590 cardSTATE
= SIM_SELECTING
;
595 * How should this flow go?
597 * send response ( waiting for Attrib)
599 * send response ( waiting for commands 7816)
601 send halt response ( waiting for wupb )
608 LogTrace(receivedCmd
, len
, 0, 0, NULL
, TRUE
);
611 case SIM_SELECTING
: {
612 TransmitFor14443b_AsTag( encodedATQB
, encodedATQBLen
);
613 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, FALSE
);
614 cardSTATE
= SIM_WORK
;
618 TransmitFor14443b_AsTag( encodedOK
, encodedOKLen
);
619 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, FALSE
);
620 cardSTATE
= SIM_HALTED
;
623 case SIM_ACKNOWLEDGE
:{
624 TransmitFor14443b_AsTag( encodedOK
, encodedOKLen
);
625 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, FALSE
);
626 cardSTATE
= SIM_IDLE
;
630 if ( len
== 7 && receivedCmd
[0] == ISO14443B_HALT
) {
631 cardSTATE
= SIM_HALTED
;
632 } else if ( len
== 11 && receivedCmd
[0] == ISO14443B_ATTRIB
) {
633 cardSTATE
= SIM_ACKNOWLEDGE
;
638 // - emulate with a memory dump
639 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len
, cmdsReceived
);
643 if (len
>= 3){ // if crc exists
644 ComputeCrc14443(CRC_14443_B
, receivedCmd
, len
-2, &b1
, &b2
);
645 if(b1
!= receivedCmd
[len
-2] || b2
!= receivedCmd
[len
-1])
646 DbpString("+++CRC fail");
648 DbpString("CRC passes");
650 cardSTATE
= SIM_IDLE
;
658 if(cmdsReceived
> 1000) {
659 DbpString("14B Simulate, 1000 commands later...");
663 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, BigBuf_get_traceLen());
664 switch_off(); //simulate
667 //=============================================================================
668 // An ISO 14443 Type B reader. We take layer two commands, code them
669 // appropriately, and then send them to the tag. We then listen for the
670 // tag's response, which we leave in the buffer to be demodulated on the
672 //=============================================================================
675 * Handles reception of a bit from the tag
677 * This function is called 2 times per bit (every 4 subcarrier cycles).
678 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
681 * LED C -> ON once we have received the SOF and are expecting the rest.
682 * LED C -> OFF once we have received EOF or are unsynced
684 * Returns: true if we received a EOF
685 * false if we are still waiting for some more
688 #ifndef SUBCARRIER_DETECT_THRESHOLD
689 # define SUBCARRIER_DETECT_THRESHOLD 8
692 static RAMFUNC
int Handle14443bTagSamplesDemod(int ci
, int cq
) {
693 int v
=0;// , myI, myQ = 0;
694 // The soft decision on the bit uses an estimate of just the
695 // quadrant of the reference angle, not the exact angle.
696 #define MAKE_SOFT_DECISION() { \
697 if(Demod.sumI > 0) { \
702 if(Demod.sumQ > 0) { \
709 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq)
710 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
711 #define CHECK_FOR_SUBCARRIER() { \
713 if(cq < 0) { /* ci < 0, cq < 0 */ \
715 v = -cq - (ci >> 1); \
717 v = -ci - (cq >> 1); \
719 } else { /* ci < 0, cq >= 0 */ \
721 v = -ci + (cq >> 1); \
723 v = cq - (ci >> 1); \
727 if(cq < 0) { /* ci >= 0, cq < 0 */ \
729 v = ci - (cq >> 1); \
731 v = -cq + (ci >> 1); \
733 } else { /* ci >= 0, cq >= 0 */ \
735 v = ci + (cq >> 1); \
737 v = cq + (ci >> 1); \
743 //note: couldn't we just use MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2) from common.h - marshmellow
744 #define CHECK_FOR_SUBCARRIER_un() { \
747 v = MAX(myI,myQ) + (MIN(myI,myQ) >> 1); \
750 switch(Demod
.state
) {
753 CHECK_FOR_SUBCARRIER();
755 // subcarrier detected
756 if(v
> SUBCARRIER_DETECT_THRESHOLD
) {
757 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
764 case DEMOD_PHASE_REF_TRAINING
:
765 if(Demod
.posCount
< 8) {
767 CHECK_FOR_SUBCARRIER();
769 if (v
> SUBCARRIER_DETECT_THRESHOLD
) {
770 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
771 // note: synchronization time > 80 1/fs
777 Demod
.state
= DEMOD_UNSYNCD
;
780 Demod
.state
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
;
784 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
:
786 MAKE_SOFT_DECISION();
788 if(v
< 0) { // logic '0' detected
789 Demod
.state
= DEMOD_GOT_FALLING_EDGE_OF_SOF
;
790 Demod
.posCount
= 0; // start of SOF sequence
792 // maximum length of TR1 = 200 1/fs
793 if(Demod
.posCount
> 25*2) Demod
.state
= DEMOD_UNSYNCD
;
798 case DEMOD_GOT_FALLING_EDGE_OF_SOF
:
801 MAKE_SOFT_DECISION();
804 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
805 if(Demod
.posCount
< 9*2) {
806 Demod
.state
= DEMOD_UNSYNCD
;
808 LED_C_ON(); // Got SOF
809 Demod
.startTime
= GetCountSspClk();
810 Demod
.state
= DEMOD_AWAITING_START_BIT
;
815 // low phase of SOF too long (> 12 etu)
816 if (Demod
.posCount
> 12*2) {
817 Demod
.state
= DEMOD_UNSYNCD
;
823 case DEMOD_AWAITING_START_BIT
:
826 MAKE_SOFT_DECISION();
829 if(Demod
.posCount
> 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
830 Demod
.state
= DEMOD_UNSYNCD
;
833 } else { // start bit detected
835 Demod
.posCount
= 1; // this was the first half
838 Demod
.state
= DEMOD_RECEIVING_DATA
;
842 case DEMOD_RECEIVING_DATA
:
844 MAKE_SOFT_DECISION();
846 if (Demod
.posCount
== 0) {
851 // second half of bit
853 Demod
.shiftReg
>>= 1;
856 if(Demod
.thisBit
> 0) Demod
.shiftReg
|= 0x200;
860 if(Demod
.bitCount
== 10) {
862 uint16_t s
= Demod
.shiftReg
;
864 // stop bit == '1', start bit == '0'
865 if((s
& 0x200) && !(s
& 0x001)) {
866 uint8_t b
= (s
>> 1);
867 Demod
.output
[Demod
.len
] = b
;
869 Demod
.state
= DEMOD_AWAITING_START_BIT
;
871 Demod
.state
= DEMOD_UNSYNCD
;
872 Demod
.endTime
= GetCountSspClk();
875 // This is EOF (start, stop and all data bits == '0'
876 if(s
== 0) return TRUE
;
884 Demod
.state
= DEMOD_UNSYNCD
;
893 * Demodulate the samples we received from the tag, also log to tracebuffer
894 * quiet: set to 'TRUE' to disable debug output
896 static void GetTagSamplesFor14443bDemod() {
897 bool gotFrame
= FALSE
;
898 int lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
899 int max
= 0, ci
= 0, cq
= 0, samples
= 0;
900 uint32_t time_0
= 0, time_stop
= 0;
904 // Set up the demodulator for tag -> reader responses.
905 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
907 // The DMA buffer, used to stream samples from the FPGA
908 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
909 int8_t *upTo
= dmaBuf
;
911 // Setup and start DMA.
912 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
) ){
913 if (MF_DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
917 time_0
= GetCountSspClk();
919 // And put the FPGA in the appropriate mode
920 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
922 while( !BUTTON_PRESS() ) {
925 int behindBy
= lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
926 if(behindBy
> max
) max
= behindBy
;
928 // rx counter - dma counter? (how much?) & (mod) dma buff / 2. (since 2bytes at the time is read)
929 while(((lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1)) > 2) {
936 // restart DMA buffer to receive again.
937 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
939 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
940 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
944 if(lastRxCounter
<= 0)
945 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
947 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
948 //gotFrame = Handle14443bTagSamplesDemod(ci & 0xfe, cq & 0xfe);
949 gotFrame
= Handle14443bTagSamplesDemod(ci
, cq
);
950 if ( gotFrame
) break;
954 time_stop
= GetCountSspClk() - time_0
;
956 if(time_stop
> iso14b_timeout
|| gotFrame
) break;
961 if (MF_DBGLEVEL
>= 3) {
962 Dbprintf("max behindby = %d, samples = %d, gotFrame = %s, Demod.state = %d, Demod.len = %u",
965 (gotFrame
) ? "true" : "false",
971 LogTrace(Demod
.output
, Demod
.len
, Demod
.startTime
, Demod
.endTime
, NULL
, FALSE
);
975 //-----------------------------------------------------------------------------
976 // Transmit the command (to the tag) that was placed in ToSend[].
977 //-----------------------------------------------------------------------------
978 static void TransmitFor14443b_AsReader(void) {
980 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
984 // we could been in following mode:
985 // FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ
986 // if its second call or more
988 // What does this loop do? Is it TR1?
989 for(c
= 0; c
< 10;) {
990 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
991 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
997 for(c
= 0; c
< ToSendMax
;) {
998 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
999 AT91C_BASE_SSC
->SSC_THR
= ToSend
[c
];
1006 //-----------------------------------------------------------------------------
1007 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1008 // so that it is ready to transmit to the tag using TransmitFor14443b().
1009 //-----------------------------------------------------------------------------
1010 static void CodeIso14443bAsReader(const uint8_t *cmd
, int len
)
1013 * Reader data transmission:
1014 * - no modulation ONES
1016 * - Command, data and CRC_B
1018 * - no modulation ONES
1021 * TR0 - 8 ETUS minimum.
1029 // 10-11 ETUs of ZERO
1030 for(i
= 0; i
< 10; ++i
) ToSendStuffBit(0);
1038 // from here we add BITS
1039 for(i
= 0; i
< len
; ++i
) {
1044 if ( b
& 1 ) ToSendStuffBit(1); else ToSendStuffBit(0);
1045 if ( (b
>>1) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1046 if ( (b
>>2) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1047 if ( (b
>>3) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1048 if ( (b
>>4) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1049 if ( (b
>>5) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1050 if ( (b
>>6) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1051 if ( (b
>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1054 // EGT extra guard time
1055 // For PCD it ranges 0-57us (1etu = 9us)
1062 // 10-11 ETUs of ZERO
1063 for(i
= 0; i
< 10; ++i
) ToSendStuffBit(0);
1065 // Transition time. TR0 - guard time
1067 // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF.
1068 for(i
= 0; i
< 40 ; ++i
) ToSendStuffBit(1);
1070 // TR1 - Synchronization time
1071 // Convert from last character reference to length
1077 Convenience function to encode, transmit and trace iso 14443b comms
1079 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd
, int len
) {
1081 CodeIso14443bAsReader(cmd
, len
);
1083 uint32_t time_start
= GetCountSspClk();
1085 TransmitFor14443b_AsReader();
1087 if(trigger
) LED_A_ON();
1089 LogTrace(cmd
, len
, time_start
, GetCountSspClk()-time_start
, NULL
, TRUE
);
1092 /* Sends an APDU to the tag
1093 * TODO: check CRC and preamble
1095 uint8_t iso14443b_apdu(uint8_t const *message
, size_t message_length
, uint8_t *response
)
1097 uint8_t crc
[2] = {0x00, 0x00};
1098 uint8_t message_frame
[message_length
+ 4];
1100 message_frame
[0] = 0x0A | pcb_blocknum
;
1103 message_frame
[1] = 0;
1105 memcpy(message_frame
+ 2, message
, message_length
);
1107 ComputeCrc14443(CRC_14443_B
, message_frame
, message_length
+ 2, &message_frame
[message_length
+ 2], &message_frame
[message_length
+ 3]);
1109 CodeAndTransmit14443bAsReader(message_frame
, message_length
+ 4); //no
1111 GetTagSamplesFor14443bDemod(); //no
1116 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1117 if ( crc
[0] != Demod
.output
[Demod
.len
-2] || crc
[1] != Demod
.output
[Demod
.len
-1] )
1120 // copy response contents
1121 if(response
!= NULL
)
1122 memcpy(response
, Demod
.output
, Demod
.len
);
1130 uint8_t iso14443b_select_srx_card(iso14b_card_select_t
*card
)
1132 // INITIATE command: wake up the tag using the INITIATE
1133 static const uint8_t init_srx
[] = { ISO14443B_INITIATE
, 0x00, 0x97, 0x5b };
1134 // SELECT command (with space for CRC)
1135 uint8_t select_srx
[] = { ISO14443B_SELECT
, 0x00, 0x00, 0x00};
1136 // temp to calc crc.
1137 uint8_t crc
[2] = {0x00, 0x00};
1139 CodeAndTransmit14443bAsReader(init_srx
, sizeof(init_srx
));
1140 GetTagSamplesFor14443bDemod(); //no
1142 if (Demod
.len
== 0) return 2;
1144 // Randomly generated Chip ID
1145 if (card
) card
->chipid
= Demod
.output
[0];
1147 select_srx
[1] = Demod
.output
[0];
1149 ComputeCrc14443(CRC_14443_B
, select_srx
, 2, &select_srx
[2], &select_srx
[3]);
1150 CodeAndTransmit14443bAsReader(select_srx
, sizeof(select_srx
));
1151 GetTagSamplesFor14443bDemod(); //no
1153 if (Demod
.len
!= 3) return 2;
1155 // Check the CRC of the answer:
1156 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2 , &crc
[0], &crc
[1]);
1157 if(crc
[0] != Demod
.output
[1] || crc
[1] != Demod
.output
[2]) return 3;
1159 // Check response from the tag: should be the same UID as the command we just sent:
1160 if (select_srx
[1] != Demod
.output
[0]) return 1;
1162 // First get the tag's UID:
1163 select_srx
[0] = ISO14443B_GET_UID
;
1165 ComputeCrc14443(CRC_14443_B
, select_srx
, 1 , &select_srx
[1], &select_srx
[2]);
1166 CodeAndTransmit14443bAsReader(select_srx
, 3); // Only first three bytes for this one
1167 GetTagSamplesFor14443bDemod(); //no
1169 if (Demod
.len
!= 10) return 2;
1171 // The check the CRC of the answer
1172 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1173 if(crc
[0] != Demod
.output
[8] || crc
[1] != Demod
.output
[9]) return 3;
1177 memcpy(card
->uid
, Demod
.output
, 8);
1182 /* Perform the ISO 14443 B Card Selection procedure
1183 * Currently does NOT do any collision handling.
1184 * It expects 0-1 cards in the device's range.
1185 * TODO: Support multiple cards (perform anticollision)
1186 * TODO: Verify CRC checksums
1188 uint8_t iso14443b_select_card(iso14b_card_select_t
*card
)
1190 // WUPB command (including CRC)
1191 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
1192 static const uint8_t wupb
[] = { ISO14443B_REQB
, 0x00, 0x08, 0x39, 0x73 };
1193 // ATTRIB command (with space for CRC)
1194 uint8_t attrib
[] = { ISO14443B_ATTRIB
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
1196 // temp to calc crc.
1197 uint8_t crc
[2] = {0x00, 0x00};
1199 // first, wake up the tag
1200 CodeAndTransmit14443bAsReader(wupb
, sizeof(wupb
));
1201 GetTagSamplesFor14443bDemod(); //select_card
1204 if (Demod
.len
< 14) return 2;
1207 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1208 if ( crc
[0] != Demod
.output
[12] || crc
[1] != Demod
.output
[13] )
1213 memcpy(card
->uid
, Demod
.output
+1, 4);
1214 memcpy(card
->atqb
, Demod
.output
+5, 7);
1217 // copy the PUPI to ATTRIB ( PUPI == UID )
1218 memcpy(attrib
+ 1, Demod
.output
+ 1, 4);
1220 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
1221 attrib
[7] = Demod
.output
[10] & 0x0F;
1222 ComputeCrc14443(CRC_14443_B
, attrib
, 9, attrib
+ 9, attrib
+ 10);
1224 CodeAndTransmit14443bAsReader(attrib
, sizeof(attrib
));
1225 GetTagSamplesFor14443bDemod();//select_card
1227 // Answer to ATTRIB too short?
1228 if(Demod
.len
< 3) return 2;
1231 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1232 if ( crc
[0] != Demod
.output
[1] || crc
[1] != Demod
.output
[2] )
1236 if (card
) card
->cid
= Demod
.output
[0];
1238 uint8_t fwt
= card
->atqb
[6]>>4;
1240 uint32_t fwt_time
= (302 << fwt
);
1241 iso14b_set_timeout( fwt_time
);
1243 // reset PCB block number
1248 // Set up ISO 14443 Type B communication (similar to iso14443a_setup)
1249 // field is setup for "Sending as Reader"
1250 void iso14443b_setup() {
1251 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup Enter");
1253 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1255 //BigBuf_Clear_ext(false);
1257 // Initialize Demod and Uart structs
1258 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1259 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1261 // connect Demodulated Signal to ADC:
1262 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1264 // Set up the synchronous serial port
1267 // Signal field is on with the appropriate LED
1268 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
1275 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup Exit");
1278 //-----------------------------------------------------------------------------
1279 // Read a SRI512 ISO 14443B tag.
1281 // SRI512 tags are just simple memory tags, here we're looking at making a dump
1282 // of the contents of the memory. No anticollision algorithm is done, we assume
1283 // we have a single tag in the field.
1285 // I tried to be systematic and check every answer of the tag, every CRC, etc...
1286 //-----------------------------------------------------------------------------
1287 void ReadSTMemoryIso14443b(uint8_t numofblocks
)
1289 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1291 // Make sure that we start from off, since the tags are stateful;
1292 // confusing things will happen if we don't reset them between reads.
1293 switch_off(); // before ReadStMemory
1299 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1302 // Now give it time to spin up.
1303 // Signal field is on with the appropriate LED
1305 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
1308 // First command: wake up the tag using the INITIATE command
1309 uint8_t cmd1
[] = {ISO14443B_INITIATE
, 0x00, 0x97, 0x5b};
1310 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1311 GetTagSamplesFor14443bDemod(); // no
1313 if (Demod
.len
== 0) {
1314 DbpString("No response from tag");
1318 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1319 Demod
.output
[0], Demod
.output
[1], Demod
.output
[2]);
1322 // There is a response, SELECT the uid
1323 DbpString("Now SELECT tag:");
1324 cmd1
[0] = ISO14443B_SELECT
; // 0x0E is SELECT
1325 cmd1
[1] = Demod
.output
[0];
1326 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1327 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1328 GetTagSamplesFor14443bDemod(); //no
1329 if (Demod
.len
!= 3) {
1330 Dbprintf("Expected 3 bytes from tag, got %d", Demod
.len
);
1334 // Check the CRC of the answer:
1335 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 1 , &cmd1
[2], &cmd1
[3]);
1336 if(cmd1
[2] != Demod
.output
[1] || cmd1
[3] != Demod
.output
[2]) {
1337 DbpString("CRC Error reading select response.");
1341 // Check response from the tag: should be the same UID as the command we just sent:
1342 if (cmd1
[1] != Demod
.output
[0]) {
1343 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1
[1], Demod
.output
[0]);
1348 // Tag is now selected,
1349 // First get the tag's UID:
1350 cmd1
[0] = ISO14443B_GET_UID
;
1351 ComputeCrc14443(CRC_14443_B
, cmd1
, 1 , &cmd1
[1], &cmd1
[2]);
1352 CodeAndTransmit14443bAsReader(cmd1
, 3); // no -- Only first three bytes for this one
1353 GetTagSamplesFor14443bDemod(); //no
1354 if (Demod
.len
!= 10) {
1355 Dbprintf("Expected 10 bytes from tag, got %d", Demod
.len
);
1359 // The check the CRC of the answer (use cmd1 as temporary variable):
1360 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 8, &cmd1
[2], &cmd1
[3]);
1361 if(cmd1
[2] != Demod
.output
[8] || cmd1
[3] != Demod
.output
[9]) {
1362 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1363 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[8]<<8)+Demod
.output
[9]);
1364 // Do not return;, let's go on... (we should retry, maybe ?)
1366 Dbprintf("Tag UID (64 bits): %08x %08x",
1367 (Demod
.output
[7]<<24) + (Demod
.output
[6]<<16) + (Demod
.output
[5]<<8) + Demod
.output
[4],
1368 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0]);
1370 // Now loop to read all 16 blocks, address from 0 to last block
1371 Dbprintf("Tag memory dump, block 0 to %d", numofblocks
);
1377 if (i
== numofblocks
) {
1378 DbpString("System area block (0xff):");
1382 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1383 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1384 GetTagSamplesFor14443bDemod(); //no
1386 if (Demod
.len
!= 6) { // Check if we got an answer from the tag
1387 DbpString("Expected 6 bytes from tag, got less...");
1390 // The check the CRC of the answer (use cmd1 as temporary variable):
1391 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 4, &cmd1
[2], &cmd1
[3]);
1392 if(cmd1
[2] != Demod
.output
[4] || cmd1
[3] != Demod
.output
[5]) {
1393 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1394 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[4]<<8)+Demod
.output
[5]);
1395 // Do not return;, let's go on... (we should retry, maybe ?)
1397 // Now print out the memory location:
1398 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i
,
1399 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0],
1400 (Demod
.output
[4]<<8)+Demod
.output
[5]);
1402 if (i
== 0xff) break;
1410 static void iso1444b_setup_snoop(void){
1411 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup_snoop Enter");
1413 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1415 BigBuf_Clear_ext(false);
1416 clear_trace();//setup snoop
1419 // Initialize Demod and Uart structs
1420 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1421 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1423 if (MF_DBGLEVEL
> 1) {
1424 // Print debug information about the buffer sizes
1425 Dbprintf("Snooping buffers initialized:");
1426 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1427 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE
);
1428 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE
);
1429 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE
);
1432 // connect Demodulated Signal to ADC:
1433 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1435 // Setup for the DMA.
1438 // Set FPGA in the appropriate mode
1439 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
| FPGA_HF_READER_RX_XCORR_SNOOP
);
1442 // Start the SSP timer
1444 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup_snoop Exit");
1447 //=============================================================================
1448 // Finally, the `sniffer' combines elements from both the reader and
1449 // simulated tag, to show both sides of the conversation.
1450 //=============================================================================
1452 //-----------------------------------------------------------------------------
1453 // Record the sequence of commands sent by the reader to the tag, with
1454 // triggering so that we start recording at the point that the tag is moved
1456 //-----------------------------------------------------------------------------
1458 * Memory usage for this function, (within BigBuf)
1459 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1460 * Last Received command (tag->reader) - MAX_FRAME_SIZE
1461 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
1462 * Demodulated samples received - all the rest
1464 void RAMFUNC
SnoopIso14443b(void) {
1466 uint32_t time_0
= 0, time_start
= 0, time_stop
= 0;
1468 // We won't start recording the frames that we acquire until we trigger;
1469 // a good trigger condition to get started is probably when we see a
1470 // response from the tag.
1471 int triggered
= TRUE
; // TODO: set and evaluate trigger condition
1473 int maxBehindBy
= 0;
1475 int lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
1477 bool TagIsActive
= FALSE
;
1478 bool ReaderIsActive
= FALSE
;
1480 iso1444b_setup_snoop();
1482 // The DMA buffer, used to stream samples from the FPGA
1483 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
1484 int8_t *upTo
= dmaBuf
;
1486 // Setup and start DMA.
1487 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
) ){
1488 if (MF_DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1493 time_0
= GetCountSspClk();
1495 // And now we loop, receiving samples.
1500 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1);
1502 if ( behindBy
> maxBehindBy
)
1503 maxBehindBy
= behindBy
;
1505 if ( behindBy
< 2 ) continue;
1513 if (upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
1515 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
1516 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
1517 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
1520 // TODO: understand whether we can increase/decrease as we want or not?
1521 if ( behindBy
> ( 9 * ISO14443B_DMA_BUFFER_SIZE
/10) ) {
1522 Dbprintf("blew circular buffer! behindBy=%d", behindBy
);
1527 DbpString("Trace full");
1531 if(BUTTON_PRESS()) {
1532 DbpString("cancelled");
1541 // no need to try decoding reader data if the tag is sending
1542 if (Handle14443bReaderUartBit(ci
& 0x01)) {
1544 time_stop
= (GetCountSspClk()-time_0
);
1547 LogTrace(Uart
.output
, Uart
.byteCnt
, time_start
, time_stop
, NULL
, TRUE
);
1549 /* And ready to receive another command. */
1551 /* And also reset the demod code, which might have been */
1552 /* false-triggered by the commands from the reader. */
1555 time_start
= (GetCountSspClk()-time_0
);
1558 if (Handle14443bReaderUartBit(cq
& 0x01)) {
1560 time_stop
= (GetCountSspClk()-time_0
);
1563 LogTrace(Uart
.output
, Uart
.byteCnt
, time_start
, time_stop
, NULL
, TRUE
);
1565 /* And ready to receive another command. */
1567 /* And also reset the demod code, which might have been */
1568 /* false-triggered by the commands from the reader. */
1571 time_start
= (GetCountSspClk()-time_0
);
1573 ReaderIsActive
= (Uart
.state
> STATE_GOT_FALLING_EDGE_OF_SOF
);
1577 if(!ReaderIsActive
) {
1578 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
1579 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
1580 if(Handle14443bTagSamplesDemod(ci
& 0xFE, cq
& 0xFE)) {
1582 time_stop
= (GetCountSspClk()-time_0
);
1584 LogTrace(Demod
.output
, Demod
.len
, time_start
, time_stop
, NULL
, FALSE
);
1588 // And ready to receive another response.
1591 time_start
= (GetCountSspClk()-time_0
);
1593 TagIsActive
= (Demod
.state
> DEMOD_GOT_FALLING_EDGE_OF_SOF
);
1597 switch_off(); // Snoop
1599 DbpString("Snoop statistics:");
1600 Dbprintf(" Max behind by: %i", maxBehindBy
);
1601 Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);
1602 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
1605 if ( dmaBuf
) dmaBuf
= NULL
;
1606 if ( upTo
) upTo
= NULL
;
1607 // Uart.byteCntMax should be set with ATQB value..
1610 void iso14b_set_trigger(bool enable
) {
1615 * Send raw command to tag ISO14443B
1617 * param flags enum ISO14B_COMMAND. (mifare.h)
1618 * len len of buffer data
1619 * data buffer with bytes to send
1625 void SendRawCommand14443B_Ex(UsbCommand
*c
)
1627 iso14b_command_t param
= c
->arg
[0];
1628 size_t len
= c
->arg
[1] & 0xffff;
1629 uint8_t *cmd
= c
->d
.asBytes
;
1631 uint32_t sendlen
= sizeof(iso14b_card_select_t
);
1632 uint8_t buf
[USB_CMD_DATA_SIZE
] = {0x00};
1634 if (MF_DBGLEVEL
> 3) Dbprintf("14b raw: param, %04x", param
);
1636 // turn on trigger (LED_A)
1637 if ((param
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
)
1638 iso14b_set_trigger(TRUE
);
1640 if ((param
& ISO14B_CONNECT
) == ISO14B_CONNECT
) {
1641 // Make sure that we start from off, since the tags are stateful;
1642 // confusing things will happen if we don't reset them between reads.
1643 //switch_off(); // before connect in raw
1649 if ((param
& ISO14B_SELECT_STD
) == ISO14B_SELECT_STD
) {
1650 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
1651 status
= iso14443b_select_card(card
);
1652 cmd_send(CMD_ACK
, status
, sendlen
, 0, buf
, sendlen
);
1653 // 0: OK 2: attrib fail, 3:crc fail,
1654 if ( status
> 0 ) return;
1657 if ((param
& ISO14B_SELECT_SR
) == ISO14B_SELECT_SR
) {
1658 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
1659 status
= iso14443b_select_srx_card(card
);
1660 cmd_send(CMD_ACK
, status
, sendlen
, 0, buf
, sendlen
);
1661 // 0: OK 2: attrib fail, 3:crc fail,
1662 if ( status
> 0 ) return;
1665 if ((param
& ISO14B_APDU
) == ISO14B_APDU
) {
1666 status
= iso14443b_apdu(cmd
, len
, buf
);
1667 cmd_send(CMD_ACK
, status
, status
, 0, buf
, status
);
1670 if ((param
& ISO14B_RAW
) == ISO14B_RAW
) {
1671 if((param
& ISO14B_APPEND_CRC
) == ISO14B_APPEND_CRC
) {
1672 AppendCrc14443b(cmd
, len
);
1676 CodeAndTransmit14443bAsReader(cmd
, len
); // raw
1677 GetTagSamplesFor14443bDemod(); // raw
1679 sendlen
= MIN(Demod
.len
, USB_CMD_DATA_SIZE
);
1680 status
= (Demod
.len
> 0) ? 0 : 1;
1681 cmd_send(CMD_ACK
, status
, sendlen
, 0, Demod
.output
, sendlen
);
1684 // turn off trigger (LED_A)
1685 if ((param
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
)
1686 iso14b_set_trigger(FALSE
);
1688 // turn off antenna et al
1689 // we don't send a HALT command.
1690 if ((param
& ISO14B_DISCONNECT
) == ISO14B_DISCONNECT
) {
1691 if (MF_DBGLEVEL
> 3) Dbprintf("disconnect");
1692 switch_off(); // disconnect raw
1694 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);