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
;
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
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
63 // BIG CHANGE - UNDERSTAND THIS BEFORE WE COMMIT
64 #define RECV_CMD_OFFSET 3032
65 #define RECV_RES_OFFSET 3096
66 #define DMA_BUFFER_OFFSET 3160
67 #define DMA_BUFFER_SIZE 4096
68 #define TRACE_LENGTH 3000
69 // card emulator memory
70 #define CARD_MEMORY 7260
71 #define CARD_MEMORY_LEN 1024
74 void iso14a_set_trigger(int enable
) {
78 //-----------------------------------------------------------------------------
79 // Generate the parity value for a byte sequence
81 //-----------------------------------------------------------------------------
82 byte_t
oddparity (const byte_t bt
)
84 return OddByteParity
[bt
];
87 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
92 // Generate the encrypted data
93 for (i
= 0; i
< iLen
; i
++) {
94 // Save the encrypted parity bit
95 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
100 void AppendCrc14443a(uint8_t* data
, int len
)
102 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
105 int LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
107 // Return when trace is full
108 if (traceLen
>= TRACE_LENGTH
) return FALSE
;
110 // Trace the random, i'm curious
111 rsamples
+= iSamples
;
112 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
113 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
114 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
115 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
117 trace
[traceLen
- 1] |= 0x80;
119 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
120 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
121 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
122 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
123 trace
[traceLen
++] = iLen
;
124 memcpy(trace
+ traceLen
, btBytes
, iLen
);
129 //-----------------------------------------------------------------------------
130 // The software UART that receives commands from the reader, and its state
132 //-----------------------------------------------------------------------------
136 STATE_START_OF_COMMUNICATION
,
160 static RAMFUNC
int MillerDecoding(int bit
)
165 if(!Uart
.bitBuffer
) {
166 Uart
.bitBuffer
= bit
^ 0xFF0;
170 Uart
.bitBuffer
<<= 4;
171 Uart
.bitBuffer
^= bit
;
176 if(Uart
.state
!= STATE_UNSYNCD
) {
179 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
185 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
191 if(bit
!= bitright
) { bit
= bitright
; }
193 if(Uart
.posCnt
== 1) {
194 // measurement first half bitperiod
196 Uart
.drop
= DROP_FIRST_HALF
;
200 // measurement second half bitperiod
201 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
202 Uart
.drop
= DROP_SECOND_HALF
;
205 // measured a drop in first and second half
206 // which should not be possible
207 Uart
.state
= STATE_ERROR_WAIT
;
214 case STATE_START_OF_COMMUNICATION
:
216 if(Uart
.drop
== DROP_SECOND_HALF
) {
217 // error, should not happen in SOC
218 Uart
.state
= STATE_ERROR_WAIT
;
223 Uart
.state
= STATE_MILLER_Z
;
230 if(Uart
.drop
== DROP_NONE
) {
231 // logic '0' followed by sequence Y
232 // end of communication
233 Uart
.state
= STATE_UNSYNCD
;
236 // if(Uart.drop == DROP_FIRST_HALF) {
237 // Uart.state = STATE_MILLER_Z; stay the same
238 // we see a logic '0' }
239 if(Uart
.drop
== DROP_SECOND_HALF
) {
240 // we see a logic '1'
241 Uart
.shiftReg
|= 0x100;
242 Uart
.state
= STATE_MILLER_X
;
248 if(Uart
.drop
== DROP_NONE
) {
249 // sequence Y, we see a '0'
250 Uart
.state
= STATE_MILLER_Y
;
253 if(Uart
.drop
== DROP_FIRST_HALF
) {
254 // Would be STATE_MILLER_Z
255 // but Z does not follow X, so error
256 Uart
.state
= STATE_ERROR_WAIT
;
259 if(Uart
.drop
== DROP_SECOND_HALF
) {
260 // We see a '1' and stay in state X
261 Uart
.shiftReg
|= 0x100;
269 if(Uart
.drop
== DROP_NONE
) {
270 // logic '0' followed by sequence Y
271 // end of communication
272 Uart
.state
= STATE_UNSYNCD
;
275 if(Uart
.drop
== DROP_FIRST_HALF
) {
277 Uart
.state
= STATE_MILLER_Z
;
279 if(Uart
.drop
== DROP_SECOND_HALF
) {
280 // We see a '1' and go to state X
281 Uart
.shiftReg
|= 0x100;
282 Uart
.state
= STATE_MILLER_X
;
286 case STATE_ERROR_WAIT
:
287 // That went wrong. Now wait for at least two bit periods
288 // and try to sync again
289 if(Uart
.drop
== DROP_NONE
) {
291 Uart
.state
= STATE_UNSYNCD
;
296 Uart
.state
= STATE_UNSYNCD
;
301 Uart
.drop
= DROP_NONE
;
303 // should have received at least one whole byte...
304 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
308 if(Uart
.bitCnt
== 9) {
309 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
312 Uart
.parityBits
<<= 1;
313 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
316 // when End of Communication received and
317 // all data bits processed..
324 Uart.output[Uart.byteCnt] = 0xAA;
326 Uart.output[Uart.byteCnt] = error & 0xFF;
328 Uart.output[Uart.byteCnt] = 0xAA;
330 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
332 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
334 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
336 Uart.output[Uart.byteCnt] = 0xAA;
344 bit
= Uart
.bitBuffer
& 0xf0;
348 // should have been high or at least (4 * 128) / fc
349 // according to ISO this should be at least (9 * 128 + 20) / fc
350 if(Uart
.highCnt
== 8) {
351 // we went low, so this could be start of communication
352 // it turns out to be safer to choose a less significant
353 // syncbit... so we check whether the neighbour also represents the drop
354 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
355 Uart
.syncBit
= bit
& 8;
357 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
358 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
359 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
360 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
361 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
362 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
365 // the first half bit period is expected in next sample
370 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
373 Uart
.state
= STATE_START_OF_COMMUNICATION
;
374 Uart
.drop
= DROP_FIRST_HALF
;
385 if(Uart
.highCnt
< 8) {
394 //=============================================================================
395 // ISO 14443 Type A - Manchester
396 //=============================================================================
401 DEMOD_START_OF_COMMUNICATION
,
424 static RAMFUNC
int ManchesterDecoding(int v
)
440 if(Demod
.state
==DEMOD_UNSYNCD
) {
441 Demod
.output
[Demod
.len
] = 0xfa;
444 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
447 Demod
.syncBit
= 0x08;
454 Demod
.syncBit
= 0x04;
461 Demod
.syncBit
= 0x02;
464 if(bit
& 0x01 && Demod
.syncBit
) {
465 Demod
.syncBit
= 0x01;
470 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
471 Demod
.sub
= SUB_FIRST_HALF
;
474 Demod
.parityBits
= 0;
477 if(trigger
) LED_A_OFF();
478 switch(Demod
.syncBit
) {
479 case 0x08: Demod
.samples
= 3; break;
480 case 0x04: Demod
.samples
= 2; break;
481 case 0x02: Demod
.samples
= 1; break;
482 case 0x01: Demod
.samples
= 0; break;
489 //modulation = bit & Demod.syncBit;
490 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
494 if(Demod
.posCount
==0) {
497 Demod
.sub
= SUB_FIRST_HALF
;
500 Demod
.sub
= SUB_NONE
;
505 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
506 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
507 Demod
.state
= DEMOD_ERROR_WAIT
;
508 Demod
.output
[Demod
.len
] = 0xaa;
512 else if(modulation
) {
513 Demod
.sub
= SUB_SECOND_HALF
;
516 switch(Demod
.state
) {
517 case DEMOD_START_OF_COMMUNICATION
:
518 if(Demod
.sub
== SUB_FIRST_HALF
) {
519 Demod
.state
= DEMOD_MANCHESTER_D
;
522 Demod
.output
[Demod
.len
] = 0xab;
523 Demod
.state
= DEMOD_ERROR_WAIT
;
528 case DEMOD_MANCHESTER_D
:
529 case DEMOD_MANCHESTER_E
:
530 if(Demod
.sub
== SUB_FIRST_HALF
) {
532 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
533 Demod
.state
= DEMOD_MANCHESTER_D
;
535 else if(Demod
.sub
== SUB_SECOND_HALF
) {
537 Demod
.shiftReg
>>= 1;
538 Demod
.state
= DEMOD_MANCHESTER_E
;
541 Demod
.state
= DEMOD_MANCHESTER_F
;
545 case DEMOD_MANCHESTER_F
:
546 // Tag response does not need to be a complete byte!
547 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
548 if(Demod
.bitCount
> 0) {
549 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
550 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
552 // No parity bit, so just shift a 0
553 Demod
.parityBits
<<= 1;
556 Demod
.state
= DEMOD_UNSYNCD
;
560 Demod
.output
[Demod
.len
] = 0xad;
561 Demod
.state
= DEMOD_ERROR_WAIT
;
566 case DEMOD_ERROR_WAIT
:
567 Demod
.state
= DEMOD_UNSYNCD
;
571 Demod
.output
[Demod
.len
] = 0xdd;
572 Demod
.state
= DEMOD_UNSYNCD
;
576 if(Demod
.bitCount
>=9) {
577 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
580 Demod
.parityBits
<<= 1;
581 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
588 Demod.output[Demod.len] = 0xBB;
590 Demod.output[Demod.len] = error & 0xFF;
592 Demod.output[Demod.len] = 0xBB;
594 Demod.output[Demod.len] = bit & 0xFF;
596 Demod.output[Demod.len] = Demod.buffer & 0xFF;
598 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
600 Demod.output[Demod.len] = 0xBB;
607 } // end (state != UNSYNCED)
612 //=============================================================================
613 // Finally, a `sniffer' for ISO 14443 Type A
614 // Both sides of communication!
615 //=============================================================================
617 //-----------------------------------------------------------------------------
618 // Record the sequence of commands sent by the reader to the tag, with
619 // triggering so that we start recording at the point that the tag is moved
621 //-----------------------------------------------------------------------------
622 void RAMFUNC
SnoopIso14443a(void)
624 // #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
625 // #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
626 // #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
627 // #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
628 // #define TRACE_LENGTH 2000 // original (working as of 21/2/09) values
630 // We won't start recording the frames that we acquire until we trigger;
631 // a good trigger condition to get started is probably when we see a
632 // response from the tag.
633 int triggered
= FALSE
; // FALSE to wait first for card
635 // The command (reader -> tag) that we're receiving.
636 // The length of a received command will in most cases be no more than 18 bytes.
637 // So 32 should be enough!
638 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
639 // The response (tag -> reader) that we're receiving.
640 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
642 // As we receive stuff, we copy it from receivedCmd or receivedResponse
643 // into trace, along with its length and other annotations.
644 //uint8_t *trace = (uint8_t *)BigBuf;
646 traceLen
= 0; // uncommented to fix ISSUE 15 - gerhard - jan2011
648 // The DMA buffer, used to stream samples from the FPGA
649 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
655 // Count of samples received so far, so that we can include timing
656 // information in the trace buffer.
660 memset(trace
, 0x44, RECV_CMD_OFFSET
);
662 // Set up the demodulator for tag -> reader responses.
663 Demod
.output
= receivedResponse
;
665 Demod
.state
= DEMOD_UNSYNCD
;
667 // Setup for the DMA.
670 lastRxCounter
= DMA_BUFFER_SIZE
;
671 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
673 // And the reader -> tag commands
674 memset(&Uart
, 0, sizeof(Uart
));
675 Uart
.output
= receivedCmd
;
676 Uart
.byteCntMax
= 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
677 Uart
.state
= STATE_UNSYNCD
;
679 // And put the FPGA in the appropriate mode
680 // Signal field is off with the appropriate LED
682 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
683 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
686 // And now we loop, receiving samples.
690 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) &
692 if(behindBy
> maxBehindBy
) {
693 maxBehindBy
= behindBy
;
695 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy
);
699 if(behindBy
< 1) continue;
705 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
706 upTo
-= DMA_BUFFER_SIZE
;
707 lastRxCounter
+= DMA_BUFFER_SIZE
;
708 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
709 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
713 if(MillerDecoding((smpl
& 0xF0) >> 4)) {
714 rsamples
= samples
- Uart
.samples
;
717 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
718 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
719 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
720 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
721 trace
[traceLen
++] = ((Uart
.parityBits
>> 0) & 0xff);
722 trace
[traceLen
++] = ((Uart
.parityBits
>> 8) & 0xff);
723 trace
[traceLen
++] = ((Uart
.parityBits
>> 16) & 0xff);
724 trace
[traceLen
++] = ((Uart
.parityBits
>> 24) & 0xff);
725 trace
[traceLen
++] = Uart
.byteCnt
;
726 memcpy(trace
+traceLen
, receivedCmd
, Uart
.byteCnt
);
727 traceLen
+= Uart
.byteCnt
;
728 if(traceLen
> TRACE_LENGTH
) break;
730 /* And ready to receive another command. */
731 Uart
.state
= STATE_UNSYNCD
;
732 /* And also reset the demod code, which might have been */
733 /* false-triggered by the commands from the reader. */
734 Demod
.state
= DEMOD_UNSYNCD
;
738 if(ManchesterDecoding(smpl
& 0x0F)) {
739 rsamples
= samples
- Demod
.samples
;
742 // timestamp, as a count of samples
743 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
744 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
745 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
746 trace
[traceLen
++] = 0x80 | ((rsamples
>> 24) & 0xff);
747 trace
[traceLen
++] = ((Demod
.parityBits
>> 0) & 0xff);
748 trace
[traceLen
++] = ((Demod
.parityBits
>> 8) & 0xff);
749 trace
[traceLen
++] = ((Demod
.parityBits
>> 16) & 0xff);
750 trace
[traceLen
++] = ((Demod
.parityBits
>> 24) & 0xff);
752 trace
[traceLen
++] = Demod
.len
;
753 memcpy(trace
+traceLen
, receivedResponse
, Demod
.len
);
754 traceLen
+= Demod
.len
;
755 if(traceLen
> TRACE_LENGTH
) break;
759 // And ready to receive another response.
760 memset(&Demod
, 0, sizeof(Demod
));
761 Demod
.output
= receivedResponse
;
762 Demod
.state
= DEMOD_UNSYNCD
;
767 DbpString("cancelled_a");
772 DbpString("COMMAND FINISHED");
774 Dbprintf("%x %x %x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
775 Dbprintf("%x %x %x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
778 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
779 Dbprintf("%x %x %x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
780 Dbprintf("%x %x %x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
787 //-----------------------------------------------------------------------------
788 // Prepare tag messages
789 //-----------------------------------------------------------------------------
790 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
)
797 // Correction bit, might be removed when not needed
802 ToSendStuffBit(1); // 1
808 ToSend
[++ToSendMax
] = SEC_D
;
810 for(i
= 0; i
< len
; i
++) {
816 for(j
= 0; j
< 8; j
++) {
817 oddparity
^= (b
& 1);
819 ToSend
[++ToSendMax
] = SEC_D
;
821 ToSend
[++ToSendMax
] = SEC_E
;
828 ToSend
[++ToSendMax
] = SEC_D
;
830 ToSend
[++ToSendMax
] = SEC_E
;
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;
851 //-----------------------------------------------------------------------------
852 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
853 //-----------------------------------------------------------------------------
854 static void CodeStrangeAnswer()
860 // Correction bit, might be removed when not needed
865 ToSendStuffBit(1); // 1
871 ToSend
[++ToSendMax
] = SEC_D
;
874 ToSend
[++ToSendMax
] = SEC_E
;
877 ToSend
[++ToSendMax
] = SEC_E
;
880 ToSend
[++ToSendMax
] = SEC_D
;
883 ToSend
[++ToSendMax
] = SEC_F
;
885 // Flush the buffer in FPGA!!
886 for(i
= 0; i
< 5; i
++) {
887 ToSend
[++ToSendMax
] = SEC_F
;
890 // Convert from last byte pos to length
893 // Add a few more for slop
894 ToSend
[ToSendMax
++] = 0x00;
895 ToSend
[ToSendMax
++] = 0x00;
899 //-----------------------------------------------------------------------------
900 // Wait for commands from reader
901 // Stop when button is pressed
902 // Or return TRUE when command is captured
903 //-----------------------------------------------------------------------------
904 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
906 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
907 // only, since we are receiving, not transmitting).
908 // Signal field is off with the appropriate LED
910 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
912 // Now run a `software UART' on the stream of incoming samples.
913 Uart
.output
= received
;
914 Uart
.byteCntMax
= maxLen
;
915 Uart
.state
= STATE_UNSYNCD
;
920 if(BUTTON_PRESS()) return FALSE
;
922 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
923 AT91C_BASE_SSC
->SSC_THR
= 0x00;
925 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
926 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
927 if(MillerDecoding((b
& 0xf0) >> 4)) {
931 if(MillerDecoding(b
& 0x0f)) {
938 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
940 //-----------------------------------------------------------------------------
941 // Main loop of simulated tag: receive commands from reader, decide what
942 // response to send, and send it.
943 //-----------------------------------------------------------------------------
944 void SimulateIso14443aTag(int tagType
, int TagUid
)
946 // This function contains the tag emulation
948 // Prepare protocol messages
949 // static const uint8_t cmd1[] = { 0x26 };
950 // static const uint8_t response1[] = { 0x02, 0x00 }; // Says: I am Mifare 4k - original line - greg
952 static const uint8_t response1
[] = { 0x44, 0x03 }; // Says: I am a DESFire Tag, ph33r me
953 // static const uint8_t response1[] = { 0x44, 0x00 }; // Says: I am a ULTRALITE Tag, 0wn me
956 // static const uint8_t cmd2[] = { 0x93, 0x20 };
957 //static const uint8_t response2[] = { 0x9a, 0xe5, 0xe4, 0x43, 0xd8 }; // original value - greg
960 static const uint8_t response2
[] = { 0x88, 0x04, 0x21, 0x3f, 0x4d }; // known uid - note cascade (0x88), 2nd byte (0x04) = NXP/Phillips
963 // When reader selects us during cascade1 it will send cmd3
964 //uint8_t response3[] = { 0x04, 0x00, 0x00 }; // SAK Select (cascade1) successful response (ULTRALITE)
965 uint8_t response3
[] = { 0x24, 0x00, 0x00 }; // SAK Select (cascade1) successful response (DESFire)
966 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
968 // send cascade2 2nd half of UID
969 static const uint8_t response2a
[] = { 0x51, 0x48, 0x1d, 0x80, 0x84 }; // uid - cascade2 - 2nd half (4 bytes) of UID+ BCCheck
970 // NOTE : THE CRC on the above may be wrong as I have obfuscated the actual UID
972 // When reader selects us during cascade2 it will send cmd3a
973 //uint8_t response3a[] = { 0x00, 0x00, 0x00 }; // SAK Select (cascade2) successful response (ULTRALITE)
974 uint8_t response3a
[] = { 0x20, 0x00, 0x00 }; // SAK Select (cascade2) successful response (DESFire)
975 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
977 static const uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
982 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
984 // 144 data bits (18 * 8)
987 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
988 // 1 just for the case
992 // 166 bytes, since every bit that needs to be send costs us a byte
995 // Respond with card type
996 uint8_t *resp1
= (((uint8_t *)BigBuf
) + 800);
999 // Anticollision cascade1 - respond with uid
1000 uint8_t *resp2
= (((uint8_t *)BigBuf
) + 970);
1003 // Anticollision cascade2 - respond with 2nd half of uid if asked
1004 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1005 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1008 // Acknowledge select - cascade 1
1009 uint8_t *resp3
= (((uint8_t *)BigBuf
) + 1310);
1012 // Acknowledge select - cascade 2
1013 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + 1480);
1016 // Response to a read request - not implemented atm
1017 uint8_t *resp4
= (((uint8_t *)BigBuf
) + 1550);
1020 // Authenticate response - nonce
1021 uint8_t *resp5
= (((uint8_t *)BigBuf
) + 1720);
1024 uint8_t *receivedCmd
= (uint8_t *)BigBuf
;
1031 // To control where we are in the protocol
1035 // Just to allow some checks
1043 memset(receivedCmd
, 0x44, 400);
1045 // Prepare the responses of the anticollision phase
1046 // there will be not enough time to do this at the moment the reader sends it REQA
1048 // Answer to request
1049 CodeIso14443aAsTag(response1
, sizeof(response1
));
1050 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1052 // Send our UID (cascade 1)
1053 CodeIso14443aAsTag(response2
, sizeof(response2
));
1054 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1056 // Answer to select (cascade1)
1057 CodeIso14443aAsTag(response3
, sizeof(response3
));
1058 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1060 // Send the cascade 2 2nd part of the uid
1061 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1062 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1064 // Answer to select (cascade 2)
1065 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1066 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1068 // Strange answer is an example of rare message size (3 bits)
1069 CodeStrangeAnswer();
1070 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1072 // Authentication answer (random nonce)
1073 CodeIso14443aAsTag(response5
, sizeof(response5
));
1074 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1076 // We need to listen to the high-frequency, peak-detected path.
1077 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1085 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, 100)) {
1086 DbpString("button press");
1089 // 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
1090 // Okay, look at the command now.
1092 i
= 1; // first byte transmitted
1093 if(receivedCmd
[0] == 0x26) {
1094 // Received a REQUEST
1095 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1096 //DbpString("Hello request from reader:");
1097 } else if(receivedCmd
[0] == 0x52) {
1098 // Received a WAKEUP
1099 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1100 // //DbpString("Wakeup request from reader:");
1102 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // greg - cascade 1 anti-collision
1103 // Received request for UID (cascade 1)
1104 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1105 // DbpString("UID (cascade 1) request from reader:");
1106 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1109 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] ==0x95) { // greg - cascade 2 anti-collision
1110 // Received request for UID (cascade 2)
1111 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1112 // DbpString("UID (cascade 2) request from reader:");
1113 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1116 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x93) { // greg - cascade 1 select
1117 // Received a SELECT
1118 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1119 // DbpString("Select (cascade 1) request from reader:");
1120 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1123 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x95) { // greg - cascade 2 select
1124 // Received a SELECT
1125 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1126 // DbpString("Select (cascade 2) request from reader:");
1127 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1130 } else if(receivedCmd
[0] == 0x30) {
1132 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1133 Dbprintf("Read request from reader: %x %x %x",
1134 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1137 } else if(receivedCmd
[0] == 0x50) {
1139 resp
= resp1
; respLen
= 0; order
= 5; // Do nothing
1140 DbpString("Reader requested we HALT!:");
1142 } else if(receivedCmd
[0] == 0x60) {
1143 // Received an authentication request
1144 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1145 Dbprintf("Authenticate request from reader: %x %x %x",
1146 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1148 } else if(receivedCmd
[0] == 0xE0) {
1149 // Received a RATS request
1150 resp
= resp1
; respLen
= 0;order
= 70;
1151 Dbprintf("RATS request from reader: %x %x %x",
1152 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1154 // Never seen this command before
1155 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1157 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2],
1158 receivedCmd
[3], receivedCmd
[4], receivedCmd
[5],
1159 receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1161 resp
= resp1
; respLen
= 0; order
= 0;
1164 // Count number of wakeups received after a halt
1165 if(order
== 6 && lastorder
== 5) { happened
++; }
1167 // Count number of other messages after a halt
1168 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1170 // Look at last parity bit to determine timing of answer
1171 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1172 // 1236, so correction bit needed
1176 memset(receivedCmd
, 0x44, 32);
1178 if(cmdsRecvd
> 999) {
1179 DbpString("1000 commands later...");
1186 if(respLen
<= 0) continue;
1187 //----------------------------
1190 fdt_indicator
= FALSE
;
1192 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1193 /* // Modulate Manchester
1194 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1195 AT91C_BASE_SSC->SSC_THR = 0x00;
1198 // ### Transmit the response ###
1201 fdt_indicator = FALSE;
1203 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1204 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1207 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1215 AT91C_BASE_SSC->SSC_THR = b;
1221 if(BUTTON_PRESS()) {
1228 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1232 //-----------------------------------------------------------------------------
1233 // Transmit the command (to the tag) that was placed in ToSend[].
1234 //-----------------------------------------------------------------------------
1235 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1239 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1245 for(c
= 0; c
< *wait
;) {
1246 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1247 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1250 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1251 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1259 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1260 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1266 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1267 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1272 if (samples
) *samples
= (c
+ *wait
) << 3;
1275 //-----------------------------------------------------------------------------
1276 // Code a 7-bit command without parity bit
1277 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1278 //-----------------------------------------------------------------------------
1279 void ShortFrameFromReader(const uint8_t bt
)
1287 // Start of Communication (Seq. Z)
1288 ToSend
[++ToSendMax
] = SEC_Z
;
1292 for(j
= 0; j
< 7; j
++) {
1295 ToSend
[++ToSendMax
] = SEC_X
;
1300 ToSend
[++ToSendMax
] = SEC_Z
;
1304 ToSend
[++ToSendMax
] = SEC_Y
;
1311 // End of Communication
1314 ToSend
[++ToSendMax
] = SEC_Z
;
1318 ToSend
[++ToSendMax
] = SEC_Y
;
1322 ToSend
[++ToSendMax
] = SEC_Y
;
1325 ToSend
[++ToSendMax
] = SEC_Y
;
1326 ToSend
[++ToSendMax
] = SEC_Y
;
1327 ToSend
[++ToSendMax
] = SEC_Y
;
1329 // Convert from last character reference to length
1333 //-----------------------------------------------------------------------------
1334 // Prepare reader command to send to FPGA
1336 //-----------------------------------------------------------------------------
1337 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1345 // Start of Communication (Seq. Z)
1346 ToSend
[++ToSendMax
] = SEC_Z
;
1349 // Generate send structure for the data bits
1350 for (i
= 0; i
< len
; i
++) {
1351 // Get the current byte to send
1354 for (j
= 0; j
< 8; j
++) {
1357 ToSend
[++ToSendMax
] = SEC_X
;
1362 ToSend
[++ToSendMax
] = SEC_Z
;
1365 ToSend
[++ToSendMax
] = SEC_Y
;
1372 // Get the parity bit
1373 if ((dwParity
>> i
) & 0x01) {
1375 ToSend
[++ToSendMax
] = SEC_X
;
1380 ToSend
[++ToSendMax
] = SEC_Z
;
1383 ToSend
[++ToSendMax
] = SEC_Y
;
1389 // End of Communication
1392 ToSend
[++ToSendMax
] = SEC_Z
;
1395 ToSend
[++ToSendMax
] = SEC_Y
;
1399 ToSend
[++ToSendMax
] = SEC_Y
;
1402 ToSend
[++ToSendMax
] = SEC_Y
;
1403 ToSend
[++ToSendMax
] = SEC_Y
;
1404 ToSend
[++ToSendMax
] = SEC_Y
;
1406 // Convert from last character reference to length
1410 //-----------------------------------------------------------------------------
1411 // Wait for commands from reader
1412 // Stop when button is pressed (return 1) or field was gone (return 2)
1413 // Or return 0 when command is captured
1414 //-----------------------------------------------------------------------------
1415 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1419 uint32_t timer
= 0, vtime
= 0;
1423 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1424 // only, since we are receiving, not transmitting).
1425 // Signal field is off with the appropriate LED
1427 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1429 // Set ADC to read field strength
1430 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1431 AT91C_BASE_ADC
->ADC_MR
=
1432 ADC_MODE_PRESCALE(32) |
1433 ADC_MODE_STARTUP_TIME(16) |
1434 ADC_MODE_SAMPLE_HOLD_TIME(8);
1435 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1437 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1439 // Now run a 'software UART' on the stream of incoming samples.
1440 Uart
.output
= received
;
1441 Uart
.byteCntMax
= maxLen
;
1442 Uart
.state
= STATE_UNSYNCD
;
1447 if (BUTTON_PRESS()) return 1;
1449 // test if the field exists
1450 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1452 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1453 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1454 if (analogCnt
>= 32) {
1455 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1456 vtime
= GetTickCount();
1457 if (!timer
) timer
= vtime
;
1458 // 50ms no field --> card to idle state
1459 if (vtime
- timer
> 50) return 2;
1461 if (timer
) timer
= 0;
1467 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1468 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1470 // receive and test the miller decoding
1471 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1472 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1473 if(MillerDecoding((b
& 0xf0) >> 4)) {
1474 *len
= Uart
.byteCnt
;
1475 if (tracing
) LogTrace(received
, *len
, 0, GetParity(received
, *len
), TRUE
);
1478 if(MillerDecoding(b
& 0x0f)) {
1479 *len
= Uart
.byteCnt
;
1480 if (tracing
) LogTrace(received
, *len
, 0, GetParity(received
, *len
), TRUE
);
1487 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1492 // Modulate Manchester
1493 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1494 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1497 // include correction bit
1499 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1500 // 1236, so correction bit needed
1506 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1507 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1510 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1518 AT91C_BASE_SSC
->SSC_THR
= b
;
1522 if(BUTTON_PRESS()) {
1530 static int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1531 CodeIso14443aAsTag(resp
, respLen
);
1532 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1533 if (tracing
) LogTrace(resp
, respLen
, 0, GetParity(resp
, respLen
), FALSE
);
1537 static int EmSendCmd(uint8_t *resp
, int respLen
){
1538 return EmSendCmdEx(resp
, respLen
, 0);
1541 //-----------------------------------------------------------------------------
1542 // Wait a certain time for tag response
1543 // If a response is captured return TRUE
1544 // If it takes to long return FALSE
1545 //-----------------------------------------------------------------------------
1546 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1548 // buffer needs to be 512 bytes
1551 // Set FPGA mode to "reader listen mode", no modulation (listen
1552 // only, since we are receiving, not transmitting).
1553 // Signal field is on with the appropriate LED
1555 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1557 // Now get the answer from the card
1558 Demod
.output
= receivedResponse
;
1560 Demod
.state
= DEMOD_UNSYNCD
;
1563 if (elapsed
) *elapsed
= 0;
1569 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1570 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1571 if (elapsed
) (*elapsed
)++;
1573 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1574 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1575 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1576 if(ManchesterDecoding((b
>>4) & 0xf)) {
1577 *samples
= ((c
- 1) << 3) + 4;
1580 if(ManchesterDecoding(b
& 0x0f)) {
1588 void ReaderTransmitShort(const uint8_t* bt
)
1593 ShortFrameFromReader(*bt
);
1596 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1598 // Store reader command in buffer
1599 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1602 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1607 // This is tied to other size changes
1608 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1609 CodeIso14443aAsReaderPar(frame
,len
,par
);
1612 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1616 // Store reader command in buffer
1617 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1621 void ReaderTransmit(uint8_t* frame
, int len
)
1623 // Generate parity and redirect
1624 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1627 int ReaderReceive(uint8_t* receivedAnswer
)
1630 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1631 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1632 if(samples
== 0) return FALSE
;
1636 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1639 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1640 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1641 *parptr
= Demod
.parityBits
;
1642 if(samples
== 0) return FALSE
;
1646 /* performs iso14443a anticolision procedure
1647 * fills the uid pointer unless NULL
1648 * fills resp_data unless NULL */
1649 int iso14443a_select_card(uint8_t * uid_ptr
, iso14a_card_select_t
* resp_data
, uint32_t * cuid_ptr
) {
1650 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1651 uint8_t sel_all
[] = { 0x93,0x20 };
1652 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1653 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1655 uint8_t* resp
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1657 uint8_t sak
= 0x04; // cascade uid
1658 int cascade_level
= 0;
1663 memset(uid_ptr
, 0, 8);
1665 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1666 ReaderTransmitShort(wupa
);
1668 if(!ReaderReceive(resp
)) return 0;
1671 memcpy(resp_data
->atqa
, resp
, 2);
1673 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1674 // which case we need to make a cascade 2 request and select - this is a long UID
1675 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1676 for(; sak
& 0x04; cascade_level
++)
1678 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1679 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1682 ReaderTransmit(sel_all
,sizeof(sel_all
));
1683 if (!ReaderReceive(resp
)) return 0;
1684 if(uid_ptr
) memcpy(uid_ptr
+ cascade_level
*4, resp
, 4);
1686 // calculate crypto UID
1687 if(cuid_ptr
) *cuid_ptr
= bytes_to_num(resp
, 4);
1689 // Construct SELECT UID command
1690 memcpy(sel_uid
+2,resp
,5);
1691 AppendCrc14443a(sel_uid
,7);
1692 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1695 if (!ReaderReceive(resp
)) return 0;
1699 resp_data
->sak
= sak
;
1700 resp_data
->ats_len
= 0;
1702 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1703 if (uid_ptr
[0] == 0x88) {
1704 memcpy(uid_ptr
, uid_ptr
+ 1, 7);
1708 if( (sak
& 0x20) == 0)
1709 return 2; // non iso14443a compliant tag
1711 // Request for answer to select
1712 if(resp_data
) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1713 AppendCrc14443a(rats
, 2);
1714 ReaderTransmit(rats
, sizeof(rats
));
1716 if (!(len
= ReaderReceive(resp
))) return 0;
1718 memcpy(resp_data
->ats
, resp
, sizeof(resp_data
->ats
));
1719 resp_data
->ats_len
= len
;
1725 void iso14443a_setup() {
1728 // Start from off (no field generated)
1729 // Signal field is off with the appropriate LED
1731 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1734 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1736 // Now give it time to spin up.
1737 // Signal field is on with the appropriate LED
1739 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1742 iso14a_timeout
= 2048; //default
1745 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1746 uint8_t real_cmd
[cmd_len
+4];
1747 real_cmd
[0] = 0x0a; //I-Block
1748 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1749 memcpy(real_cmd
+2, cmd
, cmd_len
);
1750 AppendCrc14443a(real_cmd
,cmd_len
+2);
1752 ReaderTransmit(real_cmd
, cmd_len
+4);
1753 size_t len
= ReaderReceive(data
);
1755 return -1; //DATA LINK ERROR
1761 //-----------------------------------------------------------------------------
1762 // Read an ISO 14443a tag. Send out commands and store answers.
1764 //-----------------------------------------------------------------------------
1765 void ReaderIso14443a(UsbCommand
* c
, UsbCommand
* ack
)
1767 iso14a_command_t param
= c
->arg
[0];
1768 uint8_t * cmd
= c
->d
.asBytes
;
1769 size_t len
= c
->arg
[1];
1771 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(1);
1773 if(param
& ISO14A_CONNECT
) {
1775 ack
->arg
[0] = iso14443a_select_card(ack
->d
.asBytes
, (iso14a_card_select_t
*) (ack
->d
.asBytes
+12), NULL
);
1776 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1779 if(param
& ISO14A_SET_TIMEOUT
) {
1780 iso14a_timeout
= c
->arg
[2];
1783 if(param
& ISO14A_SET_TIMEOUT
) {
1784 iso14a_timeout
= c
->arg
[2];
1787 if(param
& ISO14A_APDU
) {
1788 ack
->arg
[0] = iso14_apdu(cmd
, len
, ack
->d
.asBytes
);
1789 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1792 if(param
& ISO14A_RAW
) {
1793 if(param
& ISO14A_APPEND_CRC
) {
1794 AppendCrc14443a(cmd
,len
);
1797 ReaderTransmit(cmd
,len
);
1798 ack
->arg
[0] = ReaderReceive(ack
->d
.asBytes
);
1799 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1802 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(0);
1804 if(param
& ISO14A_NO_DISCONNECT
)
1807 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1810 //-----------------------------------------------------------------------------
1811 // Read an ISO 14443a tag. Send out commands and store answers.
1813 //-----------------------------------------------------------------------------
1814 void ReaderMifare(uint32_t parameter
)
1817 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1818 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1820 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1833 byte_t par_mask
= 0xff;
1840 byte_t nt
[4] = {0,0,0,0};
1841 byte_t nt_attacked
[4], nt_noattack
[4];
1842 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1843 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1844 num_to_bytes(parameter
, 4, nt_noattack
);
1845 int isOK
= 0, isNULL
= 0;
1850 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1852 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1855 // Test if the action was cancelled
1856 if(BUTTON_PRESS()) {
1860 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1862 // Transmit MIFARE_CLASSIC_AUTH
1863 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1865 // Receive the (16 bit) "random" nonce
1866 if (!ReaderReceive(receivedAnswer
)) continue;
1867 memcpy(nt
, receivedAnswer
, 4);
1869 // Transmit reader nonce and reader answer
1870 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1872 // Receive 4 bit answer
1873 if (ReaderReceive(receivedAnswer
))
1875 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1877 isNULL
= (nt_attacked
[0] = 0) && (nt_attacked
[1] = 0) && (nt_attacked
[2] = 0) && (nt_attacked
[3] = 0);
1878 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1883 memcpy(nt_attacked
, nt
, 4);
1885 par_low
= par
& 0x07;
1889 if(led_on
) LED_B_ON(); else LED_B_OFF();
1890 par_list
[nt_diff
] = par
;
1891 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1893 // Test if the information is complete
1894 if (nt_diff
== 0x07) {
1899 nt_diff
= (nt_diff
+ 1) & 0x07;
1900 mf_nr_ar
[3] = nt_diff
<< 5;
1907 par
= (((par
>> 3) + 1) << 3) | par_low
;
1912 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1913 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1914 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1916 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
1917 memcpy(ack
.d
.asBytes
+ 0, uid
, 4);
1918 memcpy(ack
.d
.asBytes
+ 4, nt
, 4);
1919 memcpy(ack
.d
.asBytes
+ 8, par_list
, 8);
1920 memcpy(ack
.d
.asBytes
+ 16, ks_list
, 8);
1923 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
1927 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1931 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1934 //-----------------------------------------------------------------------------
1935 // Select, Authenticaate, Read an MIFARE tag.
1937 //-----------------------------------------------------------------------------
1938 void MifareReadBlock(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
1941 uint8_t blockNo
= arg0
;
1942 uint8_t keyType
= arg1
;
1943 uint64_t ui64Key
= 0;
1944 ui64Key
= bytes_to_num(datain
, 6);
1948 byte_t dataoutbuf
[16];
1951 struct Crypto1State mpcs
= {0, 0};
1952 struct Crypto1State
*pcs
;
1966 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
1967 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
1971 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
1972 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
1976 if(mifare_classic_readblock(pcs
, cuid
, blockNo
, dataoutbuf
)) {
1977 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block error");
1981 if(mifare_classic_halt(pcs
, cuid
)) {
1982 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
1990 // ----------------------------- crypto1 destroy
1991 crypto1_destroy(pcs
);
1993 if (MF_DBGLEVEL
>= 2) DbpString("READ BLOCK FINISHED");
1995 // add trace trailer
2000 LogTrace(uid
, 4, 0, 0, TRUE
);
2002 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2003 memcpy(ack
.d
.asBytes
, dataoutbuf
, 16);
2006 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2011 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2017 //-----------------------------------------------------------------------------
2018 // Select, Authenticaate, Read an MIFARE tag.
2019 // read sector (data = 4 x 16 bytes = 64 bytes)
2020 //-----------------------------------------------------------------------------
2021 void MifareReadSector(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2024 uint8_t sectorNo
= arg0
;
2025 uint8_t keyType
= arg1
;
2026 uint64_t ui64Key
= 0;
2027 ui64Key
= bytes_to_num(datain
, 6);
2031 byte_t dataoutbuf
[16 * 4];
2034 struct Crypto1State mpcs
= {0, 0};
2035 struct Crypto1State
*pcs
;
2049 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2050 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2054 if(mifare_classic_auth(pcs
, cuid
, sectorNo
* 4, keyType
, ui64Key
, AUTH_FIRST
)) {
2055 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
2059 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 0, dataoutbuf
+ 16 * 0)) {
2060 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 0 error");
2063 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 1, dataoutbuf
+ 16 * 1)) {
2064 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 1 error");
2067 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 2, dataoutbuf
+ 16 * 2)) {
2068 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 2 error");
2071 if(mifare_classic_readblock(pcs
, cuid
, sectorNo
* 4 + 3, dataoutbuf
+ 16 * 3)) {
2072 if (MF_DBGLEVEL
>= 1) Dbprintf("Read block 3 error");
2076 if(mifare_classic_halt(pcs
, cuid
)) {
2077 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
2085 // ----------------------------- crypto1 destroy
2086 crypto1_destroy(pcs
);
2088 if (MF_DBGLEVEL
>= 2) DbpString("READ SECTOR FINISHED");
2090 // add trace trailer
2095 LogTrace(uid
, 4, 0, 0, TRUE
);
2097 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2098 memcpy(ack
.d
.asBytes
, dataoutbuf
, 16 * 2);
2101 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2105 memcpy(ack
.d
.asBytes
, dataoutbuf
+ 16 * 2, 16 * 2);
2106 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2110 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2116 //-----------------------------------------------------------------------------
2117 // Select, Authenticaate, Read an MIFARE tag.
2119 //-----------------------------------------------------------------------------
2120 void MifareWriteBlock(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2123 uint8_t blockNo
= arg0
;
2124 uint8_t keyType
= arg1
;
2125 uint64_t ui64Key
= 0;
2126 byte_t blockdata
[16];
2128 ui64Key
= bytes_to_num(datain
, 6);
2129 memcpy(blockdata
, datain
+ 10, 16);
2135 struct Crypto1State mpcs
= {0, 0};
2136 struct Crypto1State
*pcs
;
2150 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2151 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2155 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
2156 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth error");
2160 if(mifare_classic_writeblock(pcs
, cuid
, blockNo
, blockdata
)) {
2161 if (MF_DBGLEVEL
>= 1) Dbprintf("Write block error");
2165 if(mifare_classic_halt(pcs
, cuid
)) {
2166 if (MF_DBGLEVEL
>= 1) Dbprintf("Halt error");
2174 // ----------------------------- crypto1 destroy
2175 crypto1_destroy(pcs
);
2177 if (MF_DBGLEVEL
>= 2) DbpString("WRITE BLOCK FINISHED");
2179 // add trace trailer
2184 LogTrace(uid
, 4, 0, 0, TRUE
);
2186 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2189 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2194 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2200 // Return 1 if the nonce is invalid else return 0
2201 int valid_nonce(uint32_t Nt
, uint32_t NtEnc
, uint32_t Ks1
, byte_t
* parity
) {
2202 return ((oddparity((Nt
>> 24) & 0xFF) == ((parity
[0]) ^ oddparity((NtEnc
>> 24) & 0xFF) ^ BIT(Ks1
,16))) & \
2203 (oddparity((Nt
>> 16) & 0xFF) == ((parity
[1]) ^ oddparity((NtEnc
>> 16) & 0xFF) ^ BIT(Ks1
,8))) & \
2204 (oddparity((Nt
>> 8) & 0xFF) == ((parity
[2]) ^ oddparity((NtEnc
>> 8) & 0xFF) ^ BIT(Ks1
,0)))) ? 1 : 0;
2208 //-----------------------------------------------------------------------------
2209 // MIFARE nested authentication.
2211 //-----------------------------------------------------------------------------
2212 void MifareNested(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
)
2215 uint8_t blockNo
= arg0
;
2216 uint8_t keyType
= arg1
;
2217 uint8_t targetBlockNo
= arg2
& 0xff;
2218 uint8_t targetKeyType
= (arg2
>> 8) & 0xff;
2219 uint64_t ui64Key
= 0;
2221 ui64Key
= bytes_to_num(datain
, 6);
2224 int rtr
, i
, j
, m
, len
;
2225 int davg
, dmin
, dmax
;
2227 uint32_t cuid
, nt1
, nt2
, nttmp
, nttest
, par
, ks1
;
2228 uint8_t par_array
[4];
2229 nestedVector nvector
[NES_MAX_INFO
+ 1][10];
2230 int nvectorcount
[NES_MAX_INFO
+ 1];
2232 UsbCommand ack
= {CMD_ACK
, {0, 0, 0}};
2233 struct Crypto1State mpcs
= {0, 0};
2234 struct Crypto1State
*pcs
;
2236 uint8_t* receivedAnswer
= mifare_get_bigbufptr();
2239 for (i
= 0; i
< NES_MAX_INFO
+ 1; i
++) nvectorcount
[i
] = 11; // 11 - empty block;
2251 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2257 // test nonce distance
2258 for (rtr
= 0; rtr
< 10; rtr
++) {
2259 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2261 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2263 // Test if the action was cancelled
2264 if(BUTTON_PRESS()) {
2268 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2269 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2273 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
)) {
2274 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth1 error");
2278 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_NESTED
, &nt2
)) {
2279 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth2 error");
2283 nttmp
= prng_successor(nt1
, 500);
2284 for (i
= 501; i
< 2000; i
++) {
2285 nttmp
= prng_successor(nttmp
, 1);
2286 if (nttmp
== nt2
) break;
2291 if (dmin
> i
) dmin
= i
;
2292 if (dmax
< i
) dmax
= i
;
2293 if (MF_DBGLEVEL
>= 4) Dbprintf("r=%d nt1=%08x nt2=%08x distance=%d", rtr
, nt1
, nt2
, i
);
2297 if (rtr
== 0) return;
2300 if (MF_DBGLEVEL
>= 3) Dbprintf("distance: min=%d max=%d avg=%d", dmin
, dmax
, davg
);
2304 // -------------------------------------------------------------------------------------------------
2308 // get crypted nonces for target sector
2309 for (rtr
= 0; rtr
< NS_RETRIES_GETNONCE
; rtr
++) {
2310 if (MF_DBGLEVEL
>= 4) Dbprintf("------------------------------");
2312 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2314 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2316 // Test if the action was cancelled
2317 if(BUTTON_PRESS()) {
2321 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2322 if (MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2326 if(mifare_classic_authex(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
, &nt1
)) {
2327 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth1 error");
2331 // nested authentication
2332 len
= mifare_sendcmd_shortex(pcs
, AUTH_NESTED
, 0x60 + (targetKeyType
& 0x01), targetBlockNo
, receivedAnswer
, &par
);
2334 if (MF_DBGLEVEL
>= 1) Dbprintf("Auth2 error len=%d", len
);
2338 nt2
= bytes_to_num(receivedAnswer
, 4);
2339 if (MF_DBGLEVEL
>= 4) Dbprintf("r=%d nt1=%08x nt2enc=%08x nt2par=%08x", rtr
, nt1
, nt2
, par
);
2341 // Parity validity check
2342 for (i
= 0; i
< 4; i
++) {
2343 par_array
[i
] = (oddparity(receivedAnswer
[i
]) != ((par
& 0x08) >> 3));
2348 for (m
= dmin
- NS_TOLERANCE
; m
< dmax
+ NS_TOLERANCE
; m
++) {
2349 nttest
= prng_successor(nt1
, m
);
2352 if (valid_nonce(nttest
, nt2
, ks1
, par_array
) && (ncount
< 11)){
2354 nvector
[NES_MAX_INFO
][ncount
].nt
= nttest
;
2355 nvector
[NES_MAX_INFO
][ncount
].ks1
= ks1
;
2357 nvectorcount
[NES_MAX_INFO
] = ncount
;
2358 if (MF_DBGLEVEL
>= 4) Dbprintf("valid m=%d ks1=%08x nttest=%08x", m
, ks1
, nttest
);
2363 // select vector with length less than got
2364 if (nvectorcount
[NES_MAX_INFO
] != 0) {
2367 for (i
= 0; i
< NES_MAX_INFO
; i
++)
2368 if (nvectorcount
[i
] > 10) {
2373 if (m
== NES_MAX_INFO
)
2374 for (i
= 0; i
< NES_MAX_INFO
; i
++)
2375 if (nvectorcount
[NES_MAX_INFO
] < nvectorcount
[i
]) {
2380 if (m
!= NES_MAX_INFO
) {
2381 for (i
= 0; i
< nvectorcount
[m
]; i
++) {
2382 nvector
[m
][i
] = nvector
[NES_MAX_INFO
][i
];
2384 nvectorcount
[m
] = nvectorcount
[NES_MAX_INFO
];
2391 // ----------------------------- crypto1 destroy
2392 crypto1_destroy(pcs
);
2394 // add trace trailer
2399 LogTrace(uid
, 4, 0, 0, TRUE
);
2401 for (i
= 0; i
< NES_MAX_INFO
; i
++) {
2402 if (nvectorcount
[i
] > 10) continue;
2404 for (j
= 0; j
< nvectorcount
[i
]; j
+= 5) {
2405 ncount
= nvectorcount
[i
] - j
;
2406 if (ncount
> 5) ncount
= 5;
2408 ack
.arg
[0] = 0; // isEOF = 0
2409 ack
.arg
[1] = ncount
;
2410 ack
.arg
[2] = targetBlockNo
+ (targetKeyType
* 0x100);
2411 memset(ack
.d
.asBytes
, 0x00, sizeof(ack
.d
.asBytes
));
2413 memcpy(ack
.d
.asBytes
, &cuid
, 4);
2414 for (m
= 0; m
< ncount
; m
++) {
2415 memcpy(ack
.d
.asBytes
+ 8 + m
* 8 + 0, &nvector
[i
][m
+ j
].nt
, 4);
2416 memcpy(ack
.d
.asBytes
+ 8 + m
* 8 + 4, &nvector
[i
][m
+ j
].ks1
, 4);
2421 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2427 ack
.arg
[0] = 1; // isEOF = 1
2430 memset(ack
.d
.asBytes
, 0x00, sizeof(ack
.d
.asBytes
));
2434 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2437 if (MF_DBGLEVEL
>= 4) DbpString("NESTED FINISHED");
2440 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2446 //-----------------------------------------------------------------------------
2447 // MIFARE check keys. key count up to 8.
2449 //-----------------------------------------------------------------------------
2450 void MifareChkKeys(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2453 uint8_t blockNo
= arg0
;
2454 uint8_t keyType
= arg1
;
2455 uint8_t keyCount
= arg2
;
2456 uint64_t ui64Key
= 0;
2463 struct Crypto1State mpcs
= {0, 0};
2464 struct Crypto1State
*pcs
;
2467 // clear debug level
2468 int OLD_MF_DBGLEVEL
= MF_DBGLEVEL
;
2469 MF_DBGLEVEL
= MF_DBG_NONE
;
2482 for (i
= 0; i
< keyCount
; i
++) {
2483 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2485 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2487 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
2488 if (OLD_MF_DBGLEVEL
>= 1) Dbprintf("Can't select card");
2492 ui64Key
= bytes_to_num(datain
+ i
* 6, 6);
2493 if(mifare_classic_auth(pcs
, cuid
, blockNo
, keyType
, ui64Key
, AUTH_FIRST
)) {
2501 // ----------------------------- crypto1 destroy
2502 crypto1_destroy(pcs
);
2504 // add trace trailer
2509 LogTrace(uid
, 4, 0, 0, TRUE
);
2511 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
2512 if (isOK
) memcpy(ack
.d
.asBytes
, datain
+ i
* 6, 6);
2515 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
2519 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2522 // restore debug level
2523 MF_DBGLEVEL
= OLD_MF_DBGLEVEL
;
2526 //-----------------------------------------------------------------------------
2527 // MIFARE 1K simulate.
2529 //-----------------------------------------------------------------------------
2530 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2532 int cardSTATE
= MFEMUL_NOFIELD
;
2533 int vHf
= 0; // in mV
2536 uint32_t selTimer
= 0;
2537 uint32_t authTimer
= 0;
2541 uint8_t cardAUTHSC
= 0;
2542 uint8_t cardAUTHKEY
= 0xff; // no authentication
2544 struct Crypto1State mpcs
= {0, 0};
2545 struct Crypto1State
*pcs
;
2548 uint64_t key64
= 0xffffffffffffULL
;
2550 uint8_t* receivedCmd
= mifare_get_bigbufptr();
2552 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k
2554 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2555 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2557 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2559 static uint8_t rAUTH_NT
[] = {0x1a, 0xac, 0xff, 0x4f};
2560 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2561 static uint8_t cmdBuf
[18];
2567 // -------------------------------------- test area
2569 // Authenticate response - nonce
2570 uint8_t *resp1
= (((uint8_t *)BigBuf
) + CARD_MEMORY
);
2572 uint8_t *resp2
= (((uint8_t *)BigBuf
) + CARD_MEMORY
+ 200);
2574 CodeIso14443aAsTag(rAUTH_NT
, sizeof(rAUTH_NT
));
2575 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
2577 timer
= GetTickCount();
2578 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2579 uint32_t rn_enc
= 0x98d76b77; // !!!!!!!!!!!!!!!!!
2581 cuid
= bytes_to_num(rUIDBCC1
, 4);
2583 crypto1_create(pcs
, key64
);
2584 crypto1_word(pcs
, cuid
^ nonce
, 0);
2585 crypto1_word(pcs
, rn_enc
, 1);
2586 crypto1_word(pcs
, 0, 0);
2587 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2588 num_to_bytes(ans
, 4, rAUTH_AT
);
2589 CodeIso14443aAsTag(rAUTH_AT
, sizeof(rAUTH_AT
));
2590 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
2591 Dbprintf("crypto auth time: %d", GetTickCount() - timer
);
2593 // -------------------------------------- END test area
2595 // We need to listen to the high-frequency, peak-detected path.
2596 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2599 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2602 Dbprintf("--> start");
2606 // find reader field
2607 // Vref = 3300mV, and an 10:1 voltage divider on the input
2608 // can measure voltages up to 33000 mV
2609 if (cardSTATE
== MFEMUL_NOFIELD
) {
2610 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2611 if (vHf
> MF_MINFIELDV
) {
2612 cardSTATE
= MFEMUL_IDLE
;
2617 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2618 res
= EmGetCmd(receivedCmd
, &len
, 100);
2620 cardSTATE
= MFEMUL_NOFIELD
;
2627 if(BUTTON_PRESS()) {
2630 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2632 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2633 // REQ or WUP request in ANY state and WUP in HALTED state
2634 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2635 selTimer
= GetTickCount();
2636 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2637 cardSTATE
= MFEMUL_SELECT1
;
2639 // init crypto block
2642 crypto1_destroy(pcs
);
2647 switch (cardSTATE
) {
2648 case MFEMUL_NOFIELD
:{
2651 case MFEMUL_HALTED
:{
2657 case MFEMUL_SELECT1
:{
2659 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2660 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2662 if (rUIDBCC1
[0] == 0x88) {
2663 cardSTATE
= MFEMUL_SELECT2
;
2669 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2670 EmSendCmd(rSAK
, sizeof(rSAK
));
2672 cuid
= bytes_to_num(rUIDBCC1
, 4);
2673 cardSTATE
= MFEMUL_WORK
;
2675 Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2680 case MFEMUL_SELECT2
:{
2681 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2683 cuid
= bytes_to_num(rUIDBCC2
, 4);
2684 cardSTATE
= MFEMUL_WORK
;
2686 Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - timer
);
2691 timer
= GetTickCount();
2692 // ---------------------------------
2693 rn_enc
= bytes_to_num(receivedCmd
, 4);
2694 crypto1_create(pcs
, key64
);
2695 crypto1_word(pcs
, cuid
^ nonce
, 0);
2696 crypto1_word(pcs
, rn_enc
, 1);
2697 crypto1_word(pcs
, 0, 0);
2698 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2699 num_to_bytes(ans
, 4, rAUTH_AT
);
2700 // ---------------------------------
2701 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2702 // EmSendCmd14443aRaw(resp2, resp2Len, 0);
2703 cardSTATE
= MFEMUL_AUTH2
;
2705 cardSTATE
= MFEMUL_IDLE
;
2709 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2712 // test auth info here...
2715 cardSTATE
= MFEMUL_WORK
;
2716 Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d a=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
, GetTickCount() - timer
);
2721 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2722 authTimer
= GetTickCount();
2723 // EmSendCmd(rAUTH_NT, sizeof(rAUTH_NT));
2725 EmSendCmd14443aRaw(resp1
, resp1Len
, 0);
2726 // crypto1_create(pcs, key64);
2727 // if (cardAUTHKEY == 0xff) { // first auth
2728 // crypto1_word(pcs, cuid ^ bytes_to_num(rAUTH_NT, 4), 0); // uid ^ nonce
2729 // } else { // nested auth
2732 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2733 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2734 cardSTATE
= MFEMUL_AUTH1
;
2738 if (len
== 0) break;
2741 if (cardAUTHKEY
!= 0xff){
2743 for (i
= 0; i
< len
; i
++)
2744 receivedCmd
[i
] = crypto1_byte(pcs
, 0x00, 0) ^ receivedCmd
[i
];
2747 for (i
= 0; i
< 4; i
++)
2748 bt
|= (crypto1_bit(pcs
, 0, 0) ^ BIT(receivedCmd
[0], i
)) << i
;
2750 receivedCmd
[0] = bt
;
2755 if (len
== 4 && receivedCmd
[0] == 0x30) {
2758 /* memcpy(cmdBuf, blockData, 16);
2759 AppendCrc14443a(cmdBuf, 16);
2763 for (i = 0; i < 18; i++) {
2764 d_block_enc[pos] = crypto1_byte(pcs, 0x00, 0) ^ cmdBuf[pos];
2765 par = (par >> 1) | ( ((filter(pcs->odd) ^ oddparity(cmdBuf[pos])) & 0x01) * 0x20000 );
2768 //ReaderTransmitPar(d_block_enc, sizeof(d_block_enc), par);
2769 Dbprintf("read block: %d", receivedCmd
[1]);
2774 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2775 Dbprintf("write block: %d", receivedCmd
[1]);
2780 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2781 cardSTATE
= MFEMUL_HALTED
;
2784 Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2794 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2797 // add trace trailer
2798 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2800 DbpString("Emulator stopped.");