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 //-----------------------------------------------------------------------------
12 #include "proxmark3.h"
17 #include "iso14443crc.h"
19 #define RECEIVE_SAMPLES_TIMEOUT 2000
20 #define ISO14443B_DMA_BUFFER_SIZE 512
22 //=============================================================================
23 // An ISO 14443 Type B tag. We listen for commands from the reader, using
24 // a UART kind of thing that's implemented in software. When we get a
25 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
26 // If it's good, then we can do something appropriate with it, and send
28 //=============================================================================
30 //-----------------------------------------------------------------------------
31 // Code up a string of octets at layer 2 (including CRC, we don't generate
32 // that here) so that they can be transmitted to the reader. Doesn't transmit
33 // them yet, just leaves them ready to send in ToSend[].
34 //-----------------------------------------------------------------------------
35 static void CodeIso14443bAsTag(const uint8_t *cmd
, int len
)
41 // Transmit a burst of ones, as the initial thing that lets the
42 // reader get phase sync. This (TR1) must be > 80/fs, per spec,
43 // but tag that I've tried (a Paypass) exceeds that by a fair bit,
45 for(i
= 0; i
< 20; i
++) {
53 for(i
= 0; i
< 10; i
++) {
59 for(i
= 0; i
< 2; i
++) {
66 for(i
= 0; i
< len
; i
++) {
77 for(j
= 0; j
< 8; j
++) {
100 for(i
= 0; i
< 10; i
++) {
106 for(i
= 0; i
< 2; i
++) {
113 // Convert from last byte pos to length
117 //-----------------------------------------------------------------------------
118 // The software UART that receives commands from the reader, and its state
120 //-----------------------------------------------------------------------------
124 STATE_GOT_FALLING_EDGE_OF_SOF
,
125 STATE_AWAITING_START_BIT
,
126 STATE_RECEIVING_DATA
,
137 /* Receive & handle a bit coming from the reader.
139 * This function is called 4 times per bit (every 2 subcarrier cycles).
140 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
143 * LED A -> ON once we have received the SOF and are expecting the rest.
144 * LED A -> OFF once we have received EOF or are in error state or unsynced
146 * Returns: true if we received a EOF
147 * false if we are still waiting for some more
149 static int Handle14443bUartBit(int bit
)
154 // we went low, so this could be the beginning
156 Uart
.state
= STATE_GOT_FALLING_EDGE_OF_SOF
;
162 case STATE_GOT_FALLING_EDGE_OF_SOF
:
164 if(Uart
.posCnt
== 2) { // sample every 4 1/fs in the middle of a bit
166 if(Uart
.bitCnt
> 9) {
167 // we've seen enough consecutive
168 // zeros that it's a valid SOF
171 Uart
.state
= STATE_AWAITING_START_BIT
;
172 LED_A_ON(); // Indicate we got a valid SOF
174 // didn't stay down long enough
175 // before going high, error
176 Uart
.state
= STATE_ERROR_WAIT
;
179 // do nothing, keep waiting
183 if(Uart
.posCnt
>= 4) Uart
.posCnt
= 0;
184 if(Uart
.bitCnt
> 12) {
185 // Give up if we see too many zeros without
187 Uart
.state
= STATE_ERROR_WAIT
;
191 case STATE_AWAITING_START_BIT
:
194 if(Uart
.posCnt
> 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
195 // stayed high for too long between
197 Uart
.state
= STATE_ERROR_WAIT
;
200 // falling edge, this starts the data byte
204 Uart
.state
= STATE_RECEIVING_DATA
;
208 case STATE_RECEIVING_DATA
:
210 if(Uart
.posCnt
== 2) {
211 // time to sample a bit
214 Uart
.shiftReg
|= 0x200;
218 if(Uart
.posCnt
>= 4) {
221 if(Uart
.bitCnt
== 10) {
222 if((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001))
224 // this is a data byte, with correct
225 // start and stop bits
226 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xff;
229 if(Uart
.byteCnt
>= Uart
.byteCntMax
) {
230 // Buffer overflowed, give up
232 Uart
.state
= STATE_ERROR_WAIT
;
234 // so get the next byte now
236 Uart
.state
= STATE_AWAITING_START_BIT
;
238 } else if(Uart
.shiftReg
== 0x000) {
239 // this is an EOF byte
240 LED_A_OFF(); // Finished receiving
245 Uart
.state
= STATE_ERROR_WAIT
;
250 case STATE_ERROR_WAIT
:
251 // We're all screwed up, so wait a little while
252 // for whatever went wrong to finish, and then
255 if(Uart
.posCnt
> 10) {
256 Uart
.state
= STATE_UNSYNCD
;
262 Uart
.state
= STATE_UNSYNCD
;
269 //-----------------------------------------------------------------------------
270 // Receive a command (from the reader to us, where we are the simulated tag),
271 // and store it in the given buffer, up to the given maximum length. Keeps
272 // spinning, waiting for a well-framed command, until either we get one
273 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
275 // Assume that we're called with the SSC (to the FPGA) and ADC path set
277 //-----------------------------------------------------------------------------
278 static int GetIso14443bCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
283 // Set FPGA mode to "simulated ISO 14443B tag", no modulation (listen
284 // only, since we are receiving, not transmitting).
285 // Signal field is off with the appropriate LED
287 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
290 // Now run a `software UART' on the stream of incoming samples.
291 Uart
.output
= received
;
292 Uart
.byteCntMax
= maxLen
;
293 Uart
.state
= STATE_UNSYNCD
;
298 if(BUTTON_PRESS()) return FALSE
;
300 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
301 AT91C_BASE_SSC
->SSC_THR
= 0x00;
303 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
304 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
307 for(i
= 0; i
< 8; i
++, mask
>>= 1) {
309 if(Handle14443bUartBit(bit
)) {
318 //-----------------------------------------------------------------------------
319 // Main loop of simulated tag: receive commands from reader, decide what
320 // response to send, and send it.
321 //-----------------------------------------------------------------------------
322 void SimulateIso14443bTag(void)
324 // the only command we understand is REQB, AFI=0, Select All, N=0:
325 static const uint8_t cmd1
[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
326 // ... and we respond with ATQB, PUPI = 820de174, Application Data = 0x20381922,
327 // supports only 106kBit/s in both directions, max frame size = 32Bytes,
328 // supports ISO14443-4, FWI=8 (77ms), NAD supported, CID not supported:
329 static const uint8_t response1
[] = {
330 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22,
331 0x00, 0x21, 0x85, 0x5e, 0xd7
337 // allocate command receive buffer
339 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
346 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
348 // prepare the (only one) tag answer:
349 CodeIso14443bAsTag(response1
, sizeof(response1
));
350 uint8_t *resp1
= BigBuf_malloc(ToSendMax
);
351 memcpy(resp1
, ToSend
, ToSendMax
);
352 uint16_t resp1Len
= ToSendMax
;
354 // We need to listen to the high-frequency, peak-detected path.
355 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
363 if(!GetIso14443bCommandFromReader(receivedCmd
, &len
, 100)) {
364 Dbprintf("button pressed, received %d commands", cmdsRecvd
);
368 // Good, look at the command now.
370 if(len
== sizeof(cmd1
) && memcmp(receivedCmd
, cmd1
, len
) == 0) {
371 resp
= resp1
; respLen
= resp1Len
;
373 Dbprintf("new cmd from reader: len=%d, cmdsRecvd=%d", len
, cmdsRecvd
);
374 // And print whether the CRC fails, just for good measure
375 ComputeCrc14443(CRC_14443_B
, receivedCmd
, len
-2, &b1
, &b2
);
376 if(b1
!= receivedCmd
[len
-2] || b2
!= receivedCmd
[len
-1]) {
377 // Not so good, try again.
378 DbpString("+++CRC fail");
380 DbpString("CRC passes");
387 if(cmdsRecvd
> 0x30) {
388 DbpString("many commands later...");
392 if(respLen
<= 0) continue;
395 // Signal field is off with the appropriate LED
397 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
398 AT91C_BASE_SSC
->SSC_THR
= 0xff;
401 // Transmit the response.
404 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
407 AT91C_BASE_SSC
->SSC_THR
= b
;
414 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
415 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
422 //=============================================================================
423 // An ISO 14443 Type B reader. We take layer two commands, code them
424 // appropriately, and then send them to the tag. We then listen for the
425 // tag's response, which we leave in the buffer to be demodulated on the
427 //=============================================================================
432 DEMOD_PHASE_REF_TRAINING
,
433 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
,
434 DEMOD_GOT_FALLING_EDGE_OF_SOF
,
435 DEMOD_AWAITING_START_BIT
,
436 DEMOD_RECEIVING_DATA
,
442 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
454 * Handles reception of a bit from the tag
456 * This function is called 2 times per bit (every 4 subcarrier cycles).
457 * Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 4,72us
460 * LED C -> ON once we have received the SOF and are expecting the rest.
461 * LED C -> OFF once we have received EOF or are unsynced
463 * Returns: true if we received a EOF
464 * false if we are still waiting for some more
467 static RAMFUNC
int Handle14443bSamplesDemod(int ci
, int cq
)
471 // The soft decision on the bit uses an estimate of just the
472 // quadrant of the reference angle, not the exact angle.
473 #define MAKE_SOFT_DECISION() { \
474 if(Demod.sumI > 0) { \
479 if(Demod.sumQ > 0) { \
486 #define SUBCARRIER_DETECT_THRESHOLD 8
488 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by abs(ci) + abs(cq)
489 /* #define CHECK_FOR_SUBCARRIER() { \
499 // Subcarrier amplitude v = sqrt(ci^2 + cq^2), approximated here by max(abs(ci),abs(cq)) + 1/2*min(abs(ci),abs(cq)))
500 #define CHECK_FOR_SUBCARRIER() { \
502 if(cq < 0) { /* ci < 0, cq < 0 */ \
504 v = -cq - (ci >> 1); \
506 v = -ci - (cq >> 1); \
508 } else { /* ci < 0, cq >= 0 */ \
510 v = -ci + (cq >> 1); \
512 v = cq - (ci >> 1); \
516 if(cq < 0) { /* ci >= 0, cq < 0 */ \
518 v = ci - (cq >> 1); \
520 v = -cq + (ci >> 1); \
522 } else { /* ci >= 0, cq >= 0 */ \
524 v = ci + (cq >> 1); \
526 v = cq + (ci >> 1); \
532 switch(Demod
.state
) {
534 CHECK_FOR_SUBCARRIER();
535 if(v
> SUBCARRIER_DETECT_THRESHOLD
) { // subcarrier detected
536 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
543 case DEMOD_PHASE_REF_TRAINING
:
544 if(Demod
.posCount
< 8) {
545 CHECK_FOR_SUBCARRIER();
546 if (v
> SUBCARRIER_DETECT_THRESHOLD
) {
547 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
548 // note: synchronization time > 80 1/fs
552 } else { // subcarrier lost
553 Demod
.state
= DEMOD_UNSYNCD
;
556 Demod
.state
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
;
560 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
:
561 MAKE_SOFT_DECISION();
562 if(v
< 0) { // logic '0' detected
563 Demod
.state
= DEMOD_GOT_FALLING_EDGE_OF_SOF
;
564 Demod
.posCount
= 0; // start of SOF sequence
566 if(Demod
.posCount
> 200/4) { // maximum length of TR1 = 200 1/fs
567 Demod
.state
= DEMOD_UNSYNCD
;
573 case DEMOD_GOT_FALLING_EDGE_OF_SOF
:
575 MAKE_SOFT_DECISION();
577 if(Demod
.posCount
< 9*2) { // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
578 Demod
.state
= DEMOD_UNSYNCD
;
580 LED_C_ON(); // Got SOF
581 Demod
.state
= DEMOD_AWAITING_START_BIT
;
584 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
590 if(Demod
.posCount
> 12*2) { // low phase of SOF too long (> 12 etu)
591 Demod
.state
= DEMOD_UNSYNCD
;
597 case DEMOD_AWAITING_START_BIT
:
599 MAKE_SOFT_DECISION();
601 if(Demod
.posCount
> 3*2) { // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
602 Demod
.state
= DEMOD_UNSYNCD
;
605 } else { // start bit detected
607 Demod
.posCount
= 1; // this was the first half
610 Demod
.state
= DEMOD_RECEIVING_DATA
;
614 case DEMOD_RECEIVING_DATA
:
615 MAKE_SOFT_DECISION();
616 if(Demod
.posCount
== 0) { // first half of bit
619 } else { // second half of bit
622 /* this had been used to add RSSI (Received Signal Strength Indication) to traces. Currently not implemented.
623 if(Demod.thisBit > 0) {
624 Demod.metric += Demod.thisBit;
626 Demod.metric -= Demod.thisBit;
631 Demod
.shiftReg
>>= 1;
632 if(Demod
.thisBit
> 0) { // logic '1'
633 Demod
.shiftReg
|= 0x200;
637 if(Demod
.bitCount
== 10) {
638 uint16_t s
= Demod
.shiftReg
;
639 if((s
& 0x200) && !(s
& 0x001)) { // stop bit == '1', start bit == '0'
640 uint8_t b
= (s
>> 1);
641 Demod
.output
[Demod
.len
] = b
;
643 Demod
.state
= DEMOD_AWAITING_START_BIT
;
645 Demod
.state
= DEMOD_UNSYNCD
;
648 // This is EOF (start, stop and all data bits == '0'
658 Demod
.state
= DEMOD_UNSYNCD
;
667 static void DemodReset()
669 // Clear out the state of the "UART" that receives from the tag.
671 Demod
.state
= DEMOD_UNSYNCD
;
673 memset(Demod
.output
, 0x00, MAX_FRAME_SIZE
);
677 static void DemodInit(uint8_t *data
)
684 static void UartReset()
686 Uart
.byteCntMax
= MAX_FRAME_SIZE
;
687 Uart
.state
= STATE_UNSYNCD
;
693 static void UartInit(uint8_t *data
)
701 * Demodulate the samples we received from the tag, also log to tracebuffer
702 * quiet: set to 'TRUE' to disable debug output
704 static void GetSamplesFor14443bDemod(int n
, bool quiet
)
707 bool gotFrame
= FALSE
;
708 int lastRxCounter
, ci
, cq
, samples
= 0;
710 // Allocate memory from BigBuf for some buffers
711 // free all previous allocations first
714 // The response (tag -> reader) that we're receiving.
715 uint8_t *receivedResponse
= BigBuf_malloc(MAX_FRAME_SIZE
);
717 // The DMA buffer, used to stream samples from the FPGA
718 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
720 // Set up the demodulator for tag -> reader responses.
721 DemodInit(receivedResponse
);
723 // Setup and start DMA.
724 FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
);
726 int8_t *upTo
= dmaBuf
;
727 lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
729 // Signal field is ON with the appropriate LED:
731 // And put the FPGA in the appropriate mode
732 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
);
735 int behindBy
= lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
736 if(behindBy
> max
) max
= behindBy
;
738 while(((lastRxCounter
-AT91C_BASE_PDC_SSC
->PDC_RCR
) & (ISO14443B_DMA_BUFFER_SIZE
-1)) > 2) {
742 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
744 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
745 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
748 if(lastRxCounter
<= 0) {
749 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
754 if(Handle14443bSamplesDemod(ci
, cq
)) {
760 if(samples
> n
|| gotFrame
) {
765 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
767 if (!quiet
) Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d", max
, samples
, gotFrame
, Demod
.len
, Demod
.sumI
, Demod
.sumQ
);
769 if (tracing
&& Demod
.len
> 0) {
770 uint8_t parity
[MAX_PARITY_SIZE
];
771 GetParity(Demod
.output
, Demod
.len
, parity
);
772 LogTrace(Demod
.output
, Demod
.len
, 0, 0, parity
, FALSE
);
777 //-----------------------------------------------------------------------------
778 // Transmit the command (to the tag) that was placed in ToSend[].
779 //-----------------------------------------------------------------------------
780 static void TransmitFor14443b(void)
786 while(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
787 AT91C_BASE_SSC
->SSC_THR
= 0xff;
790 // Signal field is ON with the appropriate Red LED
792 // Signal we are transmitting with the Green LED
794 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
796 for(c
= 0; c
< 10;) {
797 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
798 AT91C_BASE_SSC
->SSC_THR
= 0xff;
801 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
802 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
810 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
811 AT91C_BASE_SSC
->SSC_THR
= ToSend
[c
];
817 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
818 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
823 LED_B_OFF(); // Finished sending
827 //-----------------------------------------------------------------------------
828 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
829 // so that it is ready to transmit to the tag using TransmitFor14443b().
830 //-----------------------------------------------------------------------------
831 static void CodeIso14443bAsReader(const uint8_t *cmd
, int len
)
838 // Establish initial reference level
839 for(i
= 0; i
< 40; i
++) {
843 for(i
= 0; i
< 10; i
++) {
847 for(i
= 0; i
< len
; i
++) {
855 for(j
= 0; j
< 8; j
++) {
866 for(i
= 0; i
< 10; i
++) {
869 for(i
= 0; i
< 8; i
++) {
873 // And then a little more, to make sure that the last character makes
874 // it out before we switch to rx mode.
875 for(i
= 0; i
< 24; i
++) {
879 // Convert from last character reference to length
884 //-----------------------------------------------------------------------------
885 // Read an ISO 14443B tag. We send it some set of commands, and record the
887 // The command name is misleading, it actually decodes the reponse in HEX
888 // into the output buffer (read the result using hexsamples, not hisamples)
890 // obsolete function only for test
891 //-----------------------------------------------------------------------------
892 void AcquireRawAdcSamplesIso14443b(uint32_t parameter
)
894 uint8_t cmd1
[] = { 0x05, 0x00, 0x08, 0x39, 0x73 }; // REQB with AFI=0, Request All, N=0
896 SendRawCommand14443B(sizeof(cmd1
),1,1,cmd1
);
901 Convenience function to encode, transmit and trace iso 14443b comms
903 static void CodeAndTransmit14443bAsReader(const uint8_t *cmd
, int len
)
905 CodeIso14443bAsReader(cmd
, len
);
908 uint8_t parity
[MAX_PARITY_SIZE
];
909 GetParity(cmd
, len
, parity
);
910 LogTrace(cmd
,len
, 0, 0, parity
, TRUE
);
915 //-----------------------------------------------------------------------------
916 // Read a SRI512 ISO 14443B tag.
918 // SRI512 tags are just simple memory tags, here we're looking at making a dump
919 // of the contents of the memory. No anticollision algorithm is done, we assume
920 // we have a single tag in the field.
922 // I tried to be systematic and check every answer of the tag, every CRC, etc...
923 //-----------------------------------------------------------------------------
924 void ReadSTMemoryIso14443b(uint32_t dwLast
)
931 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
932 // Make sure that we start from off, since the tags are stateful;
933 // confusing things will happen if we don't reset them between reads.
935 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
938 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
941 // Now give it time to spin up.
942 // Signal field is on with the appropriate LED
945 FPGA_MAJOR_MODE_HF_READER_RX_XCORR
);
948 // First command: wake up the tag using the INITIATE command
949 uint8_t cmd1
[] = {0x06, 0x00, 0x97, 0x5b};
951 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
));
953 GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, TRUE
);
956 if (Demod
.len
== 0) {
957 DbpString("No response from tag");
960 Dbprintf("Randomly generated UID from tag (+ 2 byte CRC): %x %x %x",
961 Demod
.output
[0], Demod
.output
[1], Demod
.output
[2]);
963 // There is a response, SELECT the uid
964 DbpString("Now SELECT tag:");
965 cmd1
[0] = 0x0E; // 0x0E is SELECT
966 cmd1
[1] = Demod
.output
[0];
967 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
968 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
));
971 GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, TRUE
);
973 if (Demod
.len
!= 3) {
974 Dbprintf("Expected 3 bytes from tag, got %d", Demod
.len
);
977 // Check the CRC of the answer:
978 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 1 , &cmd1
[2], &cmd1
[3]);
979 if(cmd1
[2] != Demod
.output
[1] || cmd1
[3] != Demod
.output
[2]) {
980 DbpString("CRC Error reading select response.");
983 // Check response from the tag: should be the same UID as the command we just sent:
984 if (cmd1
[1] != Demod
.output
[0]) {
985 Dbprintf("Bad response to SELECT from Tag, aborting: %x %x", cmd1
[1], Demod
.output
[0]);
988 // Tag is now selected,
989 // First get the tag's UID:
991 ComputeCrc14443(CRC_14443_B
, cmd1
, 1 , &cmd1
[1], &cmd1
[2]);
992 CodeAndTransmit14443bAsReader(cmd1
, 3); // Only first three bytes for this one
995 GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, TRUE
);
997 if (Demod
.len
!= 10) {
998 Dbprintf("Expected 10 bytes from tag, got %d", Demod
.len
);
1001 // The check the CRC of the answer (use cmd1 as temporary variable):
1002 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 8, &cmd1
[2], &cmd1
[3]);
1003 if(cmd1
[2] != Demod
.output
[8] || cmd1
[3] != Demod
.output
[9]) {
1004 Dbprintf("CRC Error reading block! - Below: expected, got %x %x",
1005 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[8]<<8)+Demod
.output
[9]);
1006 // Do not return;, let's go on... (we should retry, maybe ?)
1008 Dbprintf("Tag UID (64 bits): %08x %08x",
1009 (Demod
.output
[7]<<24) + (Demod
.output
[6]<<16) + (Demod
.output
[5]<<8) + Demod
.output
[4],
1010 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0]);
1012 // Now loop to read all 16 blocks, address from 0 to last block
1013 Dbprintf("Tag memory dump, block 0 to %d",dwLast
);
1019 DbpString("System area block (0xff):");
1023 ComputeCrc14443(CRC_14443_B
, cmd1
, 2, &cmd1
[2], &cmd1
[3]);
1024 CodeAndTransmit14443bAsReader(cmd1
, sizeof(cmd1
));
1027 GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, TRUE
);
1029 if (Demod
.len
!= 6) { // Check if we got an answer from the tag
1030 DbpString("Expected 6 bytes from tag, got less...");
1033 // The check the CRC of the answer (use cmd1 as temporary variable):
1034 ComputeCrc14443(CRC_14443_B
, Demod
.output
, 4, &cmd1
[2], &cmd1
[3]);
1035 if(cmd1
[2] != Demod
.output
[4] || cmd1
[3] != Demod
.output
[5]) {
1036 Dbprintf("CRC Error reading block! - Below: expected, got %x %x",
1037 (cmd1
[2]<<8)+cmd1
[3], (Demod
.output
[4]<<8)+Demod
.output
[5]);
1038 // Do not return;, let's go on... (we should retry, maybe ?)
1040 // Now print out the memory location:
1041 Dbprintf("Address=%x, Contents=%x, CRC=%x", i
,
1042 (Demod
.output
[3]<<24) + (Demod
.output
[2]<<16) + (Demod
.output
[1]<<8) + Demod
.output
[0],
1043 (Demod
.output
[4]<<8)+Demod
.output
[5]);
1052 //=============================================================================
1053 // Finally, the `sniffer' combines elements from both the reader and
1054 // simulated tag, to show both sides of the conversation.
1055 //=============================================================================
1057 //-----------------------------------------------------------------------------
1058 // Record the sequence of commands sent by the reader to the tag, with
1059 // triggering so that we start recording at the point that the tag is moved
1061 //-----------------------------------------------------------------------------
1063 * Memory usage for this function, (within BigBuf)
1064 * Last Received command (reader->tag) - MAX_FRAME_SIZE
1065 * Last Received command (tag->reader) - MAX_FRAME_SIZE
1066 * DMA Buffer - ISO14443B_DMA_BUFFER_SIZE
1067 * Demodulated samples received - all the rest
1069 void RAMFUNC
SnoopIso14443b(void)
1071 // We won't start recording the frames that we acquire until we trigger;
1072 // a good trigger condition to get started is probably when we see a
1073 // response from the tag.
1074 int triggered
= TRUE
; // TODO: set and evaluate trigger condition
1076 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1082 // The DMA buffer, used to stream samples from the FPGA
1083 int8_t *dmaBuf
= (int8_t*) BigBuf_malloc(ISO14443B_DMA_BUFFER_SIZE
);
1087 int maxBehindBy
= 0;
1089 // Count of samples received so far, so that we can include timing
1090 // information in the trace buffer.
1093 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1094 UartInit(BigBuf_malloc(MAX_FRAME_SIZE
));
1096 // Print some debug information about the buffer sizes
1097 Dbprintf("Snooping buffers initialized:");
1098 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1099 Dbprintf(" Reader -> tag: %i bytes", MAX_FRAME_SIZE
);
1100 Dbprintf(" tag -> Reader: %i bytes", MAX_FRAME_SIZE
);
1101 Dbprintf(" DMA: %i bytes", ISO14443B_DMA_BUFFER_SIZE
);
1103 // Signal field is off, no reader signal, no tag signal
1106 // And put the FPGA in the appropriate mode
1107 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_SNOOP
);
1108 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1110 // Setup for the DMA.
1113 lastRxCounter
= ISO14443B_DMA_BUFFER_SIZE
;
1114 FpgaSetupSscDma((uint8_t*) dmaBuf
, ISO14443B_DMA_BUFFER_SIZE
);
1115 uint8_t parity
[MAX_PARITY_SIZE
];
1117 bool TagIsActive
= FALSE
;
1118 bool ReaderIsActive
= FALSE
;
1120 // And now we loop, receiving samples.
1122 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) &
1123 (ISO14443B_DMA_BUFFER_SIZE
-1);
1124 if(behindBy
> maxBehindBy
) {
1125 maxBehindBy
= behindBy
;
1128 if(behindBy
< 2) continue;
1134 if(upTo
>= dmaBuf
+ ISO14443B_DMA_BUFFER_SIZE
) {
1136 lastRxCounter
+= ISO14443B_DMA_BUFFER_SIZE
;
1137 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
1138 AT91C_BASE_PDC_SSC
->PDC_RNCR
= ISO14443B_DMA_BUFFER_SIZE
;
1140 if(behindBy
> (9*ISO14443B_DMA_BUFFER_SIZE
/10)) { // TODO: understand whether we can increase/decrease as we want or not?
1141 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy
);
1145 DbpString("Reached trace limit");
1148 if(BUTTON_PRESS()) {
1149 DbpString("cancelled");
1156 if (!TagIsActive
) { // no need to try decoding reader data if the tag is sending
1157 if(Handle14443bUartBit(ci
& 0x01)) {
1158 if(triggered
&& tracing
) {
1159 GetParity(Uart
.output
, Uart
.byteCnt
, parity
);
1160 LogTrace(Uart
.output
, Uart
.byteCnt
, samples
, samples
, parity
, TRUE
);
1162 /* And ready to receive another command. */
1164 /* And also reset the demod code, which might have been */
1165 /* false-triggered by the commands from the reader. */
1168 if(Handle14443bUartBit(cq
& 0x01)) {
1169 if(triggered
&& tracing
) {
1170 GetParity(Uart
.output
, Uart
.byteCnt
, parity
);
1171 LogTrace(Uart
.output
, Uart
.byteCnt
, samples
, samples
, parity
, TRUE
);
1173 /* And ready to receive another command. */
1175 /* And also reset the demod code, which might have been */
1176 /* false-triggered by the commands from the reader. */
1179 ReaderIsActive
= (Uart
.state
!= STATE_UNSYNCD
);
1182 if(!ReaderIsActive
) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time
1183 if(Handle14443bSamplesDemod(ci
& 0xFE, cq
& 0xFE)) {
1185 //Use samples as a time measurement
1188 uint8_t parity
[MAX_PARITY_SIZE
];
1189 GetParity(Demod
.output
, Demod
.len
, parity
);
1190 LogTrace(Demod
.output
, Demod
.len
, samples
, samples
, parity
, FALSE
);
1194 // And ready to receive another response.
1197 TagIsActive
= (Demod
.state
> DEMOD_PHASE_REF_TRAINING
);
1202 FpgaDisableSscDma();
1204 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
1205 DbpString("Snoop statistics:");
1206 Dbprintf(" Max behind by: %i", maxBehindBy
);
1207 Dbprintf(" Uart State: %x", Uart
.state
);
1208 Dbprintf(" Uart ByteCnt: %i", Uart
.byteCnt
);
1209 Dbprintf(" Uart ByteCntMax: %i", Uart
.byteCntMax
);
1210 Dbprintf(" Trace length: %i", BigBuf_get_traceLen());
1215 * Send raw command to tag ISO14443B
1217 * datalen len of buffer data
1218 * recv bool when true wait for data from tag and send to client
1219 * powerfield bool leave the field on when true
1220 * data buffer with byte to send
1226 void SendRawCommand14443B(uint32_t datalen
, uint32_t recv
, uint8_t powerfield
, uint8_t data
[])
1228 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1229 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1234 /* if(!powerfield) {
1235 // Make sure that we start from off, since the tags are stateful;
1236 // confusing things will happen if we don't reset them between reads.
1237 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1243 // if(!GETBIT(GPIO_LED_D)) { // if field is off
1244 // FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR);
1245 // // Signal field is on with the appropriate LED
1250 CodeAndTransmit14443bAsReader(data
, datalen
);
1253 GetSamplesFor14443bDemod(RECEIVE_SAMPLES_TIMEOUT
, TRUE
);
1254 uint16_t iLen
= MIN(Demod
.len
, USB_CMD_DATA_SIZE
);
1255 cmd_send(CMD_ACK
, iLen
, 0, 0, Demod
.output
, iLen
);
1259 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);