1 //-----------------------------------------------------------------------------
2 // Routines to support ISO 14443. This includes both the reader software and
3 // the `fake tag' modes. At the moment only the Type B modulation is
5 // Jonathan Westhues, split Nov 2006
6 //-----------------------------------------------------------------------------
9 #include "../common/iso14443_crc.c"
12 //static void GetSamplesFor14443(BOOL weTx, int n);
14 #define DMA_BUFFER_SIZE 256
16 //=============================================================================
17 // An ISO 14443 Type B tag. We listen for commands from the reader, using
18 // a UART kind of thing that's implemented in software. When we get a
19 // frame (i.e., a group of bytes between SOF and EOF), we check the CRC.
20 // If it's good, then we can do something appropriate with it, and send
22 //=============================================================================
24 //-----------------------------------------------------------------------------
25 // Code up a string of octets at layer 2 (including CRC, we don't generate
26 // that here) so that they can be transmitted to the reader. Doesn't transmit
27 // them yet, just leaves them ready to send in ToSend[].
28 //-----------------------------------------------------------------------------
29 static void CodeIso14443bAsTag(const BYTE
*cmd
, int len
)
35 // Transmit a burst of ones, as the initial thing that lets the
36 // reader get phase sync. This (TR1) must be > 80/fs, per spec,
37 // but tag that I've tried (a Paypass) exceeds that by a fair bit,
39 for(i
= 0; i
< 20; i
++) {
47 for(i
= 0; i
< 10; i
++) {
53 for(i
= 0; i
< 2; i
++) {
60 for(i
= 0; i
< len
; i
++) {
71 for(j
= 0; j
< 8; j
++) {
94 for(i
= 0; i
< 10; i
++) {
100 for(i
= 0; i
< 10; i
++) {
107 // Convert from last byte pos to length
110 // Add a few more for slop
114 //-----------------------------------------------------------------------------
115 // The software UART that receives commands from the reader, and its state
117 //-----------------------------------------------------------------------------
121 STATE_GOT_FALLING_EDGE_OF_SOF
,
122 STATE_AWAITING_START_BIT
,
123 STATE_RECEIVING_DATA
,
134 static BOOL
Handle14443UartBit(int bit
)
139 // we went low, so this could be the beginning
141 Uart
.state
= STATE_GOT_FALLING_EDGE_OF_SOF
;
147 case STATE_GOT_FALLING_EDGE_OF_SOF
:
149 if(Uart
.posCnt
== 2) {
151 if(Uart
.bitCnt
>= 10) {
152 // we've seen enough consecutive
153 // zeros that it's a valid SOF
156 Uart
.state
= STATE_AWAITING_START_BIT
;
158 // didn't stay down long enough
159 // before going high, error
160 Uart
.state
= STATE_ERROR_WAIT
;
163 // do nothing, keep waiting
167 if(Uart
.posCnt
>= 4) Uart
.posCnt
= 0;
168 if(Uart
.bitCnt
> 14) {
169 // Give up if we see too many zeros without
171 Uart
.state
= STATE_ERROR_WAIT
;
175 case STATE_AWAITING_START_BIT
:
178 if(Uart
.posCnt
> 25) {
179 // stayed high for too long between
181 Uart
.state
= STATE_ERROR_WAIT
;
184 // falling edge, this starts the data byte
188 Uart
.state
= STATE_RECEIVING_DATA
;
192 case STATE_RECEIVING_DATA
:
194 if(Uart
.posCnt
== 2) {
195 // time to sample a bit
198 Uart
.shiftReg
|= 0x200;
202 if(Uart
.posCnt
>= 4) {
205 if(Uart
.bitCnt
== 10) {
206 if((Uart
.shiftReg
& 0x200) && !(Uart
.shiftReg
& 0x001))
208 // this is a data byte, with correct
209 // start and stop bits
210 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
>> 1) & 0xff;
213 if(Uart
.byteCnt
>= Uart
.byteCntMax
) {
214 // Buffer overflowed, give up
216 Uart
.state
= STATE_ERROR_WAIT
;
218 // so get the next byte now
220 Uart
.state
= STATE_AWAITING_START_BIT
;
222 } else if(Uart
.shiftReg
== 0x000) {
223 // this is an EOF byte
228 Uart
.state
= STATE_ERROR_WAIT
;
233 case STATE_ERROR_WAIT
:
234 // We're all screwed up, so wait a little while
235 // for whatever went wrong to finish, and then
238 if(Uart
.posCnt
> 10) {
239 Uart
.state
= STATE_UNSYNCD
;
244 Uart
.state
= STATE_UNSYNCD
;
251 //-----------------------------------------------------------------------------
252 // Receive a command (from the reader to us, where we are the simulated tag),
253 // and store it in the given buffer, up to the given maximum length. Keeps
254 // spinning, waiting for a well-framed command, until either we get one
255 // (returns TRUE) or someone presses the pushbutton on the board (FALSE).
257 // Assume that we're called with the SSC (to the FPGA) and ADC path set
259 //-----------------------------------------------------------------------------
260 static BOOL
GetIso14443CommandFromReader(BYTE
*received
, int *len
, int maxLen
)
265 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
266 // only, since we are receiving, not transmitting).
268 FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
271 // Now run a `software UART' on the stream of incoming samples.
272 Uart
.output
= received
;
273 Uart
.byteCntMax
= maxLen
;
274 Uart
.state
= STATE_UNSYNCD
;
279 if(BUTTON_PRESS()) return FALSE
;
281 if(SSC_STATUS
& (SSC_STATUS_TX_READY
)) {
282 SSC_TRANSMIT_HOLDING
= 0x00;
284 if(SSC_STATUS
& (SSC_STATUS_RX_READY
)) {
285 BYTE b
= (BYTE
)SSC_RECEIVE_HOLDING
;
288 for(i
= 0; i
< 8; i
++, mask
>>= 1) {
290 if(Handle14443UartBit(bit
)) {
299 //-----------------------------------------------------------------------------
300 // Main loop of simulated tag: receive commands from reader, decide what
301 // response to send, and send it.
302 //-----------------------------------------------------------------------------
303 void SimulateIso14443Tag(void)
305 static const BYTE cmd1
[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
306 static const BYTE response1
[] = {
307 0x50, 0x82, 0x0d, 0xe1, 0x74, 0x20, 0x38, 0x19, 0x22,
308 0x00, 0x21, 0x85, 0x5e, 0xd7
314 BYTE
*resp1
= (((BYTE
*)BigBuf
) + 800);
317 BYTE
*receivedCmd
= (BYTE
*)BigBuf
;
324 memset(receivedCmd
, 0x44, 400);
326 CodeIso14443bAsTag(response1
, sizeof(response1
));
327 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
329 // We need to listen to the high-frequency, peak-detected path.
330 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
338 if(!GetIso14443CommandFromReader(receivedCmd
, &len
, 100)) {
339 DbpIntegers(cmdsRecvd
, 0, 0);
340 DbpString("button press");
344 // Good, look at the command now.
346 if(len
== sizeof(cmd1
) && memcmp(receivedCmd
, cmd1
, len
)==0) {
347 resp
= resp1
; respLen
= resp1Len
;
349 DbpString("new cmd from reader:");
350 DbpIntegers(len
, 0x1234, cmdsRecvd
);
351 // And print whether the CRC fails, just for good measure
352 ComputeCrc14443(CRC_14443_B
, receivedCmd
, len
-2, &b1
, &b2
);
353 if(b1
!= receivedCmd
[len
-2] || b2
!= receivedCmd
[len
-1]) {
354 // Not so good, try again.
355 DbpString("+++CRC fail");
357 DbpString("CRC passes");
362 memset(receivedCmd
, 0x44, 32);
366 if(cmdsRecvd
> 0x30) {
367 DbpString("many commands later...");
371 if(respLen
<= 0) continue;
375 FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_MODULATE_BPSK
);
376 SSC_TRANSMIT_HOLDING
= 0xff;
379 // Transmit the response.
382 if(SSC_STATUS
& (SSC_STATUS_TX_READY
)) {
385 SSC_TRANSMIT_HOLDING
= b
;
392 if(SSC_STATUS
& (SSC_STATUS_RX_READY
)) {
393 volatile BYTE b
= (BYTE
)SSC_RECEIVE_HOLDING
;
400 //=============================================================================
401 // An ISO 14443 Type B reader. We take layer two commands, code them
402 // appropriately, and then send them to the tag. We then listen for the
403 // tag's response, which we leave in the buffer to be demodulated on the
405 //=============================================================================
410 DEMOD_PHASE_REF_TRAINING
,
411 DEMOD_AWAITING_FALLING_EDGE_OF_SOF
,
412 DEMOD_GOT_FALLING_EDGE_OF_SOF
,
413 DEMOD_AWAITING_START_BIT
,
414 DEMOD_RECEIVING_DATA
,
429 static BOOL
Handle14443SamplesDemod(int ci
, int cq
)
433 // The soft decision on the bit uses an estimate of just the
434 // quadrant of the reference angle, not the exact angle.
435 #define MAKE_SOFT_DECISION() { \
436 if(Demod.sumI > 0) { \
441 if(Demod.sumQ > 0) { \
448 switch(Demod
.state
) {
459 Demod
.state
= DEMOD_PHASE_REF_TRAINING
;
465 case DEMOD_PHASE_REF_TRAINING
:
466 if(Demod
.posCount
< 8) {
469 } else if(Demod
.posCount
> 100) {
470 // error, waited too long
471 Demod
.state
= DEMOD_UNSYNCD
;
473 MAKE_SOFT_DECISION();
475 Demod
.state
= DEMOD_AWAITING_FALLING_EDGE_OF_SOF
;
482 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF
:
483 MAKE_SOFT_DECISION();
485 Demod
.state
= DEMOD_GOT_FALLING_EDGE_OF_SOF
;
488 if(Demod
.posCount
> 100) {
489 Demod
.state
= DEMOD_UNSYNCD
;
495 case DEMOD_GOT_FALLING_EDGE_OF_SOF
:
496 MAKE_SOFT_DECISION();
498 if(Demod
.posCount
< 12) {
499 Demod
.state
= DEMOD_UNSYNCD
;
501 Demod
.state
= DEMOD_AWAITING_START_BIT
;
508 if(Demod
.posCount
> 100) {
509 Demod
.state
= DEMOD_UNSYNCD
;
515 case DEMOD_AWAITING_START_BIT
:
516 MAKE_SOFT_DECISION();
518 if(Demod
.posCount
> 10) {
519 Demod
.state
= DEMOD_UNSYNCD
;
526 Demod
.state
= DEMOD_RECEIVING_DATA
;
530 case DEMOD_RECEIVING_DATA
:
531 MAKE_SOFT_DECISION();
532 if(Demod
.posCount
== 0) {
538 if(Demod
.thisBit
> 0) {
539 Demod
.metric
+= Demod
.thisBit
;
541 Demod
.metric
-= Demod
.thisBit
;
545 Demod
.shiftReg
>>= 1;
546 if(Demod
.thisBit
> 0) {
547 Demod
.shiftReg
|= 0x200;
551 if(Demod
.bitCount
== 10) {
552 WORD s
= Demod
.shiftReg
;
553 if((s
& 0x200) && !(s
& 0x001)) {
555 Demod
.output
[Demod
.len
] = b
;
557 Demod
.state
= DEMOD_AWAITING_START_BIT
;
558 } else if(s
== 0x000) {
561 Demod
.state
= DEMOD_UNSYNCD
;
563 Demod
.state
= DEMOD_UNSYNCD
;
571 Demod
.state
= DEMOD_UNSYNCD
;
578 static void GetSamplesFor14443Demod(BOOL weTx
, int n
)
581 BOOL gotFrame
= FALSE
;
583 //# define DMA_BUFFER_SIZE 8
593 // Clear out the state of the "UART" that receives from the tag.
594 memset(BigBuf
, 0x44, 400);
595 Demod
.output
= (BYTE
*)BigBuf
;
597 Demod
.state
= DEMOD_UNSYNCD
;
599 // And the UART that receives from the reader
600 Uart
.output
= (((BYTE
*)BigBuf
) + 1024);
601 Uart
.byteCntMax
= 100;
602 Uart
.state
= STATE_UNSYNCD
;
604 // Setup for the DMA.
605 dmaBuf
= (SBYTE
*)(BigBuf
+ 32);
607 lastRxCounter
= DMA_BUFFER_SIZE
;
608 FpgaSetupSscDma((BYTE
*)dmaBuf
, DMA_BUFFER_SIZE
);
610 // And put the FPGA in the appropriate mode
612 FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
|
613 (weTx
? 0 : FPGA_HF_READER_RX_XCORR_SNOOP
));
616 int behindBy
= lastRxCounter
- PDC_RX_COUNTER(SSC_BASE
);
617 if(behindBy
> max
) max
= behindBy
;
620 while(((lastRxCounter
-PDC_RX_COUNTER(SSC_BASE
)) & (DMA_BUFFER_SIZE
-1))
626 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
627 upTo
-= DMA_BUFFER_SIZE
;
628 PDC_RX_NEXT_POINTER(SSC_BASE
) = (DWORD
)upTo
;
629 PDC_RX_NEXT_COUNTER(SSC_BASE
) = DMA_BUFFER_SIZE
;
632 if(lastRxCounter
<= 0) {
633 lastRxCounter
+= DMA_BUFFER_SIZE
;
638 Handle14443UartBit(1);
639 Handle14443UartBit(1);
641 if(Handle14443SamplesDemod(ci
, cq
)) {
651 PDC_CONTROL(SSC_BASE
) = PDC_RX_DISABLE
;
652 DbpIntegers(max
, gotFrame
, -1);
655 //-----------------------------------------------------------------------------
656 // Read the tag's response. We just receive a stream of slightly-processed
657 // samples from the FPGA, which we will later do some signal processing on,
659 //-----------------------------------------------------------------------------
660 /*static void GetSamplesFor14443(BOOL weTx, int n)
662 BYTE *dest = (BYTE *)BigBuf;
666 FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_848_KHZ |
667 (weTx ? 0 : FPGA_HF_READER_RX_XCORR_SNOOP));
671 if(SSC_STATUS & (SSC_STATUS_TX_READY)) {
672 SSC_TRANSMIT_HOLDING = 0x43;
674 if(SSC_STATUS & (SSC_STATUS_RX_READY)) {
676 b = (SBYTE)SSC_RECEIVE_HOLDING;
687 //-----------------------------------------------------------------------------
688 // Transmit the command (to the tag) that was placed in ToSend[].
689 //-----------------------------------------------------------------------------
690 static void TransmitFor14443(void)
696 while(SSC_STATUS
& (SSC_STATUS_TX_READY
)) {
697 SSC_TRANSMIT_HOLDING
= 0xff;
701 FPGA_MAJOR_MODE_HF_READER_TX
| FPGA_HF_READER_TX_SHALLOW_MOD
);
703 for(c
= 0; c
< 10;) {
704 if(SSC_STATUS
& (SSC_STATUS_TX_READY
)) {
705 SSC_TRANSMIT_HOLDING
= 0xff;
708 if(SSC_STATUS
& (SSC_STATUS_RX_READY
)) {
709 volatile DWORD r
= SSC_RECEIVE_HOLDING
;
717 if(SSC_STATUS
& (SSC_STATUS_TX_READY
)) {
718 SSC_TRANSMIT_HOLDING
= ToSend
[c
];
724 if(SSC_STATUS
& (SSC_STATUS_RX_READY
)) {
725 volatile DWORD r
= SSC_RECEIVE_HOLDING
;
732 //-----------------------------------------------------------------------------
733 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
734 // so that it is ready to transmit to the tag using TransmitFor14443().
735 //-----------------------------------------------------------------------------
736 void CodeIso14443bAsReader(const BYTE
*cmd
, int len
)
743 // Establish initial reference level
744 for(i
= 0; i
< 40; i
++) {
748 for(i
= 0; i
< 10; i
++) {
752 for(i
= 0; i
< len
; i
++) {
760 for(j
= 0; j
< 8; j
++) {
771 for(i
= 0; i
< 10; i
++) {
774 for(i
= 0; i
< 8; i
++) {
778 // And then a little more, to make sure that the last character makes
779 // it out before we switch to rx mode.
780 for(i
= 0; i
< 24; i
++) {
784 // Convert from last character reference to length
788 //-----------------------------------------------------------------------------
789 // Read an ISO 14443 tag. We send it some set of commands, and record the
791 //-----------------------------------------------------------------------------
792 void AcquireRawAdcSamplesIso14443(DWORD parameter
)
794 // BYTE cmd1[] = { 0x05, 0x00, 0x00, 0x71, 0xff };
795 BYTE cmd1
[] = { 0x05, 0x00, 0x08, 0x39, 0x73 };
797 // Make sure that we start from off, since the tags are stateful;
798 // confusing things will happen if we don't reset them between reads.
800 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
803 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
806 // Now give it time to spin up.
808 FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
);
811 CodeIso14443bAsReader(cmd1
, sizeof(cmd1
));
814 GetSamplesFor14443Demod(TRUE
, 2000);
818 //=============================================================================
819 // Finally, the `sniffer' combines elements from both the reader and
820 // simulated tag, to show both sides of the conversation.
821 //=============================================================================
823 //-----------------------------------------------------------------------------
824 // Record the sequence of commands sent by the reader to the tag, with
825 // triggering so that we start recording at the point that the tag is moved
827 //-----------------------------------------------------------------------------
828 void SnoopIso14443(void)
830 // We won't start recording the frames that we acquire until we trigger;
831 // a good trigger condition to get started is probably when we see a
832 // response from the tag.
833 BOOL triggered
= FALSE
;
835 // The command (reader -> tag) that we're working on receiving.
836 BYTE
*receivedCmd
= (((BYTE
*)BigBuf
) + 1024);
837 // The response (tag -> reader) that we're working on receiving.
838 BYTE
*receivedResponse
= (((BYTE
*)BigBuf
) + 1536);
840 // As we receive stuff, we copy it from receivedCmd or receivedResponse
841 // into trace, along with its length and other annotations.
842 BYTE
*trace
= (BYTE
*)BigBuf
;
845 // The DMA buffer, used to stream samples from the FPGA.
846 //# define DMA_BUFFER_SIZE 256
847 SBYTE
*dmaBuf
= ((SBYTE
*)BigBuf
) + 2048;
853 // Count of samples received so far, so that we can include timing
854 // information in the trace buffer.
857 memset(trace
, 0x44, 1000);
859 // Set up the demodulator for tag -> reader responses.
860 Demod
.output
= receivedResponse
;
862 Demod
.state
= DEMOD_UNSYNCD
;
864 // And the reader -> tag commands
865 memset(&Uart
, 0, sizeof(Uart
));
866 Uart
.output
= receivedCmd
;
867 Uart
.byteCntMax
= 100;
868 Uart
.state
= STATE_UNSYNCD
;
870 // And put the FPGA in the appropriate mode
872 FPGA_MAJOR_MODE_HF_READER_RX_XCORR
| FPGA_HF_READER_RX_XCORR_848_KHZ
|
873 FPGA_HF_READER_RX_XCORR_SNOOP
);
874 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
876 // Setup for the DMA.
879 lastRxCounter
= DMA_BUFFER_SIZE
;
880 FpgaSetupSscDma((BYTE
*)dmaBuf
, DMA_BUFFER_SIZE
);
884 // And now we loop, receiving samples.
886 int behindBy
= (lastRxCounter
- PDC_RX_COUNTER(SSC_BASE
)) &
888 if(behindBy
> maxBehindBy
) {
889 maxBehindBy
= behindBy
;
891 DbpString("blew circular buffer!");
895 if(behindBy
< 2) continue;
901 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
902 upTo
-= DMA_BUFFER_SIZE
;
903 lastRxCounter
+= DMA_BUFFER_SIZE
;
904 PDC_RX_NEXT_POINTER(SSC_BASE
) = (DWORD
)upTo
;
905 PDC_RX_NEXT_COUNTER(SSC_BASE
) = DMA_BUFFER_SIZE
;
910 #define HANDLE_BIT_IF_BODY \
912 trace[traceLen++] = ((samples >> 0) & 0xff); \
913 trace[traceLen++] = ((samples >> 8) & 0xff); \
914 trace[traceLen++] = ((samples >> 16) & 0xff); \
915 trace[traceLen++] = ((samples >> 24) & 0xff); \
916 trace[traceLen++] = 0; \
917 trace[traceLen++] = 0; \
918 trace[traceLen++] = 0; \
919 trace[traceLen++] = 0; \
920 trace[traceLen++] = Uart.byteCnt; \
921 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt); \
922 traceLen += Uart.byteCnt; \
923 if(traceLen > 1000) break; \
925 /* And ready to receive another command. */ \
926 memset(&Uart, 0, sizeof(Uart)); \
927 Uart.output = receivedCmd; \
928 Uart.byteCntMax = 100; \
929 Uart.state = STATE_UNSYNCD; \
930 /* And also reset the demod code, which might have been */ \
931 /* false-triggered by the commands from the reader. */ \
932 memset(&Demod, 0, sizeof(Demod)); \
933 Demod.output = receivedResponse; \
934 Demod.state = DEMOD_UNSYNCD; \
936 if(Handle14443UartBit(ci & 1)) {
939 if(Handle14443UartBit(cq
& 1)) {
943 if(Handle14443SamplesDemod(ci
, cq
)) {
944 // timestamp, as a count of samples
945 trace
[traceLen
++] = ((samples
>> 0) & 0xff);
946 trace
[traceLen
++] = ((samples
>> 8) & 0xff);
947 trace
[traceLen
++] = ((samples
>> 16) & 0xff);
948 trace
[traceLen
++] = 0x80 | ((samples
>> 24) & 0xff);
949 // correlation metric (~signal strength estimate)
950 if(Demod
.metricN
!= 0) {
951 Demod
.metric
/= Demod
.metricN
;
953 trace
[traceLen
++] = ((Demod
.metric
>> 0) & 0xff);
954 trace
[traceLen
++] = ((Demod
.metric
>> 8) & 0xff);
955 trace
[traceLen
++] = ((Demod
.metric
>> 16) & 0xff);
956 trace
[traceLen
++] = ((Demod
.metric
>> 24) & 0xff);
958 trace
[traceLen
++] = Demod
.len
;
959 memcpy(trace
+traceLen
, receivedResponse
, Demod
.len
);
960 traceLen
+= Demod
.len
;
961 if(traceLen
> 1000) break;
967 // And ready to receive another response.
968 memset(&Demod
, 0, sizeof(Demod
));
969 Demod
.output
= receivedResponse
;
970 Demod
.state
= DEMOD_UNSYNCD
;
974 DbpString("cancelled");
979 DbpString("in done pt");
981 DbpIntegers(maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
982 DbpIntegers(Uart
.byteCntMax
, traceLen
, 0x23);
985 PDC_CONTROL(SSC_BASE
) = PDC_RX_DISABLE
;