text
[RRG-proxmark3.git] / armsrc / iso14443b.c
blob8c7d1cc9fd9330a6827e3deb04a2fd8623dc0ac1
1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, split Nov 2006
3 // piwi 2018
4 //
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
7 // the license.
8 //-----------------------------------------------------------------------------
9 // Routines to support ISO 14443B. This includes both the reader software and
10 // the `fake tag' modes.
11 //-----------------------------------------------------------------------------
12 #include "iso14443b.h"
14 #include "proxmark3_arm.h"
15 #include "common.h" // access to global variable: DBGLEVEL
16 #include "util.h"
17 #include "string.h"
18 #include "crc16.h"
19 #include "protocols.h"
20 #include "appmain.h"
21 #include "BigBuf.h"
22 #include "cmd.h"
23 #include "fpgaloader.h"
24 #include "commonutil.h"
25 #include "dbprint.h"
26 #include "ticks.h"
27 #include "iso14b.h" // defines for ETU conversions
30 * Current timing issues with ISO14443-b implementation
31 * Proxmark3
32 * Carrier Frequency 13.56MHz
33 * SSP_CLK runs at 13.56MHz / 4 = 3,39MHz
36 * PROBLEM 1.
37 * ----------
38 * one way of calculating time, that relates both to PM3 ssp_clk 3.39MHz, ISO freq of 13.56Mhz and ETUs
39 * convert from µS -> our SSP_CLK units which is used in the DEFINES..
40 * convert from ms -> our SSP_CLK units...
41 * convert from ETU -> our SSP_CLK units...
42 * All ETU -> µS -> ms should be diveded by for to match Proxmark3 FPGA SSP_CLK :)
45 * PROBLEM 2.
46 * ----------
47 * all DEFINES is in SSP_CLK ticks
48 * all delays is in SSP_CLK ticks
51 #ifndef RECEIVE_MASK
52 # define RECEIVE_MASK (DMA_BUFFER_SIZE - 1)
53 #endif
55 // SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
56 // All values should be multiples of 2 (?)
57 #define DELAY_READER_TO_ARM 8
58 #define DELAY_ARM_TO_READER 0
60 // SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader.
61 // All values should be multiples of 16
62 #define DELAY_ARM_TO_TAG 16
63 #define DELAY_TAG_TO_ARM 32
65 // SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when sniffing.
66 // All values should be multiples of 16
67 #define DELAY_TAG_TO_ARM_SNIFF 32
68 #define DELAY_READER_TO_ARM_SNIFF 32
70 /* ISO14443-4
72 * Frame Waiting Time Integer (FWI)
73 * can be between 0 and 14.
74 * FWI_default = 4
75 * FWI_max = 14
77 * Frame Waiting Time (FWT) formula
78 * --------------------------------
79 * FWT = (256 x 16 / fc) * 2 to the power for FWI
81 * sample:
82 * ------- 2 to the power of FWI(4)
83 * FWT = (256 x 16 / fc) * (2*2*2*2) == 4.833 ms
85 * FTW(default) == FWT(4) == 4.822ms
87 * FWI_max == 2^14 = 16384
88 * FWT(max) = (256 x 16 / fc) * 16384 == 4949
90 * Which gives a maximum Frame Waiting time of FWT(max) == 4949 ms
91 * FWT(max) in ETU 4949000 / 9.4395 µS = 524286 ETU
93 * Simple calc to convert to ETU or µS
94 * -----------------------------------
95 * uint32_t fwt_time_etu = (32 << fwt);
96 * uint32_t fwt_time_us = (302 << fwt);
100 #ifndef MAX_14B_TIMEOUT
101 // FWT(max) = 4949 ms or 4.95 seconds.
102 // SSP_CLK = 4949000 * 3.39 = 16777120
103 # define MAX_14B_TIMEOUT (16777120U)
104 #endif
106 // Activation frame waiting time
107 // 512 ETU?
108 // 65536/fc == 4833 µS or 4.833ms
109 // SSP_CLK = 4833 µS * 3.39 = 16384
110 #ifndef FWT_TIMEOUT_14B
111 # define FWT_TIMEOUT_14B (16384)
112 #endif
114 // ETU 14 * 9.4395 µS = 132 µS == 0.132ms
115 // TR2, counting from start of PICC EOF 14 ETU.
116 #define DELAY_ISO14443B_PICC_TO_PCD_READER ETU_TO_SSP(14)
117 #define DELAY_ISO14443B_PCD_TO_PICC_READER ETU_TO_SSP(15)
119 /* Guard Time (per 14443-2) in ETU
121 * Transition time. TR0 - guard time
122 * TR0 - 8 ETU's minimum.
123 * TR0 - 32 ETU's maximum for ATQB only
124 * TR0 - FWT for all other commands
125 * 32,64,128,256,512, ... , 262144, 524288 ETU
126 * TR0 = FWT(1), FWT(2), FWT(3) .. FWT(14)
129 * TR0
131 #ifndef ISO14B_TR0
132 # define ISO14B_TR0 ETU_TO_SSP(32)
133 #endif
135 #ifndef ISO14B_TR0_MAX
136 # define ISO14B_TR0_MAX ETU_TO_SSP(32)
137 // * TR0 - 32 ETU's maximum for ATQB only
138 // * TR0 - FWT for all other commands
140 // TR0 max is 151/fsc = 151/848kHz = 302us or 64 samples from FPGA
141 // 32 ETU * 9.4395 µS == 302 µS
142 // 32 * 8 = 256 sub carrier cycles,
143 // 256 / 4 = 64 I/Q pairs.
144 // since 1 I/Q pair after 4 subcarrier cycles at 848kHz subcarrier
145 #endif
147 // 8 ETU = 75 µS == 256 SSP_CLK
148 #ifndef ISO14B_TR0_MIN
149 # define ISO14B_TR0_MIN ETU_TO_SSP(8)
150 #endif
152 // Synchronization time (per 14443-2) in ETU
153 // 10 ETU = 94,39 µS == 320 SSP_CLK
154 #ifndef ISO14B_TR1_MIN
155 # define ISO14B_TR1_MIN ETU_TO_SSP(10)
156 #endif
157 // Synchronization time (per 14443-2) in ETU
158 // 25 ETU == 236 µS == 800 SSP_CLK
159 #ifndef ISO14B_TR1_MAX
160 # define ISO14B_TR1 ETU_TO_SSP(25)
161 #endif
163 // Frame Delay Time PICC to PCD (per 14443-3 Amendment 1) in ETU
164 // 14 ETU == 132 µS == 448 SSP_CLK
165 #ifndef ISO14B_TR2
166 # define ISO14B_TR2 ETU_TO_SSP(14)
167 #endif
169 // 4sample
170 #define SEND4STUFFBIT(x) tosend_stuffbit(x);tosend_stuffbit(x);tosend_stuffbit(x);tosend_stuffbit(x);
172 static void iso14b_set_timeout(uint32_t timeout_etu);
173 static void iso14b_set_maxframesize(uint16_t size);
174 static void iso14b_set_fwt(uint8_t fwt);
176 // the block number for the ISO14443-4 PCB (used with APDUs)
177 static uint8_t iso14b_pcb_blocknum = 0;
178 static uint8_t iso14b_fwt = 9;
179 static uint32_t iso14b_timeout = FWT_TIMEOUT_14B;
182 * ISO 14443-B communications
183 * --------------------------
184 * Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
185 * Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
187 * It uses half duplex with a 106 kbit per second data rate in each direction.
188 * Data transmitted by the card is load modulated with a 847.5 kHz subcarrier.
190 * fc - carrier frequency 13.56 MHz
191 * TR0 - Guard Time per 14443-2
192 * TR1 - Synchronization Time per 14443-2
193 * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
195 * Elementary Time Unit (ETU)
196 * --------------------------
197 * ETU is used to denotate 1 bit period i.e. how long one bit transfer takes.
199 * - 128 Carrier cycles / 13.56MHz = 8 Subcarrier units / 848kHz = 1/106kHz = 9.4395 µS
200 * - 16 Carrier cycles = 1 Subcarrier unit = 1.17 µS
202 * Definition
203 * ----------
204 * 1 ETU = 128 / ( D x fc )
205 * where
206 * D = divisor. Which inital is 1
207 * fc = carrier frequency
208 * gives
209 * 1 ETU = 128 / fc
210 * 1 ETU = 128 / 13 560 000 = 9.4395 µS
211 * 1 ETU = 9.4395 µS
213 * (note: It seems we are using the subcarrier as base for our time calculations rather than the field clock)
215 * - 1 ETU = 1/106 KHz
216 * - 1 ETU = 8 subcarrier units ( 8 / 848kHz )
217 * - 1 ETU = 1 bit period
220 * Card sends data at 848kHz subcarrier
221 * subcar |duration| FC division| I/Q pairs
222 * -------+--------+------------+--------
223 * 106kHz | 9.44µS | FC/128 | 16
224 * 212kHz | 4.72µS | FC/64 | 8
225 * 424kHz | 2.36µS | FC/32 | 4
226 * 848kHz | 1.18µS | FC/16 | 2
227 * -------+--------+------------+--------
230 * One Character consists of 1 start, 1 stop, 8 databit with a total length of 10bits.
231 * - 1 Character = 10 ETU = 1 startbit, 8 databits, 1 stopbit
232 * - startbit is a 0
233 * - stopbit is a 1
235 * Start of frame (SOF) is
236 * - [10-11] ETU of ZEROS, unmodulated time
237 * - [2-3] ETU of ONES,
239 * End of frame (EOF) is
240 * - [10-11] ETU of ZEROS, unmodulated time
242 * Reader data transmission
243 * ------------------------
244 * - no modulation ONES
245 * - SOF
246 * - Command, data and CRC_B (1 Character)
247 * - EOF
248 * - no modulation ONES
250 * Card data transmission
251 * ----------------------
252 * - TR1
253 * - SOF
254 * - data (1 Character)
255 * - CRC_B
256 * - EOF
258 * Transfer times
259 * --------------
260 * let calc how long it takes the reader to send a message
261 * SOF 10 ETU + 4 data bytes + 2 crc bytes + EOF 2 ETU
262 * 10 + (4+2 * 10) + 2 = 72 ETU
263 * 72 * 9.4395 = 680 µS or 0.68 ms
266 * -> TO VERIFY THIS BELOW <-
267 * --------------------------
268 * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
269 * works like this:
270 * Simulation per definition is "inversed" effect on the reader antenna.
271 * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (1.18µS / pulse) == 9.44us
272 * - A 0-bit input to the FPGA becomes an unmodulated time of 1.18µS or does it become 8 nonpulses for 9.44us
275 * FPGA implementation
276 * -------------------
277 * Piwi implemented a I/Q sampling mode for the FPGA, where...
279 * FPGA doesn't seem to work with ETU. It seems to work with pulse / duration instead.
281 * This means that we are using a bit rate of 106 kbit/s, or fc/128.
282 * Oversample by 4, which ought to make things practical for the ARM
283 * (fc/32, 423.8 kbits/s, ~52 kbytes/s)
285 * We are sampling the signal at FC/32, we are reporting over SSP to PM3 each
287 * Current I/Q pair sampling
288 * -------------------------
289 * Let us report a correlation every 64 samples. I.e.
290 * 1 I/Q pair after 4 subcarrier cycles for the 848kHz subcarrier,
291 * 1 I/Q pair after 2 subcarrier cycles for the 424kHz subcarrier,
296 * Formula to calculate FWT (in ETUs) by timeout (in ms):
298 * 1 tick is about 1.5µS
299 * 1000 ms/s
301 * FWT = 13560000 * 1000 / (8*16) * timeout
302 * FWT = 13560000 * 1000 / 128 * timeout
304 * sample: 3sec == 3000ms
306 * 13560000 * 1000 / 128 * 3000 == 13560000000 / 384000 ==
307 * 13560000 / 384 = 35312 FWT
309 * 35312 * 9.4395 ==
311 * @param timeout is in frame wait time, fwt, measured in ETUs
313 * However we need to compensate for SSP_CLK ...
318 //=============================================================================
319 // An ISO 14443 Type B tag. We listen for commands from the reader, using
320 // a UART kind of thing that's implemented in software. When we get a
321 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
322 // If it's good, then we can do something appropriate with it, and send
323 // a response.
324 //=============================================================================
326 //-----------------------------------------------------------------------------
327 // Code up a string of octets at layer 2 (including CRC, we don't generate
328 // that here) so that they can be transmitted to the reader. Doesn't transmit
329 // them yet, just leaves them ready to send in ToSend[].
330 //-----------------------------------------------------------------------------
331 static void CodeIso14443bAsTag(const uint8_t *cmd, int len) {
332 int i;
334 tosend_reset();
336 // Transmit a burst of ones, as the initial thing that lets the
337 // reader get phase sync.
338 // This loop is TR1, per specification
339 // TR1 minimum must be > 80/fs
340 // TR1 maximum 200/fs
341 // 80/fs < TR1 < 200/fs
342 // 10 ETU < TR1 < 24 ETU
344 // Send TR1.
345 // 10-11 ETU * 4times samples ONES
346 for (i = 0; i < 10; i++) {
347 SEND4STUFFBIT(1);
350 // Send SOF.
351 // 10-11 ETU * 4times samples ZEROS
352 for (i = 0; i < 10; i++) {
353 SEND4STUFFBIT(0);
356 // 2-3 ETU * 4times samples ONES
357 for (i = 0; i < 2; i++) {
358 SEND4STUFFBIT(1);
361 // data
362 for (i = 0; i < len; i++) {
364 // Start bit
365 SEND4STUFFBIT(0);
367 // Data bits
368 uint8_t b = cmd[i];
369 for (int j = 0; j < 8; j++) {
370 SEND4STUFFBIT(b & 1);
371 b >>= 1;
374 // Stop bit
375 SEND4STUFFBIT(1);
377 // Extra Guard bit
378 // For PICC it ranges 0-18us (1etu = 9us)
379 //SEND4STUFFBIT(1);
382 // Send EOF.
383 // 10-11 ETU * 4 sample rate = ZEROS
384 for (i = 0; i < 10; i++) {
385 SEND4STUFFBIT(0);
388 // why this? push out transfers between arm and fpga?
389 //for (i = 0; i < 2; i++) {
390 // SEND4STUFFBIT(1);
393 tosend_t *ts = get_tosend();
394 // Convert from last byte pos to length
395 ts->max++;
398 //-----------------------------------------------------------------------------
399 // The software UART that receives commands from the reader, and its state
400 // variables.
401 //-----------------------------------------------------------------------------
402 static struct {
403 enum {
404 STATE_14B_UNSYNCD,
405 STATE_14B_GOT_FALLING_EDGE_OF_SOF,
406 STATE_14B_AWAITING_START_BIT,
407 STATE_14B_RECEIVING_DATA
408 } state;
409 uint16_t shiftReg;
410 int bitCnt;
411 int byteCnt;
412 int byteCntMax;
413 int posCnt;
414 uint8_t *output;
415 } Uart;
417 static void Uart14bReset(void) {
418 Uart.state = STATE_14B_UNSYNCD;
419 Uart.shiftReg = 0;
420 Uart.bitCnt = 0;
421 Uart.byteCnt = 0;
422 Uart.byteCntMax = MAX_FRAME_SIZE;
423 Uart.posCnt = 0;
426 static void Uart14bInit(uint8_t *data) {
427 Uart.output = data;
428 Uart14bReset();
431 // param timeout accepts ETU
432 static void iso14b_set_timeout(uint32_t timeout_etu) {
434 uint32_t ssp = ETU_TO_SSP(timeout_etu);
436 if (ssp > MAX_14B_TIMEOUT)
437 ssp = MAX_14B_TIMEOUT;
439 iso14b_timeout = ssp;
440 if (DBGLEVEL >= DBG_DEBUG) {
441 Dbprintf("ISO14443B Timeout set to %ld fwt", iso14b_timeout);
445 // keep track of FWT, also updates the timeout
446 static void iso14b_set_fwt(uint8_t fwt) {
447 iso14b_fwt = fwt;
448 iso14b_set_timeout(32 << fwt);
451 static void iso14b_set_maxframesize(uint16_t size) {
452 if (size > 256)
453 size = MAX_FRAME_SIZE;
455 Uart.byteCntMax = size;
456 if (DBGLEVEL >= DBG_DEBUG) Dbprintf("ISO14443B Max frame size set to %d bytes", Uart.byteCntMax);
459 //-----------------------------------------------------------------------------
460 // The software Demod that receives commands from the tag, and its state variables.
461 //-----------------------------------------------------------------------------
463 #define NOISE_THRESHOLD 80 // don't try to correlate noise
464 #define MAX_PREVIOUS_AMPLITUDE (-1 - NOISE_THRESHOLD)
466 static struct {
467 enum {
468 DEMOD_UNSYNCD,
469 DEMOD_PHASE_REF_TRAINING,
470 WAIT_FOR_RISING_EDGE_OF_SOF,
471 DEMOD_AWAITING_START_BIT,
472 DEMOD_RECEIVING_DATA
473 } state;
474 uint16_t bitCount;
475 int posCount;
476 int thisBit;
477 uint16_t shiftReg;
478 uint16_t max_len;
479 uint8_t *output;
480 uint16_t len;
481 int sumI;
482 int sumQ;
483 } Demod;
485 // Clear out the state of the "UART" that receives from the tag.
486 static void Demod14bReset(void) {
487 Demod.state = DEMOD_UNSYNCD;
488 Demod.bitCount = 0;
489 Demod.posCount = 0;
490 Demod.thisBit = 0;
491 Demod.shiftReg = 0;
492 Demod.len = 0;
493 Demod.sumI = 0;
494 Demod.sumQ = 0;
497 static void Demod14bInit(uint8_t *data, uint16_t max_len) {
498 Demod.output = data;
499 Demod.max_len = max_len;
500 Demod14bReset();
503 /* Receive & handle a bit coming from the reader.
505 * This function is called 4 times per bit (every 2 subcarrier cycles).
506 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
508 * LED handling:
509 * LED A -> ON once we have received the SOF and are expecting the rest.
510 * LED A -> OFF once we have received EOF or are in error state or unsynced
512 * Returns: true if we received a EOF
513 * false if we are still waiting for some more
515 static RAMFUNC int Handle14443bSampleFromReader(uint8_t bit) {
516 switch (Uart.state) {
517 case STATE_14B_UNSYNCD:
518 if (bit == false) {
519 // we went low, so this could be the beginning of an SOF
520 Uart.state = STATE_14B_GOT_FALLING_EDGE_OF_SOF;
521 Uart.posCnt = 0;
522 Uart.bitCnt = 0;
524 break;
526 case STATE_14B_GOT_FALLING_EDGE_OF_SOF:
527 Uart.posCnt++;
529 if (Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
531 if (bit) {
532 if (Uart.bitCnt > 9) {
533 // we've seen enough consecutive
534 // zeros that it's a valid SOF
535 Uart.posCnt = 0;
536 Uart.byteCnt = 0;
537 Uart.state = STATE_14B_AWAITING_START_BIT;
538 LED_A_ON(); // Indicate we got a valid SOF
539 } else {
540 // didn't stay down long enough before going high, error
541 Uart.state = STATE_14B_UNSYNCD;
543 } else {
544 // do nothing, keep waiting
546 Uart.bitCnt++;
549 if (Uart.posCnt >= 4) {
550 Uart.posCnt = 0;
553 if (Uart.bitCnt > 12) {
554 // Give up if we see too many zeros without a one, too.
555 LED_A_OFF();
556 Uart.state = STATE_14B_UNSYNCD;
558 break;
560 case STATE_14B_AWAITING_START_BIT:
561 Uart.posCnt++;
563 if (bit) {
565 // max 57us between characters = 49 1/fs,
566 // max 3 etus after low phase of SOF = 24 1/fs
567 if (Uart.posCnt > 50 / 2) {
568 // stayed high for too long between characters, error
569 Uart.state = STATE_14B_UNSYNCD;
572 } else {
573 // falling edge, this starts the data byte
574 Uart.posCnt = 0;
575 Uart.bitCnt = 0;
576 Uart.shiftReg = 0;
577 Uart.state = STATE_14B_RECEIVING_DATA;
579 break;
581 case STATE_14B_RECEIVING_DATA:
583 Uart.posCnt++;
585 if (Uart.posCnt == 2) {
586 // time to sample a bit
587 Uart.shiftReg >>= 1;
588 if (bit) {
589 Uart.shiftReg |= 0x200;
591 Uart.bitCnt++;
594 if (Uart.posCnt >= 4) {
595 Uart.posCnt = 0;
598 if (Uart.bitCnt == 10) {
599 if ((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001)) {
600 // this is a data byte, with correct
601 // start and stop bits
602 Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xFF;
603 Uart.byteCnt++;
605 if (Uart.byteCnt >= Uart.byteCntMax) {
606 // Buffer overflowed, give up
607 LED_A_OFF();
608 Uart.state = STATE_14B_UNSYNCD;
609 } else {
610 // so get the next byte now
611 Uart.posCnt = 0;
612 Uart.state = STATE_14B_AWAITING_START_BIT;
614 } else if (Uart.shiftReg == 0x000) {
615 // this is an EOF byte
616 LED_A_OFF(); // Finished receiving
617 Uart.state = STATE_14B_UNSYNCD;
618 if (Uart.byteCnt != 0)
619 return true;
621 } else {
622 // this is an error
623 LED_A_OFF();
624 Uart.state = STATE_14B_UNSYNCD;
627 break;
629 default:
630 LED_A_OFF();
631 Uart.state = STATE_14B_UNSYNCD;
632 break;
634 return false;
637 //-----------------------------------------------------------------------------
638 // Receive a command (from the reader to us, where we are the simulated tag),
639 // and store it in the given buffer, up to the given maximum length. Keeps
640 // spinning, waiting for a well-framed command, until either we get one
641 // (returns true) or someone presses the pushbutton on the board (false).
643 // Assume that we're called with the SSC (to the FPGA) and ADC path set
644 // correctly.
645 //-----------------------------------------------------------------------------
646 static int GetIso14443bCommandFromReader(uint8_t *received, uint16_t *len) {
647 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
648 // only, since we are receiving, not transmitting).
649 // Signal field is off with the appropriate LED
650 LED_D_OFF();
651 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
653 // Now run a `software UART' on the stream of incoming samples.
654 Uart14bInit(received);
656 while (BUTTON_PRESS() == false) {
657 WDT_HIT();
659 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
660 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
661 for (uint8_t mask = 0x80; mask != 0x00; mask >>= 1) {
662 if (Handle14443bSampleFromReader(b & mask)) {
663 *len = Uart.byteCnt;
664 return true;
669 return false;
672 static void TransmitFor14443b_AsTag(uint8_t *response, uint16_t len) {
674 // Signal field is off with the appropriate LED
675 LED_D_OFF();
677 // Modulate BPSK
678 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK);
679 AT91C_BASE_SSC->SSC_THR = 0xFF;
680 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
682 // Transmit the response.
683 for (uint16_t i = 0; i < len;) {
685 // Put byte into tx holding register as soon as it is ready
686 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
687 AT91C_BASE_SSC->SSC_THR = response[i++];
691 //-----------------------------------------------------------------------------
692 // Main loop of simulated tag: receive commands from reader, decide what
693 // response to send, and send it.
694 //-----------------------------------------------------------------------------
695 void SimulateIso14443bTag(uint8_t *pupi) {
697 LED_A_ON();
698 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
699 // static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
700 // ... and REQB, AFI=0, Normal Request, N=1:
701 // static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
702 // ... and HLTB
703 // static const uint8_t cmdHLTB[] = { 0x50, 0xff, 0xff, 0xff, 0xff }; // HLTB
704 // ... and ATTRIB
705 // static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
707 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
708 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
709 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
710 uint8_t respATQB[] = {
711 0x50,
712 0x82, 0x0d, 0xe1, 0x74,
713 0x20, 0x38, 0x19,
714 0x22, 0x00, 0x21, 0x85,
715 0x5e, 0xd7
718 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
719 if (memcmp("\x00\x00\x00\x00", pupi, 4) != 0) {
720 memcpy(respATQB + 1, pupi, 4);
721 AddCrc14B(respATQB, 12);
724 // response to HLTB and ATTRIB
725 static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
727 // setup device.
728 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
730 // connect Demodulated Signal to ADC:
731 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
733 // Set up the synchronous serial port
734 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
736 // allocate command receive buffer
737 BigBuf_free();
738 BigBuf_Clear_ext(false);
739 clear_trace();
740 set_tracing(true);
742 uint16_t len, cmdsReceived = 0;
743 int cardSTATE = SIM_NOFIELD;
744 int vHf = 0; // in mV
746 tosend_t *ts = get_tosend();
748 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
750 // prepare "ATQB" tag answer (encoded):
751 CodeIso14443bAsTag(respATQB, sizeof(respATQB));
752 uint8_t *encodedATQB = BigBuf_malloc(ts->max);
753 uint16_t encodedATQBLen = ts->max;
754 memcpy(encodedATQB, ts->buf, ts->max);
757 // prepare "OK" tag answer (encoded):
758 CodeIso14443bAsTag(respOK, sizeof(respOK));
759 uint8_t *encodedOK = BigBuf_malloc(ts->max);
760 uint16_t encodedOKLen = ts->max;
761 memcpy(encodedOK, ts->buf, ts->max);
763 // Simulation loop
764 while (BUTTON_PRESS() == false) {
765 WDT_HIT();
767 //iceman: limit with 2000 times..
768 if (data_available()) {
769 break;
772 // find reader field
773 if (cardSTATE == SIM_NOFIELD) {
775 #if defined RDV4
776 vHf = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
777 #else
778 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
779 #endif
780 if (vHf > MF_MINFIELDV) {
781 cardSTATE = SIM_IDLE;
782 LED_A_ON();
785 if (cardSTATE == SIM_NOFIELD) continue;
787 // Get reader command
788 if (!GetIso14443bCommandFromReader(receivedCmd, &len)) {
789 Dbprintf("button pressed, received %d commands", cmdsReceived);
790 break;
793 // ISO14443-B protocol states:
794 // REQ or WUP request in ANY state
795 // WUP in HALTED state
796 if (len == 5) {
797 if ((receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8) == 0x8 && cardSTATE == SIM_HALTED) ||
798 receivedCmd[0] == ISO14443B_REQB) {
799 LogTrace(receivedCmd, len, 0, 0, NULL, true);
800 cardSTATE = SIM_SELECTING;
805 * How should this flow go?
806 * REQB or WUPB
807 * send response ( waiting for Attrib)
808 * ATTRIB
809 * send response ( waiting for commands 7816)
810 * HALT
811 send halt response ( waiting for wupb )
814 switch (cardSTATE) {
815 //case SIM_NOFIELD:
816 case SIM_HALTED:
817 case SIM_IDLE: {
818 LogTrace(receivedCmd, len, 0, 0, NULL, true);
819 break;
821 case SIM_SELECTING: {
822 TransmitFor14443b_AsTag(encodedATQB, encodedATQBLen);
823 LogTrace(respATQB, sizeof(respATQB), 0, 0, NULL, false);
824 cardSTATE = SIM_WORK;
825 break;
827 case SIM_HALTING: {
828 TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
829 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
830 cardSTATE = SIM_HALTED;
831 break;
833 case SIM_ACKNOWLEDGE: {
834 TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
835 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
836 cardSTATE = SIM_IDLE;
837 break;
839 case SIM_WORK: {
840 if (len == 7 && receivedCmd[0] == ISO14443B_HALT) {
841 cardSTATE = SIM_HALTED;
842 } else if (len == 11 && receivedCmd[0] == ISO14443B_ATTRIB) {
843 cardSTATE = SIM_ACKNOWLEDGE;
844 } else {
845 // Todo:
846 // - SLOT MARKER
847 // - ISO7816
848 // - emulate with a memory dump
849 if (DBGLEVEL >= DBG_DEBUG)
850 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsReceived);
852 // CRC Check
853 if (len >= 3) { // if crc exists
855 if (!check_crc(CRC_14443_B, receivedCmd, len)) {
856 if (DBGLEVEL >= DBG_DEBUG) {
857 DbpString("CRC fail");
860 } else {
861 if (DBGLEVEL >= DBG_DEBUG) {
862 DbpString("CRC passed");
865 cardSTATE = SIM_IDLE;
867 break;
869 default:
870 break;
873 ++cmdsReceived;
876 if (DBGLEVEL >= DBG_DEBUG)
877 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
879 switch_off(); //simulate
883 void Simulate_iso14443b_srx_tag(uint8_t *uid) {
885 LED_A_ON();
886 / SRI512
888 > initiate 06 00 ISO14443B_INITIATE
889 < xx crc crc
890 > select 0e xx ISO14443B_SELECT
891 < xx nn nn
893 > readblock 08 blck_no ISO14443B_READ_BLK
894 < d0 d1 d2 d3 2byte crc
896 > get uid ISO14443B_GET_UID
897 < 81 93 99 20 92 11 02 (8byte UID in MSB D002 199220 999381)
899 #define ISO14443B_REQB 0x05
900 #define ISO14443B_ATTRIB 0x1D
901 #define ISO14443B_HALT 0x50
902 #define ISO14443B_INITIATE 0x06
903 #define ISO14443B_SELECT 0x0E
904 #define ISO14443B_GET_UID 0x0B
905 #define ISO14443B_READ_BLK 0x08
906 #define ISO14443B_WRITE_BLK 0x09
907 #define ISO14443B_RESET 0x0C
908 #define ISO14443B_COMPLETION 0x0F
909 #define ISO14443B_AUTHENTICATE 0x0A
910 #define ISO14443B_PING 0xBA
911 #define ISO14443B_PONG 0xAB
914 static const uint8_t resp_init_srx[] = { 0x73, 0x64, 0xb1 };
915 uint8_t resp_select_srx[] = { 0x73, 0x64, 0xb1 };
917 // a default uid, or user supplied
918 uint8_t resp_getuid_srx[10] = {
919 0x81, 0x93, 0x99, 0x20, 0x92, 0x11, 0x02, 0xD0, 0x00, 0x00
922 // ...UID supplied from user. Adjust ATQB response accordingly
923 if (memcmp("\x00\x00\x00\x00\x00\x00\x00\x00", uid, 8) != 0) {
924 memcpy(resp_getuid_srx, uid, 8);
925 AddCrc14B(resp_getuid_srx, 8);
928 // response to HLTB and ATTRIB
929 static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
931 // setup device.
932 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
934 // connect Demodulated Signal to ADC:
935 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
937 // Set up the synchronous serial port
938 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
940 // allocate command receive buffer
941 BigBuf_free();
942 BigBuf_Clear_ext(false);
943 clear_trace();
944 set_tracing(true);
946 uint16_t len, cmdsReceived = 0;
947 int cardSTATE = SIM_NOFIELD;
948 int vHf = 0; // in mV
950 tosend_t *ts = get_tosend();
952 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
954 // prepare "ATQB" tag answer (encoded):
955 CodeIso14443bAsTag(respATQB, sizeof(respATQB));
956 uint8_t *encodedATQB = BigBuf_malloc(ts->max);
957 uint16_t encodedATQBLen = ts->max;
958 memcpy(encodedATQB, ts->buf, ts->max);
961 // prepare "OK" tag answer (encoded):
962 CodeIso14443bAsTag(respOK, sizeof(respOK));
963 uint8_t *encodedOK = BigBuf_malloc(ts->max);
964 uint16_t encodedOKLen = ts->max;
965 memcpy(encodedOK, ts->buf, ts->max);
967 // Simulation loop
968 while (BUTTON_PRESS() == false) {
969 WDT_HIT();
971 //iceman: limit with 2000 times..
972 if (data_available()) {
973 break;
976 // find reader field
977 if (cardSTATE == SIM_NOFIELD) {
979 #if defined RDV4
980 vHf = (MAX_ADC_HF_VOLTAGE_RDV40 * SumAdc(ADC_CHAN_HF_RDV40, 32)) >> 15;
981 #else
982 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
983 #endif
984 if (vHf > MF_MINFIELDV) {
985 cardSTATE = SIM_IDLE;
986 LED_A_ON();
989 if (cardSTATE == SIM_NOFIELD) continue;
991 // Get reader command
992 if (!GetIso14443bCommandFromReader(receivedCmd, &len)) {
993 Dbprintf("button pressed, received %d commands", cmdsReceived);
994 break;
997 // ISO14443-B protocol states:
998 // REQ or WUP request in ANY state
999 // WUP in HALTED state
1000 if (len == 5) {
1001 if ((receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8) == 0x8 && cardSTATE == SIM_HALTED) ||
1002 receivedCmd[0] == ISO14443B_REQB) {
1003 LogTrace(receivedCmd, len, 0, 0, NULL, true);
1004 cardSTATE = SIM_SELECTING;
1009 * How should this flow go?
1010 * REQB or WUPB
1011 * send response ( waiting for Attrib)
1012 * ATTRIB
1013 * send response ( waiting for commands 7816)
1014 * HALT
1015 send halt response ( waiting for wupb )
1018 switch (cardSTATE) {
1019 //case SIM_NOFIELD:
1020 case SIM_HALTED:
1021 case SIM_IDLE: {
1022 LogTrace(receivedCmd, len, 0, 0, NULL, true);
1023 break;
1025 case SIM_SELECTING: {
1026 TransmitFor14443b_AsTag(encodedATQB, encodedATQBLen);
1027 LogTrace(respATQB, sizeof(respATQB), 0, 0, NULL, false);
1028 cardSTATE = SIM_WORK;
1029 break;
1031 case SIM_HALTING: {
1032 TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
1033 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
1034 cardSTATE = SIM_HALTED;
1035 break;
1037 case SIM_ACKNOWLEDGE: {
1038 TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
1039 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
1040 cardSTATE = SIM_IDLE;
1041 break;
1043 case SIM_WORK: {
1044 if (len == 7 && receivedCmd[0] == ISO14443B_HALT) {
1045 cardSTATE = SIM_HALTED;
1046 } else if (len == 11 && receivedCmd[0] == ISO14443B_ATTRIB) {
1047 cardSTATE = SIM_ACKNOWLEDGE;
1048 } else {
1049 // Todo:
1050 // - SLOT MARKER
1051 // - ISO7816
1052 // - emulate with a memory dump
1053 if (DBGLEVEL >= DBG_DEBUG)
1054 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsReceived);
1056 // CRC Check
1057 if (len >= 3) { // if crc exists
1059 if (!check_crc(CRC_14443_B, receivedCmd, len)) {
1060 if (DBGLEVEL >= DBG_DEBUG) {
1061 DbpString("CRC fail");
1064 } else {
1065 if (DBGLEVEL >= DBG_DEBUG) {
1066 DbpString("CRC passed");
1069 cardSTATE = SIM_IDLE;
1071 break;
1073 default:
1074 break;
1077 ++cmdsReceived;
1080 if (DBGLEVEL >= DBG_DEBUG)
1081 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
1083 switch_off(); //simulate
1087 //=============================================================================
1088 // An ISO 14443 Type B reader. We take layer two commands, code them
1089 // appropriately, and then send them to the tag. We then listen for the
1090 // tag's response, which we leave in the buffer to be demodulated on the
1091 // PC side.
1092 //=============================================================================
1093 // We support both 14b framing and 14b' framing.
1094 // 14b framing looks like:
1095 // xxxxxxxx1111111111111111-000000000011-0........1-0........1-0........1-1-0........1-0........1-1000000000011xxxxxx
1096 // TR1 SOF 10*0+2*1 start-stop ^^^^^^^^byte ^ occasional stuff bit EOF 10*0+N*1
1097 // 14b' framing looks like:
1098 // xxxxxxxxxxxxxxxx111111111111111111111-0........1-0........1-0........1-1-0........1-0........1-000000000000xxxxxxx
1099 // SOF? start-stop ^^^^^^^^byte ^ occasional stuff bit EOF
1102 * Handles reception of a bit from the tag
1104 * This function is called 2 times per bit (every 4 subcarrier cycles).
1105 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
1107 * LED handling:
1108 * LED C -> ON once we have received the SOF and are expecting the rest.
1109 * LED C -> OFF once we have received EOF or are unsynced
1111 * Returns: true if we received a EOF
1112 * false if we are still waiting for some more
1115 static RAMFUNC int Handle14443bSamplesFromTag(int ci, int cq) {
1117 int v = 0;
1119 // The soft decision on the bit uses an estimate of just the
1120 // quadrant of the reference angle, not the exact angle.
1121 #define MAKE_SOFT_DECISION() { \
1122 if(Demod.sumI > 0) { \
1123 v = ci; \
1124 } else { \
1125 v = -ci; \
1127 if(Demod.sumQ > 0) { \
1128 v += cq; \
1129 } else { \
1130 v -= cq; \
1134 #define SUBCARRIER_DETECT_THRESHOLD 8
1135 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
1136 #define AMPLITUDE(ci,cq) (MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2))
1138 switch (Demod.state) {
1140 case DEMOD_UNSYNCD: {
1141 if (AMPLITUDE(ci, cq) > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1142 Demod.state = DEMOD_PHASE_REF_TRAINING;
1143 Demod.sumI = ci;
1144 Demod.sumQ = cq;
1145 Demod.posCount = 1;
1147 break;
1149 case DEMOD_PHASE_REF_TRAINING: {
1150 // While we get a constant signal
1151 if (AMPLITUDE(ci, cq) > SUBCARRIER_DETECT_THRESHOLD) {
1152 if (((ABS(Demod.sumI) > ABS(Demod.sumQ)) && (((ci > 0) && (Demod.sumI > 0)) || ((ci < 0) && (Demod.sumI < 0)))) || // signal closer to horizontal, polarity check based on on I
1153 ((ABS(Demod.sumI) <= ABS(Demod.sumQ)) && (((cq > 0) && (Demod.sumQ > 0)) || ((cq < 0) && (Demod.sumQ < 0))))) { // signal closer to vertical, polarity check based on on Q
1155 if (Demod.posCount < 10) { // refine signal approximation during first 10 samples
1156 Demod.sumI += ci;
1157 Demod.sumQ += cq;
1159 Demod.posCount += 1;
1160 } else {
1161 // transition
1162 if (Demod.posCount < 10) {
1163 // subcarrier lost
1164 Demod.state = DEMOD_UNSYNCD;
1165 break;
1166 } else {
1167 // at this point it can be start of 14b' data or start of 14b SOF
1168 MAKE_SOFT_DECISION();
1169 Demod.posCount = 1; // this was the first half
1170 Demod.thisBit = v;
1171 Demod.shiftReg = 0;
1172 Demod.state = DEMOD_RECEIVING_DATA;
1175 } else {
1176 // subcarrier lost
1177 Demod.state = DEMOD_UNSYNCD;
1179 break;
1181 case DEMOD_AWAITING_START_BIT: {
1182 Demod.posCount++;
1183 MAKE_SOFT_DECISION();
1184 if (v > 0) {
1185 if (Demod.posCount > 3 * 2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1186 LED_C_OFF();
1187 if (Demod.bitCount == 0 && Demod.len == 0) { // received SOF only, this is valid for iClass/Picopass
1188 return true;
1189 } else {
1190 Demod.state = DEMOD_UNSYNCD;
1193 } else { // start bit detected
1194 Demod.posCount = 1; // this was the first half
1195 Demod.thisBit = v;
1196 Demod.shiftReg = 0;
1197 Demod.state = DEMOD_RECEIVING_DATA;
1199 break;
1201 case WAIT_FOR_RISING_EDGE_OF_SOF: {
1203 Demod.posCount++;
1204 MAKE_SOFT_DECISION();
1205 if (v > 0) {
1206 if (Demod.posCount < 9 * 2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1207 Demod.state = DEMOD_UNSYNCD;
1208 } else {
1209 LED_C_ON(); // Got SOF
1210 Demod.posCount = 0;
1211 Demod.bitCount = 0;
1212 Demod.len = 0;
1213 Demod.state = DEMOD_AWAITING_START_BIT;
1215 } else {
1216 if (Demod.posCount > 12 * 2) { // low phase of SOF too long (> 12 etu)
1217 Demod.state = DEMOD_UNSYNCD;
1218 LED_C_OFF();
1221 break;
1223 case DEMOD_RECEIVING_DATA: {
1225 MAKE_SOFT_DECISION();
1227 if (Demod.posCount == 0) { // first half of bit
1228 Demod.thisBit = v;
1229 Demod.posCount = 1;
1230 } else { // second half of bit
1231 Demod.thisBit += v;
1233 Demod.shiftReg >>= 1;
1234 if (Demod.thisBit > 0) { // logic '1'
1235 Demod.shiftReg |= 0x200;
1238 Demod.bitCount++;
1239 if (Demod.bitCount == 10) {
1241 uint16_t s = Demod.shiftReg;
1243 if ((s & 0x200) && !(s & 0x001)) { // stop bit == '1', start bit == '0'
1244 Demod.output[Demod.len] = (s >> 1);
1245 Demod.len++;
1246 Demod.bitCount = 0;
1247 Demod.state = DEMOD_AWAITING_START_BIT;
1248 } else {
1249 if (s == 0x000) {
1250 if (Demod.len > 0) {
1251 LED_C_OFF();
1252 // This is EOF (start, stop and all data bits == '0'
1253 return true;
1254 } else {
1255 // Zeroes but no data acquired yet?
1256 // => Still in SOF of 14b, wait for raising edge
1257 Demod.posCount = 10 * 2;
1258 Demod.bitCount = 0;
1259 Demod.len = 0;
1260 Demod.state = WAIT_FOR_RISING_EDGE_OF_SOF;
1261 break;
1264 if (AMPLITUDE(ci, cq) < SUBCARRIER_DETECT_THRESHOLD) {
1265 LED_C_OFF();
1266 // subcarrier lost
1267 Demod.state = DEMOD_UNSYNCD;
1268 if (Demod.len > 0) { // no EOF but no signal anymore and we got data, e.g. ASK CTx
1269 return true;
1272 // we have still signal but no proper byte or EOF? this shouldn't happen
1273 //Demod.posCount = 10 * 2;
1274 Demod.bitCount = 0;
1275 Demod.len = 0;
1276 Demod.state = WAIT_FOR_RISING_EDGE_OF_SOF;
1277 break;
1280 Demod.posCount = 0;
1282 break;
1284 default: {
1285 Demod.state = DEMOD_UNSYNCD;
1286 LED_C_OFF();
1287 break;
1290 return false;
1294 * Demodulate the samples we received from the tag, also log to tracebuffer
1296 static int Get14443bAnswerFromTag(uint8_t *response, uint16_t max_len, uint32_t timeout, uint32_t *eof_time) {
1298 // Set up the demodulator for tag -> reader responses.
1299 Demod14bInit(response, max_len);
1301 // The DMA buffer, used to stream samples from the FPGA
1302 dmabuf16_t *dma = get_dma16();
1303 if (FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE) == false) {
1304 if (DBGLEVEL > DBG_ERROR) Dbprintf("FpgaSetupSscDma failed. Exiting");
1305 return -1;
1308 uint32_t dma_start_time = 0;
1309 uint16_t *upTo = dma->buf;
1310 int samples = 0, ret = 0;
1312 // Put FPGA in the appropriate mode
1313 LED_D_ON();
1314 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_848_KHZ | FPGA_HF_READER_MODE_RECEIVE_IQ);
1316 for (;;) {
1318 volatile uint16_t behindBy = ((uint16_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
1319 if (behindBy == 0)
1320 continue;
1322 samples++;
1324 if (samples == 1) {
1325 // DMA has transferred the very first data
1326 dma_start_time = GetCountSspClk() & 0xfffffff0;
1329 volatile int8_t ci = *upTo >> 8;
1330 volatile int8_t cq = *upTo;
1331 upTo++;
1333 // we have read all of the DMA buffer content.
1334 if (upTo >= dma->buf + DMA_BUFFER_SIZE) {
1336 // start reading the circular buffer from the beginning again
1337 upTo = dma->buf;
1339 // DMA Counter Register had reached 0, already rotated.
1340 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) {
1342 // primary buffer was stopped
1343 if (AT91C_BASE_PDC_SSC->PDC_RCR == false) {
1344 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf;
1345 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
1347 // secondary buffer sets as primary, secondary buffer was stopped
1348 if (AT91C_BASE_PDC_SSC->PDC_RNCR == false) {
1349 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf;
1350 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
1353 WDT_HIT();
1354 if (BUTTON_PRESS()) {
1355 DbpString("stopped");
1356 break;
1361 if (Handle14443bSamplesFromTag(ci, cq)) {
1363 *eof_time = GetCountSspClkDelta(dma_start_time) - DELAY_TAG_TO_ARM; // end of EOF
1365 if (Demod.len > Demod.max_len) {
1366 ret = -2; // overflow
1368 break;
1371 if (((GetCountSspClkDelta(dma_start_time)) > timeout) && Demod.state < DEMOD_PHASE_REF_TRAINING) {
1372 ret = -1;
1373 break;
1377 FpgaDisableSscDma();
1378 if (ret < 0) {
1379 return ret;
1382 if (Demod.len > 0) {
1383 uint32_t sof_time = *eof_time
1384 - (Demod.len * (8 + 2)) // time for byte transfers
1385 - (10) // time for TR1
1386 - (10 + 2) // time for SOF transfer
1387 - (10); // time for EOF transfer
1388 LogTrace(Demod.output, Demod.len, sof_time, *eof_time, NULL, false);
1390 return Demod.len;
1393 //-----------------------------------------------------------------------------
1394 // Transmit the command (to the tag) that was placed in ToSend[].
1395 //-----------------------------------------------------------------------------
1396 // param start_time in SSP_CLK
1397 static void TransmitFor14443b_AsReader(uint32_t *start_time) {
1399 tosend_t *ts = get_tosend();
1401 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_SHALLOW_MOD);
1404 // TR2 minimum 14 ETUs
1405 if (*start_time < ISO14B_TR0) {
1406 // *start_time = DELAY_ARM_TO_TAG;
1407 *start_time = ISO14B_TR0;
1410 // *start_time = (*start_time - DELAY_ARM_TO_TAG) & 0xfffffff0;
1411 *start_time = (*start_time & 0xfffffff0);
1413 if (GetCountSspClk() > *start_time) { // we may miss the intended time
1414 *start_time = (GetCountSspClk() + 32) & 0xfffffff0; // next possible time
1417 // wait
1418 while (GetCountSspClk() < *start_time);
1420 LED_B_ON();
1421 for (int c = 0; c < ts->max; c++) {
1422 volatile uint8_t data = ts->buf[c];
1424 for (uint8_t i = 0; i < 8; i++) {
1425 volatile uint16_t send_word = (data & 0x80) ? 0x0000 : 0xFFFF;
1427 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
1428 AT91C_BASE_SSC->SSC_THR = send_word;
1430 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
1431 AT91C_BASE_SSC->SSC_THR = send_word;
1433 data <<= 1;
1435 WDT_HIT();
1437 LED_B_OFF();
1439 *start_time += DELAY_ARM_TO_TAG;
1441 // wait for last transfer to complete
1442 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY)) {};
1445 //-----------------------------------------------------------------------------
1446 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1447 // so that it is ready to transmit to the tag using TransmitFor14443b().
1448 //-----------------------------------------------------------------------------
1449 static void CodeIso14443bAsReader(const uint8_t *cmd, int len) {
1451 * QUESTION: how long is a 1 or 0 in pulses in the xcorr_848 mode?
1452 * 1 "stuffbit" = 1ETU (9us)
1454 * TR2 - After the PICC response, the PCD is required to wait the Frame Delay Time (TR2)
1455 before transmission of the next command. The minimum frame delay time required for
1456 all commands is 14 ETUs
1459 int i;
1460 tosend_reset();
1462 // Send SOF
1463 // 10-11 ETUs of ZERO
1464 for (i = 0; i < 10; i++) {
1465 tosend_stuffbit(0);
1467 // 2-3 ETUs of ONE
1468 tosend_stuffbit(1);
1469 tosend_stuffbit(1);
1471 // Sending cmd, LSB
1472 // from here we add BITS
1473 for (i = 0; i < len; i++) {
1474 // Start bit
1475 tosend_stuffbit(0);
1477 // Data bits
1478 volatile uint8_t b = cmd[i];
1479 tosend_stuffbit(b & 1);
1480 tosend_stuffbit((b >> 1) & 1);
1481 tosend_stuffbit((b >> 2) & 1);
1482 tosend_stuffbit((b >> 3) & 1);
1483 tosend_stuffbit((b >> 4) & 1);
1484 tosend_stuffbit((b >> 5) & 1);
1485 tosend_stuffbit((b >> 6) & 1);
1486 tosend_stuffbit((b >> 7) & 1);
1488 // Stop bit
1489 tosend_stuffbit(1);
1490 // EGT extra guard time 1 ETU = 9us
1491 // For PCD it ranges 0-57us === 0 - 6 ETU
1492 // FOR PICC it ranges 0-19us == 0 - 2 ETU
1495 // Send EOF
1496 // 10-11 ETUs of ZERO
1497 for (i = 0; i < 10; i++) {
1498 tosend_stuffbit(0);
1502 int pad = (10 + 2 + (len * 10) + 10) & 0x7;
1503 for (i = 0; i < 16 - pad; ++i)
1504 tosend_stuffbit(1);
1509 * Convenience function to encode, transmit and trace iso 14443b comms
1511 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd, int len, uint32_t *start_time, uint32_t *eof_time) {
1512 tosend_t *ts = get_tosend();
1513 CodeIso14443bAsReader(cmd, len);
1514 TransmitFor14443b_AsReader(start_time);
1515 if (g_trigger) LED_A_ON();
1516 *eof_time = *start_time + (10 * ts->max) + 10 + 2 + 10;
1517 LogTrace(cmd, len, *start_time, *eof_time, NULL, true);
1520 /* Sends an APDU to the tag
1521 * TODO: check CRC and preamble
1523 int iso14443b_apdu(uint8_t const *msg, size_t msg_len, bool send_chaining, void *rxdata, uint16_t rxmaxlen, uint8_t *res) {
1525 uint8_t real_cmd[msg_len + 4];
1527 if (msg_len) {
1528 // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02
1529 real_cmd[0] = 0x02; // bnr, nad, cid, chn=0; i-block(0x00)
1530 if (send_chaining) {
1531 real_cmd[0] |= 0x10;
1533 // put block number into the PCB
1534 real_cmd[0] |= iso14b_pcb_blocknum;
1535 memcpy(real_cmd + 1, msg, msg_len);
1536 } else {
1537 // R-block. ACK
1538 real_cmd[0] = 0xA2; // r-block + ACK
1539 real_cmd[0] |= iso14b_pcb_blocknum;
1542 AddCrc14B(real_cmd, msg_len + 1);
1544 // send
1545 uint32_t start_time = 0;
1546 uint32_t eof_time = 0;
1547 CodeAndTransmit14443bAsReader(real_cmd, msg_len + 3, &start_time, &eof_time);
1549 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1550 int len = Get14443bAnswerFromTag(rxdata, rxmaxlen, iso14b_timeout, &eof_time);
1551 FpgaDisableTracing();
1553 uint8_t *data_bytes = (uint8_t *) rxdata;
1555 if (len <= 0) {
1556 return 0; //DATA LINK ERROR
1557 } else {
1558 // S-Block WTX
1559 while (len && ((data_bytes[0] & 0xF2) == 0xF2)) {
1561 uint32_t save_iso14b_timeout_spp = iso14b_timeout;
1563 // 2 high bits mandatory set to 0b
1564 // byte1 - WTXM [1..59].
1565 uint8_t wtxm = data_bytes[1] & 0x3F;
1567 // command FWT = FWT * WTXM
1568 uint32_t fwt_temp = iso14b_fwt * wtxm;
1570 // temporarily increase timeout
1571 iso14b_set_timeout((32 << fwt_temp));
1573 // Transmit WTX back
1574 data_bytes[1] = wtxm;
1576 // now need to fix CRC.
1577 AddCrc14B(data_bytes, len - 2);
1579 // transmit S-Block
1580 CodeAndTransmit14443bAsReader(data_bytes, len, &start_time, &eof_time);
1582 // retrieve the result again (with increased timeout)
1583 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1584 len = Get14443bAnswerFromTag(rxdata, rxmaxlen, iso14b_timeout, &eof_time);
1585 FpgaDisableTracing();
1587 data_bytes = rxdata;
1589 // restore timeout
1590 iso14b_timeout = save_iso14b_timeout_spp;
1593 // if we received an I- or R(ACK)-Block with a block number equal to the
1594 // current block number, toggle the current block number
1595 if (len >= 3 // PCB + CRC = 3 bytes
1596 && ((data_bytes[0] & 0xC0) == 0 // I-Block
1597 || (data_bytes[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1598 && (data_bytes[0] & 0x01) == iso14b_pcb_blocknum) { // equal block numbers
1599 iso14b_pcb_blocknum ^= 1;
1602 // if we received I-block with chaining we need to send ACK and receive another block of data
1603 if (res)
1604 *res = data_bytes[0];
1606 // crc check
1607 if (len >= 3 && !check_crc(CRC_14443_B, data_bytes, len)) {
1608 return -1;
1612 if (len) {
1613 // cut frame byte
1614 len -= 1;
1615 // memmove(data_bytes, data_bytes + 1, len);
1616 for (int i = 0; i < len; i++)
1617 data_bytes[i] = data_bytes[i + 1];
1620 return len;
1624 * ASK CTS initialise.
1626 static int iso14443b_select_cts_card(iso14b_cts_card_select_t *card) {
1627 // INITIATE command: wake up the tag using the INITIATE
1628 uint8_t cmdINIT[] = {ASK_REQT, 0xF9, 0xE0};
1629 uint8_t cmdMSBUID[] = {ASK_SELECT, 0xFF, 0xFF, 0x00, 0x00};
1630 uint8_t cmdLSBUID[] = {0xC4, 0x00, 0x00};
1632 AddCrc14B(cmdMSBUID, 3);
1633 AddCrc14B(cmdLSBUID, 1);
1635 uint8_t r[8];
1637 uint32_t start_time = 0;
1638 uint32_t eof_time = 0;
1639 CodeAndTransmit14443bAsReader(cmdINIT, sizeof(cmdINIT), &start_time, &eof_time);
1641 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1642 int retlen = Get14443bAnswerFromTag(r, sizeof(r), iso14b_timeout, &eof_time);
1643 FpgaDisableTracing();
1645 if (retlen != 4) {
1646 return -1;
1648 if (check_crc(CRC_14443_B, r, retlen) == false) {
1649 return -2;
1652 if (card) {
1653 // pc. fc Product code, Facility code
1654 card->pc = r[0];
1655 card->fc = r[1];
1658 start_time = eof_time + ISO14B_TR2;
1659 CodeAndTransmit14443bAsReader(cmdMSBUID, sizeof(cmdMSBUID), &start_time, &eof_time);
1661 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1662 retlen = Get14443bAnswerFromTag(r, sizeof(r), iso14b_timeout, &eof_time);
1663 FpgaDisableTracing();
1665 if (retlen != 4) {
1666 return -1;
1668 if (check_crc(CRC_14443_B, r, retlen) == false) {
1669 return -2;
1672 if (card) {
1673 memcpy(card->uid, r, 2);
1676 start_time = eof_time + ISO14B_TR2;
1677 CodeAndTransmit14443bAsReader(cmdLSBUID, sizeof(cmdLSBUID), &start_time, &eof_time);
1679 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1680 retlen = Get14443bAnswerFromTag(r, sizeof(r), iso14b_timeout, &eof_time);
1681 FpgaDisableTracing();
1683 if (retlen != 4) {
1684 return -1;
1686 if (check_crc(CRC_14443_B, r, retlen) == false) {
1687 return -2;
1690 if (card) {
1691 memcpy(card->uid + 2, r, 2);
1694 return 0;
1697 * SRx Initialise.
1699 static int iso14443b_select_srx_card(iso14b_card_select_t *card) {
1700 // INITIATE command: wake up the tag using the INITIATE
1701 static const uint8_t init_srx[] = { ISO14443B_INITIATE, 0x00, 0x97, 0x5b };
1702 uint8_t r_init[3] = {0x0};
1703 uint8_t r_select[3] = {0x0};
1704 uint8_t r_papid[10] = {0x0};
1706 uint32_t start_time = 0;
1707 uint32_t eof_time = 0;
1708 CodeAndTransmit14443bAsReader(init_srx, sizeof(init_srx), &start_time, &eof_time);
1710 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1711 int retlen = Get14443bAnswerFromTag(r_init, sizeof(r_init), iso14b_timeout, &eof_time);
1712 FpgaDisableTracing();
1714 if (retlen <= 0) {
1715 return -1;
1718 // Randomly generated Chip ID
1719 if (card) {
1720 card->chipid = Demod.output[0];
1723 // SELECT command (with space for CRC)
1724 uint8_t select_srx[] = { ISO14443B_SELECT, 0x00, 0x00, 0x00};
1725 select_srx[1] = r_init[0];
1727 AddCrc14B(select_srx, 2);
1729 start_time = eof_time + ISO14B_TR2;
1730 CodeAndTransmit14443bAsReader(select_srx, sizeof(select_srx), &start_time, &eof_time);
1732 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1733 retlen = Get14443bAnswerFromTag(r_select, sizeof(r_select), iso14b_timeout, &eof_time);
1734 FpgaDisableTracing();
1736 if (retlen != 3) {
1737 return -1;
1739 if (check_crc(CRC_14443_B, r_select, retlen) == false) {
1740 return -2;
1743 // Check response from the tag: should be the same UID as the command we just sent:
1744 if (select_srx[1] != r_select[0]) {
1745 return -3;
1748 // First get the tag's UID:
1749 select_srx[0] = ISO14443B_GET_UID;
1751 AddCrc14B(select_srx, 1);
1753 start_time = eof_time + ISO14B_TR2;
1754 CodeAndTransmit14443bAsReader(select_srx, 3, &start_time, &eof_time); // Only first three bytes for this one
1756 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1757 retlen = Get14443bAnswerFromTag(r_papid, sizeof(r_papid), iso14b_timeout, &eof_time);
1758 FpgaDisableTracing();
1760 if (retlen != 10) {
1761 return -1;
1763 if (!check_crc(CRC_14443_B, r_papid, retlen)) {
1764 return -2;
1767 if (card) {
1768 card->uidlen = 8;
1769 memcpy(card->uid, r_papid, 8);
1772 return 0;
1774 /* Perform the ISO 14443 B Card Selection procedure
1775 * Currently does NOT do any collision handling.
1776 * It expects 0-1 cards in the device's range.
1777 * TODO: Support multiple cards (perform anticollision)
1778 * TODO: Verify CRC checksums
1780 int iso14443b_select_card(iso14b_card_select_t *card) {
1781 // WUPB command (including CRC)
1782 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
1783 // WUTB or REQB is denoted in the third byte, lower nibble. 0 vs 8
1784 //static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 };
1785 static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xff };
1787 // ATTRIB command (with space for CRC)
1788 uint8_t attrib[] = { ISO14443B_ATTRIB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
1790 uint8_t r_pupid[14] = {0x0};
1791 uint8_t r_attrib[3] = {0x0};
1793 // first, wake up the tag
1794 uint32_t start_time = 0;
1795 uint32_t eof_time = 0;
1796 CodeAndTransmit14443bAsReader(wupb, sizeof(wupb), &start_time, &eof_time);
1798 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1799 int retlen = Get14443bAnswerFromTag(r_pupid, sizeof(r_pupid), iso14b_timeout, &eof_time);
1800 FpgaDisableTracing();
1802 // ATQB too short?
1803 if (retlen < 14) {
1804 return -1;
1807 // VALIDATE CRC
1808 if (check_crc(CRC_14443_B, r_pupid, retlen) == false) {
1809 return -2;
1812 if (card) {
1813 card->uidlen = 4;
1814 memcpy(card->uid, r_pupid + 1, 4);
1815 memcpy(card->atqb, r_pupid + 5, 7);
1818 // copy the PUPI to ATTRIB ( PUPI == UID )
1819 memcpy(attrib + 1, r_pupid + 1, 4);
1821 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
1822 attrib[7] = r_pupid[10] & 0x0F;
1823 AddCrc14B(attrib, 9);
1824 start_time = eof_time + ISO14B_TR2;
1825 CodeAndTransmit14443bAsReader(attrib, sizeof(attrib), &start_time, &eof_time);
1827 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1828 retlen = Get14443bAnswerFromTag(r_attrib, sizeof(r_attrib), iso14b_timeout, &eof_time);
1829 FpgaDisableTracing();
1831 // Answer to ATTRIB too short?
1832 if (retlen < 3) {
1833 return -1;
1836 // VALIDATE CRC
1837 if (check_crc(CRC_14443_B, r_attrib, retlen) == false) {
1838 return -2;
1841 if (card) {
1843 // CID
1844 card->cid = r_attrib[0];
1846 // MAX FRAME
1847 uint16_t maxFrame = card->atqb[5] >> 4;
1848 if (maxFrame < 5) maxFrame = 8 * maxFrame + 16;
1849 else if (maxFrame == 5) maxFrame = 64;
1850 else if (maxFrame == 6) maxFrame = 96;
1851 else if (maxFrame == 7) maxFrame = 128;
1852 else if (maxFrame == 8) maxFrame = 256;
1853 else maxFrame = 257;
1854 iso14b_set_maxframesize(maxFrame);
1856 // FWT
1857 uint8_t fwt = card->atqb[6] >> 4;
1858 if (fwt < 15) {
1859 iso14b_set_fwt(fwt);
1862 // reset PCB block number
1863 iso14b_pcb_blocknum = 0;
1864 return 0;
1867 // Set up ISO 14443 Type B communication (similar to iso14443a_setup)
1868 // field is setup for "Sending as Reader"
1869 void iso14443b_setup(void) {
1870 LEDsoff();
1871 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1873 // allocate command receive buffer
1874 BigBuf_free();
1875 BigBuf_Clear_ext(false);
1877 // Initialize Demod and Uart structs
1878 Demod14bInit(BigBuf_malloc(MAX_FRAME_SIZE), MAX_FRAME_SIZE);
1879 Uart14bInit(BigBuf_malloc(MAX_FRAME_SIZE));
1881 // connect Demodulated Signal to ADC:
1882 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1884 // Set up the synchronous serial port
1885 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
1887 // Signal field is on with the appropriate LED
1888 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_SHALLOW_MOD);
1889 SpinDelay(100);
1891 // Start the timer
1892 StartCountSspClk();
1894 // reset timeout
1895 iso14b_set_fwt(8);
1897 LED_D_ON();
1900 //-----------------------------------------------------------------------------
1901 // Read a SRI512 ISO 14443B tag.
1903 // SRI512 tags are just simple memory tags, here we're looking at making a dump
1904 // of the contents of the memory. No anticollision algorithm is done, we assume
1905 // we have a single tag in the field.
1907 // I tried to be systematic and check every answer of the tag, every CRC, etc...
1908 //-----------------------------------------------------------------------------
1909 static int read_srx_block(uint8_t blocknr, uint8_t *block) {
1911 uint8_t cmd[] = {ISO14443B_READ_BLK, blocknr, 0x00, 0x00};
1912 AddCrc14B(cmd, 2);
1914 uint8_t r_block[6] = {0};
1916 uint32_t start_time = 0;
1917 uint32_t eof_time = 0;
1918 CodeAndTransmit14443bAsReader(cmd, sizeof(cmd), &start_time, &eof_time);
1920 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
1921 int retlen = Get14443bAnswerFromTag(r_block, sizeof(r_block), iso14b_timeout, &eof_time);
1922 FpgaDisableTracing();
1924 // Check if we got an answer from the tag
1925 if (retlen != 6) {
1926 DbpString("[!] expected 6 bytes from tag, got less...");
1927 return PM3_EWRONGANSWER;
1929 // The check the CRC of the answer
1930 if (check_crc(CRC_14443_B, r_block, retlen) == false) {
1931 DbpString("CRC fail");
1932 return PM3_ECRC;
1935 if (block) {
1936 memcpy(block, r_block, 4);
1939 if (DBGLEVEL >= DBG_DEBUG) {
1940 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x",
1941 blocknr,
1942 (r_block[3] << 24) + (r_block[2] << 16) + (r_block[1] << 8) + r_block[0],
1943 (r_block[4] << 8) + r_block[5]
1947 return PM3_SUCCESS;
1950 void ReadSTBlock(uint8_t blocknr) {
1951 iso14443b_setup();
1952 iso14b_card_select_t card;
1953 int res = iso14443b_select_srx_card(&card);
1954 // 0: OK -1 wrong len, -2: attrib fail, -3:crc fail,
1955 switch (res) {
1956 case -1:
1957 case -3: {
1958 reply_ng(CMD_HF_SRI_READ, PM3_EWRONGANSWER, NULL, 0);
1959 goto out;
1961 case -2: {
1962 reply_ng(CMD_HF_SRI_READ, PM3_ECRC, NULL, 0);
1963 goto out;
1966 uint8_t *data = BigBuf_malloc(4);
1967 res = read_srx_block(blocknr, data);
1968 reply_ng(CMD_HF_SRI_READ, res, data, 4);
1970 out:
1971 BigBuf_free();
1972 switch_off();
1975 //=============================================================================
1976 // Finally, the `sniffer' combines elements from both the reader and
1977 // simulated tag, to show both sides of the conversation.
1978 //=============================================================================
1980 //-----------------------------------------------------------------------------
1981 // Record the sequence of commands sent by the reader to the tag, with
1982 // triggering so that we start recording at the point that the tag is moved
1983 // near the reader.
1984 //-----------------------------------------------------------------------------
1986 * Memory usage for this function, (within BigBuf)
1987 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1988 * Last Received command (tag->reader) - MAX_FRAME_SIZE
1989 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
1990 * Demodulated samples received - all the rest
1992 void SniffIso14443b(void) {
1994 LEDsoff();
1995 LED_A_ON();
1997 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1999 DbpString("Starting to sniff. Press PM3 Button to stop.");
2001 BigBuf_free();
2002 clear_trace();
2003 set_tracing(true);
2005 // Initialize Demod and Uart structs
2006 uint8_t dm_buf[MAX_FRAME_SIZE] = {0};
2007 Demod14bInit(dm_buf, sizeof(dm_buf));
2009 uint8_t ua_buf[MAX_FRAME_SIZE] = {0};
2010 Uart14bInit(ua_buf);
2012 //Demod14bInit(BigBuf_malloc(MAX_FRAME_SIZE), MAX_FRAME_SIZE);
2013 //Uart14bInit(BigBuf_malloc(MAX_FRAME_SIZE));
2015 // Set FPGA in the appropriate mode
2016 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_848_KHZ | FPGA_HF_READER_MODE_SNIFF_IQ);
2017 // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_848_KHZ | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE);
2019 // connect Demodulated Signal to ADC:
2020 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2021 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
2023 StartCountSspClk();
2025 // The DMA buffer, used to stream samples from the FPGA
2026 dmabuf16_t *dma = get_dma16();
2028 // Setup and start DMA.
2029 if (!FpgaSetupSscDma((uint8_t *) dma->buf, DMA_BUFFER_SIZE)) {
2030 if (DBGLEVEL > DBG_ERROR) DbpString("FpgaSetupSscDma failed. Exiting");
2031 switch_off();
2032 return;
2035 // We won't start recording the frames that we acquire until we trigger;
2036 // a good trigger condition to get started is probably when we see a
2037 // response from the tag.
2038 bool tag_is_active = false;
2039 bool reader_is_active = false;
2040 bool expect_tag_answer = false;
2041 int dma_start_time = 0;
2043 // Count of samples received so far, so that we can include timing
2044 int samples = 0;
2046 uint16_t *upTo = dma->buf;
2048 for (;;) {
2050 volatile int behind_by = ((uint16_t *)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (DMA_BUFFER_SIZE - 1);
2051 if (behind_by < 1) continue;
2053 samples++;
2054 if (samples == 1) {
2055 // DMA has transferred the very first data
2056 dma_start_time = GetCountSspClk() & 0xfffffff0;
2059 volatile int8_t ci = *upTo >> 8;
2060 volatile int8_t cq = *upTo;
2061 upTo++;
2063 // we have read all of the DMA buffer content.
2064 if (upTo >= dma->buf + DMA_BUFFER_SIZE) {
2066 // start reading the circular buffer from the beginning again
2067 upTo = dma->buf;
2069 // DMA Counter Register had reached 0, already rotated.
2070 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) {
2072 // primary buffer was stopped
2073 if (AT91C_BASE_PDC_SSC->PDC_RCR == false) {
2074 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dma->buf;
2075 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
2077 // secondary buffer sets as primary, secondary buffer was stopped
2078 if (AT91C_BASE_PDC_SSC->PDC_RNCR == false) {
2079 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dma->buf;
2080 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
2083 WDT_HIT();
2084 if (BUTTON_PRESS()) {
2085 DbpString("Sniff stopped");
2086 break;
2091 // no need to try decoding reader data if the tag is sending
2092 if (tag_is_active == false) {
2094 if (Handle14443bSampleFromReader(ci & 0x01)) {
2095 uint32_t eof_time = dma_start_time + (samples * 16) + 8; // - DELAY_READER_TO_ARM_SNIFF; // end of EOF
2096 if (Uart.byteCnt > 0) {
2097 uint32_t sof_time = eof_time
2098 - Uart.byteCnt * 1 // time for byte transfers
2099 - 32 * 16 // time for SOF transfer
2100 - 16 * 16; // time for EOF transfer
2101 LogTrace(Uart.output, Uart.byteCnt, (sof_time * 4), (eof_time * 4), NULL, true);
2103 // And ready to receive another command.
2104 Uart14bReset();
2105 Demod14bReset();
2106 reader_is_active = false;
2107 expect_tag_answer = true;
2110 if (Handle14443bSampleFromReader(cq & 0x01)) {
2112 uint32_t eof_time = dma_start_time + (samples * 16) + 16; // - DELAY_READER_TO_ARM_SNIFF; // end of EOF
2113 if (Uart.byteCnt > 0) {
2114 uint32_t sof_time = eof_time
2115 - Uart.byteCnt * 1 // time for byte transfers
2116 - 32 * 16 // time for SOF transfer
2117 - 16 * 16; // time for EOF transfer
2118 LogTrace(Uart.output, Uart.byteCnt, (sof_time * 4), (eof_time * 4), NULL, true);
2120 // And ready to receive another command
2121 Uart14bReset();
2122 Demod14bReset();
2123 reader_is_active = false;
2124 expect_tag_answer = true;
2127 reader_is_active = (Uart.state > STATE_14B_GOT_FALLING_EDGE_OF_SOF);
2130 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
2131 if (reader_is_active == false && expect_tag_answer) {
2133 if (Handle14443bSamplesFromTag((ci >> 1), (cq >> 1))) {
2135 uint32_t eof_time = dma_start_time + (samples * 16); // - DELAY_TAG_TO_ARM_SNIFF; // end of EOF
2136 uint32_t sof_time = eof_time
2137 - Demod.len * 8 * 8 * 16 // time for byte transfers
2138 - (32 * 16) // time for SOF transfer
2139 - 0; // time for EOF transfer
2141 LogTrace(Demod.output, Demod.len, (sof_time * 4), (eof_time * 4), NULL, false);
2142 // And ready to receive another response.
2143 Uart14bReset();
2144 Demod14bReset();
2145 expect_tag_answer = false;
2146 tag_is_active = false;
2147 } else {
2148 tag_is_active = (Demod.state > WAIT_FOR_RISING_EDGE_OF_SOF);
2153 FpgaDisableTracing();
2154 switch_off();
2156 DbpString("");
2157 DbpString(_CYAN_("Sniff statistics"));
2158 DbpString("=================================");
2159 Dbprintf(" DecodeTag State........%d", Demod.state);
2160 Dbprintf(" DecodeTag byteCnt......%d", Demod.len);
2161 Dbprintf(" DecodeTag posCount.....%d", Demod.posCount);
2162 Dbprintf(" DecodeReader State.....%d", Uart.state);
2163 Dbprintf(" DecodeReader byteCnt...%d", Uart.byteCnt);
2164 Dbprintf(" DecodeReader posCount..%d", Uart.posCnt);
2165 Dbprintf(" Trace length..........." _YELLOW_("%d"), BigBuf_get_traceLen());
2166 DbpString("");
2169 static void iso14b_set_trigger(bool enable) {
2170 g_trigger = enable;
2173 void SendRawCommand14443B_Ex(iso14b_raw_cmd_t *p) {
2175 // receive buffer
2176 uint8_t buf[PM3_CMD_DATA_SIZE];
2177 memset(buf, 0, sizeof(buf));
2178 if (DBGLEVEL > DBG_DEBUG) {
2179 Dbprintf("14b raw: param, %04x", p->flags);
2182 // turn on trigger (LED_A)
2183 if ((p->flags & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER)
2184 iso14b_set_trigger(true);
2186 if ((p->flags & ISO14B_CONNECT) == ISO14B_CONNECT) {
2187 iso14443b_setup();
2190 if ((p->flags & ISO14B_SET_TIMEOUT) == ISO14B_SET_TIMEOUT) {
2191 iso14b_set_timeout(p->timeout);
2194 if ((p->flags & ISO14B_CLEARTRACE) == ISO14B_CLEARTRACE) {
2195 clear_trace();
2197 set_tracing(true);
2199 int status;
2200 uint32_t sendlen = sizeof(iso14b_card_select_t);
2201 iso14b_card_select_t card;
2202 memset((void *)&card, 0x00, sizeof(card));
2204 if ((p->flags & ISO14B_SELECT_STD) == ISO14B_SELECT_STD) {
2205 status = iso14443b_select_card(&card);
2206 reply_mix(CMD_HF_ISO14443B_COMMAND, status, sendlen, 0, (uint8_t *)&card, sendlen);
2207 // 0: OK -1: attrib fail, -2:crc fail,
2208 if (status != 0) goto out;
2211 if ((p->flags & ISO14B_SELECT_SR) == ISO14B_SELECT_SR) {
2212 status = iso14443b_select_srx_card(&card);
2213 reply_mix(CMD_HF_ISO14443B_COMMAND, status, sendlen, 0, (uint8_t *)&card, sendlen);
2214 // 0: OK 2: demod fail, 3:crc fail,
2215 if (status > 0) goto out;
2218 if ((p->flags & ISO14B_SELECT_CTS) == ISO14B_SELECT_CTS) {
2219 iso14b_cts_card_select_t cts;
2220 sendlen = sizeof(iso14b_cts_card_select_t);
2221 status = iso14443b_select_cts_card(&cts);
2222 reply_mix(CMD_HF_ISO14443B_COMMAND, status, sendlen, 0, (uint8_t *)&cts, sendlen);
2223 // 0: OK 2: demod fail, 3:crc fail,
2224 if (status > 0) goto out;
2227 if ((p->flags & ISO14B_APDU) == ISO14B_APDU) {
2228 uint8_t res;
2229 status = iso14443b_apdu(p->raw, p->rawlen, (p->flags & ISO14B_SEND_CHAINING), buf, sizeof(buf), &res);
2230 sendlen = MIN(Demod.len, PM3_CMD_DATA_SIZE);
2231 reply_mix(CMD_HF_ISO14443B_COMMAND, status, res, 0, buf, sendlen);
2234 if ((p->flags & ISO14B_RAW) == ISO14B_RAW) {
2235 if ((p->flags & ISO14B_APPEND_CRC) == ISO14B_APPEND_CRC) {
2236 if (p->rawlen > 0) {
2237 AddCrc14B(p->raw, p->rawlen);
2238 p->rawlen += 2;
2241 uint32_t start_time = 0;
2242 uint32_t eof_time = 0;
2243 CodeAndTransmit14443bAsReader(p->raw, p->rawlen, &start_time, &eof_time);
2245 if (tearoff_hook() == PM3_ETEAROFF) { // tearoff occurred
2246 FpgaDisableTracing();
2247 reply_mix(CMD_HF_ISO14443B_COMMAND, -2, 0, 0, NULL, 0);
2248 } else {
2249 eof_time += DELAY_ISO14443B_PCD_TO_PICC_READER;
2250 status = Get14443bAnswerFromTag(buf, sizeof(buf), iso14b_timeout, &eof_time); // raw
2251 FpgaDisableTracing();
2253 sendlen = MIN(Demod.len, PM3_CMD_DATA_SIZE);
2254 reply_mix(CMD_HF_ISO14443B_COMMAND, status, sendlen, 0, Demod.output, sendlen);
2258 out:
2259 // turn off trigger (LED_A)
2260 if ((p->flags & ISO14B_REQUEST_TRIGGER) == ISO14B_REQUEST_TRIGGER)
2261 iso14b_set_trigger(false);
2263 // turn off antenna et al
2264 // we don't send a HALT command.
2265 if ((p->flags & ISO14B_DISCONNECT) == ISO14B_DISCONNECT) {
2266 switch_off(); // disconnect raw
2267 SpinDelay(20);