1 //-----------------------------------------------------------------------------
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
9 //-----------------------------------------------------------------------------
10 // Routines to support ISO 14443 type A.
11 //-----------------------------------------------------------------------------
13 #include "proxmark3.h"
18 #include "iso14443crc.h"
19 #include "iso14443a.h"
21 #include "mifareutil.h"
23 static uint8_t *trace
= (uint8_t *) BigBuf
;
24 static int traceLen
= 0;
25 static int rsamples
= 0;
26 static int tracing
= TRUE
;
27 static uint32_t iso14a_timeout
;
29 // CARD TO READER - manchester
30 // Sequence D: 11110000 modulation with subcarrier during first half
31 // Sequence E: 00001111 modulation with subcarrier during second half
32 // Sequence F: 00000000 no modulation with subcarrier
33 // READER TO CARD - miller
34 // Sequence X: 00001100 drop after half a period
35 // Sequence Y: 00000000 no drop
36 // Sequence Z: 11000000 drop at start
44 static const uint8_t OddByteParity
[256] = {
45 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
46 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
47 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
48 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
49 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
50 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
51 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
52 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
57 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
58 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
59 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
60 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
64 void iso14a_set_trigger(int enable
) {
68 //-----------------------------------------------------------------------------
69 // Generate the parity value for a byte sequence
71 //-----------------------------------------------------------------------------
72 byte_t
oddparity (const byte_t bt
)
74 return OddByteParity
[bt
];
77 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
82 // Generate the encrypted data
83 for (i
= 0; i
< iLen
; i
++) {
84 // Save the encrypted parity bit
85 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
90 void AppendCrc14443a(uint8_t* data
, int len
)
92 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
95 int LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
97 // Return when trace is full
98 if (traceLen
>= TRACE_LENGTH
) return FALSE
;
100 // Trace the random, i'm curious
101 rsamples
+= iSamples
;
102 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
103 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
104 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
105 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
107 trace
[traceLen
- 1] |= 0x80;
109 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
110 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
111 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
112 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
113 trace
[traceLen
++] = iLen
;
114 memcpy(trace
+ traceLen
, btBytes
, iLen
);
119 //-----------------------------------------------------------------------------
120 // The software UART that receives commands from the reader, and its state
122 //-----------------------------------------------------------------------------
126 STATE_START_OF_COMMUNICATION
,
150 static RAMFUNC
int MillerDecoding(int bit
)
155 if(!Uart
.bitBuffer
) {
156 Uart
.bitBuffer
= bit
^ 0xFF0;
160 Uart
.bitBuffer
<<= 4;
161 Uart
.bitBuffer
^= bit
;
166 if(Uart
.state
!= STATE_UNSYNCD
) {
169 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
175 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
181 if(bit
!= bitright
) { bit
= bitright
; }
183 if(Uart
.posCnt
== 1) {
184 // measurement first half bitperiod
186 Uart
.drop
= DROP_FIRST_HALF
;
190 // measurement second half bitperiod
191 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
192 Uart
.drop
= DROP_SECOND_HALF
;
195 // measured a drop in first and second half
196 // which should not be possible
197 Uart
.state
= STATE_ERROR_WAIT
;
204 case STATE_START_OF_COMMUNICATION
:
206 if(Uart
.drop
== DROP_SECOND_HALF
) {
207 // error, should not happen in SOC
208 Uart
.state
= STATE_ERROR_WAIT
;
213 Uart
.state
= STATE_MILLER_Z
;
220 if(Uart
.drop
== DROP_NONE
) {
221 // logic '0' followed by sequence Y
222 // end of communication
223 Uart
.state
= STATE_UNSYNCD
;
226 // if(Uart.drop == DROP_FIRST_HALF) {
227 // Uart.state = STATE_MILLER_Z; stay the same
228 // we see a logic '0' }
229 if(Uart
.drop
== DROP_SECOND_HALF
) {
230 // we see a logic '1'
231 Uart
.shiftReg
|= 0x100;
232 Uart
.state
= STATE_MILLER_X
;
238 if(Uart
.drop
== DROP_NONE
) {
239 // sequence Y, we see a '0'
240 Uart
.state
= STATE_MILLER_Y
;
243 if(Uart
.drop
== DROP_FIRST_HALF
) {
244 // Would be STATE_MILLER_Z
245 // but Z does not follow X, so error
246 Uart
.state
= STATE_ERROR_WAIT
;
249 if(Uart
.drop
== DROP_SECOND_HALF
) {
250 // We see a '1' and stay in state X
251 Uart
.shiftReg
|= 0x100;
259 if(Uart
.drop
== DROP_NONE
) {
260 // logic '0' followed by sequence Y
261 // end of communication
262 Uart
.state
= STATE_UNSYNCD
;
265 if(Uart
.drop
== DROP_FIRST_HALF
) {
267 Uart
.state
= STATE_MILLER_Z
;
269 if(Uart
.drop
== DROP_SECOND_HALF
) {
270 // We see a '1' and go to state X
271 Uart
.shiftReg
|= 0x100;
272 Uart
.state
= STATE_MILLER_X
;
276 case STATE_ERROR_WAIT
:
277 // That went wrong. Now wait for at least two bit periods
278 // and try to sync again
279 if(Uart
.drop
== DROP_NONE
) {
281 Uart
.state
= STATE_UNSYNCD
;
286 Uart
.state
= STATE_UNSYNCD
;
291 Uart
.drop
= DROP_NONE
;
293 // should have received at least one whole byte...
294 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
298 if(Uart
.bitCnt
== 9) {
299 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
302 Uart
.parityBits
<<= 1;
303 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
306 // when End of Communication received and
307 // all data bits processed..
314 Uart.output[Uart.byteCnt] = 0xAA;
316 Uart.output[Uart.byteCnt] = error & 0xFF;
318 Uart.output[Uart.byteCnt] = 0xAA;
320 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
322 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
324 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
326 Uart.output[Uart.byteCnt] = 0xAA;
334 bit
= Uart
.bitBuffer
& 0xf0;
338 // should have been high or at least (4 * 128) / fc
339 // according to ISO this should be at least (9 * 128 + 20) / fc
340 if(Uart
.highCnt
== 8) {
341 // we went low, so this could be start of communication
342 // it turns out to be safer to choose a less significant
343 // syncbit... so we check whether the neighbour also represents the drop
344 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
345 Uart
.syncBit
= bit
& 8;
347 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
348 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
349 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
350 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
351 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
352 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
355 // the first half bit period is expected in next sample
360 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
363 Uart
.state
= STATE_START_OF_COMMUNICATION
;
364 Uart
.drop
= DROP_FIRST_HALF
;
375 if(Uart
.highCnt
< 8) {
384 //=============================================================================
385 // ISO 14443 Type A - Manchester
386 //=============================================================================
391 DEMOD_START_OF_COMMUNICATION
,
414 static RAMFUNC
int ManchesterDecoding(int v
)
430 if(Demod
.state
==DEMOD_UNSYNCD
) {
431 Demod
.output
[Demod
.len
] = 0xfa;
434 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
437 Demod
.syncBit
= 0x08;
444 Demod
.syncBit
= 0x04;
451 Demod
.syncBit
= 0x02;
454 if(bit
& 0x01 && Demod
.syncBit
) {
455 Demod
.syncBit
= 0x01;
460 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
461 Demod
.sub
= SUB_FIRST_HALF
;
464 Demod
.parityBits
= 0;
467 if(trigger
) LED_A_OFF();
468 switch(Demod
.syncBit
) {
469 case 0x08: Demod
.samples
= 3; break;
470 case 0x04: Demod
.samples
= 2; break;
471 case 0x02: Demod
.samples
= 1; break;
472 case 0x01: Demod
.samples
= 0; break;
479 //modulation = bit & Demod.syncBit;
480 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
484 if(Demod
.posCount
==0) {
487 Demod
.sub
= SUB_FIRST_HALF
;
490 Demod
.sub
= SUB_NONE
;
495 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
496 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
497 Demod
.state
= DEMOD_ERROR_WAIT
;
498 Demod
.output
[Demod
.len
] = 0xaa;
502 else if(modulation
) {
503 Demod
.sub
= SUB_SECOND_HALF
;
506 switch(Demod
.state
) {
507 case DEMOD_START_OF_COMMUNICATION
:
508 if(Demod
.sub
== SUB_FIRST_HALF
) {
509 Demod
.state
= DEMOD_MANCHESTER_D
;
512 Demod
.output
[Demod
.len
] = 0xab;
513 Demod
.state
= DEMOD_ERROR_WAIT
;
518 case DEMOD_MANCHESTER_D
:
519 case DEMOD_MANCHESTER_E
:
520 if(Demod
.sub
== SUB_FIRST_HALF
) {
522 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
523 Demod
.state
= DEMOD_MANCHESTER_D
;
525 else if(Demod
.sub
== SUB_SECOND_HALF
) {
527 Demod
.shiftReg
>>= 1;
528 Demod
.state
= DEMOD_MANCHESTER_E
;
531 Demod
.state
= DEMOD_MANCHESTER_F
;
535 case DEMOD_MANCHESTER_F
:
536 // Tag response does not need to be a complete byte!
537 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
538 if(Demod
.bitCount
> 0) {
539 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
540 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
542 // No parity bit, so just shift a 0
543 Demod
.parityBits
<<= 1;
546 Demod
.state
= DEMOD_UNSYNCD
;
550 Demod
.output
[Demod
.len
] = 0xad;
551 Demod
.state
= DEMOD_ERROR_WAIT
;
556 case DEMOD_ERROR_WAIT
:
557 Demod
.state
= DEMOD_UNSYNCD
;
561 Demod
.output
[Demod
.len
] = 0xdd;
562 Demod
.state
= DEMOD_UNSYNCD
;
566 if(Demod
.bitCount
>=9) {
567 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
570 Demod
.parityBits
<<= 1;
571 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
578 Demod.output[Demod.len] = 0xBB;
580 Demod.output[Demod.len] = error & 0xFF;
582 Demod.output[Demod.len] = 0xBB;
584 Demod.output[Demod.len] = bit & 0xFF;
586 Demod.output[Demod.len] = Demod.buffer & 0xFF;
588 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
590 Demod.output[Demod.len] = 0xBB;
597 } // end (state != UNSYNCED)
602 //=============================================================================
603 // Finally, a `sniffer' for ISO 14443 Type A
604 // Both sides of communication!
605 //=============================================================================
607 //-----------------------------------------------------------------------------
608 // Record the sequence of commands sent by the reader to the tag, with
609 // triggering so that we start recording at the point that the tag is moved
611 //-----------------------------------------------------------------------------
612 void RAMFUNC
SnoopIso14443a(void)
614 // #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
615 // #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
616 // #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
617 // #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
618 // #define TRACE_LENGTH 2000 // original (working as of 21/2/09) values
620 // We won't start recording the frames that we acquire until we trigger;
621 // a good trigger condition to get started is probably when we see a
622 // response from the tag.
623 int triggered
= FALSE
; // FALSE to wait first for card
625 // The command (reader -> tag) that we're receiving.
626 // The length of a received command will in most cases be no more than 18 bytes.
627 // So 32 should be enough!
628 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
629 // The response (tag -> reader) that we're receiving.
630 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
632 // As we receive stuff, we copy it from receivedCmd or receivedResponse
633 // into trace, along with its length and other annotations.
634 //uint8_t *trace = (uint8_t *)BigBuf;
636 traceLen
= 0; // uncommented to fix ISSUE 15 - gerhard - jan2011
638 // The DMA buffer, used to stream samples from the FPGA
639 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
645 // Count of samples received so far, so that we can include timing
646 // information in the trace buffer.
650 memset(trace
, 0x44, RECV_CMD_OFFSET
);
652 // Set up the demodulator for tag -> reader responses.
653 Demod
.output
= receivedResponse
;
655 Demod
.state
= DEMOD_UNSYNCD
;
657 // Setup for the DMA.
660 lastRxCounter
= DMA_BUFFER_SIZE
;
661 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
663 // And the reader -> tag commands
664 memset(&Uart
, 0, sizeof(Uart
));
665 Uart
.output
= receivedCmd
;
666 Uart
.byteCntMax
= 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
667 Uart
.state
= STATE_UNSYNCD
;
669 // And put the FPGA in the appropriate mode
670 // Signal field is off with the appropriate LED
672 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
673 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
676 // And now we loop, receiving samples.
680 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) &
682 if(behindBy
> maxBehindBy
) {
683 maxBehindBy
= behindBy
;
685 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy
);
689 if(behindBy
< 1) continue;
695 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
696 upTo
-= DMA_BUFFER_SIZE
;
697 lastRxCounter
+= DMA_BUFFER_SIZE
;
698 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
699 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
703 if(MillerDecoding((smpl
& 0xF0) >> 4)) {
704 rsamples
= samples
- Uart
.samples
;
707 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
708 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
709 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
710 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
711 trace
[traceLen
++] = ((Uart
.parityBits
>> 0) & 0xff);
712 trace
[traceLen
++] = ((Uart
.parityBits
>> 8) & 0xff);
713 trace
[traceLen
++] = ((Uart
.parityBits
>> 16) & 0xff);
714 trace
[traceLen
++] = ((Uart
.parityBits
>> 24) & 0xff);
715 trace
[traceLen
++] = Uart
.byteCnt
;
716 memcpy(trace
+traceLen
, receivedCmd
, Uart
.byteCnt
);
717 traceLen
+= Uart
.byteCnt
;
718 if(traceLen
> TRACE_LENGTH
) break;
720 /* And ready to receive another command. */
721 Uart
.state
= STATE_UNSYNCD
;
722 /* And also reset the demod code, which might have been */
723 /* false-triggered by the commands from the reader. */
724 Demod
.state
= DEMOD_UNSYNCD
;
728 if(ManchesterDecoding(smpl
& 0x0F)) {
729 rsamples
= samples
- Demod
.samples
;
732 // timestamp, as a count of samples
733 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
734 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
735 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
736 trace
[traceLen
++] = 0x80 | ((rsamples
>> 24) & 0xff);
737 trace
[traceLen
++] = ((Demod
.parityBits
>> 0) & 0xff);
738 trace
[traceLen
++] = ((Demod
.parityBits
>> 8) & 0xff);
739 trace
[traceLen
++] = ((Demod
.parityBits
>> 16) & 0xff);
740 trace
[traceLen
++] = ((Demod
.parityBits
>> 24) & 0xff);
742 trace
[traceLen
++] = Demod
.len
;
743 memcpy(trace
+traceLen
, receivedResponse
, Demod
.len
);
744 traceLen
+= Demod
.len
;
745 if(traceLen
> TRACE_LENGTH
) break;
749 // And ready to receive another response.
750 memset(&Demod
, 0, sizeof(Demod
));
751 Demod
.output
= receivedResponse
;
752 Demod
.state
= DEMOD_UNSYNCD
;
757 DbpString("cancelled_a");
762 DbpString("COMMAND FINISHED");
764 Dbprintf("%x %x %x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
765 Dbprintf("%x %x %x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
768 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
769 Dbprintf("%x %x %x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
770 Dbprintf("%x %x %x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
777 //-----------------------------------------------------------------------------
778 // Prepare tag messages
779 //-----------------------------------------------------------------------------
780 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
787 // Correction bit, might be removed when not needed
792 ToSendStuffBit(1); // 1
798 ToSend
[++ToSendMax
] = SEC_D
;
800 for(i
= 0; i
< len
; i
++) {
806 for(j
= 0; j
< 8; j
++) {
807 // oddparity ^= (b & 1);
809 ToSend
[++ToSendMax
] = SEC_D
;
811 ToSend
[++ToSendMax
] = SEC_E
;
816 // Get the parity bit
817 if ((dwParity
>> i
) & 0x01) {
818 ToSend
[++ToSendMax
] = SEC_D
;
820 ToSend
[++ToSendMax
] = SEC_E
;
825 // ToSend[++ToSendMax] = SEC_D;
827 // ToSend[++ToSendMax] = SEC_E;
830 // if (oddparity != ((dwParity >> i) & 0x01))
831 // Dbprintf("par error. i=%d", i);
835 ToSend
[++ToSendMax
] = SEC_F
;
837 // Flush the buffer in FPGA!!
838 for(i
= 0; i
< 5; i
++) {
839 ToSend
[++ToSendMax
] = SEC_F
;
842 // Convert from last byte pos to length
845 // Add a few more for slop
846 // ToSend[ToSendMax++] = 0x00;
847 // ToSend[ToSendMax++] = 0x00;
850 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
851 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
854 //-----------------------------------------------------------------------------
855 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
856 //-----------------------------------------------------------------------------
857 static void CodeStrangeAnswerAsTag()
863 // Correction bit, might be removed when not needed
868 ToSendStuffBit(1); // 1
874 ToSend
[++ToSendMax
] = SEC_D
;
877 ToSend
[++ToSendMax
] = SEC_E
;
880 ToSend
[++ToSendMax
] = SEC_E
;
883 ToSend
[++ToSendMax
] = SEC_D
;
886 ToSend
[++ToSendMax
] = SEC_F
;
888 // Flush the buffer in FPGA!!
889 for(i
= 0; i
< 5; i
++) {
890 ToSend
[++ToSendMax
] = SEC_F
;
893 // Convert from last byte pos to length
897 static void Code4bitAnswerAsTag(uint8_t cmd
)
903 // Correction bit, might be removed when not needed
908 ToSendStuffBit(1); // 1
914 ToSend
[++ToSendMax
] = SEC_D
;
917 for(i
= 0; i
< 4; i
++) {
919 ToSend
[++ToSendMax
] = SEC_D
;
921 ToSend
[++ToSendMax
] = SEC_E
;
927 ToSend
[++ToSendMax
] = SEC_F
;
929 // Flush the buffer in FPGA!!
930 for(i
= 0; i
< 5; i
++) {
931 ToSend
[++ToSendMax
] = SEC_F
;
934 // Convert from last byte pos to length
938 //-----------------------------------------------------------------------------
939 // Wait for commands from reader
940 // Stop when button is pressed
941 // Or return TRUE when command is captured
942 //-----------------------------------------------------------------------------
943 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
945 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
946 // only, since we are receiving, not transmitting).
947 // Signal field is off with the appropriate LED
949 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
951 // Now run a `software UART' on the stream of incoming samples.
952 Uart
.output
= received
;
953 Uart
.byteCntMax
= maxLen
;
954 Uart
.state
= STATE_UNSYNCD
;
959 if(BUTTON_PRESS()) return FALSE
;
961 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
962 AT91C_BASE_SSC
->SSC_THR
= 0x00;
964 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
965 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
966 if(MillerDecoding((b
& 0xf0) >> 4)) {
970 if(MillerDecoding(b
& 0x0f)) {
977 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
979 //-----------------------------------------------------------------------------
980 // Main loop of simulated tag: receive commands from reader, decide what
981 // response to send, and send it.
982 //-----------------------------------------------------------------------------
983 void SimulateIso14443aTag(int tagType
, int TagUid
)
985 // This function contains the tag emulation
987 // Prepare protocol messages
988 // static const uint8_t cmd1[] = { 0x26 };
989 // static const uint8_t response1[] = { 0x02, 0x00 }; // Says: I am Mifare 4k - original line - greg
991 static const uint8_t response1
[] = { 0x44, 0x03 }; // Says: I am a DESFire Tag, ph33r me
992 // static const uint8_t response1[] = { 0x44, 0x00 }; // Says: I am a ULTRALITE Tag, 0wn me
995 // static const uint8_t cmd2[] = { 0x93, 0x20 };
996 //static const uint8_t response2[] = { 0x9a, 0xe5, 0xe4, 0x43, 0xd8 }; // original value - greg
999 static const uint8_t response2
[] = { 0x88, 0x04, 0x21, 0x3f, 0x4d }; // known uid - note cascade (0x88), 2nd byte (0x04) = NXP/Phillips
1002 // When reader selects us during cascade1 it will send cmd3
1003 //uint8_t response3[] = { 0x04, 0x00, 0x00 }; // SAK Select (cascade1) successful response (ULTRALITE)
1004 uint8_t response3
[] = { 0x24, 0x00, 0x00 }; // SAK Select (cascade1) successful response (DESFire)
1005 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
1007 // send cascade2 2nd half of UID
1008 static const uint8_t response2a
[] = { 0x51, 0x48, 0x1d, 0x80, 0x84 }; // uid - cascade2 - 2nd half (4 bytes) of UID+ BCCheck
1009 // NOTE : THE CRC on the above may be wrong as I have obfuscated the actual UID
1011 // When reader selects us during cascade2 it will send cmd3a
1012 //uint8_t response3a[] = { 0x00, 0x00, 0x00 }; // SAK Select (cascade2) successful response (ULTRALITE)
1013 uint8_t response3a
[] = { 0x20, 0x00, 0x00 }; // SAK Select (cascade2) successful response (DESFire)
1014 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
1016 static const uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
1021 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
1023 // 144 data bits (18 * 8)
1026 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
1027 // 1 just for the case
1031 // 166 bytes, since every bit that needs to be send costs us a byte
1034 // Respond with card type
1035 uint8_t *resp1
= (((uint8_t *)BigBuf
) + 800);
1038 // Anticollision cascade1 - respond with uid
1039 uint8_t *resp2
= (((uint8_t *)BigBuf
) + 970);
1042 // Anticollision cascade2 - respond with 2nd half of uid if asked
1043 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1044 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1047 // Acknowledge select - cascade 1
1048 uint8_t *resp3
= (((uint8_t *)BigBuf
) + 1310);
1051 // Acknowledge select - cascade 2
1052 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + 1480);
1055 // Response to a read request - not implemented atm
1056 uint8_t *resp4
= (((uint8_t *)BigBuf
) + 1550);
1059 // Authenticate response - nonce
1060 uint8_t *resp5
= (((uint8_t *)BigBuf
) + 1720);
1063 uint8_t *receivedCmd
= (uint8_t *)BigBuf
;
1070 // To control where we are in the protocol
1074 // Just to allow some checks
1082 memset(receivedCmd
, 0x44, 400);
1084 // Prepare the responses of the anticollision phase
1085 // there will be not enough time to do this at the moment the reader sends it REQA
1087 // Answer to request
1088 CodeIso14443aAsTag(response1
, sizeof(response1
));
1089 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1091 // Send our UID (cascade 1)
1092 CodeIso14443aAsTag(response2
, sizeof(response2
));
1093 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1095 // Answer to select (cascade1)
1096 CodeIso14443aAsTag(response3
, sizeof(response3
));
1097 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1099 // Send the cascade 2 2nd part of the uid
1100 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1101 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1103 // Answer to select (cascade 2)
1104 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1105 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1107 // Strange answer is an example of rare message size (3 bits)
1108 CodeStrangeAnswerAsTag();
1109 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1111 // Authentication answer (random nonce)
1112 CodeIso14443aAsTag(response5
, sizeof(response5
));
1113 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1115 // We need to listen to the high-frequency, peak-detected path.
1116 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1124 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, 100)) {
1125 DbpString("button press");
1128 // 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
1129 // Okay, look at the command now.
1131 i
= 1; // first byte transmitted
1132 if(receivedCmd
[0] == 0x26) {
1133 // Received a REQUEST
1134 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1135 //DbpString("Hello request from reader:");
1136 } else if(receivedCmd
[0] == 0x52) {
1137 // Received a WAKEUP
1138 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1139 // //DbpString("Wakeup request from reader:");
1141 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // greg - cascade 1 anti-collision
1142 // Received request for UID (cascade 1)
1143 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1144 // DbpString("UID (cascade 1) request from reader:");
1145 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1148 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] ==0x95) { // greg - cascade 2 anti-collision
1149 // Received request for UID (cascade 2)
1150 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1151 // DbpString("UID (cascade 2) request from reader:");
1152 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1155 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x93) { // greg - cascade 1 select
1156 // Received a SELECT
1157 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1158 // DbpString("Select (cascade 1) request from reader:");
1159 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1162 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x95) { // greg - cascade 2 select
1163 // Received a SELECT
1164 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1165 // DbpString("Select (cascade 2) request from reader:");
1166 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1169 } else if(receivedCmd
[0] == 0x30) {
1171 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1172 Dbprintf("Read request from reader: %x %x %x",
1173 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1176 } else if(receivedCmd
[0] == 0x50) {
1178 resp
= resp1
; respLen
= 0; order
= 5; // Do nothing
1179 DbpString("Reader requested we HALT!:");
1181 } else if(receivedCmd
[0] == 0x60) {
1182 // Received an authentication request
1183 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1184 Dbprintf("Authenticate request from reader: %x %x %x",
1185 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1187 } else if(receivedCmd
[0] == 0xE0) {
1188 // Received a RATS request
1189 resp
= resp1
; respLen
= 0;order
= 70;
1190 Dbprintf("RATS request from reader: %x %x %x",
1191 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1193 // Never seen this command before
1194 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1196 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2],
1197 receivedCmd
[3], receivedCmd
[4], receivedCmd
[5],
1198 receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1200 resp
= resp1
; respLen
= 0; order
= 0;
1203 // Count number of wakeups received after a halt
1204 if(order
== 6 && lastorder
== 5) { happened
++; }
1206 // Count number of other messages after a halt
1207 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1209 // Look at last parity bit to determine timing of answer
1210 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1211 // 1236, so correction bit needed
1215 memset(receivedCmd
, 0x44, 32);
1217 if(cmdsRecvd
> 999) {
1218 DbpString("1000 commands later...");
1225 if(respLen
<= 0) continue;
1226 //----------------------------
1229 fdt_indicator
= FALSE
;
1231 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1232 /* // Modulate Manchester
1233 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1234 AT91C_BASE_SSC->SSC_THR = 0x00;
1237 // ### Transmit the response ###
1240 fdt_indicator = FALSE;
1242 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1243 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1246 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1254 AT91C_BASE_SSC->SSC_THR = b;
1260 if(BUTTON_PRESS()) {
1267 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1271 //-----------------------------------------------------------------------------
1272 // Transmit the command (to the tag) that was placed in ToSend[].
1273 //-----------------------------------------------------------------------------
1274 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1278 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1284 for(c
= 0; c
< *wait
;) {
1285 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1286 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1289 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1290 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1298 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1299 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1305 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1306 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1311 if (samples
) *samples
= (c
+ *wait
) << 3;
1314 //-----------------------------------------------------------------------------
1315 // Code a 7-bit command without parity bit
1316 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1317 //-----------------------------------------------------------------------------
1318 void ShortFrameFromReader(const uint8_t bt
)
1326 // Start of Communication (Seq. Z)
1327 ToSend
[++ToSendMax
] = SEC_Z
;
1331 for(j
= 0; j
< 7; j
++) {
1334 ToSend
[++ToSendMax
] = SEC_X
;
1339 ToSend
[++ToSendMax
] = SEC_Z
;
1343 ToSend
[++ToSendMax
] = SEC_Y
;
1350 // End of Communication
1353 ToSend
[++ToSendMax
] = SEC_Z
;
1357 ToSend
[++ToSendMax
] = SEC_Y
;
1361 ToSend
[++ToSendMax
] = SEC_Y
;
1364 ToSend
[++ToSendMax
] = SEC_Y
;
1365 ToSend
[++ToSendMax
] = SEC_Y
;
1366 ToSend
[++ToSendMax
] = SEC_Y
;
1368 // Convert from last character reference to length
1372 //-----------------------------------------------------------------------------
1373 // Prepare reader command to send to FPGA
1375 //-----------------------------------------------------------------------------
1376 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1384 // Start of Communication (Seq. Z)
1385 ToSend
[++ToSendMax
] = SEC_Z
;
1388 // Generate send structure for the data bits
1389 for (i
= 0; i
< len
; i
++) {
1390 // Get the current byte to send
1393 for (j
= 0; j
< 8; j
++) {
1396 ToSend
[++ToSendMax
] = SEC_X
;
1401 ToSend
[++ToSendMax
] = SEC_Z
;
1404 ToSend
[++ToSendMax
] = SEC_Y
;
1411 // Get the parity bit
1412 if ((dwParity
>> i
) & 0x01) {
1414 ToSend
[++ToSendMax
] = SEC_X
;
1419 ToSend
[++ToSendMax
] = SEC_Z
;
1422 ToSend
[++ToSendMax
] = SEC_Y
;
1428 // End of Communication
1431 ToSend
[++ToSendMax
] = SEC_Z
;
1434 ToSend
[++ToSendMax
] = SEC_Y
;
1438 ToSend
[++ToSendMax
] = SEC_Y
;
1441 ToSend
[++ToSendMax
] = SEC_Y
;
1442 ToSend
[++ToSendMax
] = SEC_Y
;
1443 ToSend
[++ToSendMax
] = SEC_Y
;
1445 // Convert from last character reference to length
1449 //-----------------------------------------------------------------------------
1450 // Wait for commands from reader
1451 // Stop when button is pressed (return 1) or field was gone (return 2)
1452 // Or return 0 when command is captured
1453 //-----------------------------------------------------------------------------
1454 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1458 uint32_t timer
= 0, vtime
= 0;
1462 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1463 // only, since we are receiving, not transmitting).
1464 // Signal field is off with the appropriate LED
1466 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1468 // Set ADC to read field strength
1469 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1470 AT91C_BASE_ADC
->ADC_MR
=
1471 ADC_MODE_PRESCALE(32) |
1472 ADC_MODE_STARTUP_TIME(16) |
1473 ADC_MODE_SAMPLE_HOLD_TIME(8);
1474 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1476 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1478 // Now run a 'software UART' on the stream of incoming samples.
1479 Uart
.output
= received
;
1480 Uart
.byteCntMax
= maxLen
;
1481 Uart
.state
= STATE_UNSYNCD
;
1486 if (BUTTON_PRESS()) return 1;
1488 // test if the field exists
1489 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1491 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1492 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1493 if (analogCnt
>= 32) {
1494 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1495 vtime
= GetTickCount();
1496 if (!timer
) timer
= vtime
;
1497 // 50ms no field --> card to idle state
1498 if (vtime
- timer
> 50) return 2;
1500 if (timer
) timer
= 0;
1506 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1507 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1509 // receive and test the miller decoding
1510 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1511 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1512 if(MillerDecoding((b
& 0xf0) >> 4)) {
1513 *len
= Uart
.byteCnt
;
1514 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1517 if(MillerDecoding(b
& 0x0f)) {
1518 *len
= Uart
.byteCnt
;
1519 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1526 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1531 // Modulate Manchester
1532 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1533 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1536 // include correction bit
1538 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1539 // 1236, so correction bit needed
1545 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1546 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1549 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1551 b
= 0xff; // was 0x00
1557 AT91C_BASE_SSC
->SSC_THR
= b
;
1561 if(BUTTON_PRESS()) {
1569 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1570 Code4bitAnswerAsTag(resp
);
1571 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1572 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1576 int EmSend4bit(uint8_t resp
){
1577 return EmSend4bitEx(resp
, 0);
1580 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1581 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1582 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1583 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1587 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1588 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1591 int EmSendCmd(uint8_t *resp
, int respLen
){
1592 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1595 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1596 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1599 //-----------------------------------------------------------------------------
1600 // Wait a certain time for tag response
1601 // If a response is captured return TRUE
1602 // If it takes to long return FALSE
1603 //-----------------------------------------------------------------------------
1604 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1606 // buffer needs to be 512 bytes
1609 // Set FPGA mode to "reader listen mode", no modulation (listen
1610 // only, since we are receiving, not transmitting).
1611 // Signal field is on with the appropriate LED
1613 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1615 // Now get the answer from the card
1616 Demod
.output
= receivedResponse
;
1618 Demod
.state
= DEMOD_UNSYNCD
;
1621 if (elapsed
) *elapsed
= 0;
1627 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1628 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1629 if (elapsed
) (*elapsed
)++;
1631 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1632 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1633 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1634 if(ManchesterDecoding((b
>>4) & 0xf)) {
1635 *samples
= ((c
- 1) << 3) + 4;
1638 if(ManchesterDecoding(b
& 0x0f)) {
1646 void ReaderTransmitShort(const uint8_t* bt
)
1651 ShortFrameFromReader(*bt
);
1654 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1656 // Store reader command in buffer
1657 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1660 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1665 // This is tied to other size changes
1666 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1667 CodeIso14443aAsReaderPar(frame
,len
,par
);
1670 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1674 // Store reader command in buffer
1675 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1679 void ReaderTransmit(uint8_t* frame
, int len
)
1681 // Generate parity and redirect
1682 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1685 int ReaderReceive(uint8_t* receivedAnswer
)
1688 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1689 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1690 if(samples
== 0) return FALSE
;
1694 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1697 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1698 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1699 *parptr
= Demod
.parityBits
;
1700 if(samples
== 0) return FALSE
;
1704 /* performs iso14443a anticolision procedure
1705 * fills the uid pointer unless NULL
1706 * fills resp_data unless NULL */
1707 int iso14443a_select_card(uint8_t * uid_ptr
, iso14a_card_select_t
* resp_data
, uint32_t * cuid_ptr
) {
1708 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1709 uint8_t sel_all
[] = { 0x93,0x20 };
1710 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1711 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1713 uint8_t* resp
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1715 uint8_t sak
= 0x04; // cascade uid
1716 int cascade_level
= 0;
1721 memset(uid_ptr
, 0, 8);
1723 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1724 ReaderTransmitShort(wupa
);
1726 if(!ReaderReceive(resp
)) return 0;
1729 memcpy(resp_data
->atqa
, resp
, 2);
1731 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1732 // which case we need to make a cascade 2 request and select - this is a long UID
1733 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1734 for(; sak
& 0x04; cascade_level
++)
1736 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1737 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1740 ReaderTransmit(sel_all
,sizeof(sel_all
));
1741 if (!ReaderReceive(resp
)) return 0;
1742 if(uid_ptr
) memcpy(uid_ptr
+ cascade_level
*4, resp
, 4);
1744 // calculate crypto UID
1745 if(cuid_ptr
) *cuid_ptr
= bytes_to_num(resp
, 4);
1747 // Construct SELECT UID command
1748 memcpy(sel_uid
+2,resp
,5);
1749 AppendCrc14443a(sel_uid
,7);
1750 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1753 if (!ReaderReceive(resp
)) return 0;
1757 resp_data
->sak
= sak
;
1758 resp_data
->ats_len
= 0;
1760 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1761 if (uid_ptr
[0] == 0x88) {
1762 memcpy(uid_ptr
, uid_ptr
+ 1, 7);
1766 if( (sak
& 0x20) == 0)
1767 return 2; // non iso14443a compliant tag
1769 // Request for answer to select
1770 if(resp_data
) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1771 AppendCrc14443a(rats
, 2);
1772 ReaderTransmit(rats
, sizeof(rats
));
1774 if (!(len
= ReaderReceive(resp
))) return 0;
1776 memcpy(resp_data
->ats
, resp
, sizeof(resp_data
->ats
));
1777 resp_data
->ats_len
= len
;
1783 void iso14443a_setup() {
1786 // Start from off (no field generated)
1787 // Signal field is off with the appropriate LED
1789 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1792 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1794 // Now give it time to spin up.
1795 // Signal field is on with the appropriate LED
1797 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1800 iso14a_timeout
= 2048; //default
1803 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1804 uint8_t real_cmd
[cmd_len
+4];
1805 real_cmd
[0] = 0x0a; //I-Block
1806 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1807 memcpy(real_cmd
+2, cmd
, cmd_len
);
1808 AppendCrc14443a(real_cmd
,cmd_len
+2);
1810 ReaderTransmit(real_cmd
, cmd_len
+4);
1811 size_t len
= ReaderReceive(data
);
1813 return -1; //DATA LINK ERROR
1819 //-----------------------------------------------------------------------------
1820 // Read an ISO 14443a tag. Send out commands and store answers.
1822 //-----------------------------------------------------------------------------
1823 void ReaderIso14443a(UsbCommand
* c
, UsbCommand
* ack
)
1825 iso14a_command_t param
= c
->arg
[0];
1826 uint8_t * cmd
= c
->d
.asBytes
;
1827 size_t len
= c
->arg
[1];
1829 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(1);
1831 if(param
& ISO14A_CONNECT
) {
1833 ack
->arg
[0] = iso14443a_select_card(ack
->d
.asBytes
, (iso14a_card_select_t
*) (ack
->d
.asBytes
+12), NULL
);
1834 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1837 if(param
& ISO14A_SET_TIMEOUT
) {
1838 iso14a_timeout
= c
->arg
[2];
1841 if(param
& ISO14A_SET_TIMEOUT
) {
1842 iso14a_timeout
= c
->arg
[2];
1845 if(param
& ISO14A_APDU
) {
1846 ack
->arg
[0] = iso14_apdu(cmd
, len
, ack
->d
.asBytes
);
1847 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1850 if(param
& ISO14A_RAW
) {
1851 if(param
& ISO14A_APPEND_CRC
) {
1852 AppendCrc14443a(cmd
,len
);
1855 ReaderTransmit(cmd
,len
);
1856 ack
->arg
[0] = ReaderReceive(ack
->d
.asBytes
);
1857 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1860 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(0);
1862 if(param
& ISO14A_NO_DISCONNECT
)
1865 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1868 //-----------------------------------------------------------------------------
1869 // Read an ISO 14443a tag. Send out commands and store answers.
1871 //-----------------------------------------------------------------------------
1872 void ReaderMifare(uint32_t parameter
)
1875 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1876 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1878 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1891 byte_t par_mask
= 0xff;
1898 byte_t nt
[4] = {0,0,0,0};
1899 byte_t nt_attacked
[4], nt_noattack
[4];
1900 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1901 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1902 num_to_bytes(parameter
, 4, nt_noattack
);
1903 int isOK
= 0, isNULL
= 0;
1908 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1910 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1913 // Test if the action was cancelled
1914 if(BUTTON_PRESS()) {
1918 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1920 // Transmit MIFARE_CLASSIC_AUTH
1921 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1923 // Receive the (16 bit) "random" nonce
1924 if (!ReaderReceive(receivedAnswer
)) continue;
1925 memcpy(nt
, receivedAnswer
, 4);
1927 // Transmit reader nonce and reader answer
1928 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1930 // Receive 4 bit answer
1931 if (ReaderReceive(receivedAnswer
))
1933 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1935 isNULL
= (nt_attacked
[0] = 0) && (nt_attacked
[1] = 0) && (nt_attacked
[2] = 0) && (nt_attacked
[3] = 0);
1936 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1941 memcpy(nt_attacked
, nt
, 4);
1943 par_low
= par
& 0x07;
1947 if(led_on
) LED_B_ON(); else LED_B_OFF();
1948 par_list
[nt_diff
] = par
;
1949 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1951 // Test if the information is complete
1952 if (nt_diff
== 0x07) {
1957 nt_diff
= (nt_diff
+ 1) & 0x07;
1958 mf_nr_ar
[3] = nt_diff
<< 5;
1965 par
= (((par
>> 3) + 1) << 3) | par_low
;
1970 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1971 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1972 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1974 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
1975 memcpy(ack
.d
.asBytes
+ 0, uid
, 4);
1976 memcpy(ack
.d
.asBytes
+ 4, nt
, 4);
1977 memcpy(ack
.d
.asBytes
+ 8, par_list
, 8);
1978 memcpy(ack
.d
.asBytes
+ 16, ks_list
, 8);
1981 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
1985 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1989 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1992 //-----------------------------------------------------------------------------
1993 // Select, Authenticaate, Read an MIFARE tag.
1995 //-----------------------------------------------------------------------------
1996 void MifareReadBlock(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
1999 uint8_t blockNo
= arg0
;
2000 uint8_t keyType
= arg1
;
2001 uint64_t ui64Key
= 0;
2002 ui64Key
= bytes_to_num(datain
, 6);
2006 byte_t dataoutbuf
[16];
2009 struct Crypto1State mpcs
= {0, 0};
2010 struct Crypto1State
*pcs
;
2024 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2025 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2029 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
2030 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
2034 if(mifare_classic_readblock(pcs
, cuid
, blockNo
, dataoutbuf
)) {
2035 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block error");
2039 if(mifare_classic_halt(pcs
, cuid
)) {
2040 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
2048 // ----------------------------- crypto1 destroy
2049 crypto1_destroy(pcs
);
2051 if (MF_DBGLEVEL
>= 2) DbpString("READ BLOCK FINISHED");
2053 // add trace trailer
2054 memset(uid
, 0x44, 4);
2055 LogTrace(uid
, 4, 0, 0, TRUE
);
2057 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2058 memcpy(ack
.d
.asBytes
, dataoutbuf
, 16);
2061 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2066 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2072 //-----------------------------------------------------------------------------
2073 // Select, Authenticaate, Read an MIFARE tag.
2074 // read sector (data = 4 x 16 bytes = 64 bytes)
2075 //-----------------------------------------------------------------------------
2076 void MifareReadSector(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2079 uint8_t sectorNo
= arg0
;
2080 uint8_t keyType
= arg1
;
2081 uint64_t ui64Key
= 0;
2082 ui64Key
= bytes_to_num(datain
, 6);
2086 byte_t dataoutbuf
[16 * 4];
2089 struct Crypto1State mpcs
= {0, 0};
2090 struct Crypto1State
*pcs
;
2104 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2105 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2109 if(mifare_classic_auth(pcs
, cuid
, sectorNo
* 4, keyType
, ui64Key
, AUTH_FIRST
)) {
2110 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
2114 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 0, dataoutbuf
+ 16 * 0)) {
2115 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 0 error");
2118 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 1, dataoutbuf
+ 16 * 1)) {
2119 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 1 error");
2122 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 2, dataoutbuf
+ 16 * 2)) {
2123 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 2 error");
2126 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 3, dataoutbuf
+ 16 * 3)) {
2127 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 3 error");
2131 if(mifare_classic_halt(pcs
, cuid
)) {
2132 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
2140 // ----------------------------- crypto1 destroy
2141 crypto1_destroy(pcs
);
2143 if (MF_DBGLEVEL
>= 2) DbpString("READ SECTOR FINISHED");
2145 // add trace trailer
2146 memset(uid
, 0x44, 4);
2147 LogTrace(uid
, 4, 0, 0, TRUE
);
2149 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2150 memcpy(ack
.d
.asBytes
, dataoutbuf
, 16 * 2);
2153 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2157 memcpy(ack
.d
.asBytes
, dataoutbuf
+ 16 * 2, 16 * 2);
2158 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2162 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2168 //-----------------------------------------------------------------------------
2169 // Select, Authenticaate, Read an MIFARE tag.
2171 //-----------------------------------------------------------------------------
2172 void MifareWriteBlock(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2175 uint8_t blockNo
= arg0
;
2176 uint8_t keyType
= arg1
;
2177 uint64_t ui64Key
= 0;
2178 byte_t blockdata
[16];
2180 ui64Key
= bytes_to_num(datain
, 6);
2181 memcpy(blockdata
, datain
+ 10, 16);
2187 struct Crypto1State mpcs
= {0, 0};
2188 struct Crypto1State
*pcs
;
2202 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2203 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2207 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
2208 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
2212 if(mifare_classic_writeblock(pcs
, cuid
, blockNo
, blockdata
)) {
2213 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
2217 if(mifare_classic_halt(pcs
, cuid
)) {
2218 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
2226 // ----------------------------- crypto1 destroy
2227 crypto1_destroy(pcs
);
2229 if (MF_DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
2231 // add trace trailer
2232 memset(uid
, 0x44, 4);
2233 LogTrace(uid
, 4, 0, 0, TRUE
);
2235 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2238 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2243 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2249 // Return 1 if the nonce is invalid else return 0
2250 int valid_nonce(uint32_t Nt
, uint32_t NtEnc
, uint32_t Ks1
, byte_t
* parity
) {
2251 return ((oddparity((Nt
>> 24) & 0xFF) == ((parity
[0]) ^ oddparity((NtEnc
>> 24) & 0xFF) ^ BIT(Ks1
,16))) & \
2252 (oddparity((Nt
>> 16) & 0xFF) == ((parity
[1]) ^ oddparity((NtEnc
>> 16) & 0xFF) ^ BIT(Ks1
,8))) & \
2253 (oddparity((Nt
>> 8) & 0xFF) == ((parity
[2]) ^ oddparity((NtEnc
>> 8) & 0xFF) ^ BIT(Ks1
,0)))) ? 1 : 0;
2257 //-----------------------------------------------------------------------------
2258 // MIFARE nested authentication.
2260 //-----------------------------------------------------------------------------
2261 void MifareNested(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
)
2264 uint8_t blockNo
= arg0
;
2265 uint8_t keyType
= arg1
;
2266 uint8_t targetBlockNo
= arg2
& 0xff;
2267 uint8_t targetKeyType
= (arg2
>> 8) & 0xff;
2268 uint64_t ui64Key
= 0;
2270 ui64Key
= bytes_to_num(datain
, 6);
2273 int rtr
, i
, j
, m
, len
;
2274 int davg
, dmin
, dmax
;
2276 uint32_t cuid
, nt1
, nt2
, nttmp
, nttest
, par
, ks1
;
2277 uint8_t par_array
[4];
2278 nestedVector nvector
[NES_MAX_INFO
+ 1][10];
2279 int nvectorcount
[NES_MAX_INFO
+ 1];
2281 UsbCommand ack
= {CMD_ACK
, {0, 0, 0}};
2282 struct Crypto1State mpcs
= {0, 0};
2283 struct Crypto1State
*pcs
;
2285 uint8_t* receivedAnswer
= mifare_get_bigbufptr();
2288 for (i
= 0; i
< NES_MAX_INFO
+ 1; i
++) nvectorcount
[i
] = 11; // 11 - empty block;
2300 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2306 // test nonce distance
2307 for (rtr
= 0; rtr
< 10; rtr
++) {
2308 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2310 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2312 // Test if the action was cancelled
2313 if(BUTTON_PRESS()) {
2317 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2318 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2322 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
)) {
2323 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth1 error");
2327 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt2
)) {
2328 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth2 error");
2332 nttmp
= prng_successor(nt1
, 500);
2333 for (i
= 501; i
< 2000; i
++) {
2334 nttmp
= prng_successor(nttmp
, 1);
2335 if (nttmp
== nt2
) break;
2340 if (dmin
> i
) dmin
= i
;
2341 if (dmax
< i
) dmax
= i
;
2342 if (MF_DBGLEVEL
>= 4) Dbprintf("r=%d nt1=%08x nt2=%08x distance=%d", rtr
, nt1
, nt2
, i
);
2346 if (rtr
== 0) return;
2349 if (MF_DBGLEVEL
>= 3) Dbprintf("distance: min=%d max=%d avg=%d", dmin
, dmax
, davg
);
2353 // -------------------------------------------------------------------------------------------------
2357 // get crypted nonces for target sector
2358 for (rtr
= 0; rtr
< NS_RETRIES_GETNONCE
; rtr
++) {
2359 if (MF_DBGLEVEL
>= 4) Dbprintf("------------------------------");
2361 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2363 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2365 // Test if the action was cancelled
2366 if(BUTTON_PRESS()) {
2370 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2371 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2375 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
)) {
2376 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth1 error");
2380 // nested authentication
2381 len
= mifare_sendcmd_shortex(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, &par
);
2383 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth2 error len=%d", len
);
2387 nt2
= bytes_to_num(receivedAnswer
, 4);
2388 if (MF_DBGLEVEL
>= 4) Dbprintf("r=%d nt1=%08x nt2enc=%08x nt2par=%08x", rtr
, nt1
, nt2
, par
);
2390 // Parity validity check
2391 for (i
= 0; i
< 4; i
++) {
2392 par_array
[i
] = (oddparity(receivedAnswer
[i
]) != ((par
& 0x08) >> 3));
2397 for (m
= dmin
- NS_TOLERANCE
; m
< dmax
+ NS_TOLERANCE
; m
++) {
2398 nttest
= prng_successor(nt1
, m
);
2401 if (valid_nonce(nttest
, nt2
, ks1
, par_array
) && (ncount
< 11)){
2403 nvector
[NES_MAX_INFO
][ncount
].nt
= nttest
;
2404 nvector
[NES_MAX_INFO
][ncount
].ks1
= ks1
;
2406 nvectorcount
[NES_MAX_INFO
] = ncount
;
2407 if (MF_DBGLEVEL
>= 4) Dbprintf("valid m=%d ks1=%08x nttest=%08x", m
, ks1
, nttest
);
2412 // select vector with length less than got
2413 if (nvectorcount
[NES_MAX_INFO
] != 0) {
2416 for (i
= 0; i
< NES_MAX_INFO
; i
++)
2417 if (nvectorcount
[i
] > 10) {
2422 if (m
== NES_MAX_INFO
)
2423 for (i
= 0; i
< NES_MAX_INFO
; i
++)
2424 if (nvectorcount
[NES_MAX_INFO
] < nvectorcount
[i
]) {
2429 if (m
!= NES_MAX_INFO
) {
2430 for (i
= 0; i
< nvectorcount
[m
]; i
++) {
2431 nvector
[m
][i
] = nvector
[NES_MAX_INFO
][i
];
2433 nvectorcount
[m
] = nvectorcount
[NES_MAX_INFO
];
2440 // ----------------------------- crypto1 destroy
2441 crypto1_destroy(pcs
);
2443 // add trace trailer
2444 memset(uid
, 0x44, 4);
2445 LogTrace(uid
, 4, 0, 0, TRUE
);
2447 for (i
= 0; i
< NES_MAX_INFO
; i
++) {
2448 if (nvectorcount
[i
] > 10) continue;
2450 for (j
= 0; j
< nvectorcount
[i
]; j
+= 5) {
2451 ncount
= nvectorcount
[i
] - j
;
2452 if (ncount
> 5) ncount
= 5;
2454 ack
.arg
[0] = 0; // isEOF = 0
2455 ack
.arg
[1] = ncount
;
2456 ack
.arg
[2] = targetBlockNo
+ (targetKeyType
* 0x100);
2457 memset(ack
.d
.asBytes
, 0x00, sizeof(ack
.d
.asBytes
));
2459 memcpy(ack
.d
.asBytes
, &cuid
, 4);
2460 for (m
= 0; m
< ncount
; m
++) {
2461 memcpy(ack
.d
.asBytes
+ 8 + m
* 8 + 0, &nvector
[i
][m
+ j
].nt
, 4);
2462 memcpy(ack
.d
.asBytes
+ 8 + m
* 8 + 4, &nvector
[i
][m
+ j
].ks1
, 4);
2467 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2473 ack
.arg
[0] = 1; // isEOF = 1
2476 memset(ack
.d
.asBytes
, 0x00, sizeof(ack
.d
.asBytes
));
2480 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2483 if (MF_DBGLEVEL
>= 4) DbpString("NESTED FINISHED");
2486 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2492 //-----------------------------------------------------------------------------
2493 // MIFARE check keys. key count up to 8.
2495 //-----------------------------------------------------------------------------
2496 void MifareChkKeys(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2499 uint8_t blockNo
= arg0
;
2500 uint8_t keyType
= arg1
;
2501 uint8_t keyCount
= arg2
;
2502 uint64_t ui64Key
= 0;
2509 struct Crypto1State mpcs
= {0, 0};
2510 struct Crypto1State
*pcs
;
2513 // clear debug level
2514 int OLD_MF_DBGLEVEL
= MF_DBGLEVEL
;
2515 MF_DBGLEVEL
= MF_DBG_NONE
;
2528 for (i
= 0; i
< keyCount
; i
++) {
2529 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2531 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2533 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2534 if (OLD_MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2538 ui64Key
= bytes_to_num(datain
+ i
* 6, 6);
2539 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
2547 // ----------------------------- crypto1 destroy
2548 crypto1_destroy(pcs
);
2550 // add trace trailer
2551 memset(uid
, 0x44, 4);
2552 LogTrace(uid
, 4, 0, 0, TRUE
);
2554 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2555 if (isOK
) memcpy(ack
.d
.asBytes
, datain
+ i
* 6, 6);
2558 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2562 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2565 // restore debug level
2566 MF_DBGLEVEL
= OLD_MF_DBGLEVEL
;
2569 //-----------------------------------------------------------------------------
2570 // MIFARE 1K simulate.
2572 //-----------------------------------------------------------------------------
2573 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2575 int cardSTATE
= MFEMUL_NOFIELD
;
2576 int vHf
= 0; // in mV
2577 int nextCycleTimeout
= 0;
2580 uint32_t selTimer
= 0;
2581 uint32_t authTimer
= 0;
2584 uint8_t cardWRBL
= 0;
2585 uint8_t cardAUTHSC
= 0;
2586 uint8_t cardAUTHKEY
= 0xff; // no authentication
2588 struct Crypto1State mpcs
= {0, 0};
2589 struct Crypto1State
*pcs
;
2592 uint64_t key64
= 0xffffffffffffULL
;
2594 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
2595 uint8_t *response
= eml_get_bigbufptr_sendbuf();
2597 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k
2599 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2600 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2602 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2604 static uint8_t rAUTH_NT
[] = {0x1a, 0xac, 0xff, 0x4f};
2605 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2613 emlGetMemBt(rUIDBCC1
, 0, 4);
2614 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2616 // -------------------------------------- test area
2618 // Authenticate response - nonce
2619 uint8_t *resp1
= (((uint8_t *)BigBuf
) + EML_RESPONSES
);
2621 // uint8_t *resp2 = (((uint8_t *)BigBuf) + EML_RESPONSES + 200);
2623 CodeIso14443aAsTag(rAUTH_NT
, sizeof(rAUTH_NT
));
2624 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
2626 timer
= GetTickCount();
2627 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2628 uint32_t rn_enc
= 0x98d76b77; // !!!!!!!!!!!!!!!!!
2630 cuid
= bytes_to_num(rUIDBCC1
, 4);
2632 crypto1_create(pcs, key64);
2633 crypto1_word(pcs, cuid ^ nonce, 0);
2634 crypto1_word(pcs, rn_enc , 1);
2635 crypto1_word(pcs, 0, 0);
2636 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2637 num_to_bytes(ans, 4, rAUTH_AT);
2638 CodeIso14443aAsTag(rAUTH_AT, sizeof(rAUTH_AT));
2639 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
2640 Dbprintf("crypto auth time: %d", GetTickCount() - timer);
2642 // -------------------------------------- END test area
2643 // start mkseconds counter
2646 // We need to listen to the high-frequency, peak-detected path.
2647 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2650 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2653 Dbprintf("--> start");
2654 // calibrate mkseconds counter
2659 if(BUTTON_PRESS()) {
2663 // find reader field
2664 // Vref = 3300mV, and an 10:1 voltage divider on the input
2665 // can measure voltages up to 33000 mV
2666 if (cardSTATE
== MFEMUL_NOFIELD
) {
2667 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2668 if (vHf
> MF_MINFIELDV
) {
2669 cardSTATE
= MFEMUL_IDLE
;
2674 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2675 res
= EmGetCmd(receivedCmd
, &len
, 100); // (+ nextCycleTimeout)
2677 cardSTATE
= MFEMUL_NOFIELD
;
2684 nextCycleTimeout
= 0;
2686 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2688 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2689 // REQ or WUP request in ANY state and WUP in HALTED state
2690 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2691 selTimer
= GetTickCount();
2692 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2693 cardSTATE
= MFEMUL_SELECT1
;
2695 // init crypto block
2698 crypto1_destroy(pcs
);
2703 switch (cardSTATE
) {
2704 case MFEMUL_NOFIELD
:{
2707 case MFEMUL_HALTED
:{
2713 case MFEMUL_SELECT1
:{
2715 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2716 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2718 if (rUIDBCC1
[0] == 0x88) {
2719 cardSTATE
= MFEMUL_SELECT2
;
2725 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2726 EmSendCmd(rSAK
, sizeof(rSAK
));
2728 cuid
= bytes_to_num(rUIDBCC1
, 4);
2729 cardSTATE
= MFEMUL_WORK
;
2731 Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2736 case MFEMUL_SELECT2
:{
2737 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2739 cuid
= bytes_to_num(rUIDBCC2
, 4);
2740 cardSTATE
= MFEMUL_WORK
;
2742 Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2747 // ---------------------------------
2748 rn_enc
= bytes_to_num(receivedCmd
, 4);
2749 crypto1_create(pcs
, key64
);
2750 crypto1_word(pcs
, cuid
^ nonce
, 0);
2751 crypto1_word(pcs
, rn_enc
, 1);
2752 crypto1_word(pcs
, 0, 0);
2753 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2754 num_to_bytes(ans
, 4, rAUTH_AT
);
2755 // ---------------------------------
2756 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2757 cardSTATE
= MFEMUL_AUTH2
;
2759 cardSTATE
= MFEMUL_IDLE
;
2763 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2766 // test auth info here...
2769 cardSTATE
= MFEMUL_WORK
;
2770 Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2775 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2776 authTimer
= GetTickCount();
2777 // EmSendCmd(rAUTH_NT, sizeof(rAUTH_NT));
2778 EmSendCmd14443aRaw(resp1
, resp1Len
, 0);
2779 LogTrace(NULL
, 0, GetDeltaCountUS(), 0, TRUE
);
2780 // crypto1_create(pcs, key64);
2781 // if (cardAUTHKEY == 0xff) { // first auth
2782 // crypto1_word(pcs, cuid ^ bytes_to_num(rAUTH_NT, 4), 0); // uid ^ nonce
2783 // } else { // nested auth
2786 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2787 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2788 cardSTATE
= MFEMUL_AUTH1
;
2789 nextCycleTimeout
= 10;
2793 if (len
== 0) break;
2796 if (cardAUTHKEY
!= 0xff) mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2798 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2799 // BUT... ACK --> NACK
2800 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2801 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2805 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2806 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2807 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2812 if (len
== 4 && receivedCmd
[0] == 0x30) {
2813 if (receivedCmd
[1] >= 16 * 4) {
2814 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2817 emlGetMem(response
, receivedCmd
[1], 1);
2818 AppendCrc14443a(response
, 16);
2819 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2820 EmSendCmdPar(response
, 18, par
);
2825 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2826 if (receivedCmd
[1] >= 16 * 4) {
2827 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2830 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2831 nextCycleTimeout
= 50;
2832 cardSTATE
= MFEMUL_WRITEBL2
;
2833 cardWRBL
= receivedCmd
[1];
2838 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2839 cardSTATE
= MFEMUL_HALTED
;
2842 Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2847 // command not allowed
2849 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2853 case MFEMUL_WRITEBL2
:{
2855 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2856 emlSetMem(receivedCmd
, cardWRBL
, 1);
2857 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2858 cardSTATE
= MFEMUL_WORK
;
2861 Dbprintf("err write block: %d len:%d", cardWRBL
, len
);
2869 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2872 // add trace trailer
2873 memset(rAUTH_NT
, 0x44, 4);
2874 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2876 DbpString("Emulator stopped.");