1 //-----------------------------------------------------------------------------
2 // Routines to support ISO 14443 type A.
4 // Gerhard de Koning Gans - May 2008
5 //-----------------------------------------------------------------------------
8 #include "../common/iso14443_crc.c"
10 static BYTE
*trace
= (BYTE
*) BigBuf
;
11 static int traceLen
= 0;
12 static int rsamples
= 0;
23 static const BYTE OddByteParity
[256] = {
24 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
25 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
26 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
27 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
28 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
29 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
30 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
31 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
32 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
33 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
34 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
35 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
36 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
37 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
38 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
39 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
42 // BIG CHANGE - UNDERSTAND THIS BEFORE WE COMMIT
43 #define RECV_CMD_OFFSET 3032
44 #define RECV_RES_OFFSET 3096
45 #define DMA_BUFFER_OFFSET 3160
46 #define DMA_BUFFER_SIZE 4096
47 #define TRACE_LENGTH 3000
49 //-----------------------------------------------------------------------------
50 // Generate the parity value for a byte sequence
52 //-----------------------------------------------------------------------------
53 DWORD
GetParity(const BYTE
* pbtCmd
, int iLen
)
58 // Generate the encrypted data
59 for (i
= 0; i
< iLen
; i
++) {
60 // Save the encrypted parity bit
61 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
66 static void AppendCrc14443a(BYTE
* data
, int len
)
68 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
71 BOOL
LogTrace(const BYTE
* btBytes
, int iLen
, int iSamples
, DWORD dwParity
, BOOL bReader
)
73 // Return when trace is full
74 if (traceLen
>= TRACE_LENGTH
) return FALSE
;
76 // Trace the random, i'm curious
78 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
79 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
80 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
81 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
83 trace
[traceLen
- 1] |= 0x80;
85 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
86 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
87 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
88 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
89 trace
[traceLen
++] = iLen
;
90 memcpy(trace
+ traceLen
, btBytes
, iLen
);
95 //-----------------------------------------------------------------------------
96 // The software UART that receives commands from the reader, and its state
98 //-----------------------------------------------------------------------------
102 STATE_START_OF_COMMUNICATION
,
126 static BOOL
MillerDecoding(int bit
)
131 if(!Uart
.bitBuffer
) {
132 Uart
.bitBuffer
= bit
^ 0xFF0;
136 Uart
.bitBuffer
<<= 4;
137 Uart
.bitBuffer
^= bit
;
142 if(Uart
.state
!= STATE_UNSYNCD
) {
145 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
151 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
157 if(bit
!= bitright
) { bit
= bitright
; }
159 if(Uart
.posCnt
== 1) {
160 // measurement first half bitperiod
162 Uart
.drop
= DROP_FIRST_HALF
;
166 // measurement second half bitperiod
167 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
168 Uart
.drop
= DROP_SECOND_HALF
;
171 // measured a drop in first and second half
172 // which should not be possible
173 Uart
.state
= STATE_ERROR_WAIT
;
180 case STATE_START_OF_COMMUNICATION
:
182 if(Uart
.drop
== DROP_SECOND_HALF
) {
183 // error, should not happen in SOC
184 Uart
.state
= STATE_ERROR_WAIT
;
189 Uart
.state
= STATE_MILLER_Z
;
196 if(Uart
.drop
== DROP_NONE
) {
197 // logic '0' followed by sequence Y
198 // end of communication
199 Uart
.state
= STATE_UNSYNCD
;
202 // if(Uart.drop == DROP_FIRST_HALF) {
203 // Uart.state = STATE_MILLER_Z; stay the same
204 // we see a logic '0' }
205 if(Uart
.drop
== DROP_SECOND_HALF
) {
206 // we see a logic '1'
207 Uart
.shiftReg
|= 0x100;
208 Uart
.state
= STATE_MILLER_X
;
214 if(Uart
.drop
== DROP_NONE
) {
215 // sequence Y, we see a '0'
216 Uart
.state
= STATE_MILLER_Y
;
219 if(Uart
.drop
== DROP_FIRST_HALF
) {
220 // Would be STATE_MILLER_Z
221 // but Z does not follow X, so error
222 Uart
.state
= STATE_ERROR_WAIT
;
225 if(Uart
.drop
== DROP_SECOND_HALF
) {
226 // We see a '1' and stay in state X
227 Uart
.shiftReg
|= 0x100;
235 if(Uart
.drop
== DROP_NONE
) {
236 // logic '0' followed by sequence Y
237 // end of communication
238 Uart
.state
= STATE_UNSYNCD
;
241 if(Uart
.drop
== DROP_FIRST_HALF
) {
243 Uart
.state
= STATE_MILLER_Z
;
245 if(Uart
.drop
== DROP_SECOND_HALF
) {
246 // We see a '1' and go to state X
247 Uart
.shiftReg
|= 0x100;
248 Uart
.state
= STATE_MILLER_X
;
252 case STATE_ERROR_WAIT
:
253 // That went wrong. Now wait for at least two bit periods
254 // and try to sync again
255 if(Uart
.drop
== DROP_NONE
) {
257 Uart
.state
= STATE_UNSYNCD
;
262 Uart
.state
= STATE_UNSYNCD
;
267 Uart
.drop
= DROP_NONE
;
269 // should have received at least one whole byte...
270 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
274 if(Uart
.bitCnt
== 9) {
275 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
278 Uart
.parityBits
<<= 1;
279 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
282 // when End of Communication received and
283 // all data bits processed..
290 Uart.output[Uart.byteCnt] = 0xAA;
292 Uart.output[Uart.byteCnt] = error & 0xFF;
294 Uart.output[Uart.byteCnt] = 0xAA;
296 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
298 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
300 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
302 Uart.output[Uart.byteCnt] = 0xAA;
310 bit
= Uart
.bitBuffer
& 0xf0;
314 // should have been high or at least (4 * 128) / fc
315 // according to ISO this should be at least (9 * 128 + 20) / fc
316 if(Uart
.highCnt
== 8) {
317 // we went low, so this could be start of communication
318 // it turns out to be safer to choose a less significant
319 // syncbit... so we check whether the neighbour also represents the drop
320 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
321 Uart
.syncBit
= bit
& 8;
323 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
324 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
325 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
326 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
327 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
328 if(Uart
.syncBit
& (Uart
.bitBuffer
& 8)) {
331 // the first half bit period is expected in next sample
336 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
339 Uart
.state
= STATE_START_OF_COMMUNICATION
;
340 Uart
.drop
= DROP_FIRST_HALF
;
351 if(Uart
.highCnt
< 8) {
360 //=============================================================================
361 // ISO 14443 Type A - Manchester
362 //=============================================================================
367 DEMOD_START_OF_COMMUNICATION
,
390 static BOOL
ManchesterDecoding(int v
)
406 if(Demod
.state
==DEMOD_UNSYNCD
) {
407 Demod
.output
[Demod
.len
] = 0xfa;
410 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
411 if(bit
& 0x08) { Demod
.syncBit
= 0x08; }
413 if(bit
& 0x04) { Demod
.syncBit
= 0x04; }
415 else if(bit
& 0x04) { Demod
.syncBit
= 0x04; bit
<<= 4; }
417 if(bit
& 0x02) { Demod
.syncBit
= 0x02; }
419 else if(bit
& 0x02) { Demod
.syncBit
= 0x02; bit
<<= 4; }
421 if(bit
& 0x01) { Demod
.syncBit
= 0x01; }
423 if(Demod
.syncBit
& (Demod
.buffer
& 0x08)) {
424 Demod
.syncBit
= 0x08;
426 // The first half bitperiod is expected in next sample
428 Demod
.output
[Demod
.len
] = 0xfb;
431 else if(bit
& 0x01) { Demod
.syncBit
= 0x01; }
435 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
436 Demod
.sub
= SUB_FIRST_HALF
;
439 Demod
.parityBits
= 0;
442 switch(Demod
.syncBit
) {
443 case 0x08: Demod
.samples
= 3; break;
444 case 0x04: Demod
.samples
= 2; break;
445 case 0x02: Demod
.samples
= 1; break;
446 case 0x01: Demod
.samples
= 0; break;
453 //modulation = bit & Demod.syncBit;
454 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
458 if(Demod
.posCount
==0) {
461 Demod
.sub
= SUB_FIRST_HALF
;
464 Demod
.sub
= SUB_NONE
;
469 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
470 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
471 Demod
.state
= DEMOD_ERROR_WAIT
;
472 Demod
.output
[Demod
.len
] = 0xaa;
476 else if(modulation
) {
477 Demod
.sub
= SUB_SECOND_HALF
;
480 switch(Demod
.state
) {
481 case DEMOD_START_OF_COMMUNICATION
:
482 if(Demod
.sub
== SUB_FIRST_HALF
) {
483 Demod
.state
= DEMOD_MANCHESTER_D
;
486 Demod
.output
[Demod
.len
] = 0xab;
487 Demod
.state
= DEMOD_ERROR_WAIT
;
492 case DEMOD_MANCHESTER_D
:
493 case DEMOD_MANCHESTER_E
:
494 if(Demod
.sub
== SUB_FIRST_HALF
) {
496 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
497 Demod
.state
= DEMOD_MANCHESTER_D
;
499 else if(Demod
.sub
== SUB_SECOND_HALF
) {
501 Demod
.shiftReg
>>= 1;
502 Demod
.state
= DEMOD_MANCHESTER_E
;
505 Demod
.state
= DEMOD_MANCHESTER_F
;
509 case DEMOD_MANCHESTER_F
:
510 // Tag response does not need to be a complete byte!
511 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
512 if(Demod
.bitCount
> 0) {
513 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
514 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
516 // No parity bit, so just shift a 0
517 Demod
.parityBits
<<= 1;
520 Demod
.state
= DEMOD_UNSYNCD
;
524 Demod
.output
[Demod
.len
] = 0xad;
525 Demod
.state
= DEMOD_ERROR_WAIT
;
530 case DEMOD_ERROR_WAIT
:
531 Demod
.state
= DEMOD_UNSYNCD
;
535 Demod
.output
[Demod
.len
] = 0xdd;
536 Demod
.state
= DEMOD_UNSYNCD
;
540 if(Demod
.bitCount
>=9) {
541 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
544 Demod
.parityBits
<<= 1;
545 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
552 Demod.output[Demod.len] = 0xBB;
554 Demod.output[Demod.len] = error & 0xFF;
556 Demod.output[Demod.len] = 0xBB;
558 Demod.output[Demod.len] = bit & 0xFF;
560 Demod.output[Demod.len] = Demod.buffer & 0xFF;
562 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
564 Demod.output[Demod.len] = 0xBB;
571 } // end (state != UNSYNCED)
576 //=============================================================================
577 // Finally, a `sniffer' for ISO 14443 Type A
578 // Both sides of communication!
579 //=============================================================================
581 //-----------------------------------------------------------------------------
582 // Record the sequence of commands sent by the reader to the tag, with
583 // triggering so that we start recording at the point that the tag is moved
585 //-----------------------------------------------------------------------------
586 void SnoopIso14443a(void)
588 // #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
589 // #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
590 // #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
591 // #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
592 // #define TRACE_LENGTH 2000 // original (working as of 21/2/09) values
594 // We won't start recording the frames that we acquire until we trigger;
595 // a good trigger condition to get started is probably when we see a
596 // response from the tag.
597 BOOL triggered
= TRUE
; // FALSE to wait first for card
599 // The command (reader -> tag) that we're receiving.
600 // The length of a received command will in most cases be no more than 18 bytes.
601 // So 32 should be enough!
602 BYTE
*receivedCmd
= (((BYTE
*)BigBuf
) + RECV_CMD_OFFSET
);
603 // The response (tag -> reader) that we're receiving.
604 BYTE
*receivedResponse
= (((BYTE
*)BigBuf
) + RECV_RES_OFFSET
);
606 // As we receive stuff, we copy it from receivedCmd or receivedResponse
607 // into trace, along with its length and other annotations.
608 //BYTE *trace = (BYTE *)BigBuf;
611 // The DMA buffer, used to stream samples from the FPGA
612 SBYTE
*dmaBuf
= ((SBYTE
*)BigBuf
) + DMA_BUFFER_OFFSET
;
618 // Count of samples received so far, so that we can include timing
619 // information in the trace buffer.
623 memset(trace
, 0x44, RECV_CMD_OFFSET
);
625 // Set up the demodulator for tag -> reader responses.
626 Demod
.output
= receivedResponse
;
628 Demod
.state
= DEMOD_UNSYNCD
;
630 // And the reader -> tag commands
631 memset(&Uart
, 0, sizeof(Uart
));
632 Uart
.output
= receivedCmd
;
633 Uart
.byteCntMax
= 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
634 Uart
.state
= STATE_UNSYNCD
;
636 // And put the FPGA in the appropriate mode
637 // Signal field is off with the appropriate LED
639 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
640 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
642 // Setup for the DMA.
645 lastRxCounter
= DMA_BUFFER_SIZE
;
646 FpgaSetupSscDma((BYTE
*)dmaBuf
, DMA_BUFFER_SIZE
);
650 // And now we loop, receiving samples.
653 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) &
655 if(behindBy
> maxBehindBy
) {
656 maxBehindBy
= behindBy
;
658 DbpString("blew circular buffer!");
662 if(behindBy
< 1) continue;
667 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
668 upTo
-= DMA_BUFFER_SIZE
;
669 lastRxCounter
+= DMA_BUFFER_SIZE
;
670 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (DWORD
)upTo
;
671 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
675 #define HANDLE_BIT_IF_BODY \
678 trace[traceLen++] = ((rsamples >> 0) & 0xff); \
679 trace[traceLen++] = ((rsamples >> 8) & 0xff); \
680 trace[traceLen++] = ((rsamples >> 16) & 0xff); \
681 trace[traceLen++] = ((rsamples >> 24) & 0xff); \
682 trace[traceLen++] = ((Uart.parityBits >> 0) & 0xff); \
683 trace[traceLen++] = ((Uart.parityBits >> 8) & 0xff); \
684 trace[traceLen++] = ((Uart.parityBits >> 16) & 0xff); \
685 trace[traceLen++] = ((Uart.parityBits >> 24) & 0xff); \
686 trace[traceLen++] = Uart.byteCnt; \
687 memcpy(trace+traceLen, receivedCmd, Uart.byteCnt); \
688 traceLen += Uart.byteCnt; \
689 if(traceLen > TRACE_LENGTH) break; \
691 /* And ready to receive another command. */ \
692 Uart.state = STATE_UNSYNCD; \
693 /* And also reset the demod code, which might have been */ \
694 /* false-triggered by the commands from the reader. */ \
695 Demod.state = DEMOD_UNSYNCD; \
698 if(MillerDecoding((smpl & 0xF0) >> 4)) {
699 rsamples
= samples
- Uart
.samples
;
702 if(ManchesterDecoding(smpl
& 0x0F)) {
703 rsamples
= samples
- Demod
.samples
;
706 // timestamp, as a count of samples
707 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
708 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
709 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
710 trace
[traceLen
++] = 0x80 | ((rsamples
>> 24) & 0xff);
711 trace
[traceLen
++] = ((Demod
.parityBits
>> 0) & 0xff);
712 trace
[traceLen
++] = ((Demod
.parityBits
>> 8) & 0xff);
713 trace
[traceLen
++] = ((Demod
.parityBits
>> 16) & 0xff);
714 trace
[traceLen
++] = ((Demod
.parityBits
>> 24) & 0xff);
716 trace
[traceLen
++] = Demod
.len
;
717 memcpy(trace
+traceLen
, receivedResponse
, Demod
.len
);
718 traceLen
+= Demod
.len
;
719 if(traceLen
> TRACE_LENGTH
) break;
723 // And ready to receive another response.
724 memset(&Demod
, 0, sizeof(Demod
));
725 Demod
.output
= receivedResponse
;
726 Demod
.state
= DEMOD_UNSYNCD
;
731 DbpString("cancelled_a");
736 DbpString("COMMAND FINISHED");
738 DbpIntegers(maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
739 DbpIntegers(Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
742 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
743 DbpIntegers(maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
744 DbpIntegers(Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
751 // Prepare communication bits to send to FPGA
752 void Sequence(SecType seq
)
758 // Sequence D: 11110000
759 // modulation with subcarrier during first half
760 ToSend
[ToSendMax
] = 0xf0;
763 // Sequence E: 00001111
764 // modulation with subcarrier during second half
765 ToSend
[ToSendMax
] = 0x0f;
768 // Sequence F: 00000000
769 // no modulation with subcarrier
770 ToSend
[ToSendMax
] = 0x00;
774 // Sequence X: 00001100
775 // drop after half a period
776 ToSend
[ToSendMax
] = 0x0c;
780 // Sequence Y: 00000000
782 ToSend
[ToSendMax
] = 0x00;
785 // Sequence Z: 11000000
787 ToSend
[ToSendMax
] = 0xc0;
792 //-----------------------------------------------------------------------------
793 // Prepare tag messages
794 //-----------------------------------------------------------------------------
795 static void CodeIso14443aAsTag(const BYTE
*cmd
, int len
)
802 // Correction bit, might be removed when not needed
807 ToSendStuffBit(1); // 1
815 for(i
= 0; i
< len
; i
++) {
821 for(j
= 0; j
< 8; j
++) {
822 oddparity
^= (b
& 1);
842 // Flush the buffer in FPGA!!
843 for(i
= 0; i
< 5; i
++) {
847 // Convert from last byte pos to length
850 // Add a few more for slop
851 ToSend
[ToSendMax
++] = 0x00;
852 ToSend
[ToSendMax
++] = 0x00;
856 //-----------------------------------------------------------------------------
857 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
858 //-----------------------------------------------------------------------------
859 static void CodeStrangeAnswer()
865 // Correction bit, might be removed when not needed
870 ToSendStuffBit(1); // 1
890 // Flush the buffer in FPGA!!
891 for(i
= 0; i
< 5; i
++) {
895 // Convert from last byte pos to length
898 // Add a few more for slop
899 ToSend
[ToSendMax
++] = 0x00;
900 ToSend
[ToSendMax
++] = 0x00;
904 //-----------------------------------------------------------------------------
905 // Wait for commands from reader
906 // Stop when button is pressed
907 // Or return TRUE when command is captured
908 //-----------------------------------------------------------------------------
909 static BOOL
GetIso14443aCommandFromReader(BYTE
*received
, int *len
, int maxLen
)
911 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
912 // only, since we are receiving, not transmitting).
913 // Signal field is off with the appropriate LED
915 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
917 // Now run a `software UART' on the stream of incoming samples.
918 Uart
.output
= received
;
919 Uart
.byteCntMax
= maxLen
;
920 Uart
.state
= STATE_UNSYNCD
;
925 if(BUTTON_PRESS()) return FALSE
;
927 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
928 AT91C_BASE_SSC
->SSC_THR
= 0x00;
930 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
931 BYTE b
= (BYTE
)AT91C_BASE_SSC
->SSC_RHR
;
932 if(MillerDecoding((b
& 0xf0) >> 4)) {
936 if(MillerDecoding(b
& 0x0f)) {
944 //-----------------------------------------------------------------------------
945 // Main loop of simulated tag: receive commands from reader, decide what
946 // response to send, and send it.
947 //-----------------------------------------------------------------------------
948 void SimulateIso14443aTag(int tagType
, int TagUid
)
950 // This function contains the tag emulation
952 // Prepare protocol messages
953 // static const BYTE cmd1[] = { 0x26 };
954 // static const BYTE response1[] = { 0x02, 0x00 }; // Says: I am Mifare 4k - original line - greg
956 static const BYTE response1
[] = { 0x44, 0x03 }; // Says: I am a DESFire Tag, ph33r me
957 // static const BYTE response1[] = { 0x44, 0x00 }; // Says: I am a ULTRALITE Tag, 0wn me
960 // static const BYTE cmd2[] = { 0x93, 0x20 };
961 //static const BYTE response2[] = { 0x9a, 0xe5, 0xe4, 0x43, 0xd8 }; // original value - greg
966 static const BYTE response2
[] = { 0x88, 0x04, 0x21, 0x3f, 0x4d }; // known uid - note cascade (0x88), 2nd byte (0x04) = NXP/Phillips
969 // When reader selects us during cascade1 it will send cmd3
970 //BYTE response3[] = { 0x04, 0x00, 0x00 }; // SAK Select (cascade1) successful response (ULTRALITE)
971 BYTE response3
[] = { 0x24, 0x00, 0x00 }; // SAK Select (cascade1) successful response (DESFire)
972 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
974 // send cascade2 2nd half of UID
975 static const BYTE response2a
[] = { 0x51, 0x48, 0x1d, 0x80, 0x84 }; // uid - cascade2 - 2nd half (4 bytes) of UID+ BCCheck
976 // NOTE : THE CRC on the above may be wrong as I have obfuscated the actual UID
979 // When reader selects us during cascade2 it will send cmd3a
980 //BYTE response3a[] = { 0x00, 0x00, 0x00 }; // SAK Select (cascade2) successful response (ULTRALITE)
981 BYTE response3a
[] = { 0x20, 0x00, 0x00 }; // SAK Select (cascade2) successful response (DESFire)
982 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
984 static const BYTE response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
989 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
991 // 144 data bits (18 * 8)
994 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
995 // 1 just for the case
999 // 166 bytes, since every bit that needs to be send costs us a byte
1003 // Respond with card type
1004 BYTE
*resp1
= (((BYTE
*)BigBuf
) + 800);
1007 // Anticollision cascade1 - respond with uid
1008 BYTE
*resp2
= (((BYTE
*)BigBuf
) + 970);
1011 // Anticollision cascade2 - respond with 2nd half of uid if asked
1012 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1013 BYTE
*resp2a
= (((BYTE
*)BigBuf
) + 1140);
1016 // Acknowledge select - cascade 1
1017 BYTE
*resp3
= (((BYTE
*)BigBuf
) + 1310);
1020 // Acknowledge select - cascade 2
1021 BYTE
*resp3a
= (((BYTE
*)BigBuf
) + 1480);
1024 // Response to a read request - not implemented atm
1025 BYTE
*resp4
= (((BYTE
*)BigBuf
) + 1550);
1028 // Authenticate response - nonce
1029 BYTE
*resp5
= (((BYTE
*)BigBuf
) + 1720);
1032 BYTE
*receivedCmd
= (BYTE
*)BigBuf
;
1039 // To control where we are in the protocol
1043 // Just to allow some checks
1051 memset(receivedCmd
, 0x44, 400);
1053 // Prepare the responses of the anticollision phase
1054 // there will be not enough time to do this at the moment the reader sends it REQA
1056 // Answer to request
1057 CodeIso14443aAsTag(response1
, sizeof(response1
));
1058 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1060 // Send our UID (cascade 1)
1061 CodeIso14443aAsTag(response2
, sizeof(response2
));
1062 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1064 // Answer to select (cascade1)
1065 CodeIso14443aAsTag(response3
, sizeof(response3
));
1066 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1068 // Send the cascade 2 2nd part of the uid
1069 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1070 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1072 // Answer to select (cascade 2)
1073 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1074 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1076 // Strange answer is an example of rare message size (3 bits)
1077 CodeStrangeAnswer();
1078 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1080 // Authentication answer (random nonce)
1081 CodeIso14443aAsTag(response5
, sizeof(response5
));
1082 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1084 // We need to listen to the high-frequency, peak-detected path.
1085 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1093 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, 100)) {
1094 DbpString("button press");
1097 // doob - added loads of debug strings so we can see what the reader is saying to us during the sim as hi14alist is not populated
1098 // Okay, look at the command now.
1100 i
= 1; // first byte transmitted
1101 if(receivedCmd
[0] == 0x26) {
1102 // Received a REQUEST
1103 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1104 //DbpString("Hello request from reader:");
1105 } else if(receivedCmd
[0] == 0x52) {
1106 // Received a WAKEUP
1107 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1108 // //DbpString("Wakeup request from reader:");
1110 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // greg - cascade 1 anti-collision
1111 // Received request for UID (cascade 1)
1112 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1113 // DbpString("UID (cascade 1) request from reader:");
1114 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1117 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] ==0x95) { // greg - cascade 2 anti-collision
1118 // Received request for UID (cascade 2)
1119 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1120 // DbpString("UID (cascade 2) request from reader:");
1121 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1124 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x93) { // greg - cascade 1 select
1125 // Received a SELECT
1126 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1127 // DbpString("Select (cascade 1) request from reader:");
1128 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1131 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x95) { // greg - cascade 2 select
1132 // Received a SELECT
1133 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1134 // DbpString("Select (cascade 2) request from reader:");
1135 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1138 } else if(receivedCmd
[0] == 0x30) {
1140 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1141 DbpString("Read request from reader:");
1142 DbpIntegers(receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1145 } else if(receivedCmd
[0] == 0x50) {
1147 resp
= resp1
; respLen
= 0; order
= 5; // Do nothing
1148 DbpString("Reader requested we HALT!:");
1150 } else if(receivedCmd
[0] == 0x60) {
1151 // Received an authentication request
1152 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1153 DbpString("Authenticate request from reader:");
1154 DbpIntegers(receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1156 } else if(receivedCmd
[0] == 0xE0) {
1157 // Received a RATS request
1158 resp
= resp1
; respLen
= 0;order
= 70;
1159 DbpString("RATS request from reader:");
1160 DbpIntegers(receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1162 // Never seen this command before
1163 DbpString("Unknown command received from reader:");
1164 DbpIntegers(receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1165 DbpIntegers(receivedCmd
[3], receivedCmd
[4], receivedCmd
[5]);
1166 DbpIntegers(receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1169 resp
= resp1
; respLen
= 0; order
= 0;
1172 // Count number of wakeups received after a halt
1173 if(order
== 6 && lastorder
== 5) { happened
++; }
1175 // Count number of other messages after a halt
1176 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1178 // Look at last parity bit to determine timing of answer
1179 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1180 // 1236, so correction bit needed
1184 memset(receivedCmd
, 0x44, 32);
1186 if(cmdsRecvd
> 999) {
1187 DbpString("1000 commands later...");
1194 if(respLen
<= 0) continue;
1196 // Modulate Manchester
1197 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1198 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1201 // ### Transmit the response ###
1204 fdt_indicator
= FALSE
;
1206 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1207 volatile BYTE b
= (BYTE
)AT91C_BASE_SSC
->SSC_RHR
;
1210 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1218 AT91C_BASE_SSC
->SSC_THR
= b
;
1224 if(BUTTON_PRESS()) {
1231 DbpIntegers(happened
, happened2
, cmdsRecvd
);
1235 //-----------------------------------------------------------------------------
1236 // Transmit the command (to the tag) that was placed in ToSend[].
1237 //-----------------------------------------------------------------------------
1238 static void TransmitFor14443a(const BYTE
*cmd
, int len
, int *samples
, int *wait
)
1242 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1248 for(c
= 0; c
< *wait
;) {
1249 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1250 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1253 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1254 volatile DWORD r
= AT91C_BASE_SSC
->SSC_RHR
;
1262 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1263 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1269 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1270 volatile DWORD r
= AT91C_BASE_SSC
->SSC_RHR
;
1275 if (samples
) *samples
= (c
+ *wait
) << 3;
1278 //-----------------------------------------------------------------------------
1279 // To generate an arbitrary stream from reader
1281 //-----------------------------------------------------------------------------
1282 void ArbitraryFromReader(const BYTE
*cmd
, int parity
, int len
)
1291 // Start of Communication (Seq. Z)
1295 for(i
= 0; i
< len
; i
++) {
1298 for(j
= 0; j
< 8; j
++) {
1318 // Predefined parity bit, the flipper flips when needed, because of flips in byte sent
1319 if(((parity
>> (len
- i
- 1)) & 1)) {
1336 // End of Communication
1354 // Convert from last character reference to length
1358 //-----------------------------------------------------------------------------
1359 // Code a 7-bit command without parity bit
1360 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1361 //-----------------------------------------------------------------------------
1362 void ShortFrameFromReader(const BYTE bt
)
1370 // Start of Communication (Seq. Z)
1375 for(j
= 0; j
< 7; j
++) {
1394 // End of Communication
1412 // Convert from last character reference to length
1416 //-----------------------------------------------------------------------------
1417 // Prepare reader command to send to FPGA
1419 //-----------------------------------------------------------------------------
1420 void CodeIso14443aAsReaderPar(const BYTE
* cmd
, int len
, DWORD dwParity
)
1428 // Start of Communication (Seq. Z)
1432 // Generate send structure for the data bits
1433 for (i
= 0; i
< len
; i
++) {
1434 // Get the current byte to send
1437 for (j
= 0; j
< 8; j
++) {
1455 // Get the parity bit
1456 if ((dwParity
>> i
) & 0x01) {
1472 // End of Communication
1489 // Convert from last character reference to length
1493 //-----------------------------------------------------------------------------
1494 // Wait a certain time for tag response
1495 // If a response is captured return TRUE
1496 // If it takes to long return FALSE
1497 //-----------------------------------------------------------------------------
1498 static BOOL
GetIso14443aAnswerFromTag(BYTE
*receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //BYTE *buffer
1500 // buffer needs to be 512 bytes
1503 // Set FPGA mode to "reader listen mode", no modulation (listen
1504 // only, since we are receiving, not transmitting).
1505 // Signal field is on with the appropriate LED
1507 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1509 // Now get the answer from the card
1510 Demod
.output
= receivedResponse
;
1512 Demod
.state
= DEMOD_UNSYNCD
;
1515 if (elapsed
) *elapsed
= 0;
1521 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1522 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1523 if (elapsed
) (*elapsed
)++;
1525 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1526 if(c
< 512) { c
++; } else { return FALSE
; }
1527 b
= (BYTE
)AT91C_BASE_SSC
->SSC_RHR
;
1528 if(ManchesterDecoding((b
& 0xf0) >> 4)) {
1529 *samples
= ((c
- 1) << 3) + 4;
1532 if(ManchesterDecoding(b
& 0x0f)) {
1540 void ReaderTransmitShort(const BYTE
* bt
)
1545 ShortFrameFromReader(*bt
);
1548 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1550 // Store reader command in buffer
1551 LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1554 void ReaderTransmitPar(BYTE
* frame
, int len
, DWORD par
)
1559 // This is tied to other size changes
1560 // BYTE* frame_addr = ((BYTE*)BigBuf) + 2024;
1562 CodeIso14443aAsReaderPar(frame
,len
,par
);
1565 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1567 // Store reader command in buffer
1568 LogTrace(frame
,len
,0,par
,TRUE
);
1572 void ReaderTransmit(BYTE
* frame
, int len
)
1574 // Generate parity and redirect
1575 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1578 BOOL
ReaderReceive(BYTE
* receivedAnswer
)
1581 if (!GetIso14443aAnswerFromTag(receivedAnswer
,100,&samples
,0)) return FALSE
;
1582 LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1586 //-----------------------------------------------------------------------------
1587 // Read an ISO 14443a tag. Send out commands and store answers.
1589 //-----------------------------------------------------------------------------
1590 void ReaderIso14443a(DWORD parameter
)
1593 BYTE wupa
[] = { 0x52 };
1594 BYTE sel_all
[] = { 0x93,0x20 };
1595 BYTE sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1596 BYTE sel_all_c2
[] = { 0x95,0x20 };
1597 BYTE sel_uid_c2
[] = { 0x95,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1600 BYTE mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1601 // BYTE mf_nr_ar[] = { 0x00,0x00,0x00,0x00 };
1603 BYTE
* receivedAnswer
= (((BYTE
*)BigBuf
) + 3560); // was 3560 - tied to other size changes
1609 // Start from off (no field generated)
1610 // Signal field is off with the appropriate LED
1612 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1615 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1618 // Now give it time to spin up.
1619 // Signal field is on with the appropriate LED
1621 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1628 while(traceLen
< TRACE_LENGTH
)
1630 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1631 ReaderTransmitShort(wupa
);
1633 // Test if the action was cancelled
1634 if(BUTTON_PRESS()) {
1639 if (!ReaderReceive(receivedAnswer
)) continue;
1641 // Transmit SELECT_ALL
1642 ReaderTransmit(sel_all
,sizeof(sel_all
));
1645 if (!ReaderReceive(receivedAnswer
)) continue;
1647 // Construct SELECT UID command
1648 // First copy the 5 bytes (Mifare Classic) after the 93 70
1649 memcpy(sel_uid
+2,receivedAnswer
,5);
1650 // Secondly compute the two CRC bytes at the end
1651 AppendCrc14443a(sel_uid
,7);
1653 // Transmit SELECT_UID
1654 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1657 if (!ReaderReceive(receivedAnswer
)) continue;
1659 // OK we have selected at least at cascade 1, lets see if first byte of UID was 0x88 in
1660 // which case we need to make a cascade 2 request and select - this is a long UID
1661 // When the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1662 if (receivedAnswer
[0] &= 0x04)
1664 // Transmit SELECT_ALL
1665 ReaderTransmit(sel_all_c2
,sizeof(sel_all_c2
));
1668 if (!ReaderReceive(receivedAnswer
)) continue;
1670 // Construct SELECT UID command
1671 memcpy(sel_uid_c2
+2,receivedAnswer
,5);
1672 // Secondly compute the two CRC bytes at the end
1673 AppendCrc14443a(sel_uid_c2
,7);
1675 // Transmit SELECT_UID
1676 ReaderTransmit(sel_uid_c2
,sizeof(sel_uid_c2
));
1679 if (!ReaderReceive(receivedAnswer
)) continue;
1682 // Transmit MIFARE_CLASSIC_AUTH
1683 ReaderTransmit(mf_auth
,sizeof(mf_auth
));
1685 // Receive the (16 bit) "random" nonce
1686 if (!ReaderReceive(receivedAnswer
)) continue;
1690 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1692 DbpIntegers(rsamples
, 0xCC, 0xCC);
1693 DbpString("ready..");