1 //-----------------------------------------------------------------------------
2 // Jonathan Westhues, split Nov 2006
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
7 //-----------------------------------------------------------------------------
8 // Routines to support ISO 14443B. This includes both the reader software and
9 // the `fake tag' modes.
10 //-----------------------------------------------------------------------------
11 #include "iso14443b.h"
13 #ifndef FWT_TIMEOUT_14B
15 # define FWT_TIMEOUT_14B 35312
17 #ifndef ISO14443B_DMA_BUFFER_SIZE
18 # define ISO14443B_DMA_BUFFER_SIZE 256
21 # define RECEIVE_MASK (ISO14443B_DMA_BUFFER_SIZE-1)
24 // Guard Time (per 14443-2)
29 // Synchronization time (per 14443-2)
33 // Frame Delay Time PICC to PCD (per 14443-3 Amendment 1)
39 #define SEND4STUFFBIT(x) ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);ToSendStuffBit(x);
40 //#define SEND4STUFFBIT(x) ToSendStuffBit(x);
41 // iceman, this threshold value, what makes 8 a good amplituted for this IQ values?
42 #ifndef SUBCARRIER_DETECT_THRESHOLD
43 # define SUBCARRIER_DETECT_THRESHOLD 6
46 static void iso14b_set_timeout(uint32_t timeout
);
47 static void iso14b_set_maxframesize(uint16_t size
);
48 static void switch_off(void);
50 // the block number for the ISO14443-4 PCB (used with APDUs)
51 static uint8_t pcb_blocknum
= 0;
52 static uint32_t iso14b_timeout
= FWT_TIMEOUT_14B
;
55 //=============================================================================
56 // An ISO 14443 Type B tag. We listen for commands from the reader, using
57 // a UART kind of thing that's implemented in software. When we get a
58 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
59 // If it's good, then we can do something appropriate with it, and send
61 //=============================================================================
64 //-----------------------------------------------------------------------------
65 // The software UART that receives commands from the reader, and its state variables.
66 //-----------------------------------------------------------------------------
70 STATE_GOT_FALLING_EDGE_OF_SOF
,
71 STATE_AWAITING_START_BIT
,
82 static void UartReset() {
83 Uart
.state
= STATE_UNSYNCD
;
87 Uart
.byteCntMax
= MAX_FRAME_SIZE
;
91 static void UartInit(uint8_t *data
) {
94 // memset(Uart.output, 0x00, MAX_FRAME_SIZE);
97 //-----------------------------------------------------------------------------
98 // The software Demod that receives commands from the tag, and its state variables.
99 //-----------------------------------------------------------------------------
103 DEMOD_PHASE_REF_TRAINING
,
104 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
,
105 DEMOD_GOT_FALLING_EDGE_OF_SOF
,
106 DEMOD_AWAITING_START_BIT
,
112 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
121 uint32_t startTime
, endTime
;
124 // Clear out the state of the "UART" that receives from the tag.
125 static void DemodReset() {
126 Demod
.state
= DEMOD_UNSYNCD
;
138 static void DemodInit(uint8_t *data
) {
141 // memset(Demod.output, 0x00, MAX_FRAME_SIZE);
146 * 9.4395 us = 1 ETU and clock is about 1.5 us
149 * timeout in ETUs (time to transfer 1 bit, 9.4395 us)
151 * Formula to calculate FWT (in ETUs) by timeout (in ms):
152 * fwt = 13560000 * 1000 / (8*16) * timeout;
153 * Sample: 3sec == 3000ms
154 * 13560000 * 1000 / (8*16) * 3000 ==
155 * 13560000000 / 384000 = 35312 FWT
156 * @param timeout is in frame wait time, fwt, measured in ETUs
158 static void iso14b_set_timeout(uint32_t timeout
) {
159 #define MAX_TIMEOUT 40542464 // 13560000Hz * 1000ms / (2^32-1) * (8*16)
160 if(timeout
> MAX_TIMEOUT
)
161 timeout
= MAX_TIMEOUT
;
163 iso14b_timeout
= timeout
;
164 if(MF_DBGLEVEL
>= 3) Dbprintf("ISO14443B Timeout set to %ld fwt", iso14b_timeout
);
166 static void iso14b_set_maxframesize(uint16_t size
) {
168 size
= MAX_FRAME_SIZE
;
170 Uart
.byteCntMax
= size
;
171 if(MF_DBGLEVEL
>= 3) Dbprintf("ISO14443B Max frame size set to %d bytes", Uart
.byteCntMax
);
173 static void switch_off(void){
174 if (MF_DBGLEVEL
> 3) Dbprintf("switch_off");
175 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
182 void AppendCrc14443b(uint8_t* data
, int len
) {
183 ComputeCrc14443(CRC_14443_B
, data
, len
, data
+len
, data
+len
+1);
186 //-----------------------------------------------------------------------------
187 // Code up a string of octets at layer 2 (including CRC, we don't generate
188 // that here) so that they can be transmitted to the reader. Doesn't transmit
189 // them yet, just leaves them ready to send in ToSend[].
190 //-----------------------------------------------------------------------------
191 static void CodeIso14443bAsTag(const uint8_t *cmd
, int len
) {
194 * Reader to card | ASK - Amplitude Shift Keying Modulation (PCD to PICC for Type B) (NRZ-L encodig)
195 * Card to reader | BPSK - Binary Phase Shift Keying Modulation, (PICC to PCD for Type B)
197 * fc - carrier frequency 13.56mHz
198 * TR0 - Guard Time per 14443-2
199 * TR1 - Synchronization Time per 14443-2
200 * TR2 - PICC to PCD Frame Delay Time (per 14443-3 Amendment 1)
202 * Elementary Time Unit (ETU) is
203 * - 128 Carrier Cycles (9.4395 µS) = 8 Subcarrier Units
205 * - 10 ETU = 1 startbit, 8 databits, 1 stopbit (10bits length)
209 * Start of frame (SOF) is
210 * - [10-11] ETU of ZEROS, unmodulated time
211 * - [2-3] ETU of ONES,
213 * End of frame (EOF) is
214 * - [10-11] ETU of ZEROS, unmodulated time
216 * -TO VERIFY THIS BELOW-
217 * The mode FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_BPSK which we use to simulate tag
219 * - A 1-bit input to the FPGA becomes 8 pulses at 847.5kHz (9.44µS)
220 * - A 0-bit input to the FPGA becomes an unmodulated time of 9.44µS
224 * Card sends data ub 847.e kHz subcarrier
225 * 848k = 9.44µS = 128 fc
226 * 424k = 18.88µS = 256 fc
227 * 212k = 37.76µS = 512 fc
228 * 106k = 75.52µS = 1024 fc
230 * Reader data transmission:
231 * - no modulation ONES
233 * - Command, data and CRC_B
235 * - no modulation ONES
237 * Card data transmission
240 * - data (each bytes is: 1startbit,8bits, 1stopbit)
244 * FPGA implementation :
245 * At this point only Type A is implemented. This means that we are using a
246 * bit rate of 106 kbit/s, or fc/128. Oversample by 4, which ought to make
247 * things practical for the ARM (fc/32, 423.8 kbits/s, ~50 kbytes/s)
256 // Transmit a burst of ones, as the initial thing that lets the
257 // reader get phase sync.
258 // This loop is TR1, per specification
259 // TR1 minimum must be > 80/fs
260 // TR1 maximum 200/fs
261 // 80/fs < TR1 < 200/fs
262 // 10 ETU < TR1 < 24 ETU
265 // 10-11 ETU * 4times samples ZEROS
266 for(i
= 0; i
< 10; i
++) { SEND4STUFFBIT(0); }
267 //for(i = 0; i < 10; i++) { ToSendStuffBit(0); }
269 // 2-3 ETU * 4times samples ONES
270 for(i
= 0; i
< 3; i
++) { SEND4STUFFBIT(1); }
271 //for(i = 0; i < 3; i++) { ToSendStuffBit(1); }
274 for(i
= 0; i
< len
; ++i
) {
282 for(j
= 0; j
< 8; ++j
) {
298 // For PICC it ranges 0-18us (1etu = 9us)
304 // 10-11 ETU * 4 sample rate = ZEROS
305 for(i
= 0; i
< 10; i
++) { SEND4STUFFBIT(0); }
306 //for(i = 0; i < 10; i++) { ToSendStuffBit(0); }
309 for(i
= 0; i
< 40; i
++) { SEND4STUFFBIT(1); }
310 //for(i = 0; i < 40; i++) { ToSendStuffBit(1); }
312 // Convert from last byte pos to length
317 /* Receive & handle a bit coming from the reader.
319 * This function is called 4 times per bit (every 2 subcarrier cycles).
320 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
323 * LED A -> ON once we have received the SOF and are expecting the rest.
324 * LED A -> OFF once we have received EOF or are in error state or unsynced
326 * Returns: true if we received a EOF
327 * false if we are still waiting for some more
329 static RAMFUNC
int Handle14443bReaderUartBit(uint8_t bit
) {
330 switch (Uart
.state
) {
333 // we went low, so this could be the beginning of an SOF
334 Uart
.state
= STATE_GOT_FALLING_EDGE_OF_SOF
;
340 case STATE_GOT_FALLING_EDGE_OF_SOF
:
342 if (Uart
.posCnt
== 2) { // sample every 4 1/fs in the middle of a bit
344 if (Uart
.bitCnt
> 9) {
345 // we've seen enough consecutive
346 // zeros that it's a valid SOF
349 Uart
.state
= STATE_AWAITING_START_BIT
;
350 LED_A_ON(); // Indicate we got a valid SOF
352 // didn't stay down long enough before going high, error
353 Uart
.state
= STATE_UNSYNCD
;
356 // do nothing, keep waiting
360 if (Uart
.posCnt
>= 4) Uart
.posCnt
= 0;
361 if (Uart
.bitCnt
> 12) {
362 // Give up if we see too many zeros without a one, too.
364 Uart
.state
= STATE_UNSYNCD
;
368 case STATE_AWAITING_START_BIT
:
371 if (Uart
.posCnt
> 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
372 // stayed high for too long between characters, error
373 Uart
.state
= STATE_UNSYNCD
;
376 // falling edge, this starts the data byte
380 Uart
.state
= STATE_RECEIVING_DATA
;
384 case STATE_RECEIVING_DATA
:
386 if (Uart
.posCnt
== 2) {
387 // time to sample a bit
390 Uart
.shiftReg
|= 0x200;
394 if (Uart
.posCnt
>= 4) {
397 if (Uart
.bitCnt
== 10) {
398 if ((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001))
400 // this is a data byte, with correct
401 // start and stop bits
402 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xff;
405 if (Uart
.byteCnt
>= Uart
.byteCntMax
) {
406 // Buffer overflowed, give up
408 Uart
.state
= STATE_UNSYNCD
;
410 // so get the next byte now
412 Uart
.state
= STATE_AWAITING_START_BIT
;
414 } else if (Uart
.shiftReg
== 0x000) {
415 // this is an EOF byte
416 LED_A_OFF(); // Finished receiving
417 Uart
.state
= STATE_UNSYNCD
;
418 if (Uart
.byteCnt
!= 0)
424 Uart
.state
= STATE_UNSYNCD
;
431 Uart
.state
= STATE_UNSYNCD
;
437 //-----------------------------------------------------------------------------
438 // Receive a command (from the reader to us, where we are the simulated tag),
439 // and store it in the given buffer, up to the given maximum length. Keeps
440 // spinning, waiting for a well-framed command, until either we get one
441 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
443 // Assume that we're called with the SSC (to the FPGA) and ADC path set
445 //-----------------------------------------------------------------------------
446 static int GetIso14443bCommandFromReader(uint8_t *received
, uint16_t *len
) {
447 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
448 // only, since we are receiving, not transmitting).
449 // Signal field is off with the appropriate LED
451 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
457 // clear receiving shift register and holding register
458 // What does this loop do? Is it TR1?
459 for(uint8_t c
= 0; c
< 10;) {
460 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
461 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
466 // Now run a `software UART' on the stream of incoming samples.
471 while( !BUTTON_PRESS() ) {
474 if ( AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
) {
475 b
= (uint8_t) AT91C_BASE_SSC
->SSC_RHR
;
476 for ( mask
= 0x80; mask
!= 0; mask
>>= 1) {
477 if ( Handle14443bReaderUartBit(b
& mask
)) {
487 void ClearFpgaShiftingRegisters(void){
491 // clear receiving shift register and holding register
492 while(!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
494 b
= AT91C_BASE_SSC
->SSC_RHR
; (void) b
;
496 while(!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
498 b
= AT91C_BASE_SSC
->SSC_RHR
; (void) b
;
501 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
502 for (uint8_t j
= 0; j
< 5; j
++) { // allow timeout - better late than never
503 while(!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
504 if (AT91C_BASE_SSC
->SSC_RHR
) break;
508 //AT91C_BASE_SSC->SSC_THR = 0xFF;
511 void WaitForFpgaDelayQueueIsEmpty( uint16_t delay
){
512 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
513 uint8_t fpga_queued_bits
= delay
>> 3; // twich /8 ?? >>3,
514 for (uint8_t i
= 0; i
<= fpga_queued_bits
/8 + 1; ) {
515 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
516 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
522 static void TransmitFor14443b_AsTag( uint8_t *response
, uint16_t len
) {
526 // Signal field is off with the appropriate LED
528 //uint16_t fpgasendQueueDelay = 0;
531 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
534 ClearFpgaShiftingRegisters();
538 // Transmit the response.
539 for(uint16_t i
= 0; i
< len
;) {
540 if(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_TXRDY
) {
541 AT91C_BASE_SSC
->SSC_THR
= response
[++i
];
543 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
544 b
= AT91C_BASE_SSC
->SSC_RHR
;
549 //WaitForFpgaDelayQueueIsEmpty(fpgasendQueueDelay);
550 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
552 //-----------------------------------------------------------------------------
553 // Main loop of simulated tag: receive commands from reader, decide what
554 // response to send, and send it.
555 //-----------------------------------------------------------------------------
556 void SimulateIso14443bTag(uint32_t pupi
) {
558 ///////////// setup device.
559 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
561 // allocate command receive buffer
563 BigBuf_Clear_ext(false);
567 // connect Demodulated Signal to ADC:
568 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
570 // Set up the synchronous serial port
574 uint16_t len
, cmdsReceived
= 0;
575 int cardSTATE
= SIM_NOFIELD
;
576 int vHf
= 0; // in mV
577 // uint32_t time_0 = 0;
578 // uint32_t t2r_time = 0;
579 // uint32_t r2t_time = 0;
580 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
582 // the only commands we understand is WUPB, AFI=0, Select All, N=1:
583 // static const uint8_t cmdWUPB[] = { ISO14443B_REQB, 0x00, 0x08, 0x39, 0x73 }; // WUPB
584 // ... and REQB, AFI=0, Normal Request, N=1:
585 // static const uint8_t cmdREQB[] = { ISO14443B_REQB, 0x00, 0x00, 0x71, 0xFF }; // REQB
587 // static const uint8_t cmdATTRIB[] = { ISO14443B_ATTRIB, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}; // ATTRIB
589 // ... if not PUPI/UID is supplied we always respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
590 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
591 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
592 uint8_t respATQB
[] = { 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19,
593 0x22, 0x00, 0x21, 0x85, 0x5e, 0xd7 };
595 // response to HLTB and ATTRIB
596 static const uint8_t respOK
[] = {0x00, 0x78, 0xF0};
598 // ...PUPI/UID supplied from user. Adjust ATQB response accordingly
600 uint8_t len
= sizeof(respATQB
);
601 num_to_bytes(pupi
, 4, respATQB
+1);
602 ComputeCrc14443(CRC_14443_B
, respATQB
, 12, &respATQB
[len
-2], &respATQB
[len
-1]);
605 // prepare "ATQB" tag answer (encoded):
606 CodeIso14443bAsTag(respATQB
, sizeof(respATQB
));
607 uint8_t *encodedATQB
= BigBuf_malloc(ToSendMax
);
608 uint16_t encodedATQBLen
= ToSendMax
;
609 memcpy(encodedATQB
, ToSend
, ToSendMax
);
612 // prepare "OK" tag answer (encoded):
613 CodeIso14443bAsTag(respOK
, sizeof(respOK
));
614 uint8_t *encodedOK
= BigBuf_malloc(ToSendMax
);
615 uint16_t encodedOKLen
= ToSendMax
;
616 memcpy(encodedOK
, ToSend
, ToSendMax
);
619 while (!BUTTON_PRESS() && !usb_poll_validate_length()) {
623 if (cardSTATE
== SIM_NOFIELD
) {
624 vHf
= (MAX_ADC_HF_VOLTAGE
* AvgAdc(ADC_CHAN_HF
)) >> 10;
625 if ( vHf
> MF_MINFIELDV
) {
626 cardSTATE
= SIM_IDLE
;
630 if (cardSTATE
== SIM_NOFIELD
) continue;
632 // Get reader command
633 if (!GetIso14443bCommandFromReader(receivedCmd
, &len
)) {
634 Dbprintf("button pressed, received %d commands", cmdsReceived
);
638 // ISO14443-B protocol states:
639 // REQ or WUP request in ANY state
640 // WUP in HALTED state
642 if ( (receivedCmd
[0] == ISO14443B_REQB
&& (receivedCmd
[2] & 0x8)== 0x8 && cardSTATE
== SIM_HALTED
) ||
643 receivedCmd
[0] == ISO14443B_REQB
){
644 LogTrace(receivedCmd
, len
, 0, 0, NULL
, TRUE
);
645 cardSTATE
= SIM_SELECTING
;
650 * How should this flow go?
652 * send response ( waiting for Attrib)
654 * send response ( waiting for commands 7816)
656 send halt response ( waiting for wupb )
663 LogTrace(receivedCmd
, len
, 0, 0, NULL
, TRUE
);
666 case SIM_SELECTING
: {
667 TransmitFor14443b_AsTag( encodedATQB
, encodedATQBLen
);
668 LogTrace(respATQB
, sizeof(respATQB
), 0, 0, NULL
, FALSE
);
669 cardSTATE
= SIM_WORK
;
673 TransmitFor14443b_AsTag( encodedOK
, encodedOKLen
);
674 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, FALSE
);
675 cardSTATE
= SIM_HALTED
;
678 case SIM_ACKNOWLEDGE
: {
679 TransmitFor14443b_AsTag( encodedOK
, encodedOKLen
);
680 LogTrace(respOK
, sizeof(respOK
), 0, 0, NULL
, FALSE
);
681 cardSTATE
= SIM_IDLE
;
685 if ( len
== 7 && receivedCmd
[0] == ISO14443B_HALT
) {
686 cardSTATE
= SIM_HALTED
;
687 } else if ( len
== 11 && receivedCmd
[0] == ISO14443B_ATTRIB
) {
688 cardSTATE
= SIM_ACKNOWLEDGE
;
693 // - emulate with a memory dump
694 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len
, cmdsReceived
);
698 if (len
>= 3){ // if crc exists
699 ComputeCrc14443(CRC_14443_B
, receivedCmd
, len
-2, &b1
, &b2
);
700 if(b1
!= receivedCmd
[len
-2] || b2
!= receivedCmd
[len
-1])
701 DbpString("+++CRC fail");
703 DbpString("CRC passes");
705 cardSTATE
= SIM_IDLE
;
713 // iceman, could add a switch to turn this on/off (if off, no logging?)
714 if(cmdsReceived
> 1000) {
715 DbpString("14B Simulate, 1000 commands later...");
719 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, BigBuf_get_traceLen());
720 switch_off(); //simulate
723 //=============================================================================
724 // An ISO 14443 Type B reader. We take layer two commands, code them
725 // appropriately, and then send them to the tag. We then listen for the
726 // tag's response, which we leave in the buffer to be demodulated on the
728 //=============================================================================
731 * Handles reception of a bit from the tag
733 * This function is called 2 times per bit (every 4 subcarrier cycles).
734 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
737 * LED C -> ON once we have received the SOF and are expecting the rest.
738 * LED C -> OFF once we have received EOF or are unsynced
740 * Returns: true if we received a EOF
741 * false if we are still waiting for some more
744 static RAMFUNC
int Handle14443bTagSamplesDemod(int ci
, int cq
) {
745 int v
= 0, myI
= ABS(ci
), myQ
= ABS(cq
);
747 // The soft decision on the bit uses an estimate of just the
748 // quadrant of the reference angle, not the exact angle.
749 #define MAKE_SOFT_DECISION() { \
750 if(Demod.sumI > 0) { \
755 if(Demod.sumQ > 0) { \
762 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq)
763 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
764 #define CHECK_FOR_SUBCARRIER_old() { \
766 if(cq < 0) { /* ci < 0, cq < 0 */ \
768 v = -cq - (ci >> 1); \
770 v = -ci - (cq >> 1); \
772 } else { /* ci < 0, cq >= 0 */ \
774 v = -ci + (cq >> 1); \
776 v = cq - (ci >> 1); \
780 if(cq < 0) { /* ci >= 0, cq < 0 */ \
782 v = ci - (cq >> 1); \
784 v = -cq + (ci >> 1); \
786 } else { /* ci >= 0, cq >= 0 */ \
788 v = ci + (cq >> 1); \
790 v = cq + (ci >> 1); \
796 //note: couldn't we just use MAX(ABS(ci),ABS(cq)) + (MIN(ABS(ci),ABS(cq))/2) from common.h - marshmellow
797 #define CHECK_FOR_SUBCARRIER() { \
798 v = MAX(myI, myQ) + (MIN(myI, myQ) >> 1); \
801 switch(Demod
.state
) {
804 CHECK_FOR_SUBCARRIER();
806 // subcarrier detected
807 if(v
> SUBCARRIER_DETECT_THRESHOLD
) {
808 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
815 case DEMOD_PHASE_REF_TRAINING
:
816 if(Demod
.posCount
< 8) {
818 CHECK_FOR_SUBCARRIER();
820 if (v
> SUBCARRIER_DETECT_THRESHOLD
) {
821 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
822 // note: synchronization time > 80 1/fs
828 Demod
.state
= DEMOD_UNSYNCD
;
831 Demod
.state
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
;
835 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
:
837 MAKE_SOFT_DECISION();
839 if(v
< 0) { // logic '0' detected
840 Demod
.state
= DEMOD_GOT_FALLING_EDGE_OF_SOF
;
841 Demod
.posCount
= 0; // start of SOF sequence
843 // maximum length of TR1 = 200 1/fs
844 if(Demod
.posCount
> 26*2) Demod
.state
= DEMOD_UNSYNCD
;
849 case DEMOD_GOT_FALLING_EDGE_OF_SOF
:
852 MAKE_SOFT_DECISION();
855 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
856 if(Demod
.posCount
< 8*2) {
857 Demod
.state
= DEMOD_UNSYNCD
;
859 LED_C_ON(); // Got SOF
860 Demod
.startTime
= GetCountSspClk();
861 Demod
.state
= DEMOD_AWAITING_START_BIT
;
866 // low phase of SOF too long (> 12 etu)
867 if (Demod
.posCount
> 14*2) {
868 Demod
.state
= DEMOD_UNSYNCD
;
874 case DEMOD_AWAITING_START_BIT
:
877 MAKE_SOFT_DECISION();
880 if(Demod
.posCount
> 2*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
881 Demod
.state
= DEMOD_UNSYNCD
;
884 } else { // start bit detected
886 Demod
.posCount
= 1; // this was the first half
889 Demod
.state
= DEMOD_RECEIVING_DATA
;
893 case DEMOD_RECEIVING_DATA
:
895 MAKE_SOFT_DECISION();
897 if (Demod
.posCount
== 0) {
902 // second half of bit
904 Demod
.shiftReg
>>= 1;
907 if (Demod
.thisBit
> 0) Demod
.shiftReg
|= 0x200;
911 // 1 start 8 data 1 stop = 10
912 if (Demod
.bitCount
== 10) {
914 uint16_t s
= Demod
.shiftReg
;
916 // stop bit == '1', start bit == '0'
917 if ((s
& 0x200) && (s
& 0x001) == 0 ) {
918 // left shift to drop the startbit
919 Demod
.output
[Demod
.len
] = (s
>> 1) & 0xFF;
921 Demod
.state
= DEMOD_AWAITING_START_BIT
;
923 // this one is a bit hard, either its a correc byte or its unsynced.
924 Demod
.state
= DEMOD_UNSYNCD
;
925 Demod
.endTime
= GetCountSspClk();
928 // This is EOF (start, stop and all data bits == '0'
929 if (s
== 0) return TRUE
;
937 Demod
.state
= DEMOD_UNSYNCD
;
946 * Demodulate the samples we received from the tag, also log to tracebuffer
947 * quiet: set to 'TRUE' to disable debug output
949 static void GetTagSamplesFor14443bDemod() {
950 bool gotFrame
= FALSE
, finished
= FALSE
;
951 int lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
953 uint32_t time_0
= 0, time_stop
= 0;
957 // Set up the demodulator for tag -> reader responses.
958 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
960 // The DMA buffer, used to stream samples from the FPGA
961 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
962 int8_t *upTo
= dmaBuf
;
964 // Setup and start DMA.
965 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
) ){
966 if (MF_DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
970 // And put the FPGA in the appropriate mode
971 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
974 time_0
= GetCountSspClk();
976 // rx counter - dma counter? (how much?) & (mod) mask > 2. (since 2bytes at the time is read)
977 while ( !finished
) {
982 // LSB is a fpga signal bit.
988 // restart DMA buffer to receive again.
989 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
991 lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
992 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
993 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
996 // https://github.com/Proxmark/proxmark3/issues/103
997 gotFrame
= Handle14443bTagSamplesDemod(ci
, cq
);
998 time_stop
= GetCountSspClk() - time_0
;
1000 finished
= (time_stop
> iso14b_timeout
|| gotFrame
);
1003 FpgaDisableSscDma();
1005 if ( upTo
) upTo
= NULL
;
1007 if (MF_DBGLEVEL
>= 3) {
1008 Dbprintf("Demod.state = %d, Demod.len = %u, PDC_RCR = %u",
1011 AT91C_BASE_PDC_SSC
->PDC_RCR
1015 // print the last batch of IQ values from FPGA
1016 if (MF_DBGLEVEL
== 4)
1017 Dbhexdump(ISO14443B_DMA_BUFFER_SIZE
, (uint8_t *)dmaBuf
, FALSE
);
1019 if ( Demod
.len
> 0 )
1020 LogTrace(Demod
.output
, Demod
.len
, Demod
.startTime
, Demod
.endTime
, NULL
, FALSE
);
1024 //-----------------------------------------------------------------------------
1025 // Transmit the command (to the tag) that was placed in ToSend[].
1026 //-----------------------------------------------------------------------------
1027 static void TransmitFor14443b_AsReader(void) {
1029 // we could been in following mode:
1030 // FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ
1031 // if its second call or more
1033 // while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1034 // AT91C_BASE_SSC->SSC_THR = 0XFF;
1037 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
1041 volatile uint32_t b
;
1043 // What does this loop do? Is it TR1?
1044 // 0xFF = 8 bits of 1. 1 bit == 1Etu,..
1045 // loop 10 * 8 = 80 ETU of delay, with a non modulated signal. why?
1047 for(c
= 0; c
< 50;) {
1048 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1049 AT91C_BASE_SSC
->SSC_THR
= 0xFF;
1052 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1053 b
= AT91C_BASE_SSC
->SSC_RHR
;
1059 for(c
= 0; c
< ToSendMax
;) {
1060 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1061 AT91C_BASE_SSC
->SSC_THR
= ToSend
[c
++];
1063 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1064 b
= AT91C_BASE_SSC
->SSC_RHR
;
1068 //WaitForFpgaDelayQueueIsEmpty(delay);
1069 // We should wait here for the FPGA to send all bits.
1073 //-----------------------------------------------------------------------------
1074 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1075 // so that it is ready to transmit to the tag using TransmitFor14443b().
1076 //-----------------------------------------------------------------------------
1077 static void CodeIso14443bAsReader(const uint8_t *cmd
, int len
)
1080 * Reader data transmission:
1081 * - no modulation ONES
1083 * - Command, data and CRC_B
1085 * - no modulation ONES
1088 * TR0 - 8 ETUS minimum.
1090 * QUESTION: how long is a 1 or 0 in pulses in the xcorr_848 mode?
1091 * 1 "stuffbit" = 1ETU (9us)
1099 // 10-11 ETUs of ZERO
1100 for(i
= 0; i
< 10; ++i
) ToSendStuffBit(0);
1108 // from here we add BITS
1109 for(i
= 0; i
< len
; ++i
) {
1114 if ( b
& 1 ) ToSendStuffBit(1); else ToSendStuffBit(0);
1115 if ( (b
>>1) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1116 if ( (b
>>2) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1117 if ( (b
>>3) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1118 if ( (b
>>4) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1119 if ( (b
>>5) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1120 if ( (b
>>6) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1121 if ( (b
>>7) & 1) ToSendStuffBit(1); else ToSendStuffBit(0);
1124 // EGT extra guard time
1125 // For PCD it ranges 0-57us (1etu = 9us)
1132 // 10-11 ETUs of ZERO
1133 for(i
= 0; i
< 10; ++i
) ToSendStuffBit(0);
1135 // Transition time. TR0 - guard time
1137 // Per specification, Subcarrier must be stopped no later than 2 ETUs after EOF.
1138 // I'm guessing this is for the FPGA to be able to send all bits before we switch to listening mode
1139 for(i
= 0; i
< 32 ; ++i
) ToSendStuffBit(1);
1141 // TR1 - Synchronization time
1142 // Convert from last character reference to length
1148 Convenience function to encode, transmit and trace iso 14443b comms
1150 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd
, int len
) {
1152 CodeIso14443bAsReader(cmd
, len
);
1154 uint32_t time_start
= GetCountSspClk();
1156 TransmitFor14443b_AsReader();
1158 if(trigger
) LED_A_ON();
1160 LogTrace(cmd
, len
, time_start
, GetCountSspClk()-time_start
, NULL
, TRUE
);
1163 /* Sends an APDU to the tag
1164 * TODO: check CRC and preamble
1166 uint8_t iso14443b_apdu(uint8_t const *message
, size_t message_length
, uint8_t *response
)
1168 uint8_t crc
[2] = {0x00, 0x00};
1169 uint8_t message_frame
[message_length
+ 4];
1171 message_frame
[0] = 0x0A | pcb_blocknum
;
1174 message_frame
[1] = 0;
1176 memcpy(message_frame
+ 2, message
, message_length
);
1178 ComputeCrc14443(CRC_14443_B
, message_frame
, message_length
+ 2, &message_frame
[message_length
+ 2], &message_frame
[message_length
+ 3]);
1180 CodeAndTransmit14443bAsReader(message_frame
, message_length
+ 4); //no
1182 GetTagSamplesFor14443bDemod(); //no
1187 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1188 if ( crc
[0] != Demod
.output
[Demod
.len
-2] || crc
[1] != Demod
.output
[Demod
.len
-1] )
1191 // copy response contents
1192 if(response
!= NULL
)
1193 memcpy(response
, Demod
.output
, Demod
.len
);
1201 uint8_t iso14443b_select_srx_card(iso14b_card_select_t
*card
)
1203 // INITIATE command: wake up the tag using the INITIATE
1204 static const uint8_t init_srx
[] = { ISO14443B_INITIATE
, 0x00, 0x97, 0x5b };
1205 // SELECT command (with space for CRC)
1206 uint8_t select_srx
[] = { ISO14443B_SELECT
, 0x00, 0x00, 0x00};
1207 // temp to calc crc.
1208 uint8_t crc
[2] = {0x00, 0x00};
1210 CodeAndTransmit14443bAsReader(init_srx
, sizeof(init_srx
));
1211 GetTagSamplesFor14443bDemod(); //no
1213 if (Demod
.len
== 0) return 2;
1215 // Randomly generated Chip ID
1216 if (card
) card
->chipid
= Demod
.output
[0];
1218 select_srx
[1] = Demod
.output
[0];
1220 ComputeCrc14443(CRC_14443_B
, select_srx
, 2, &select_srx
[2], &select_srx
[3]);
1221 CodeAndTransmit14443bAsReader(select_srx
, sizeof(select_srx
));
1222 GetTagSamplesFor14443bDemod(); //no
1224 if (Demod
.len
!= 3) return 2;
1226 // Check the CRC of the answer:
1227 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2 , &crc
[0], &crc
[1]);
1228 if(crc
[0] != Demod
.output
[1] || crc
[1] != Demod
.output
[2]) return 3;
1230 // Check response from the tag: should be the same UID as the command we just sent:
1231 if (select_srx
[1] != Demod
.output
[0]) return 1;
1233 // First get the tag's UID:
1234 select_srx
[0] = ISO14443B_GET_UID
;
1236 ComputeCrc14443(CRC_14443_B
, select_srx
, 1 , &select_srx
[1], &select_srx
[2]);
1237 CodeAndTransmit14443bAsReader(select_srx
, 3); // Only first three bytes for this one
1238 GetTagSamplesFor14443bDemod(); //no
1240 if (Demod
.len
!= 10) return 2;
1242 // The check the CRC of the answer
1243 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1244 if(crc
[0] != Demod
.output
[8] || crc
[1] != Demod
.output
[9]) return 3;
1248 memcpy(card
->uid
, Demod
.output
, 8);
1253 /* Perform the ISO 14443 B Card Selection procedure
1254 * Currently does NOT do any collision handling.
1255 * It expects 0-1 cards in the device's range.
1256 * TODO: Support multiple cards (perform anticollision)
1257 * TODO: Verify CRC checksums
1259 uint8_t iso14443b_select_card(iso14b_card_select_t
*card
)
1261 // WUPB command (including CRC)
1262 // Note: WUPB wakes up all tags, REQB doesn't wake up tags in HALT state
1263 static const uint8_t wupb
[] = { ISO14443B_REQB
, 0x00, 0x08, 0x39, 0x73 };
1264 // ATTRIB command (with space for CRC)
1265 uint8_t attrib
[] = { ISO14443B_ATTRIB
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00};
1267 // temp to calc crc.
1268 uint8_t crc
[2] = {0x00, 0x00};
1270 // first, wake up the tag
1271 CodeAndTransmit14443bAsReader(wupb
, sizeof(wupb
));
1272 GetTagSamplesFor14443bDemod(); //select_card
1275 if (Demod
.len
< 14) return 2;
1278 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1279 if ( crc
[0] != Demod
.output
[12] || crc
[1] != Demod
.output
[13] )
1284 memcpy(card
->uid
, Demod
.output
+1, 4);
1285 memcpy(card
->atqb
, Demod
.output
+5, 7);
1288 // copy the PUPI to ATTRIB ( PUPI == UID )
1289 memcpy(attrib
+ 1, Demod
.output
+ 1, 4);
1291 // copy the protocol info from ATQB (Protocol Info -> Protocol_Type) into ATTRIB (Param 3)
1292 attrib
[7] = Demod
.output
[10] & 0x0F;
1293 ComputeCrc14443(CRC_14443_B
, attrib
, 9, attrib
+ 9, attrib
+ 10);
1295 CodeAndTransmit14443bAsReader(attrib
, sizeof(attrib
));
1296 GetTagSamplesFor14443bDemod();//select_card
1298 // Answer to ATTRIB too short?
1299 if(Demod
.len
< 3) return 2;
1302 ComputeCrc14443(CRC_14443_B
, Demod
.output
, Demod
.len
-2, &crc
[0], &crc
[1]);
1303 if ( crc
[0] != Demod
.output
[1] || crc
[1] != Demod
.output
[2] )
1309 card
->cid
= Demod
.output
[0];
1312 uint16_t maxFrame
= card
->atqb
[5] >> 4;
1313 if (maxFrame
< 5) maxFrame
= 8 * maxFrame
+ 16;
1314 else if (maxFrame
== 5) maxFrame
= 64;
1315 else if (maxFrame
== 6) maxFrame
= 96;
1316 else if (maxFrame
== 7) maxFrame
= 128;
1317 else if (maxFrame
== 8) maxFrame
= 256;
1318 else maxFrame
= 257;
1319 iso14b_set_maxframesize(maxFrame
);
1322 uint8_t fwt
= card
->atqb
[6] >> 4;
1324 uint32_t fwt_time
= (302 << fwt
);
1325 iso14b_set_timeout( fwt_time
);
1328 // reset PCB block number
1333 // Set up ISO 14443 Type B communication (similar to iso14443a_setup)
1334 // field is setup for "Sending as Reader"
1335 void iso14443b_setup() {
1336 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup Enter");
1338 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1340 //BigBuf_Clear_ext(false);
1342 // Initialize Demod and Uart structs
1343 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1344 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1346 // connect Demodulated Signal to ADC:
1347 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1349 // Set up the synchronous serial port
1352 // Signal field is on with the appropriate LED
1353 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
1360 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup Exit");
1363 //-----------------------------------------------------------------------------
1364 // Read a SRI512 ISO 14443B tag.
1366 // SRI512 tags are just simple memory tags, here we're looking at making a dump
1367 // of the contents of the memory. No anticollision algorithm is done, we assume
1368 // we have a single tag in the field.
1370 // I tried to be systematic and check every answer of the tag, every CRC, etc...
1371 //-----------------------------------------------------------------------------
1372 void ReadSTMemoryIso14443b(uint8_t numofblocks
)
1374 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1376 // Make sure that we start from off, since the tags are stateful;
1377 // confusing things will happen if we don't reset them between reads.
1378 switch_off(); // before ReadStMemory
1384 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1387 // Now give it time to spin up.
1388 // Signal field is on with the appropriate LED
1390 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
1393 // First command: wake up the tag using the INITIATE command
1394 uint8_t cmd1
[] = {ISO14443B_INITIATE
, 0x00, 0x97, 0x5b};
1395 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1396 GetTagSamplesFor14443bDemod(); // no
1398 if (Demod
.len
== 0) {
1399 DbpString("No response from tag");
1403 Dbprintf("Randomly generated Chip ID (+ 2 byte CRC): %02x %02x %02x",
1404 Demod
.output
[0], Demod
.output
[1], Demod
.output
[2]);
1407 // There is a response, SELECT the uid
1408 DbpString("Now SELECT tag:");
1409 cmd1
[0] = ISO14443B_SELECT
; // 0x0E is SELECT
1410 cmd1
[1] = Demod
.output
[0];
1411 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1412 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1413 GetTagSamplesFor14443bDemod(); //no
1414 if (Demod
.len
!= 3) {
1415 Dbprintf("Expected 3 bytes from tag, got %d", Demod
.len
);
1419 // Check the CRC of the answer:
1420 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 1 , &cmd1
[2], &cmd1
[3]);
1421 if(cmd1
[2] != Demod
.output
[1] || cmd1
[3] != Demod
.output
[2]) {
1422 DbpString("CRC Error reading select response.");
1426 // Check response from the tag: should be the same UID as the command we just sent:
1427 if (cmd1
[1] != Demod
.output
[0]) {
1428 Dbprintf("Bad response to SELECT from Tag, aborting: %02x %02x", cmd1
[1], Demod
.output
[0]);
1433 // Tag is now selected,
1434 // First get the tag's UID:
1435 cmd1
[0] = ISO14443B_GET_UID
;
1436 ComputeCrc14443(CRC_14443_B
, cmd1
, 1 , &cmd1
[1], &cmd1
[2]);
1437 CodeAndTransmit14443bAsReader(cmd1
, 3); // no -- Only first three bytes for this one
1438 GetTagSamplesFor14443bDemod(); //no
1439 if (Demod
.len
!= 10) {
1440 Dbprintf("Expected 10 bytes from tag, got %d", Demod
.len
);
1444 // The check the CRC of the answer (use cmd1 as temporary variable):
1445 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 8, &cmd1
[2], &cmd1
[3]);
1446 if(cmd1
[2] != Demod
.output
[8] || cmd1
[3] != Demod
.output
[9]) {
1447 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1448 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[8]<<8)+Demod
.output
[9]);
1449 // Do not return;, let's go on... (we should retry, maybe ?)
1451 Dbprintf("Tag UID (64 bits): %08x %08x",
1452 (Demod
.output
[7]<<24) + (Demod
.output
[6]<<16) + (Demod
.output
[5]<<8) + Demod
.output
[4],
1453 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0]);
1455 // Now loop to read all 16 blocks, address from 0 to last block
1456 Dbprintf("Tag memory dump, block 0 to %d", numofblocks
);
1462 if (i
== numofblocks
) {
1463 DbpString("System area block (0xff):");
1467 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1468 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
)); //no
1469 GetTagSamplesFor14443bDemod(); //no
1471 if (Demod
.len
!= 6) { // Check if we got an answer from the tag
1472 DbpString("Expected 6 bytes from tag, got less...");
1475 // The check the CRC of the answer (use cmd1 as temporary variable):
1476 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 4, &cmd1
[2], &cmd1
[3]);
1477 if(cmd1
[2] != Demod
.output
[4] || cmd1
[3] != Demod
.output
[5]) {
1478 Dbprintf("CRC Error reading block! Expected: %04x got: %04x",
1479 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[4]<<8)+Demod
.output
[5]);
1480 // Do not return;, let's go on... (we should retry, maybe ?)
1482 // Now print out the memory location:
1483 Dbprintf("Address=%02x, Contents=%08x, CRC=%04x", i
,
1484 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0],
1485 (Demod
.output
[4]<<8)+Demod
.output
[5]);
1487 if (i
== 0xff) break;
1495 static void iso1444b_setup_snoop(void){
1496 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup_snoop Enter");
1498 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1500 BigBuf_Clear_ext(false);
1501 clear_trace();//setup snoop
1504 // Initialize Demod and Uart structs
1505 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1506 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1508 if (MF_DBGLEVEL
> 1) {
1509 // Print debug information about the buffer sizes
1510 Dbprintf("Snooping buffers initialized:");
1511 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1512 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE
);
1513 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE
);
1514 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE
);
1517 // connect Demodulated Signal to ADC:
1518 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1520 // Setup for the DMA.
1523 // Set FPGA in the appropriate mode
1524 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
| FPGA_HF_READER_RX_XCORR_SNOOP
);
1527 // Start the SSP timer
1529 if (MF_DBGLEVEL
> 3) Dbprintf("iso1443b_setup_snoop Exit");
1532 //=============================================================================
1533 // Finally, the `sniffer' combines elements from both the reader and
1534 // simulated tag, to show both sides of the conversation.
1535 //=============================================================================
1537 //-----------------------------------------------------------------------------
1538 // Record the sequence of commands sent by the reader to the tag, with
1539 // triggering so that we start recording at the point that the tag is moved
1541 //-----------------------------------------------------------------------------
1543 * Memory usage for this function, (within BigBuf)
1544 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1545 * Last Received command (tag->reader) - MAX_FRAME_SIZE
1546 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
1547 * Demodulated samples received - all the rest
1549 void RAMFUNC
SnoopIso14443b(void) {
1551 uint32_t time_0
= 0, time_start
= 0, time_stop
= 0;
1553 int lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
1555 // We won't start recording the frames that we acquire until we trigger;
1556 // a good trigger condition to get started is probably when we see a
1557 // response from the tag.
1558 bool triggered
= TRUE
; // TODO: set and evaluate trigger condition
1559 bool TagIsActive
= FALSE
;
1560 bool ReaderIsActive
= FALSE
;
1562 iso1444b_setup_snoop();
1564 // The DMA buffer, used to stream samples from the FPGA
1565 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
1566 int8_t *upTo
= dmaBuf
;
1568 // Setup and start DMA.
1569 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
) ){
1570 if (MF_DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1575 time_0
= GetCountSspClk();
1577 // And now we loop, receiving samples.
1587 if (upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
1589 lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
1590 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
1591 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
1594 if (MF_DBGLEVEL
>= 2) DbpString("Trace full");
1598 if (BUTTON_PRESS()) {
1599 if (MF_DBGLEVEL
>= 2) DbpString("cancelled");
1608 // no need to try decoding reader data if the tag is sending
1609 if (Handle14443bReaderUartBit(ci
& 0x01)) {
1611 time_stop
= GetCountSspClk() - time_0
;
1614 LogTrace(Uart
.output
, Uart
.byteCnt
, time_start
, time_stop
, NULL
, TRUE
);
1616 /* And ready to receive another command. */
1618 /* And also reset the demod code, which might have been */
1619 /* false-triggered by the commands from the reader. */
1622 time_start
= GetCountSspClk() - time_0
;
1625 if (Handle14443bReaderUartBit(cq
& 0x01)) {
1627 time_stop
= GetCountSspClk() - time_0
;
1630 LogTrace(Uart
.output
, Uart
.byteCnt
, time_start
, time_stop
, NULL
, TRUE
);
1632 /* And ready to receive another command. */
1634 /* And also reset the demod code, which might have been */
1635 /* false-triggered by the commands from the reader. */
1638 time_start
= GetCountSspClk() - time_0
;
1640 ReaderIsActive
= (Uart
.state
> STATE_GOT_FALLING_EDGE_OF_SOF
);
1644 if (!ReaderIsActive
) {
1645 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
1646 // is this | 0x01 the error? & 0xfe in https://github.com/Proxmark/proxmark3/issues/103
1647 // LSB is a fpga signal bit.
1648 if (Handle14443bTagSamplesDemod(ci
>> 1, cq
>> 1)) {
1650 time_stop
= GetCountSspClk() - time_0
;
1652 LogTrace(Demod
.output
, Demod
.len
, time_start
, time_stop
, NULL
, FALSE
);
1656 // And ready to receive another response.
1659 time_start
= GetCountSspClk() - time_0
;
1661 TagIsActive
= (Demod
.state
> DEMOD_GOT_FALLING_EDGE_OF_SOF
);
1665 switch_off(); // Snoop
1667 DbpString("Snoop statistics:");
1668 Dbprintf(" Uart State: %x ByteCount: %i ByteCountMax: %i", Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);
1669 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
1672 if ( upTo
) upTo
= NULL
;
1674 // Uart.byteCntMax should be set with ATQB value..
1677 void iso14b_set_trigger(bool enable
) {
1682 * Send raw command to tag ISO14443B
1684 * param flags enum ISO14B_COMMAND. (mifare.h)
1685 * len len of buffer data
1686 * data buffer with bytes to send
1692 void SendRawCommand14443B_Ex(UsbCommand
*c
)
1694 iso14b_command_t param
= c
->arg
[0];
1695 size_t len
= c
->arg
[1] & 0xffff;
1696 uint8_t *cmd
= c
->d
.asBytes
;
1698 uint32_t sendlen
= sizeof(iso14b_card_select_t
);
1699 uint8_t buf
[USB_CMD_DATA_SIZE
] = {0x00};
1701 if (MF_DBGLEVEL
> 3) Dbprintf("14b raw: param, %04x", param
);
1703 // turn on trigger (LED_A)
1704 if ((param
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
)
1705 iso14b_set_trigger(TRUE
);
1707 if ((param
& ISO14B_CONNECT
) == ISO14B_CONNECT
) {
1708 // Make sure that we start from off, since the tags are stateful;
1709 // confusing things will happen if we don't reset them between reads.
1710 //switch_off(); // before connect in raw
1716 if ((param
& ISO14B_SELECT_STD
) == ISO14B_SELECT_STD
) {
1717 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
1718 status
= iso14443b_select_card(card
);
1719 cmd_send(CMD_ACK
, status
, sendlen
, 0, buf
, sendlen
);
1720 // 0: OK 2: attrib fail, 3:crc fail,
1721 if ( status
> 0 ) return;
1724 if ((param
& ISO14B_SELECT_SR
) == ISO14B_SELECT_SR
) {
1725 iso14b_card_select_t
*card
= (iso14b_card_select_t
*)buf
;
1726 status
= iso14443b_select_srx_card(card
);
1727 cmd_send(CMD_ACK
, status
, sendlen
, 0, buf
, sendlen
);
1728 // 0: OK 2: attrib fail, 3:crc fail,
1729 if ( status
> 0 ) return;
1732 if ((param
& ISO14B_APDU
) == ISO14B_APDU
) {
1733 status
= iso14443b_apdu(cmd
, len
, buf
);
1734 cmd_send(CMD_ACK
, status
, status
, 0, buf
, status
);
1737 if ((param
& ISO14B_RAW
) == ISO14B_RAW
) {
1738 if((param
& ISO14B_APPEND_CRC
) == ISO14B_APPEND_CRC
) {
1739 AppendCrc14443b(cmd
, len
);
1743 CodeAndTransmit14443bAsReader(cmd
, len
); // raw
1744 GetTagSamplesFor14443bDemod(); // raw
1746 sendlen
= MIN(Demod
.len
, USB_CMD_DATA_SIZE
);
1747 status
= (Demod
.len
> 0) ? 0 : 1;
1748 cmd_send(CMD_ACK
, status
, sendlen
, 0, Demod
.output
, sendlen
);
1751 // turn off trigger (LED_A)
1752 if ((param
& ISO14B_REQUEST_TRIGGER
) == ISO14B_REQUEST_TRIGGER
)
1753 iso14b_set_trigger(FALSE
);
1755 // turn off antenna et al
1756 // we don't send a HALT command.
1757 if ((param
& ISO14B_DISCONNECT
) == ISO14B_DISCONNECT
) {
1758 if (MF_DBGLEVEL
> 3) Dbprintf("disconnect");
1759 switch_off(); // disconnect raw
1761 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);