1 //-----------------------------------------------------------------------------
2 // Copyright (C) Jonathan Westhues, Nov 2006
3 // Copyright (C) Gerhard de Koning Gans - May 2008
4 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // See LICENSE.txt for the text of the license.
17 //-----------------------------------------------------------------------------
18 // Routines to support ISO 14443B. This includes both the reader software and
19 // the `fake tag' modes.
20 //-----------------------------------------------------------------------------
21 #include "iso14443b.h"
23 #include "proxmark3_arm.h"
24 #include "common.h" // access to global variable: g_dbglevel
28 #include "protocols.h"
32 #include "fpgaloader.h"
33 #include "commonutil.h"
36 #include "iso14b.h" // defines for ETU conversions
37 #include "iclass.h" // picopass buffer defines
40 * Current timing issues with ISO14443-b implementation
42 * Carrier Frequency 13.56MHz
43 * 1 / 13 560 000 = 73.74 nano seconds ( 0.07374 µs )
45 * SSP_CLK runs at 13.56MHz / 4 = 3,39MHz
46 * 1 / 3 390 000 = 294.98 nano seconds ( 0.2949 µs )
48 * 1 ETU = 9.4395 µs = 32 SSP_CLK = 128 FC
50 * 1 µs 3 SSP_CLK about 14 FC
53 * one way of calculating time, that relates both to PM3 ssp_clk 3.39MHz, ISO freq of 13.56Mhz and ETUs
54 * convert from µS -> our SSP_CLK units which is used in the DEFINES..
55 * convert from ms -> our SSP_CLK units...
56 * convert from ETU -> our SSP_CLK units...
57 * All ETU -> µS -> ms should be diveded by for to match Proxmark3 FPGA SSP_CLK :)
62 * all DEFINES is in SSP_CLK ticks
63 * all delays is in SSP_CLK ticks
67 # define RECEIVE_MASK (DMA_BUFFER_SIZE - 1)
70 // SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
71 // All values should be multiples of 2 (?)
72 #define DELAY_READER_TO_ARM 8
73 #define DELAY_ARM_TO_READER 0
75 // SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader.
76 // All values should be multiples of 16
77 #define DELAY_ARM_TO_TAG 16
78 #define DELAY_TAG_TO_ARM 32
80 // SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when sniffing.
81 // All values should be multiples of 16
82 #define DELAY_TAG_TO_ARM_SNIFF 32
83 #define DELAY_READER_TO_ARM_SNIFF 32
87 * Frame Waiting Time Integer (FWI)
88 * can be between 0 and 14.
92 * Frame Waiting Time (FWT) formula
93 * --------------------------------
94 * FWT = (256 x 16 / fc) * 2 to the power for FWI
97 * ------- 2 to the power of FWI(4)
98 * FWT = (256 x 16 / fc) * (2*2*2*2) == 4.833 ms
100 * FTW(default) == FWT(4) == 4.822ms
102 * FWI_max == 2^14 = 16384
103 * FWT(max) = (256 x 16 / fc) * 16384 == 4949
105 * Which gives a maximum Frame Waiting time of FWT(max) == 4949 ms
106 * FWT(max) in ETU 4949000 / 9.4395 µS = 524286 ETU
108 * Simple calc to convert to ETU or µS
109 * -----------------------------------
110 * uint32_t fwt_time_etu = (32 << fwt);
111 * uint32_t fwt_time_us = (302 << fwt);
115 #ifndef MAX_14B_TIMEOUT
116 // FWT(max) = 4949 ms or 4.95 seconds.
117 // SSP_CLK = 4949000 * 3.39 = 16777120
118 # define MAX_14B_TIMEOUT (16777120U)
121 // Activation frame waiting time
123 // 65536/fc == 4833 µS or 4.833ms
124 // SSP_CLK = 4833 µS * 3.39 = 16384
125 #ifndef FWT_TIMEOUT_14B
126 # define FWT_TIMEOUT_14B (16384)
129 // ETU 14 * 9.4395 µS = 132 µS == 0.132ms
130 // TR2, counting from start of PICC EOF 14 ETU.
131 #define DELAY_ISO14443B_PICC_TO_PCD_READER HF14_ETU_TO_SSP(14)
132 #define DELAY_ISO14443B_PCD_TO_PICC_READER HF14_ETU_TO_SSP(15)
134 /* Guard Time (per 14443-2) in ETU
136 * Transition time. TR0 - guard time
137 * TR0 - 8 ETU's minimum.
138 * TR0 - 32 ETU's maximum for ATQB only
139 * TR0 - FWT for all other commands
140 * 32,64,128,256,512, ... , 262144, 524288 ETU
141 * TR0 = FWT(1), FWT(2), FWT(3) .. FWT(14)
147 # define ISO14B_TR0 HF14_ETU_TO_SSP(16)
150 #ifndef ISO14B_TR0_MAX
151 # define ISO14B_TR0_MAX HF14_ETU_TO_SSP(32)
152 // * TR0 - 32 ETU's maximum for ATQB only
153 // * TR0 - FWT for all other commands
155 // TR0 max is 159 µS or 32 samples from FPGA
156 // 16 ETU * 9.4395 µS == 151 µS
157 // 16 * 8 = 128 sub carrier cycles,
158 // 128 / 4 = 32 I/Q pairs.
159 // since 1 I/Q pair after 4 subcarrier cycles at 848kHz subcarrier
162 // 8 ETU = 75 µS == 256 SSP_CLK
163 #ifndef ISO14B_TR0_MIN
164 # define ISO14B_TR0_MIN HF14_ETU_TO_SSP(8)
167 // Synchronization time (per 14443-2) in ETU
168 // 16 ETU = 151 µS == 512 SSP_CLK
169 #ifndef ISO14B_TR1_MIN
170 # define ISO14B_TR1_MIN HF14_ETU_TO_SSP(16)
172 // Synchronization time (per 14443-2) in ETU
173 // 25 ETU == 236 µS == 800 SSP_CLK
174 #ifndef ISO14B_TR1_MAX
175 # define ISO14B_TR1 HF14_ETU_TO_SSP(25)
178 // Frame Delay Time PICC to PCD (per 14443-3 Amendment 1) in ETU
179 // 14 ETU == 132 µS == 448 SSP_CLK
181 # define ISO14B_TR2 HF14_ETU_TO_SSP(14)
184 #ifndef ISO14B_BLOCK_SIZE
185 # define ISO14B_BLOCK_SIZE 4
189 #define SEND4STUFFBIT(x) tosend_stuffbit(!(x));tosend_stuffbit(!(x));tosend_stuffbit(!(x));tosend_stuffbit(!(x));
191 static void iso14b_set_timeout(uint32_t timeout_etu
);
192 static void iso14b_set_maxframesize(uint16_t size
);
193 static void iso14b_set_fwt(uint8_t fwt
);
195 // the block number for the ISO14443-4 PCB (used with APDUs)
196 static uint8_t s_iso14b_pcb_blocknum
= 0;
197 static uint8_t s_iso14b_fwt
= 9;
198 static uint32_t s_iso14b_timeout
= MAX_14B_TIMEOUT
;
200 static bool s_field_on
= false;
203 * ISO 14443-B communications
204 * --------------------------
205 * Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
206 * Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
208 * It uses half duplex with a 106 kbit per second data rate in each direction.
209 * Data transmitted by the card is load modulated with a 847.5 kHz subcarrier.
211 * fc - carrier frequency 13.56 MHz
212 * TR0 - Guard Time per 14443-2
213 * TR1 - Synchronization Time per 14443-2
214 * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
216 * Elementary Time Unit (ETU)
217 * --------------------------
218 * ETU is used to denote 1 bit period i.e. how long one bit transfer takes.
220 * - 128 Carrier cycles / 13.56MHz = 8 Subcarrier units / 848kHz = 1/106kHz = 9.4395 µS
221 * - 16 Carrier cycles = 1 Subcarrier unit = 1.17 µS
225 * 1 ETU = 128 / ( D x fc )
227 * D = divisor. Which initial is 1
228 * fc = carrier frequency
231 * 1 ETU = 128 / 13 560 000 = 9.4395 µS
234 * (note: It seems we are using the subcarrier as base for our time calculations rather than the field clock)
236 * - 1 ETU = 1/106 KHz
237 * - 1 ETU = 8 subcarrier units ( 8 / 848kHz )
238 * - 1 ETU = 1 bit period
241 * Card sends data at 848kHz subcarrier
242 * subcar |duration| FC division| I/Q pairs
243 * -------+--------+------------+--------
244 * 106kHz | 9.44µS | FC/128 | 16
245 * 212kHz | 4.72µS | FC/64 | 8
246 * 424kHz | 2.36µS | FC/32 | 4
247 * 848kHz | 1.18µS | FC/16 | 2
248 * -------+--------+------------+--------
251 * One Character consists of 1 start, 1 stop, 8 databit with a total length of 10bits.
252 * - 1 Character = 10 ETU = 1 startbit, 8 databits, 1 stopbit
256 * Start of frame (SOF) is
257 * - [10-11] ETU of ZEROS, unmodulated time
258 * - [2-3] ETU of ONES,
260 * End of frame (EOF) is
261 * - [10-11] ETU of ZEROS, unmodulated time
263 * Reader data transmission
264 * ------------------------
265 * - no modulation ONES
267 * - Command, data and CRC_B (1 Character)
269 * - no modulation ONES
271 * Card data transmission
272 * ----------------------
275 * - data (1 Character)
281 * let calc how long it takes the reader to send a message
282 * SOF 10 ETU + 4 data bytes + 2 crc bytes + EOF 2 ETU
283 * 10 + (4+2 * 10) + 2 = 72 ETU
284 * 72 * 9.4395 = 680 µS or 0.68 ms
287 * -> TO VERIFY THIS BELOW <-
288 * --------------------------
289 * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
291 * Simulation per definition is "inverted" effect on the reader antenna.
292 * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (1.18µS / pulse) == 9.44us
293 * - A 0-bit input to the FPGA becomes an unmodulated time of 1.18µS or does it become 8 nonpulses for 9.44us
296 * FPGA implementation
297 * -------------------
298 * Piwi implemented a I/Q sampling mode for the FPGA, where...
300 * FPGA doesn't seem to work with ETU. It seems to work with pulse / duration instead.
302 * This means that we are using a bit rate of 106 kbit/s, or fc/128.
303 * Oversample by 4, which ought to make things practical for the ARM
304 * (fc/32, 423.8 kbits/s, ~52 kbytes/s)
306 * We are sampling the signal at FC/32, we are reporting over SSP to PM3 each
308 * Current I/Q pair sampling
309 * -------------------------
310 * Let us report a correlation every 64 samples. I.e.
311 * 1 I/Q pair after 4 subcarrier cycles for the 848kHz subcarrier,
312 * 1 I/Q pair after 2 subcarrier cycles for the 424kHz subcarrier,
317 * Formula to calculate FWT (in ETUs) by timeout (in ms):
319 * 1 tick is about 1.5µS
322 * FWT = 13560000 * 1000 / (8*16) * timeout
323 * FWT = 13560000 * 1000 / 128 * timeout
325 * sample: 3sec == 3000ms
327 * 13560000 * 1000 / 128 * 3000 == 13560000000 / 384000 ==
328 * 13560000 / 384 = 35312 FWT
332 * @param timeout is in frame wait time, fwt, measured in ETUs
334 * However we need to compensate for SSP_CLK ...
339 //=============================================================================
340 // An ISO 14443 Type B tag. We listen for commands from the reader, using
341 // a UART kind of thing that's implemented in software. When we get a
342 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
343 // If it's good, then we can do something appropriate with it, and send
345 //=============================================================================
347 //-----------------------------------------------------------------------------
348 // Code up a string of octets at layer 2 (including CRC, we don't generate
349 // that here) so that they can be transmitted to the reader. Doesn't transmit
350 // them yet, just leaves them ready to send in ToSend[].
351 //-----------------------------------------------------------------------------
352 static void CodeIso14443bAsTag(const uint8_t *cmd
, int len
) {
356 // Transmit a burst of ones, as the initial thing that lets the
357 // reader get phase sync.
358 // This loop is TR1, per specification
359 // TR1 minimum must be > 80/fs
360 // TR1 maximum 200/fs
361 // 80/fs < TR1 < 200/fs
362 // 10 ETU < TR1 < 24 ETU
366 // 10-11 ETU * 4times samples ONES
367 for (i
= 0; i
< 10; i
++) {
372 // 10-11 ETU * 4times samples ZEROS
373 for (i
= 0; i
< 10; i
++) {
377 // 2-3 ETU * 4times samples ONES
378 for (i
= 0; i
< 2; i
++) {
383 for (i
= 0; i
< len
; i
++) {
390 for (int j
= 0; j
< 8; j
++) {
391 SEND4STUFFBIT(b
& 1);
399 // For PICC it ranges 0-18us (1etu = 9us)
404 // 10-11 ETU * 4 sample rate = ZEROS
405 for (i
= 0; i
< 10; i
++) {
409 // why this? push out transfers between arm and fpga?
410 //for (i = 0; i < 2; i++) {
414 tosend_t
*ts
= get_tosend();
415 // Convert from last byte pos to length
419 //-----------------------------------------------------------------------------
420 // The software UART that receives commands from the reader, and its state
422 //-----------------------------------------------------------------------------
426 STATE_14B_GOT_FALLING_EDGE_OF_SOF
,
427 STATE_14B_AWAITING_START_BIT
,
428 STATE_14B_RECEIVING_DATA
438 static void Uart14bReset(void) {
439 Uart
.state
= STATE_14B_UNSYNCD
;
443 Uart
.byteCntMax
= MAX_FRAME_SIZE
;
447 static void Uart14bInit(uint8_t *data
) {
452 // param timeout accepts ETU
453 static void iso14b_set_timeout(uint32_t timeout_etu
) {
455 uint32_t ssp
= HF14_ETU_TO_SSP(timeout_etu
);
457 if (ssp
> MAX_14B_TIMEOUT
) {
458 ssp
= MAX_14B_TIMEOUT
;
461 s_iso14b_timeout
= ssp
;
462 if (g_dbglevel
>= DBG_DEBUG
) {
463 Dbprintf("ISO14443B Timeout set to %ld fwt", s_iso14b_timeout
);
467 // keep track of FWT, also updates the timeout
468 static void iso14b_set_fwt(uint8_t fwt
) {
470 if (g_dbglevel
>= DBG_DEBUG
) {
471 Dbprintf("ISO14443B FWT Timeout set to %ld fwt", s_iso14b_fwt
);
473 iso14b_set_timeout(32 << fwt
);
476 static void iso14b_set_maxframesize(uint16_t size
) {
478 size
= MAX_FRAME_SIZE
;
481 Uart
.byteCntMax
= size
;
482 if (g_dbglevel
>= DBG_DEBUG
) {
483 Dbprintf("ISO14443B Max frame size set to %d bytes", Uart
.byteCntMax
);
487 //-----------------------------------------------------------------------------
488 // The software Demod that receives commands from the tag, and its state variables.
489 //-----------------------------------------------------------------------------
491 #define NOISE_THRESHOLD 80 // don't try to correlate noise
492 #define MAX_PREVIOUS_AMPLITUDE (-1 - NOISE_THRESHOLD)
497 DEMOD_PHASE_REF_TRAINING
,
498 WAIT_FOR_RISING_EDGE_OF_SOF
,
499 DEMOD_AWAITING_START_BIT
,
513 // Clear out the state of the "UART" that receives from the tag.
514 static void Demod14bReset(void) {
515 Demod
.state
= DEMOD_UNSYNCD
;
525 static void Demod14bInit(uint8_t *data
, uint16_t max_len
) {
527 Demod
.max_len
= max_len
;
531 /* Receive & handle a bit coming from the reader.
533 * This function is called 4 times per bit (every 2 subcarrier cycles).
534 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
537 * LED A -> ON once we have received the SOF and are expecting the rest.
538 * LED A -> OFF once we have received EOF or are in error state or unsynced
540 * Returns: true if we received a EOF
541 * false if we are still waiting for some more
543 static RAMFUNC
int Handle14443bSampleFromReader(uint8_t bit
) {
544 switch (Uart
.state
) {
545 case STATE_14B_UNSYNCD
:
547 // we went low, so this could be the beginning of an SOF
548 Uart
.state
= STATE_14B_GOT_FALLING_EDGE_OF_SOF
;
554 case STATE_14B_GOT_FALLING_EDGE_OF_SOF
:
557 if (Uart
.posCnt
== 2) { // sample every 4 1/fs in the middle of a bit
560 if (Uart
.bitCnt
> 9) {
561 // we've seen enough consecutive
562 // zeros that it's a valid SOF
565 Uart
.state
= STATE_14B_AWAITING_START_BIT
;
566 LED_A_ON(); // Indicate we got a valid SOF
568 // didn't stay down long enough before going high, error
569 Uart
.state
= STATE_14B_UNSYNCD
;
572 // do nothing, keep waiting
577 if (Uart
.posCnt
>= 4) {
581 if (Uart
.bitCnt
> 12) {
582 // Give up if we see too many zeros without a one, too.
584 Uart
.state
= STATE_14B_UNSYNCD
;
588 case STATE_14B_AWAITING_START_BIT
:
593 // max 57us between characters = 49 1/fs,
594 // max 3 etus after low phase of SOF = 24 1/fs
595 if (Uart
.posCnt
> 50 / 2) {
596 // stayed high for too long between characters, error
597 Uart
.state
= STATE_14B_UNSYNCD
;
601 // falling edge, this starts the data byte
605 Uart
.state
= STATE_14B_RECEIVING_DATA
;
609 case STATE_14B_RECEIVING_DATA
:
613 if (Uart
.posCnt
== 2) {
614 // time to sample a bit
617 Uart
.shiftReg
|= 0x200;
622 if (Uart
.posCnt
>= 4) {
626 if (Uart
.bitCnt
== 10) {
627 if ((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001)) {
628 // this is a data byte, with correct
629 // start and stop bits
630 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xFF;
633 if (Uart
.byteCnt
>= Uart
.byteCntMax
) {
634 // Buffer overflowed, give up
636 Uart
.state
= STATE_14B_UNSYNCD
;
638 // so get the next byte now
640 Uart
.state
= STATE_14B_AWAITING_START_BIT
;
642 } else if (Uart
.shiftReg
== 0x000) {
643 // this is an EOF byte
644 LED_A_OFF(); // Finished receiving
645 Uart
.state
= STATE_14B_UNSYNCD
;
646 if (Uart
.byteCnt
!= 0)
652 Uart
.state
= STATE_14B_UNSYNCD
;
659 Uart
.state
= STATE_14B_UNSYNCD
;
665 //-----------------------------------------------------------------------------
666 // Receive a command (from the reader to us, where we are the simulated tag),
667 // and store it in the given buffer, up to the given maximum length. Keeps
668 // spinning, waiting for a well-framed command, until either we get one
669 // (returns true) or someone presses the pushbutton on the board (false).
671 // Assume that we're called with the SSC (to the FPGA) and ADC path set
673 //-----------------------------------------------------------------------------
674 static bool GetIso14443bCommandFromReader(uint8_t *received
, uint16_t *len
) {
675 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
676 // only, since we are receiving, not transmitting).
677 // Signal field is off with the appropriate LED
679 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
681 // Now run a `software UART' on the stream of incoming samples.
682 Uart14bInit(received
);
684 while (BUTTON_PRESS() == false) {
687 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
688 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
689 for (uint8_t mask
= 0x80; mask
!= 0x00; mask
>>= 1) {
690 if (Handle14443bSampleFromReader(b
& mask
)) {
700 static void TransmitFor14443b_AsTag(const uint8_t *response
, uint16_t len
) {
702 // Signal field is off with the appropriate LED
705 // TR0: min - 1024 cycles = 75.52 us - max 4096 cycles = 302.08 us
709 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
711 // Transmit the response.
712 for (uint16_t i
= 0; i
< len
;) {
714 // Put byte into tx holding register as soon as it is ready
715 if (AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_TXRDY
) {
716 AT91C_BASE_SSC
->SSC_THR
= response
[i
++];
718 // Start-up SSC once first byte is in SSC_THR
720 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
725 //-----------------------------------------------------------------------------
726 // Main loop of simulated tag: receive commands from reader, decide what
727 // response to send, and send it.
728 //-----------------------------------------------------------------------------
729 void SimulateIso14443bTag(const uint8_t *pupi
) {
732 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
733 static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 };
734 // ... and REQB, AFI=0, Normal Request, N=1:
735 static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF };
737 static const uint8_t cmdHLTB[] = { 0x50, 0xff, 0xff, 0xff, 0xff };
739 static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
744 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
746 // connect Demodulated Signal to ADC:
747 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
749 // Set up the synchronous serial port
750 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
752 // allocate command receive buffer
753 BigBuf_free_keep_EM();
754 BigBuf_Clear_keep_EM();
759 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
760 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
761 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
762 uint8_t respATQB
[] = {
764 0x82, 0x0d, 0xe1, 0x74,
766 0x22, 0x00, 0x21, 0x85,
770 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
771 if (memcmp("\x00\x00\x00\x00", pupi
, 4) != 0) {
772 memcpy(respATQB
+ 1, pupi
, 4);
773 AddCrc14B(respATQB
, 12);
776 // response to HLTB and ATTRIB
777 static const uint8_t respOK
[] = {0x00, 0x78, 0xF0};
779 uint16_t len
, cmdsReceived
= 0;
780 int cardSTATE
= SIM_POWER_OFF
;
781 int vHf
= 0; // in mV
783 const tosend_t
*ts
= get_tosend();
785 uint8_t *receivedCmd
= BigBuf_calloc(MAX_FRAME_SIZE
);
787 // prepare "ATQB" tag answer (encoded):
788 CodeIso14443bAsTag(respATQB
, sizeof(respATQB
));
789 uint8_t *encodedATQB
= BigBuf_malloc(ts
->max
);
790 uint16_t encodedATQBLen
= ts
->max
;
791 memcpy(encodedATQB
, ts
->buf
, ts
->max
);
794 // prepare "OK" tag answer (encoded):
795 CodeIso14443bAsTag(respOK
, sizeof(respOK
));
796 uint8_t *encodedOK
= BigBuf_malloc(ts
->max
);
797 uint16_t encodedOKLen
= ts
->max
;
798 memcpy(encodedOK
, ts
->buf
, ts
->max
);
801 while (BUTTON_PRESS() == false) {
804 //iceman: limit with 2000 times..
805 if (data_available()) {
810 vHf
= (MAX_ADC_HF_VOLTAGE
* SumAdc(ADC_CHAN_HF
, 32)) >> 15;
811 if (vHf
> MF_MINFIELDV
) {
812 if (cardSTATE
== SIM_POWER_OFF
) {
813 cardSTATE
= SIM_IDLE
;
817 cardSTATE
= SIM_POWER_OFF
;
821 if (cardSTATE
== SIM_POWER_OFF
) {
825 // Get reader command
826 if (GetIso14443bCommandFromReader(receivedCmd
, &len
) == false) {
827 Dbprintf("button pressed, received %d commands", cmdsReceived
);
831 LogTrace(receivedCmd
, len
, 0, 0, NULL
, true);
833 if ((len
== 5) && (receivedCmd
[0] == ISO14443B_REQB
) && (receivedCmd
[2] & 0x08)) {
839 TransmitFor14443b_AsTag(encodedATQB
, encodedATQBLen
);
840 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, false);
841 cardSTATE
= SIM_READY
;
846 TransmitFor14443b_AsTag(encodedATQB
, encodedATQBLen
);
847 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, false);
851 } else if ((len
== 5) && (receivedCmd
[0] == ISO14443B_REQB
) && !(receivedCmd
[2] & 0x08)) {
856 TransmitFor14443b_AsTag(encodedATQB
, encodedATQBLen
);
857 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, false);
858 cardSTATE
= SIM_READY
;
862 TransmitFor14443b_AsTag(encodedATQB
, encodedATQBLen
);
863 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, false);
871 } else if ((len
== 7) && (receivedCmd
[0] == ISO14443B_HALT
)) {
875 TransmitFor14443b_AsTag(encodedOK
, encodedOKLen
);
876 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, false);
877 cardSTATE
= SIM_HALT
;
882 TransmitFor14443b_AsTag(encodedOK
, encodedOKLen
);
883 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, false);
891 } else if (len
== 11 && receivedCmd
[0] == ISO14443B_ATTRIB
) {
895 TransmitFor14443b_AsTag(encodedOK
, encodedOKLen
);
896 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, false);
897 cardSTATE
= SIM_ACTIVE
;
902 TransmitFor14443b_AsTag(encodedOK
, encodedOKLen
);
903 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, false);
917 if (g_dbglevel
>= DBG_DEBUG
) {
918 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
923 void Simulate_iso14443b_srx_tag(uint8_t *uid) {
928 > initiate 06 00 ISO14443B_INITIATE
930 > select 0e xx ISO14443B_SELECT
933 > readblock 08 blck_no ISO14443B_READ_BLK
934 < d0 d1 d2 d3 2byte crc
936 > get uid ISO14443B_GET_UID
937 < 81 93 99 20 92 11 02 (8byte UID in MSB D002 199220 999381)
939 #define ISO14443B_REQB 0x05
940 #define ISO14443B_ATTRIB 0x1D
941 #define ISO14443B_HALT 0x50
942 #define ISO14443B_INITIATE 0x06
943 #define ISO14443B_SELECT 0x0E
944 #define ISO14443B_GET_UID 0x0B
945 #define ISO14443B_READ_BLK 0x08
946 #define ISO14443B_WRITE_BLK 0x09
947 #define ISO14443B_RESET 0x0C
948 #define ISO14443B_COMPLETION 0x0F
949 #define ISO14443B_AUTHENTICATE 0x0A
950 #define ISO14443B_PING 0xBA
951 #define ISO14443B_PONG 0xAB
954 static const uint8_t resp_init_srx[] = { 0x73, 0x64, 0xb1 };
955 uint8_t resp_select_srx[] = { 0x73, 0x64, 0xb1 };
957 // a default uid, or user supplied
958 uint8_t resp_getuid_srx[10] = {
959 0x81, 0x93, 0x99, 0x20, 0x92, 0x11, 0x02, 0xD0, 0x00, 0x00
962 // ...UID supplied from user. Adjust ATQB response accordingly
963 if (memcmp("\x00\x00\x00\x00\x00\x00\x00\x00", uid, 8) != 0) {
964 memcpy(resp_getuid_srx, uid, 8);
965 AddCrc14B(resp_getuid_srx, 8);
968 // response to HLTB and ATTRIB
969 static const uint8_t respOK[] = {0x00, 0x78, 0xF0};
972 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
974 // connect Demodulated Signal to ADC:
975 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
977 // Set up the synchronous serial port
978 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
980 // allocate command receive buffer
982 BigBuf_Clear_ext(false);
986 uint16_t len, cmdsReceived = 0;
987 int cardSTATE = SIM_NOFIELD;
988 int vHf = 0; // in mV
990 tosend_t *ts = get_tosend();
992 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
994 // prepare "ATQB" tag answer (encoded):
995 CodeIso14443bAsTag(respATQB, sizeof(respATQB));
996 uint8_t *encodedATQB = BigBuf_malloc(ts->max);
997 uint16_t encodedATQBLen = ts->max;
998 memcpy(encodedATQB, ts->buf, ts->max);
1001 // prepare "OK" tag answer (encoded):
1002 CodeIso14443bAsTag(respOK, sizeof(respOK));
1003 uint8_t *encodedOK = BigBuf_malloc(ts->max);
1004 uint16_t encodedOKLen = ts->max;
1005 memcpy(encodedOK, ts->buf, ts->max);
1008 while (BUTTON_PRESS() == false) {
1011 //iceman: limit with 2000 times..
1012 if (data_available()) {
1016 // find reader field
1017 if (cardSTATE == SIM_NOFIELD) {
1019 vHf = (MAX_ADC_HF_VOLTAGE * SumAdc(ADC_CHAN_HF, 32)) >> 15;
1020 if (vHf > MF_MINFIELDV) {
1021 cardSTATE = SIM_IDLE;
1025 if (cardSTATE == SIM_NOFIELD) continue;
1027 // Get reader command
1028 if (GetIso14443bCommandFromReader(receivedCmd, &len) == false) {
1029 Dbprintf("button pressed, received %d commands", cmdsReceived);
1033 // ISO14443-B protocol states:
1034 // REQ or WUP request in ANY state
1035 // WUP in HALTED state
1037 if ((receivedCmd[0] == ISO14443B_REQB && (receivedCmd[2] & 0x8) == 0x8 && cardSTATE == SIM_HALTED) ||
1038 receivedCmd[0] == ISO14443B_REQB) {
1039 LogTrace(receivedCmd, len, 0, 0, NULL, true);
1040 cardSTATE = SIM_SELECTING;
1045 * How should this flow go?
1047 * send response ( waiting for Attrib)
1049 * send response ( waiting for commands 7816)
1051 send halt response ( waiting for wupb )
1054 switch (cardSTATE) {
1058 LogTrace(receivedCmd, len, 0, 0, NULL, true);
1061 case SIM_SELECTING: {
1062 TransmitFor14443b_AsTag(encodedATQB, encodedATQBLen);
1063 LogTrace(respATQB, sizeof(respATQB), 0, 0, NULL, false);
1064 cardSTATE = SIM_WORK;
1068 TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
1069 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
1070 cardSTATE = SIM_HALTED;
1073 case SIM_ACKNOWLEDGE: {
1074 TransmitFor14443b_AsTag(encodedOK, encodedOKLen);
1075 LogTrace(respOK, sizeof(respOK), 0, 0, NULL, false);
1076 cardSTATE = SIM_IDLE;
1080 if (len == 7 && receivedCmd[0] == ISO14443B_HALT) {
1081 cardSTATE = SIM_HALTED;
1082 } else if (len == 11 && receivedCmd[0] == ISO14443B_ATTRIB) {
1083 cardSTATE = SIM_ACKNOWLEDGE;
1088 // - emulate with a memory dump
1089 if (g_dbglevel >= DBG_DEBUG)
1090 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len, cmdsReceived);
1093 if (len >= 3) { // if crc exists
1095 if (check_crc(CRC_14443_B, receivedCmd, len) == false) {
1096 if (g_dbglevel >= DBG_DEBUG) {
1097 DbpString("CRC fail");
1101 if (g_dbglevel >= DBG_DEBUG) {
1102 DbpString("CRC ok");
1105 cardSTATE = SIM_IDLE;
1116 if (g_dbglevel >= DBG_DEBUG)
1117 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
1119 switch_off(); //simulate
1123 //=============================================================================
1124 // An ISO 14443 Type B reader. We take layer two commands, code them
1125 // appropriately, and then send them to the tag. We then listen for the
1126 // tag's response, which we leave in the buffer to be demodulated on the
1128 //=============================================================================
1129 // We support both 14b framing and 14b' framing.
1130 // 14b framing looks like:
1131 // xxxxxxxx1111111111111111-000000000011-0........1-0........1-0........1-1-0........1-0........1-1000000000011xxxxxx
1132 // TR1 SOF 10*0+2*1 start-stop ^^^^^^^^byte ^ occasional stuff bit EOF 10*0+N*1
1133 // 14b' framing looks like:
1134 // xxxxxxxxxxxxxxxx111111111111111111111-0........1-0........1-0........1-1-0........1-0........1-000000000000xxxxxxx
1135 // SOF? start-stop ^^^^^^^^byte ^ occasional stuff bit EOF
1138 * Handles reception of a bit from the tag
1140 * This function is called 2 times per bit (every 4 subcarrier cycles).
1141 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
1144 * LED C -> ON once we have received the SOF and are expecting the rest.
1145 * LED C -> OFF once we have received EOF or are unsynced
1147 * Returns: true if we received a EOF
1148 * false if we are still waiting for some more
1151 static RAMFUNC
int Handle14443bSamplesFromTag(int ci
, int cq
) {
1155 // The soft decision on the bit uses an estimate of just the
1156 // quadrant of the reference angle, not the exact angle.
1157 #define MAKE_SOFT_DECISION() { \
1158 if(Demod.sumI > 0) { \
1163 if(Demod.sumQ > 0) { \
1170 #define SUBCARRIER_DETECT_THRESHOLD 8
1171 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
1172 #define AMPLITUDE(ci,cq) (MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2))
1174 switch (Demod
.state
) {
1176 case DEMOD_UNSYNCD
: {
1177 if (AMPLITUDE(ci
, cq
) > SUBCARRIER_DETECT_THRESHOLD
) { // subcarrier detected
1178 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
1185 case DEMOD_PHASE_REF_TRAINING
: {
1186 // While we get a constant signal
1187 if (AMPLITUDE(ci
, cq
) > SUBCARRIER_DETECT_THRESHOLD
) {
1188 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
1189 ((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
1191 if (Demod
.posCount
< 10) { // refine signal approximation during first 10 samples
1195 Demod
.posCount
+= 1;
1198 if (Demod
.posCount
< 10) {
1200 Demod
.state
= DEMOD_UNSYNCD
;
1203 // at this point it can be start of 14b' data or start of 14b SOF
1204 MAKE_SOFT_DECISION();
1205 Demod
.posCount
= 1; // this was the first half
1208 Demod
.state
= DEMOD_RECEIVING_DATA
;
1213 Demod
.state
= DEMOD_UNSYNCD
;
1217 case DEMOD_AWAITING_START_BIT
: {
1219 MAKE_SOFT_DECISION();
1221 if (Demod
.posCount
> 3 * 2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1223 if (Demod
.bitCount
== 0 && Demod
.len
== 0) { // received SOF only, this is valid for iClass/Picopass
1226 Demod
.state
= DEMOD_UNSYNCD
;
1229 } else { // start bit detected
1230 Demod
.posCount
= 1; // this was the first half
1233 Demod
.state
= DEMOD_RECEIVING_DATA
;
1237 case WAIT_FOR_RISING_EDGE_OF_SOF
: {
1240 MAKE_SOFT_DECISION();
1242 if (Demod
.posCount
< 9 * 2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1243 Demod
.state
= DEMOD_UNSYNCD
;
1245 LED_C_ON(); // Got SOF
1249 Demod
.state
= DEMOD_AWAITING_START_BIT
;
1252 if (Demod
.posCount
> 12 * 2) { // low phase of SOF too long (> 12 etu)
1253 Demod
.state
= DEMOD_UNSYNCD
;
1259 case DEMOD_RECEIVING_DATA
: {
1261 MAKE_SOFT_DECISION();
1263 if (Demod
.posCount
== 0) { // first half of bit
1266 } else { // second half of bit
1269 Demod
.shiftReg
>>= 1;
1270 if (Demod
.thisBit
> 0) { // logic '1'
1271 Demod
.shiftReg
|= 0x200;
1275 if (Demod
.bitCount
== 10) {
1277 uint16_t s
= Demod
.shiftReg
;
1279 if ((s
& 0x200) && !(s
& 0x001)) { // stop bit == '1', start bit == '0'
1280 Demod
.output
[Demod
.len
] = (s
>> 1);
1283 Demod
.state
= DEMOD_AWAITING_START_BIT
;
1286 if (Demod
.len
> 0) {
1288 // This is EOF (start, stop and all data bits == '0'
1291 // Zeroes but no data acquired yet?
1292 // => Still in SOF of 14b, wait for raising edge
1293 Demod
.posCount
= 10 * 2;
1296 Demod
.state
= WAIT_FOR_RISING_EDGE_OF_SOF
;
1300 if (AMPLITUDE(ci
, cq
) < SUBCARRIER_DETECT_THRESHOLD
) {
1303 Demod
.state
= DEMOD_UNSYNCD
;
1304 if (Demod
.len
> 0) { // no EOF but no signal anymore and we got data, e.g. ASK CTx
1308 // we have still signal but no proper byte or EOF? this shouldn't happen
1309 //Demod.posCount = 10 * 2;
1312 Demod
.state
= WAIT_FOR_RISING_EDGE_OF_SOF
;
1321 Demod
.state
= DEMOD_UNSYNCD
;
1330 * Demodulate the samples we received from the tag, also log to tracebuffer
1332 static int Get14443bAnswerFromTag(uint8_t *response
, uint16_t max_len
, uint32_t timeout
, uint32_t *eof_time
, uint16_t *retlen
) {
1334 // Set up the demodulator for tag -> reader responses.
1335 Demod14bInit(response
, max_len
);
1337 // The DMA buffer, used to stream samples from the FPGA
1338 dmabuf16_t
*dma
= get_dma16();
1343 if (FpgaSetupSscDma((uint8_t *) dma
->buf
, DMA_BUFFER_SIZE
) == false) {
1344 if (g_dbglevel
> DBG_ERROR
) Dbprintf("FpgaSetupSscDma failed. Exiting");
1348 uint32_t dma_start_time
= 0;
1349 uint16_t *upTo
= dma
->buf
;
1350 int samples
= 0, ret
= 0;
1352 // Put FPGA in the appropriate mode
1354 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_848_KHZ
| FPGA_HF_READER_MODE_RECEIVE_IQ
);
1358 volatile uint16_t behindBy
= ((uint16_t *)AT91C_BASE_PDC_SSC
->PDC_RPR
- upTo
) & (DMA_BUFFER_SIZE
- 1);
1359 if (behindBy
== 0) {
1366 // DMA has transferred the very first data
1367 dma_start_time
= GetCountSspClk() & 0xfffffff0;
1370 volatile int8_t ci
= *upTo
>> 8;
1371 volatile int8_t cq
= *upTo
;
1374 // we have read all of the DMA buffer content.
1375 if (upTo
>= dma
->buf
+ DMA_BUFFER_SIZE
) {
1377 // start reading the circular buffer from the beginning again
1380 // DMA Counter Register had reached 0, already rotated.
1381 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_ENDRX
)) {
1383 // primary buffer was stopped
1384 if (AT91C_BASE_PDC_SSC
->PDC_RCR
== false) {
1385 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dma
->buf
;
1386 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
1388 // secondary buffer sets as primary, secondary buffer was stopped
1389 if (AT91C_BASE_PDC_SSC
->PDC_RNCR
== false) {
1390 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dma
->buf
;
1391 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
1395 if (BUTTON_PRESS()) {
1396 DbpString("stopped");
1402 if (Handle14443bSamplesFromTag(ci
, cq
)) {
1404 *eof_time
= GetCountSspClkDelta(dma_start_time
) - DELAY_TAG_TO_ARM
; // end of EOF
1406 if (Demod
.len
> Demod
.max_len
) {
1412 if (((GetCountSspClkDelta(dma_start_time
)) > timeout
) && Demod
.state
< DEMOD_PHASE_REF_TRAINING
) {
1418 FpgaDisableSscDma();
1425 // 3 * 10 + 20 + 10 == 60, 60 << 5 = 1920
1427 // We are counting backwards here from EOF
1428 // tranfers time (in ETU) for
1430 uint32_t deduct
= (Demod
.len
* (8 + 2)) + (10 + 2) + 10;
1431 uint32_t sof_time
= *eof_time
- HF14_ETU_TO_SSP(deduct
);
1432 LogTrace(Demod
.output
, Demod
.len
, sof_time
, *eof_time
, NULL
, false);
1436 *retlen
= Demod
.len
;
1441 //-----------------------------------------------------------------------------
1442 // Transmit the command (to the tag) that was placed in ToSend[].
1443 //-----------------------------------------------------------------------------
1444 // param start_time in SSP_CLK
1445 static void TransmitFor14443b_AsReader(uint32_t *start_time
) {
1447 tosend_t
*ts
= get_tosend();
1450 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD_RDV4
);
1452 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD
);
1455 // TR2 minimum 14 ETUs
1456 if (*start_time
< ISO14B_TR0
) {
1457 // *start_time = DELAY_ARM_TO_TAG;
1458 *start_time
= ISO14B_TR0
;
1461 // *start_time = (*start_time - DELAY_ARM_TO_TAG) & 0xfffffff0;
1462 *start_time
= (*start_time
& 0xfffffff0);
1464 if (GetCountSspClk() > *start_time
) { // we may miss the intended time
1465 *start_time
= (GetCountSspClk() + 32) & 0xfffffff0; // next possible time
1469 while (GetCountSspClk() < *start_time
);
1472 for (int c
= 0; c
< ts
->max
; c
++) {
1473 volatile uint8_t data
= ts
->buf
[c
];
1475 for (uint8_t i
= 0; i
< 8; i
++) {
1476 volatile uint16_t send_word
= (data
& 0x80) ? 0x0000 : 0xFFFF;
1478 while (!(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
))) ;
1479 AT91C_BASE_SSC
->SSC_THR
= send_word
;
1481 while (!(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
))) ;
1482 AT91C_BASE_SSC
->SSC_THR
= send_word
;
1489 // transmit remaining bits. we need one-sample granularity now
1491 volatile uint8_t data
= ts
->buf
[ts
->max
], last_bits
= ts
->bit
;
1493 for (uint8_t i
= 0; i
< last_bits
; i
++) {
1494 volatile uint16_t send_word
= (data
& 0x80) ? 0x0000 : 0xFFFF;
1496 while (!(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
))) ;
1497 AT91C_BASE_SSC
->SSC_THR
= send_word
;
1499 while (!(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
))) ;
1500 AT91C_BASE_SSC
->SSC_THR
= send_word
;
1509 // *start_time += DELAY_ARM_TO_TAG;
1511 // wait for last transfer to complete
1512 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_TXEMPTY
)) {};
1515 //-----------------------------------------------------------------------------
1516 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1517 // so that it is ready to transmit to the tag using TransmitFor14443b().
1518 //-----------------------------------------------------------------------------
1519 static void CodeIso14443bAsReader(const uint8_t *cmd
, int len
, bool framing
) {
1521 * QUESTION: how long is a 1 or 0 in pulses in the xcorr_848 mode?
1522 * 1 "stuffbit" = 1ETU (9us)
1524 * TR2 - After the PICC response, the PCD is required to wait the Frame Delay Time (TR2)
1525 before transmission of the next command. The minimum frame delay time required for
1526 all commands is 14 ETUs
1532 // add framing enable flag.
1533 // xerox chips use unframed commands during anticollision
1536 // 10-11 ETUs of ZERO
1537 for (i
= 0; i
< 10; i
++) {
1546 // from here we add BITS
1547 for (i
= 0; i
< len
; i
++) {
1552 volatile uint8_t b
= cmd
[i
];
1553 tosend_stuffbit(b
& 1);
1554 tosend_stuffbit((b
>> 1) & 1);
1555 tosend_stuffbit((b
>> 2) & 1);
1556 tosend_stuffbit((b
>> 3) & 1);
1557 tosend_stuffbit((b
>> 4) & 1);
1558 tosend_stuffbit((b
>> 5) & 1);
1559 tosend_stuffbit((b
>> 6) & 1);
1560 tosend_stuffbit((b
>> 7) & 1);
1564 // EGT extra guard time 1 ETU = 9us
1565 // For PCD it ranges 0-57us === 0 - 6 ETU
1566 // FOR PICC it ranges 0-19us == 0 - 2 ETU
1571 // 10-11 ETUs of ZERO
1572 for (i
= 0; i
< 10; i
++) {
1577 // we can't use padding now
1579 int pad = (10 + 2 + (len * 10) + 10) & 0x7;
1580 for (i = 0; i < 16 - pad; ++i)
1586 * Convenience function to encode, transmit and trace iso 14443b comms
1588 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd
, int len
, uint32_t *start_time
, uint32_t *eof_time
, bool framing
) {
1589 const tosend_t
*ts
= get_tosend();
1590 CodeIso14443bAsReader(cmd
, len
, framing
);
1591 TransmitFor14443b_AsReader(start_time
);
1592 if (g_trigger
) LED_A_ON();
1594 // eof_time in ssp clocks, but bits was added here!
1595 // *eof_time = *start_time + (10 * ts->max) + 10 + 2 + 10;
1597 *eof_time
= *start_time
+ HF14_ETU_TO_SSP(8 * ts
->max
);
1599 LogTrace(cmd
, len
, *start_time
, *eof_time
, NULL
, true);
1602 /* Sends an APDU to the tag
1603 * TODO: check CRC and preamble
1605 int iso14443b_apdu(uint8_t const *msg
, size_t msg_len
, bool send_chaining
, void *rxdata
, uint16_t rxmaxlen
, uint8_t *response_byte
, uint16_t *responselen
) {
1607 uint8_t real_cmd
[msg_len
+ 4];
1610 // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02
1611 real_cmd
[0] = 0x02; // bnr, nad, cid, chn=0; i-block(0x00)
1613 if (send_chaining
) {
1614 real_cmd
[0] |= 0x10;
1617 // put block number into the PCB
1618 real_cmd
[0] |= s_iso14b_pcb_blocknum
;
1619 memcpy(real_cmd
+ 1, msg
, msg_len
);
1622 real_cmd
[0] = 0xA2; // r-block + ACK
1623 real_cmd
[0] |= s_iso14b_pcb_blocknum
;
1626 AddCrc14B(real_cmd
, msg_len
+ 1);
1629 uint32_t start_time
= 0;
1630 uint32_t eof_time
= 0;
1631 CodeAndTransmit14443bAsReader(real_cmd
, msg_len
+ 3, &start_time
, &eof_time
, true);
1633 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1635 // Activation frame waiting time
1636 // 65536/fc == 4833 µS
1637 // SSP_CLK = 4833 µS * 3.39 = 16384
1640 int status
= Get14443bAnswerFromTag(rxdata
, rxmaxlen
, s_iso14b_timeout
, &eof_time
, &len
);
1641 if (status
!= PM3_SUCCESS
) {
1645 uint8_t *data_bytes
= (uint8_t *) rxdata
;
1649 while (len
&& ((data_bytes
[0] & 0xF2) == 0xF2)) {
1651 uint32_t save_iso14b_timeout_spp
= s_iso14b_timeout
;
1653 // 2 high bits mandatory set to 0b
1654 // byte1 - WTXM [1..59].
1655 uint8_t wtxm
= data_bytes
[1] & 0x3F;
1657 // command FWT = FWT * WTXM
1658 uint32_t fwt_temp
= (s_iso14b_fwt
* wtxm
);
1660 // temporarily increase timeout
1661 iso14b_set_timeout((32 << fwt_temp
));
1663 // Transmit WTX back
1664 data_bytes
[1] = wtxm
;
1666 // now need to fix CRC.
1667 AddCrc14B(data_bytes
, len
- 2);
1670 CodeAndTransmit14443bAsReader(data_bytes
, len
, &start_time
, &eof_time
, true);
1672 // retrieve the result again (with increased timeout)
1673 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1675 if (Get14443bAnswerFromTag(rxdata
, rxmaxlen
, s_iso14b_timeout
, &eof_time
, &len
) != PM3_SUCCESS
) {
1676 return PM3_ECARDEXCHANGE
;
1679 data_bytes
= rxdata
;
1682 s_iso14b_timeout
= save_iso14b_timeout_spp
;
1685 // if we received an I- or R(ACK)-Block with a block number equal to the
1686 // current block number, toggle the current block number
1688 if ((len
>= 3) && // PCB + CRC = 3 bytes
1689 (((data_bytes
[0] & 0xC0) == 0) || (data_bytes
[0] & 0xD0) == 0x80) && // I-Block OR R-Block with ACK bit set to 0
1690 ((data_bytes
[0] & 0x01) == s_iso14b_pcb_blocknum
)) { // equal block numbers
1692 s_iso14b_pcb_blocknum
^= 1;
1696 // if we received I-block with chaining we need to send ACK and receive another block of data
1697 if (response_byte
) {
1698 *response_byte
= data_bytes
[0];
1702 if (len
>= 3 && (check_crc(CRC_14443_B
, data_bytes
, len
) == false)) {
1711 for (int i
= 0; i
< len
; i
++) {
1712 data_bytes
[i
] = data_bytes
[i
+ 1];
1723 * ASK CTS initialise.
1725 static int iso14443b_select_cts_card(iso14b_cts_card_select_t
*card
) {
1726 // INITIATE command: wake up the tag using the INITIATE
1727 uint8_t cmdINIT
[] = {ASK_REQT
, 0xF9, 0xE0};
1728 uint8_t cmdMSBUID
[] = {ASK_SELECT
, 0xFF, 0xFF, 0x00, 0x00};
1729 uint8_t cmdLSBUID
[] = {0xC4, 0x00, 0x00};
1731 // iceman: todo static crc
1732 AddCrc14B(cmdMSBUID
, 3);
1733 AddCrc14B(cmdLSBUID
, 1);
1735 uint8_t r
[8] = { 0x00 };
1737 uint32_t start_time
= 0;
1738 uint32_t eof_time
= 0;
1739 CodeAndTransmit14443bAsReader(cmdINIT
, sizeof(cmdINIT
), &start_time
, &eof_time
, true);
1741 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1742 uint16_t retlen
= 0;
1743 if (Get14443bAnswerFromTag(r
, sizeof(r
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1744 return PM3_ECARDEXCHANGE
;
1750 if (check_crc(CRC_14443_B
, r
, retlen
) == false) {
1755 // pc. fc Product code, Facility code
1760 start_time
= eof_time
+ ISO14B_TR2
;
1761 CodeAndTransmit14443bAsReader(cmdMSBUID
, sizeof(cmdMSBUID
), &start_time
, &eof_time
, true);
1763 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1764 if (Get14443bAnswerFromTag(r
, sizeof(r
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1765 return PM3_ECARDEXCHANGE
;
1771 if (check_crc(CRC_14443_B
, r
, retlen
) == false) {
1776 memcpy(card
->uid
, r
, 2);
1779 start_time
= eof_time
+ ISO14B_TR2
;
1780 CodeAndTransmit14443bAsReader(cmdLSBUID
, sizeof(cmdLSBUID
), &start_time
, &eof_time
, true);
1782 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1783 if (Get14443bAnswerFromTag(r
, sizeof(r
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1784 return PM3_ECARDEXCHANGE
;
1790 if (check_crc(CRC_14443_B
, r
, retlen
) == false) {
1795 memcpy(card
->uid
+ 2, r
, 2);
1803 static int iso14443b_select_srx_card(iso14b_card_select_t
*card
) {
1804 // INITIATE command: wake up the tag using the INITIATE
1805 static const uint8_t init_srx
[] = { ISO14443B_INITIATE
, 0x00, 0x97, 0x5b };
1806 uint8_t r_init
[3] = { 0x00 };
1807 uint8_t r_select
[3] = { 0x00 };
1808 uint8_t r_papid
[10] = { 0x00 };
1810 uint32_t start_time
= 0;
1811 uint32_t eof_time
= 0;
1812 CodeAndTransmit14443bAsReader(init_srx
, sizeof(init_srx
), &start_time
, &eof_time
, true);
1814 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1815 uint16_t retlen
= 0;
1816 if (Get14443bAnswerFromTag(r_init
, sizeof(r_init
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1817 return PM3_ECARDEXCHANGE
;
1820 // Randomly generated Chip ID
1822 card
->chipid
= Demod
.output
[0];
1825 // SELECT command (with space for CRC)
1826 uint8_t select_srx
[] = { ISO14443B_SELECT
, 0x00, 0x00, 0x00};
1827 select_srx
[1] = r_init
[0];
1829 AddCrc14B(select_srx
, 2);
1831 start_time
= eof_time
+ ISO14B_TR2
;
1832 CodeAndTransmit14443bAsReader(select_srx
, sizeof(select_srx
), &start_time
, &eof_time
, true);
1834 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1835 if (Get14443bAnswerFromTag(r_select
, sizeof(r_select
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1836 return PM3_ECARDEXCHANGE
;
1842 if (check_crc(CRC_14443_B
, r_select
, retlen
) == false) {
1846 // Check response from the tag: should be the same UID as the command we just sent:
1847 if (select_srx
[1] != r_select
[0]) {
1848 return PM3_EWRONGANSWER
;
1851 // First get the tag's UID:
1852 select_srx
[0] = ISO14443B_GET_UID
;
1853 select_srx
[1] = 0xAB;
1854 select_srx
[2] = 0x4E;
1856 start_time
= eof_time
+ ISO14B_TR2
;
1857 CodeAndTransmit14443bAsReader(select_srx
, 3, &start_time
, &eof_time
, true); // Only first three bytes for this one
1859 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1860 if (Get14443bAnswerFromTag(r_papid
, sizeof(r_papid
), s_iso14b_timeout
, &eof_time
, & retlen
) != PM3_SUCCESS
) {
1861 return PM3_ECARDEXCHANGE
;
1868 if (check_crc(CRC_14443_B
, r_papid
, retlen
) == false) {
1874 memcpy(card
->uid
, r_papid
, 8);
1879 // Xerox tag connect function: wup, anticoll, attrib, password
1880 // the original chips require all commands in this sequence
1882 // 0: OK, 1: select fail, 2: attrib fail, 3: crc fail, 4: password fail
1883 static int iso14443b_select_xrx_card(iso14b_card_select_t
*card
) {
1885 static const uint8_t x_wup1
[] = { 0x0D, 0x37, 0x21, 0x92, 0xf2 };
1886 static const uint8_t x_wup2
[] = { 0x5D, 0x37, 0x21, 0x71, 0x71 };
1887 uint8_t slot_mark
[1] = { 0x00 };
1888 uint8_t x_atqb
[24] = { 0x00 }; // ATQB len = 18
1890 uint32_t start_time
= 0;
1891 uint32_t eof_time
= 0;
1894 iso14b_set_timeout(24);
1897 CodeAndTransmit14443bAsReader(x_wup1
, sizeof(x_wup1
), &start_time
, &eof_time
, true);
1899 start_time
= eof_time
+ US_TO_SSP(9000); // 9ms before next cmd ( 30510 )
1902 CodeAndTransmit14443bAsReader(x_wup2
, sizeof(x_wup2
), &start_time
, &eof_time
, true);
1905 uint16_t retlen
= 0;
1907 for (uint8_t uid_pos
= 0; uid_pos
< 64; uid_pos
+= 2) {
1910 for (slot
= 0; slot
< 4; slot
++) {
1912 // next slot after 24 ETU (786)
1913 start_time
= eof_time
+ HF14_ETU_TO_SSP(30);
1914 Get14443bAnswerFromTag(x_atqb
, sizeof(x_atqb
), s_iso14b_timeout
, &eof_time
, &retlen
);
1916 Dbprintf("unexpected data %d", retlen
);
1917 return PM3_ECARDEXCHANGE
;
1920 // tx unframed slot-marker
1921 if (Demod
.posCount
) { // no rx, but subcarrier burst detected
1922 uid
|= (uint64_t)slot
<< uid_pos
;
1924 slot_mark
[0] = 0xB1 + (slot
<< 1); // ack slot
1925 CodeAndTransmit14443bAsReader(slot_mark
, sizeof(slot_mark
), &start_time
, &eof_time
, false);
1927 } else { // no subcarrier burst
1928 slot_mark
[0] = 0xA1 + (slot
<< 1); // nak slot
1929 CodeAndTransmit14443bAsReader(slot_mark
, sizeof(slot_mark
), &start_time
, &eof_time
, false);
1934 if (g_dbglevel
>= DBG_DEBUG
) {
1935 DbpString("no answer to anticollision");
1941 if (Get14443bAnswerFromTag(x_atqb
, sizeof(x_atqb
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1942 return PM3_ECARDEXCHANGE
;
1945 if (g_dbglevel
>= DBG_DEBUG
) {
1946 Dbprintf("anticollision uid %llx", uid
);
1955 if (check_crc(CRC_14443_B
, x_atqb
, 18) == false) { // use fixed len because unstable EOF catch
1959 if (x_atqb
[0] != 0x50) {
1960 return PM3_EWRONGANSWER
;
1965 memcpy(card
->uid
, x_atqb
+ 1, 8);
1966 memcpy(card
->atqb
, x_atqb
+ 9, 7);
1969 // send ATTRIB command
1974 memcpy(txbuf
+ 2, &uid
, 8);
1980 AddCrc14B(txbuf
+ 1, 13);
1982 start_time
= eof_time
+ ISO14B_TR2
;
1983 CodeAndTransmit14443bAsReader(txbuf
+ 1, 15, &start_time
, &eof_time
, true);
1985 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
1986 if (Get14443bAnswerFromTag(x_atqb
, sizeof(x_atqb
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
1987 return PM3_ECARDEXCHANGE
;
1994 if (check_crc(CRC_14443_B
, x_atqb
, 3) == false) {
1998 if (x_atqb
[0] != 0) {
1999 return PM3_EWRONGANSWER
;
2002 // apply PASSWORD command
2006 // uid from previous command used
2013 AddCrc14B(txbuf
, 15);
2015 start_time
= eof_time
+ ISO14B_TR2
;
2016 CodeAndTransmit14443bAsReader(txbuf
, 17, &start_time
, &eof_time
, true);
2018 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2019 if (Get14443bAnswerFromTag(x_atqb
, sizeof(x_atqb
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2020 return PM3_ECARDEXCHANGE
;
2027 if (check_crc(CRC_14443_B
, x_atqb
, 4) == false) {
2031 if (x_atqb
[0] != 0x02 || x_atqb
[1] != 0x00) {
2032 return PM3_EWRONGANSWER
;
2038 /* Perform the ISO 14443 B Card Selection procedure
2039 * Currently does NOT do any collision handling.
2040 * It expects 0-1 cards in the device's range.
2041 * TODO: Support multiple cards (perform anticollision)
2042 * TODO: Verify CRC checksums
2044 int iso14443b_select_card(iso14b_card_select_t
*card
) {
2045 // WUPB command (including CRC)
2046 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
2047 // WUTB or REQB is denoted in the third byte, lower nibble. 0 vs 8
2048 //static const uint8_t wupb[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 };
2049 static const uint8_t wupb
[] = { ISO14443B_REQB
, 0x00, 0x00, 0x71, 0xff };
2051 // ATTRIB command (with space for CRC)
2052 uint8_t attrib
[11] = { ISO14443B_ATTRIB
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
2053 uint8_t r_pupid
[14] = { 0x00 };
2054 uint8_t r_attrib
[3] = { 0x00 };
2056 // first, wake up the tag
2057 uint32_t start_time
= 0;
2058 uint32_t eof_time
= 0;
2059 CodeAndTransmit14443bAsReader(wupb
, sizeof(wupb
), &start_time
, &eof_time
, true);
2061 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2062 uint16_t retlen
= 0;
2063 if (Get14443bAnswerFromTag(r_pupid
, sizeof(r_pupid
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2064 return PM3_ECARDEXCHANGE
;
2073 if (check_crc(CRC_14443_B
, r_pupid
, retlen
) == false) {
2079 memcpy(card
->uid
, r_pupid
+ 1, 4);
2080 memcpy(card
->atqb
, r_pupid
+ 5, 7);
2083 // copy the PUPI to ATTRIB ( PUPI == UID )
2084 memcpy(attrib
+ 1, r_pupid
+ 1, 4);
2086 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
2087 attrib
[7] = r_pupid
[10] & 0x0F;
2088 AddCrc14B(attrib
, 9);
2089 start_time
= eof_time
+ ISO14B_TR2
;
2090 CodeAndTransmit14443bAsReader(attrib
, sizeof(attrib
), &start_time
, &eof_time
, true);
2092 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2093 if (Get14443bAnswerFromTag(r_attrib
, sizeof(r_attrib
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2094 return PM3_ECARDEXCHANGE
;
2097 // Answer to ATTRIB too short?
2103 if (check_crc(CRC_14443_B
, r_attrib
, retlen
) == false) {
2110 card
->cid
= r_attrib
[0];
2113 uint16_t maxFrame
= card
->atqb
[5] >> 4;
2114 if (maxFrame
< 5) maxFrame
= 8 * maxFrame
+ 16;
2115 else if (maxFrame
== 5) maxFrame
= 64;
2116 else if (maxFrame
== 6) maxFrame
= 96;
2117 else if (maxFrame
== 7) maxFrame
= 128;
2118 else if (maxFrame
== 8) maxFrame
= 256;
2119 else maxFrame
= 257;
2120 iso14b_set_maxframesize(maxFrame
);
2123 uint8_t fwt
= card
->atqb
[6] >> 4;
2125 iso14b_set_fwt(fwt
);
2128 // reset PCB block number
2129 s_iso14b_pcb_blocknum
= 0;
2133 static int iso14443b_select_picopass_card(picopass_hdr_t
*hdr
) {
2135 static uint8_t act_all
[] = { ICLASS_CMD_ACTALL
};
2136 static uint8_t identify
[] = { ICLASS_CMD_READ_OR_IDENTIFY
};
2137 static uint8_t read_conf
[] = { ICLASS_CMD_READ_OR_IDENTIFY
, 0x01, 0xfa, 0x22 };
2138 uint8_t select
[] = { 0x80 | ICLASS_CMD_SELECT
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
2139 uint8_t read_aia
[] = { ICLASS_CMD_READ_OR_IDENTIFY
, 0x05, 0xde, 0x64};
2140 uint8_t read_check_cc
[] = { 0x80 | ICLASS_CMD_READCHECK
, 0x02 };
2141 uint8_t resp
[ICLASS_BUFFER_SIZE
] = {0};
2143 uint32_t start_time
= 0;
2144 uint32_t eof_time
= 0;
2145 uint16_t retlen
= 0;
2147 // first, wake up the tag 0x0A
2148 CodeAndTransmit14443bAsReader(act_all
, sizeof(act_all
), &start_time
, &eof_time
, true);
2149 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2152 // start_time = eof_time + ISO14B_TR2;
2153 start_time
= eof_time
+ US_TO_SSP(330); // 330ms before next cmd
2154 CodeAndTransmit14443bAsReader(identify
, sizeof(identify
), &start_time
, &eof_time
, true);
2155 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2157 // expect a 10-byte response here, 8 byte anticollision-CSN and 2 byte CRC
2158 if (Get14443bAnswerFromTag(resp
, sizeof(resp
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2159 return PM3_ECARDEXCHANGE
;
2165 // copy the Anti-collision CSN to our select-packet
2166 memcpy(&select
[1], resp
, 8);
2169 start_time
= eof_time
+ ISO14B_TR2
;
2170 CodeAndTransmit14443bAsReader(select
, sizeof(select
), &start_time
, &eof_time
, true);
2171 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2173 // expect a 10-byte response here, 8 byte CSN and 2 byte CRC
2174 if (Get14443bAnswerFromTag(resp
, sizeof(resp
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2175 return PM3_ECARDEXCHANGE
;
2182 memcpy(hdr
->csn
, resp
, sizeof(hdr
->csn
));
2184 // card selected, now read config (block1) (only 8 bytes no CRC)
2185 start_time
= eof_time
+ ISO14B_TR2
;
2186 CodeAndTransmit14443bAsReader(read_conf
, sizeof(read_conf
), &start_time
, &eof_time
, true);
2187 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2189 // expect a 10-byte response here, 8 bytes CONFIGURATION and 2 byte CRC)
2190 if (Get14443bAnswerFromTag(resp
, sizeof(resp
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2191 return PM3_ECARDEXCHANGE
;
2198 memcpy((uint8_t *)&hdr
->conf
, resp
, sizeof(hdr
->conf
));
2200 uint8_t pagemap
= get_pagemap(hdr
);
2201 if (pagemap
!= PICOPASS_NON_SECURE_PAGEMODE
) {
2203 // read App Issuer Area block 5
2204 start_time
= eof_time
+ ISO14B_TR2
;
2205 CodeAndTransmit14443bAsReader(read_aia
, sizeof(read_aia
), &start_time
, &eof_time
, true);
2206 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2208 // expect AIA, a 10-byte response here
2209 if (Get14443bAnswerFromTag(resp
, sizeof(resp
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2210 return PM3_ECARDEXCHANGE
;
2216 memcpy(hdr
->app_issuer_area
, resp
, sizeof(hdr
->app_issuer_area
));
2218 // card selected, now read e-purse (cc) (block2) (only 8 bytes no CRC)
2219 start_time
= eof_time
+ ISO14B_TR2
;
2220 CodeAndTransmit14443bAsReader(read_check_cc
, sizeof(read_check_cc
), &start_time
, &eof_time
, true);
2221 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2223 // expect EPURSE, a 8 byte response here
2224 if (Get14443bAnswerFromTag(resp
, sizeof(resp
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2225 return PM3_ECARDEXCHANGE
;
2231 memcpy(hdr
->epurse
, resp
, sizeof(hdr
->epurse
));
2235 // on NON_SECURE_PAGEMODE cards, AIA is on block2..
2237 // read App Issuer Area block 2
2242 start_time
= eof_time
+ ISO14B_TR2
;
2243 CodeAndTransmit14443bAsReader(read_aia
, sizeof(read_aia
), &start_time
, &eof_time
, true);
2244 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2246 // expect AIA, a 10-byte response here
2247 if (Get14443bAnswerFromTag(resp
, sizeof(resp
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2248 return PM3_ECARDEXCHANGE
;
2254 memcpy(hdr
->epurse
, resp
, sizeof(hdr
->epurse
));
2259 // Set up ISO 14443 Type B communication (similar to iso14443a_setup)
2260 // field is setup for "Sending as Reader"
2261 void iso14443b_setup(void) {
2263 switch_off(); // disconnect raw
2266 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
2268 // allocate command receive buffer
2271 // Initialize Demod and Uart structs
2272 Demod14bInit(BigBuf_calloc(MAX_FRAME_SIZE
), MAX_FRAME_SIZE
);
2273 Uart14bInit(BigBuf_calloc(MAX_FRAME_SIZE
));
2275 // connect Demodulated Signal to ADC:
2276 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2278 // Set up the synchronous serial port
2279 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
2281 // Signal field is on with the appropriate LED
2283 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD_RDV4
);
2285 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_MODE_SEND_SHALLOW_MOD
);
2301 //-----------------------------------------------------------------------------
2302 // Read a SRI512 ISO 14443B tag.
2304 // SRI512 tags are just simple memory tags, here we're looking at making a dump
2305 // of the contents of the memory. No anticollision algorithm is done, we assume
2306 // we have a single tag in the field.
2308 // I tried to be systematic and check every answer of the tag, every CRC, etc...
2309 //-----------------------------------------------------------------------------
2310 static int read_14b_srx_block(uint8_t blocknr
, uint8_t *block
) {
2312 uint8_t cmd
[] = {ISO14443B_READ_BLK
, blocknr
, 0x00, 0x00};
2315 uint8_t r_block
[6] = {0};
2317 uint32_t start_time
= 0;
2318 uint32_t eof_time
= 0;
2319 CodeAndTransmit14443bAsReader(cmd
, sizeof(cmd
), &start_time
, &eof_time
, true);
2321 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2322 uint16_t retlen
= 0;
2323 if (Get14443bAnswerFromTag(r_block
, sizeof(r_block
), s_iso14b_timeout
, &eof_time
, &retlen
) != PM3_SUCCESS
) {
2324 return PM3_ECARDEXCHANGE
;
2327 // Check if we got an answer from the tag
2329 return PM3_EWRONGANSWER
;
2331 // The check the CRC of the answer
2332 if (check_crc(CRC_14443_B
, r_block
, retlen
) == false) {
2337 memcpy(block
, r_block
, ISO14B_BLOCK_SIZE
);
2343 void read_14b_st_block(uint8_t blocknr
) {
2348 uint8_t *data
= BigBuf_calloc(ISO14B_BLOCK_SIZE
);
2349 iso14b_card_select_t
*card
= (iso14b_card_select_t
*) BigBuf_calloc(sizeof(iso14b_card_select_t
));
2351 int res
= iso14443b_select_srx_card(card
);
2352 if (res
!= PM3_SUCCESS
) {
2353 reply_ng(CMD_HF_SRI_READ
, res
, NULL
, 0);
2357 res
= read_14b_srx_block(blocknr
, data
);
2358 reply_ng(CMD_HF_SRI_READ
, res
, data
, ISO14B_BLOCK_SIZE
);
2362 BigBuf_free_keep_EM();
2366 //=============================================================================
2367 // Finally, the `sniffer' combines elements from both the reader and
2368 // simulated tag, to show both sides of the conversation.
2369 //=============================================================================
2371 //-----------------------------------------------------------------------------
2372 // Record the sequence of commands sent by the reader to the tag, with
2373 // triggering so that we start recording at the point that the tag is moved
2375 //-----------------------------------------------------------------------------
2377 * Memory usage for this function, (within BigBuf)
2378 * Last Received command (reader->tag) - MAX_FRAME_SIZE
2379 * Last Received command (tag->reader) - MAX_FRAME_SIZE
2380 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
2381 * Demodulated samples received - all the rest
2383 void SniffIso14443b(void) {
2388 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
2390 if (g_dbglevel
>= DBG_INFO
) {
2391 DbpString("Press " _GREEN_("pm3 button") " to abort sniffing");
2398 // Initialize Demod and Uart structs
2399 uint8_t dm_buf
[MAX_FRAME_SIZE
] = {0};
2400 Demod14bInit(dm_buf
, sizeof(dm_buf
));
2402 uint8_t ua_buf
[MAX_FRAME_SIZE
] = {0};
2403 Uart14bInit(ua_buf
);
2405 //Demod14bInit(BigBuf_malloc(MAX_FRAME_SIZE), MAX_FRAME_SIZE);
2406 //Uart14bInit(BigBuf_malloc(MAX_FRAME_SIZE));
2408 // Set FPGA in the appropriate mode
2409 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER
| FPGA_HF_READER_SUBCARRIER_848_KHZ
| FPGA_HF_READER_MODE_SNIFF_IQ
);
2410 // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_848_KHZ | FPGA_HF_READER_MODE_SNIFF_AMPLITUDE);
2412 // connect Demodulated Signal to ADC:
2413 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2414 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER
);
2418 // The DMA buffer, used to stream samples from the FPGA
2419 dmabuf16_t
*dma
= get_dma16();
2421 // Setup and start DMA.
2422 if (!FpgaSetupSscDma((uint8_t *) dma
->buf
, DMA_BUFFER_SIZE
)) {
2423 if (g_dbglevel
> DBG_ERROR
) DbpString("FpgaSetupSscDma failed. Exiting");
2428 // We won't start recording the frames that we acquire until we trigger;
2429 // a good trigger condition to get started is probably when we see a
2430 // response from the tag.
2431 bool tag_is_active
= false;
2432 bool reader_is_active
= false;
2433 bool expect_tag_answer
= false;
2434 int dma_start_time
= 0;
2436 // Count of samples received so far, so that we can include timing
2439 uint16_t *upTo
= dma
->buf
;
2443 volatile int behind_by
= ((uint16_t *)AT91C_BASE_PDC_SSC
->PDC_RPR
- upTo
) & (DMA_BUFFER_SIZE
- 1);
2444 if (behind_by
< 1) continue;
2448 // DMA has transferred the very first data
2449 dma_start_time
= GetCountSspClk() & 0xfffffff0;
2452 volatile int8_t ci
= *upTo
>> 8;
2453 volatile int8_t cq
= *upTo
;
2456 // we have read all of the DMA buffer content.
2457 if (upTo
>= dma
->buf
+ DMA_BUFFER_SIZE
) {
2459 // start reading the circular buffer from the beginning again
2462 // DMA Counter Register had reached 0, already rotated.
2463 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_ENDRX
)) {
2465 // primary buffer was stopped
2466 if (AT91C_BASE_PDC_SSC
->PDC_RCR
== false) {
2467 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dma
->buf
;
2468 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
2470 // secondary buffer sets as primary, secondary buffer was stopped
2471 if (AT91C_BASE_PDC_SSC
->PDC_RNCR
== false) {
2472 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dma
->buf
;
2473 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
2477 if (BUTTON_PRESS()) {
2478 DbpString("Sniff stopped");
2484 // no need to try decoding reader data if the tag is sending
2485 if (tag_is_active
== false) {
2487 if (Handle14443bSampleFromReader(ci
& 0x01)) {
2488 uint32_t eof_time
= dma_start_time
+ (samples
* 16) + 8; // - DELAY_READER_TO_ARM_SNIFF; // end of EOF
2489 if (Uart
.byteCnt
> 0) {
2490 uint32_t sof_time
= eof_time
2491 - Uart
.byteCnt
* 1 // time for byte transfers
2492 - 32 * 16 // time for SOF transfer
2493 - 16 * 16; // time for EOF transfer
2494 LogTrace(Uart
.output
, Uart
.byteCnt
, (sof_time
* 4), (eof_time
* 4), NULL
, true);
2496 // And ready to receive another command.
2499 expect_tag_answer
= true;
2502 if (Handle14443bSampleFromReader(cq
& 0x01)) {
2504 uint32_t eof_time
= dma_start_time
+ (samples
* 16) + 16; // - DELAY_READER_TO_ARM_SNIFF; // end of EOF
2505 if (Uart
.byteCnt
> 0) {
2506 uint32_t sof_time
= eof_time
2507 - Uart
.byteCnt
* 1 // time for byte transfers
2508 - 32 * 16 // time for SOF transfer
2509 - 16 * 16; // time for EOF transfer
2510 LogTrace(Uart
.output
, Uart
.byteCnt
, (sof_time
* 4), (eof_time
* 4), NULL
, true);
2512 // And ready to receive another command
2515 expect_tag_answer
= true;
2518 reader_is_active
= (Uart
.state
> STATE_14B_GOT_FALLING_EDGE_OF_SOF
);
2521 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
2522 if (reader_is_active
== false && expect_tag_answer
) {
2524 if (Handle14443bSamplesFromTag((ci
>> 1), (cq
>> 1))) {
2526 uint32_t eof_time
= dma_start_time
+ (samples
* 16); // - DELAY_TAG_TO_ARM_SNIFF; // end of EOF
2527 uint32_t sof_time
= eof_time
2528 - Demod
.len
* 8 * 8 * 16 // time for byte transfers
2529 - (32 * 16) // time for SOF transfer
2530 - 0; // time for EOF transfer
2532 LogTrace(Demod
.output
, Demod
.len
, (sof_time
* 4), (eof_time
* 4), NULL
, false);
2533 // And ready to receive another response.
2536 expect_tag_answer
= false;
2537 tag_is_active
= false;
2539 tag_is_active
= (Demod
.state
> WAIT_FOR_RISING_EDGE_OF_SOF
);
2544 FpgaDisableTracing();
2548 DbpString(_CYAN_("Sniff statistics"));
2549 DbpString("=================================");
2550 Dbprintf(" DecodeTag State........%d", Demod
.state
);
2551 Dbprintf(" DecodeTag byteCnt......%d", Demod
.len
);
2552 Dbprintf(" DecodeTag posCount.....%d", Demod
.posCount
);
2553 Dbprintf(" DecodeReader State.....%d", Uart
.state
);
2554 Dbprintf(" DecodeReader byteCnt...%d", Uart
.byteCnt
);
2555 Dbprintf(" DecodeReader posCount..%d", Uart
.posCnt
);
2556 Dbprintf(" Trace length..........." _YELLOW_("%d"), BigBuf_get_traceLen());
2560 static void iso14b_set_trigger(bool enable
) {
2564 void SendRawCommand14443B(iso14b_raw_cmd_t
*p
) {
2566 // turn on trigger (LED_A)
2567 if ((p
->flags
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
) {
2568 iso14b_set_trigger(true);
2571 if ((p
->flags
& ISO14B_CONNECT
) == ISO14B_CONNECT
) {
2575 if ((p
->flags
& ISO14B_SET_TIMEOUT
) == ISO14B_SET_TIMEOUT
) {
2576 iso14b_set_timeout(p
->timeout
);
2579 if ((p
->flags
& ISO14B_CLEARTRACE
) == ISO14B_CLEARTRACE
) {
2581 BigBuf_Clear_ext(false);
2587 uint8_t buf
[PM3_CMD_DATA_SIZE
] = {0x00};
2590 uint32_t sendlen
= sizeof(iso14b_card_select_t
);
2591 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
2593 if ((p
->flags
& ISO14B_SELECT_STD
) == ISO14B_SELECT_STD
) {
2594 status
= iso14443b_select_card(card
);
2595 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, (uint8_t *)card
, sendlen
);
2596 if (status
!= PM3_SUCCESS
) goto out
;
2599 if ((p
->flags
& ISO14B_SELECT_SR
) == ISO14B_SELECT_SR
) {
2600 memset(card
, 0, sizeof(iso14b_card_select_t
));
2601 status
= iso14443b_select_srx_card(card
);
2602 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, (uint8_t *)card
, sendlen
);
2603 if (status
!= PM3_SUCCESS
) goto out
;
2606 if ((p
->flags
& ISO14B_SELECT_XRX
) == ISO14B_SELECT_XRX
) {
2607 memset(card
, 0, sizeof(iso14b_card_select_t
));
2608 status
= iso14443b_select_xrx_card(card
);
2609 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, (uint8_t *)card
, sendlen
);
2610 // 0: OK, 1: select fail, 2: attrib fail, 3: crc fail, 4: password fail
2611 if (status
!= PM3_SUCCESS
) goto out
;
2614 if ((p
->flags
& ISO14B_SELECT_CTS
) == ISO14B_SELECT_CTS
) {
2615 iso14b_cts_card_select_t
*cts
= (iso14b_cts_card_select_t
*)buf
;
2616 memset(cts
, 0, sizeof(iso14b_cts_card_select_t
));
2617 sendlen
= sizeof(iso14b_cts_card_select_t
);
2618 status
= iso14443b_select_cts_card(cts
);
2619 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, (uint8_t *)cts
, sendlen
);
2620 if (status
!= PM3_SUCCESS
) goto out
;
2623 if ((p
->flags
& ISO14B_SELECT_PICOPASS
) == ISO14B_SELECT_PICOPASS
) {
2624 picopass_hdr_t
*hdr
= (picopass_hdr_t
*)buf
;
2625 memset(hdr
, 0, sizeof(picopass_hdr_t
));
2626 sendlen
= sizeof(picopass_hdr_t
);
2627 status
= iso14443b_select_picopass_card(hdr
);
2628 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, (uint8_t *)hdr
, sendlen
);
2629 if (status
!= PM3_SUCCESS
) goto out
;
2632 // if field is off...
2634 ((p
->flags
& ISO14B_APDU
) == ISO14B_APDU
) ||
2635 ((p
->flags
& ISO14B_RAW
) == ISO14B_RAW
)
2637 if (s_field_on
== false) {
2638 DbpString("Field is off");
2639 reply_ng(CMD_HF_ISO14443B_COMMAND
, PM3_ERFTRANS
, NULL
, 0);
2644 if ((p
->flags
& ISO14B_APDU
) == ISO14B_APDU
) {
2646 uint16_t responselen
= 0;
2647 uint8_t response_byte
= 0;
2648 bool chaining
= ((p
->flags
& ISO14B_SEND_CHAINING
) == ISO14B_SEND_CHAINING
);
2649 status
= iso14443b_apdu(p
->raw
, p
->rawlen
, chaining
, buf
, sizeof(buf
), &response_byte
, &responselen
);
2651 if (tearoff_hook() == PM3_ETEAROFF
) { // tearoff occurred
2652 reply_ng(CMD_HF_ISO14443B_COMMAND
, PM3_ETEAROFF
, NULL
, 0);
2654 uint8_t packet
[responselen
+ 1 + 2];
2655 iso14b_raw_apdu_response_t
*payload
= (iso14b_raw_apdu_response_t
*)packet
;
2656 payload
->response_byte
= response_byte
;
2657 payload
->datalen
= responselen
;
2658 memcpy(payload
->data
, buf
, payload
->datalen
);
2659 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, packet
, sizeof(packet
));
2663 if ((p
->flags
& ISO14B_RAW
) == ISO14B_RAW
) {
2665 if (((p
->flags
& ISO14B_APPEND_CRC
) == ISO14B_APPEND_CRC
) && (p
->rawlen
)) {
2667 // Picopass uses different CRC algo
2668 // it also excludes the first instruction byte
2669 if ((p
->flags
& ISO14B_SELECT_PICOPASS
) == ISO14B_SELECT_PICOPASS
) {
2670 AddCrc15(p
->raw
+ 1, p
->rawlen
- 1);
2672 AddCrc14B(p
->raw
, p
->rawlen
);
2677 uint32_t start_time
= 0;
2678 uint32_t eof_time
= 0;
2679 CodeAndTransmit14443bAsReader(p
->raw
, p
->rawlen
, &start_time
, &eof_time
, true);
2681 if (tearoff_hook() == PM3_ETEAROFF
) { // tearoff occurred
2682 reply_ng(CMD_HF_ISO14443B_COMMAND
, PM3_ETEAROFF
, NULL
, 0);
2685 eof_time
+= DELAY_ISO14443B_PCD_TO_PICC_READER
;
2687 uint16_t retlen
= 0;
2688 status
= Get14443bAnswerFromTag(buf
, sizeof(buf
), s_iso14b_timeout
, &eof_time
, &retlen
);
2689 if (status
== PM3_SUCCESS
) {
2690 sendlen
= MIN(retlen
, PM3_CMD_DATA_SIZE
);
2691 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, Demod
.output
, sendlen
);
2693 reply_ng(CMD_HF_ISO14443B_COMMAND
, status
, NULL
, 0);
2699 // turn off trigger (LED_A)
2700 if ((p
->flags
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
) {
2701 iso14b_set_trigger(false);
2704 // turn off antenna et al
2705 // we don't send a HALT command.
2706 if ((p
->flags
& ISO14B_DISCONNECT
) == ISO14B_DISCONNECT
) {
2707 switch_off(); // disconnect raw
2709 BigBuf_free_keep_EM();