1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
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"
19 #include "iso14443crc.h"
20 #include "iso14443a.h"
22 #include "mifareutil.h"
24 static uint32_t iso14a_timeout
;
25 uint8_t *trace
= (uint8_t *) BigBuf
+TRACE_OFFSET
;
30 // the block number for the ISO14443-4 PCB
31 static uint8_t iso14_pcb_blocknum
= 0;
33 // CARD TO READER - manchester
34 // Sequence D: 11110000 modulation with subcarrier during first half
35 // Sequence E: 00001111 modulation with subcarrier during second half
36 // Sequence F: 00000000 no modulation with subcarrier
37 // READER TO CARD - miller
38 // Sequence X: 00001100 drop after half a period
39 // Sequence Y: 00000000 no drop
40 // Sequence Z: 11000000 drop at start
48 const uint8_t OddByteParity
[256] = {
49 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
50 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
51 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
52 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
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 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
58 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
59 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
60 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
61 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
62 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
63 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
64 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
68 void iso14a_set_trigger(bool enable
) {
72 void iso14a_clear_trace() {
73 memset(trace
, 0x44, TRACE_SIZE
);
77 void iso14a_set_tracing(bool enable
) {
81 void iso14a_set_timeout(uint32_t timeout
) {
82 iso14a_timeout
= timeout
;
85 //-----------------------------------------------------------------------------
86 // Generate the parity value for a byte sequence
88 //-----------------------------------------------------------------------------
89 byte_t
oddparity (const byte_t bt
)
91 return OddByteParity
[bt
];
94 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
99 // Generate the encrypted data
100 for (i
= 0; i
< iLen
; i
++) {
101 // Save the encrypted parity bit
102 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
107 void AppendCrc14443a(uint8_t* data
, int len
)
109 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
112 // The function LogTrace() is also used by the iClass implementation in iClass.c
113 int RAMFUNC
LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
115 // Return when trace is full
116 if (traceLen
>= TRACE_SIZE
) return FALSE
;
118 // Trace the random, i'm curious
119 rsamples
+= iSamples
;
120 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
121 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
122 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
123 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
125 trace
[traceLen
- 1] |= 0x80;
127 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
128 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
129 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
130 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
131 trace
[traceLen
++] = iLen
;
132 memcpy(trace
+ traceLen
, btBytes
, iLen
);
137 //-----------------------------------------------------------------------------
138 // The software UART that receives commands from the reader, and its state
140 //-----------------------------------------------------------------------------
143 static RAMFUNC
int MillerDecoding(int bit
)
148 if(!Uart
.bitBuffer
) {
149 Uart
.bitBuffer
= bit
^ 0xFF0;
153 Uart
.bitBuffer
<<= 4;
154 Uart
.bitBuffer
^= bit
;
159 if(Uart
.state
!= STATE_UNSYNCD
) {
162 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
168 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
174 if(bit
!= bitright
) { bit
= bitright
; }
176 if(Uart
.posCnt
== 1) {
177 // measurement first half bitperiod
179 Uart
.drop
= DROP_FIRST_HALF
;
183 // measurement second half bitperiod
184 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
185 Uart
.drop
= DROP_SECOND_HALF
;
188 // measured a drop in first and second half
189 // which should not be possible
190 Uart
.state
= STATE_ERROR_WAIT
;
197 case STATE_START_OF_COMMUNICATION
:
199 if(Uart
.drop
== DROP_SECOND_HALF
) {
200 // error, should not happen in SOC
201 Uart
.state
= STATE_ERROR_WAIT
;
206 Uart
.state
= STATE_MILLER_Z
;
213 if(Uart
.drop
== DROP_NONE
) {
214 // logic '0' followed by sequence Y
215 // end of communication
216 Uart
.state
= STATE_UNSYNCD
;
219 // if(Uart.drop == DROP_FIRST_HALF) {
220 // Uart.state = STATE_MILLER_Z; stay the same
221 // we see a logic '0' }
222 if(Uart
.drop
== DROP_SECOND_HALF
) {
223 // we see a logic '1'
224 Uart
.shiftReg
|= 0x100;
225 Uart
.state
= STATE_MILLER_X
;
231 if(Uart
.drop
== DROP_NONE
) {
232 // sequence Y, we see a '0'
233 Uart
.state
= STATE_MILLER_Y
;
236 if(Uart
.drop
== DROP_FIRST_HALF
) {
237 // Would be STATE_MILLER_Z
238 // but Z does not follow X, so error
239 Uart
.state
= STATE_ERROR_WAIT
;
242 if(Uart
.drop
== DROP_SECOND_HALF
) {
243 // We see a '1' and stay in state X
244 Uart
.shiftReg
|= 0x100;
252 if(Uart
.drop
== DROP_NONE
) {
253 // logic '0' followed by sequence Y
254 // end of communication
255 Uart
.state
= STATE_UNSYNCD
;
258 if(Uart
.drop
== DROP_FIRST_HALF
) {
260 Uart
.state
= STATE_MILLER_Z
;
262 if(Uart
.drop
== DROP_SECOND_HALF
) {
263 // We see a '1' and go to state X
264 Uart
.shiftReg
|= 0x100;
265 Uart
.state
= STATE_MILLER_X
;
269 case STATE_ERROR_WAIT
:
270 // That went wrong. Now wait for at least two bit periods
271 // and try to sync again
272 if(Uart
.drop
== DROP_NONE
) {
274 Uart
.state
= STATE_UNSYNCD
;
279 Uart
.state
= STATE_UNSYNCD
;
284 Uart
.drop
= DROP_NONE
;
286 // should have received at least one whole byte...
287 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
291 if(Uart
.bitCnt
== 9) {
292 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
295 Uart
.parityBits
<<= 1;
296 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
299 // when End of Communication received and
300 // all data bits processed..
307 Uart.output[Uart.byteCnt] = 0xAA;
309 Uart.output[Uart.byteCnt] = error & 0xFF;
311 Uart.output[Uart.byteCnt] = 0xAA;
313 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
315 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
317 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
319 Uart.output[Uart.byteCnt] = 0xAA;
327 bit
= Uart
.bitBuffer
& 0xf0;
331 // should have been high or at least (4 * 128) / fc
332 // according to ISO this should be at least (9 * 128 + 20) / fc
333 if(Uart
.highCnt
== 8) {
334 // we went low, so this could be start of communication
335 // it turns out to be safer to choose a less significant
336 // syncbit... so we check whether the neighbour also represents the drop
337 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
338 Uart
.syncBit
= bit
& 8;
340 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
341 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
342 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
343 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
344 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
345 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
348 // the first half bit period is expected in next sample
353 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
356 Uart
.state
= STATE_START_OF_COMMUNICATION
;
357 Uart
.drop
= DROP_FIRST_HALF
;
368 if(Uart
.highCnt
< 8) {
377 //=============================================================================
378 // ISO 14443 Type A - Manchester
379 //=============================================================================
382 static RAMFUNC
int ManchesterDecoding(int v
)
398 if(Demod
.state
==DEMOD_UNSYNCD
) {
399 Demod
.output
[Demod
.len
] = 0xfa;
402 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
405 Demod
.syncBit
= 0x08;
412 Demod
.syncBit
= 0x04;
419 Demod
.syncBit
= 0x02;
422 if(bit
& 0x01 && Demod
.syncBit
) {
423 Demod
.syncBit
= 0x01;
428 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
429 Demod
.sub
= SUB_FIRST_HALF
;
432 Demod
.parityBits
= 0;
435 if(trigger
) LED_A_OFF();
436 switch(Demod
.syncBit
) {
437 case 0x08: Demod
.samples
= 3; break;
438 case 0x04: Demod
.samples
= 2; break;
439 case 0x02: Demod
.samples
= 1; break;
440 case 0x01: Demod
.samples
= 0; break;
447 //modulation = bit & Demod.syncBit;
448 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
452 if(Demod
.posCount
==0) {
455 Demod
.sub
= SUB_FIRST_HALF
;
458 Demod
.sub
= SUB_NONE
;
463 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
464 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
465 Demod
.state
= DEMOD_ERROR_WAIT
;
466 Demod
.output
[Demod
.len
] = 0xaa;
470 else if(modulation
) {
471 Demod
.sub
= SUB_SECOND_HALF
;
474 switch(Demod
.state
) {
475 case DEMOD_START_OF_COMMUNICATION
:
476 if(Demod
.sub
== SUB_FIRST_HALF
) {
477 Demod
.state
= DEMOD_MANCHESTER_D
;
480 Demod
.output
[Demod
.len
] = 0xab;
481 Demod
.state
= DEMOD_ERROR_WAIT
;
486 case DEMOD_MANCHESTER_D
:
487 case DEMOD_MANCHESTER_E
:
488 if(Demod
.sub
== SUB_FIRST_HALF
) {
490 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
491 Demod
.state
= DEMOD_MANCHESTER_D
;
493 else if(Demod
.sub
== SUB_SECOND_HALF
) {
495 Demod
.shiftReg
>>= 1;
496 Demod
.state
= DEMOD_MANCHESTER_E
;
499 Demod
.state
= DEMOD_MANCHESTER_F
;
503 case DEMOD_MANCHESTER_F
:
504 // Tag response does not need to be a complete byte!
505 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
506 if(Demod
.bitCount
> 0) {
507 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
508 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
510 // No parity bit, so just shift a 0
511 Demod
.parityBits
<<= 1;
514 Demod
.state
= DEMOD_UNSYNCD
;
518 Demod
.output
[Demod
.len
] = 0xad;
519 Demod
.state
= DEMOD_ERROR_WAIT
;
524 case DEMOD_ERROR_WAIT
:
525 Demod
.state
= DEMOD_UNSYNCD
;
529 Demod
.output
[Demod
.len
] = 0xdd;
530 Demod
.state
= DEMOD_UNSYNCD
;
534 if(Demod
.bitCount
>=9) {
535 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
538 Demod
.parityBits
<<= 1;
539 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
546 Demod.output[Demod.len] = 0xBB;
548 Demod.output[Demod.len] = error & 0xFF;
550 Demod.output[Demod.len] = 0xBB;
552 Demod.output[Demod.len] = bit & 0xFF;
554 Demod.output[Demod.len] = Demod.buffer & 0xFF;
556 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
558 Demod.output[Demod.len] = 0xBB;
565 } // end (state != UNSYNCED)
570 //=============================================================================
571 // Finally, a `sniffer' for ISO 14443 Type A
572 // Both sides of communication!
573 //=============================================================================
575 //-----------------------------------------------------------------------------
576 // Record the sequence of commands sent by the reader to the tag, with
577 // triggering so that we start recording at the point that the tag is moved
579 //-----------------------------------------------------------------------------
580 void RAMFUNC
SnoopIso14443a(uint8_t param
) {
582 // bit 0 - trigger from first card answer
583 // bit 1 - trigger from first reader 7-bit request
587 iso14a_clear_trace();
589 // We won't start recording the frames that we acquire until we trigger;
590 // a good trigger condition to get started is probably when we see a
591 // response from the tag.
592 // triggered == FALSE -- to wait first for card
593 int triggered
= !(param
& 0x03);
595 // The command (reader -> tag) that we're receiving.
596 // The length of a received command will in most cases be no more than 18 bytes.
597 // So 32 should be enough!
598 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
599 // The response (tag -> reader) that we're receiving.
600 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
602 // As we receive stuff, we copy it from receivedCmd or receivedResponse
603 // into trace, along with its length and other annotations.
604 //uint8_t *trace = (uint8_t *)BigBuf;
606 // The DMA buffer, used to stream samples from the FPGA
607 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
608 int8_t *data
= dmaBuf
;
612 // Set up the demodulator for tag -> reader responses.
613 Demod
.output
= receivedResponse
;
615 Demod
.state
= DEMOD_UNSYNCD
;
617 // Set up the demodulator for the reader -> tag commands
618 memset(&Uart
, 0, sizeof(Uart
));
619 Uart
.output
= receivedCmd
;
620 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
621 Uart
.state
= STATE_UNSYNCD
;
623 // Setup for the DMA.
625 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
627 // And put the FPGA in the appropriate mode
628 // Signal field is off with the appropriate LED
630 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
631 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
633 // Count of samples received so far, so that we can include timing
634 // information in the trace buffer.
636 // And now we loop, receiving samples.
639 DbpString("cancelled by button");
646 int register readBufDataP
= data
- dmaBuf
;
647 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
648 if (readBufDataP
<= dmaBufDataP
){
649 dataLen
= dmaBufDataP
- readBufDataP
;
651 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
653 // test for length of buffer
654 if(dataLen
> maxDataLen
) {
655 maxDataLen
= dataLen
;
657 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
661 if(dataLen
< 1) continue;
663 // primary buffer was stopped( <-- we lost data!
664 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
665 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
666 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
668 // secondary buffer sets as primary, secondary buffer was stopped
669 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
670 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
671 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
677 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
680 // check - if there is a short 7bit request from reader
681 if ((!triggered
) && (param
& 0x02) && (Uart
.byteCnt
== 1) && (Uart
.bitCnt
= 9)) triggered
= TRUE
;
684 if (!LogTrace(receivedCmd
, Uart
.byteCnt
, 0 - Uart
.samples
, Uart
.parityBits
, TRUE
)) break;
686 /* And ready to receive another command. */
687 Uart
.state
= STATE_UNSYNCD
;
688 /* And also reset the demod code, which might have been */
689 /* false-triggered by the commands from the reader. */
690 Demod
.state
= DEMOD_UNSYNCD
;
694 if(ManchesterDecoding(data
[0] & 0x0F)) {
697 if (!LogTrace(receivedResponse
, Demod
.len
, 0 - Demod
.samples
, Demod
.parityBits
, FALSE
)) break;
699 if ((!triggered
) && (param
& 0x01)) triggered
= TRUE
;
701 // And ready to receive another response.
702 memset(&Demod
, 0, sizeof(Demod
));
703 Demod
.output
= receivedResponse
;
704 Demod
.state
= DEMOD_UNSYNCD
;
709 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
714 DbpString("COMMAND FINISHED");
717 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
718 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
);
719 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
723 //-----------------------------------------------------------------------------
724 // Prepare tag messages
725 //-----------------------------------------------------------------------------
726 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
732 // Correction bit, might be removed when not needed
737 ToSendStuffBit(1); // 1
743 ToSend
[++ToSendMax
] = SEC_D
;
745 for(i
= 0; i
< len
; i
++) {
750 for(j
= 0; j
< 8; j
++) {
752 ToSend
[++ToSendMax
] = SEC_D
;
754 ToSend
[++ToSendMax
] = SEC_E
;
759 // Get the parity bit
760 if ((dwParity
>> i
) & 0x01) {
761 ToSend
[++ToSendMax
] = SEC_D
;
763 ToSend
[++ToSendMax
] = SEC_E
;
768 ToSend
[++ToSendMax
] = SEC_F
;
770 // Convert from last byte pos to length
774 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
775 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
778 ////-----------------------------------------------------------------------------
779 //// This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
780 ////-----------------------------------------------------------------------------
781 //static void CodeStrangeAnswerAsTag()
787 // // Correction bit, might be removed when not needed
788 // ToSendStuffBit(0);
789 // ToSendStuffBit(0);
790 // ToSendStuffBit(0);
791 // ToSendStuffBit(0);
792 // ToSendStuffBit(1); // 1
793 // ToSendStuffBit(0);
794 // ToSendStuffBit(0);
795 // ToSendStuffBit(0);
798 // ToSend[++ToSendMax] = SEC_D;
801 // ToSend[++ToSendMax] = SEC_E;
804 // ToSend[++ToSendMax] = SEC_E;
807 // ToSend[++ToSendMax] = SEC_D;
810 // ToSend[++ToSendMax] = SEC_F;
812 // // Flush the buffer in FPGA!!
813 // for(i = 0; i < 5; i++) {
814 // ToSend[++ToSendMax] = SEC_F;
817 // // Convert from last byte pos to length
821 static void Code4bitAnswerAsTag(uint8_t cmd
)
827 // Correction bit, might be removed when not needed
832 ToSendStuffBit(1); // 1
838 ToSend
[++ToSendMax
] = SEC_D
;
841 for(i
= 0; i
< 4; i
++) {
843 ToSend
[++ToSendMax
] = SEC_D
;
845 ToSend
[++ToSendMax
] = SEC_E
;
851 ToSend
[++ToSendMax
] = SEC_F
;
853 // Flush the buffer in FPGA!!
854 for(i
= 0; i
< 5; i
++) {
855 ToSend
[++ToSendMax
] = SEC_F
;
858 // Convert from last byte pos to length
862 //-----------------------------------------------------------------------------
863 // Wait for commands from reader
864 // Stop when button is pressed
865 // Or return TRUE when command is captured
866 //-----------------------------------------------------------------------------
867 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
869 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
870 // only, since we are receiving, not transmitting).
871 // Signal field is off with the appropriate LED
873 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
875 // Now run a `software UART' on the stream of incoming samples.
876 Uart
.output
= received
;
877 Uart
.byteCntMax
= maxLen
;
878 Uart
.state
= STATE_UNSYNCD
;
883 if(BUTTON_PRESS()) return FALSE
;
885 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
886 AT91C_BASE_SSC
->SSC_THR
= 0x00;
888 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
889 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
890 if(MillerDecoding((b
& 0xf0) >> 4)) {
894 if(MillerDecoding(b
& 0x0f)) {
902 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
903 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
);
904 int EmSend4bit(uint8_t resp
);
905 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
);
906 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
);
907 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
);
908 int EmSendCmd(uint8_t *resp
, int respLen
);
909 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
);
911 static uint8_t* free_buffer_pointer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
918 } tag_response_info_t
;
920 void reset_free_buffer() {
921 free_buffer_pointer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
924 bool prepare_tag_modulation(tag_response_info_t
* response_info
, size_t max_buffer_size
) {
925 // Exmaple response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
926 // This will need the following byte array for a modulation sequence
927 // 144 data bits (18 * 8)
930 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
931 // 1 just for the case
933 // 166 bytes, since every bit that needs to be send costs us a byte
936 // Prepare the tag modulation bits from the message
937 CodeIso14443aAsTag(response_info
->response
,response_info
->response_n
);
939 // Make sure we do not exceed the free buffer space
940 if (ToSendMax
> max_buffer_size
) {
941 Dbprintf("Out of memory, when modulating bits for tag answer:");
942 Dbhexdump(response_info
->response_n
,response_info
->response
,false);
946 // Copy the byte array, used for this modulation to the buffer position
947 memcpy(response_info
->modulation
,ToSend
,ToSendMax
);
949 // Store the number of bytes that were used for encoding/modulation
950 response_info
->modulation_n
= ToSendMax
;
955 bool prepare_allocated_tag_modulation(tag_response_info_t
* response_info
) {
956 // Retrieve and store the current buffer index
957 response_info
->modulation
= free_buffer_pointer
;
959 // Determine the maximum size we can use from our buffer
960 size_t max_buffer_size
= (((uint8_t *)BigBuf
)+FREE_BUFFER_OFFSET
+FREE_BUFFER_SIZE
)-free_buffer_pointer
;
962 // Forward the prepare tag modulation function to the inner function
963 if (prepare_tag_modulation(response_info
,max_buffer_size
)) {
964 // Update the free buffer offset
965 free_buffer_pointer
+= ToSendMax
;
972 //-----------------------------------------------------------------------------
973 // Main loop of simulated tag: receive commands from reader, decide what
974 // response to send, and send it.
975 //-----------------------------------------------------------------------------
976 void SimulateIso14443aTag(int tagType
, int uid_1st
, int uid_2nd
, byte_t
* data
)
978 // Enable and clear the trace
980 iso14a_clear_trace();
982 // This function contains the tag emulation
985 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
986 uint8_t response1
[2];
989 case 1: { // MIFARE Classic
990 // Says: I am Mifare 1k - original line
995 case 2: { // MIFARE Ultralight
996 // Says: I am a stupid memory tag, no crypto
1001 case 3: { // MIFARE DESFire
1002 // Says: I am a DESFire tag, ph33r me
1003 response1
[0] = 0x04;
1004 response1
[1] = 0x03;
1007 case 4: { // ISO/IEC 14443-4
1008 // Says: I am a javacard (JCOP)
1009 response1
[0] = 0x04;
1010 response1
[1] = 0x00;
1014 Dbprintf("Error: unkown tagtype (%d)",tagType
);
1019 // The second response contains the (mandatory) first 24 bits of the UID
1020 uint8_t response2
[5];
1022 // Check if the uid uses the (optional) part
1023 uint8_t response2a
[5];
1025 response2
[0] = 0x88;
1026 num_to_bytes(uid_1st
,3,response2
+1);
1027 num_to_bytes(uid_2nd
,4,response2a
);
1028 response2a
[4] = response2a
[0] ^ response2a
[1] ^ response2a
[2] ^ response2a
[3];
1030 // Configure the ATQA and SAK accordingly
1031 response1
[0] |= 0x40;
1034 num_to_bytes(uid_1st
,4,response2
);
1035 // Configure the ATQA and SAK accordingly
1036 response1
[0] &= 0xBF;
1040 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
1041 response2
[4] = response2
[0] ^ response2
[1] ^ response2
[2] ^ response2
[3];
1043 // Prepare the mandatory SAK (for 4 and 7 byte UID)
1044 uint8_t response3
[3];
1046 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
1048 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
1049 uint8_t response3a
[3];
1050 response3a
[0] = sak
& 0xFB;
1051 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
1053 uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
1054 uint8_t response6
[] = { 0x04, 0x58, 0x00, 0x02, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
1055 ComputeCrc14443(CRC_14443_A
, response6
, 4, &response6
[4], &response6
[5]);
1057 #define TAG_RESPONSE_COUNT 7
1058 tag_response_info_t responses
[TAG_RESPONSE_COUNT
] = {
1059 { .response
= response1
, .response_n
= sizeof(response1
) }, // Answer to request - respond with card type
1060 { .response
= response2
, .response_n
= sizeof(response2
) }, // Anticollision cascade1 - respond with uid
1061 { .response
= response2a
, .response_n
= sizeof(response2a
) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1062 { .response
= response3
, .response_n
= sizeof(response3
) }, // Acknowledge select - cascade 1
1063 { .response
= response3a
, .response_n
= sizeof(response3a
) }, // Acknowledge select - cascade 2
1064 { .response
= response5
, .response_n
= sizeof(response5
) }, // Authentication answer (random nonce)
1065 { .response
= response6
, .response_n
= sizeof(response6
) }, // dummy ATS (pseudo-ATR), answer to RATS
1068 // Allocate 512 bytes for the dynamic modulation, created when the reader querries for it
1069 // Such a response is less time critical, so we can prepare them on the fly
1070 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1071 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1072 uint8_t dynamic_response_buffer
[DYNAMIC_RESPONSE_BUFFER_SIZE
];
1073 uint8_t dynamic_modulation_buffer
[DYNAMIC_MODULATION_BUFFER_SIZE
];
1074 tag_response_info_t dynamic_response_info
= {
1075 .response
= dynamic_response_buffer
,
1077 .modulation
= dynamic_modulation_buffer
,
1081 // Reset the offset pointer of the free buffer
1082 reset_free_buffer();
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
1086 for (size_t i
=0; i
<TAG_RESPONSE_COUNT
; i
++) {
1087 prepare_allocated_tag_modulation(&responses
[i
]);
1090 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
1093 // To control where we are in the protocol
1097 // Just to allow some checks
1102 // We need to listen to the high-frequency, peak-detected path.
1103 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1107 tag_response_info_t
* p_response
;
1111 // Clean receive command buffer
1112 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1114 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, RECV_CMD_SIZE
)) {
1115 DbpString("Button press");
1120 LogTrace(receivedCmd
,len
, 0, Uart
.parityBits
, TRUE
);
1125 // 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
1126 // Okay, look at the command now.
1128 if(receivedCmd
[0] == 0x26) { // Received a REQUEST
1129 p_response
= &responses
[0]; order
= 1;
1130 } else if(receivedCmd
[0] == 0x52) { // Received a WAKEUP
1131 p_response
= &responses
[0]; order
= 6;
1132 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // Received request for UID (cascade 1)
1133 p_response
= &responses
[1]; order
= 2;
1134 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x95) { // Received request for UID (cascade 2)
1135 p_response
= &responses
[2]; order
= 20;
1136 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x93) { // Received a SELECT (cascade 1)
1137 p_response
= &responses
[3]; order
= 3;
1138 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x95) { // Received a SELECT (cascade 2)
1139 p_response
= &responses
[4]; order
= 30;
1140 } else if(receivedCmd
[0] == 0x30) { // Received a (plain) READ
1141 EmSendCmdEx(data
+(4*receivedCmd
[0]),16,false);
1142 Dbprintf("Read request from reader: %x %x",receivedCmd
[0],receivedCmd
[1]);
1143 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1145 } else if(receivedCmd
[0] == 0x50) { // Received a HALT
1146 // DbpString("Reader requested we HALT!:");
1148 } else if(receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61) { // Received an authentication request
1149 p_response
= &responses
[5]; order
= 7;
1150 } else if(receivedCmd
[0] == 0xE0) { // Received a RATS request
1151 p_response
= &responses
[6]; order
= 70;
1152 } else if (order
== 7 && len
==8) { // Received authentication request
1153 uint32_t nr
= bytes_to_num(receivedCmd
,4);
1154 uint32_t ar
= bytes_to_num(receivedCmd
+4,4);
1155 Dbprintf("Auth attempt {nr}{ar}: %08x %08x",nr
,ar
);
1157 // Check for ISO 14443A-4 compliant commands, look at left nibble
1158 switch (receivedCmd
[0]) {
1161 case 0x0A: { // IBlock (command)
1162 dynamic_response_info
.response
[0] = receivedCmd
[0];
1163 dynamic_response_info
.response
[1] = 0x00;
1164 dynamic_response_info
.response
[2] = 0x90;
1165 dynamic_response_info
.response
[3] = 0x00;
1166 dynamic_response_info
.response_n
= 4;
1170 case 0x1B: { // Chaining command
1171 dynamic_response_info
.response
[0] = 0xaa | ((receivedCmd
[0]) & 1);
1172 dynamic_response_info
.response_n
= 2;
1177 dynamic_response_info
.response
[0] = receivedCmd
[0] ^ 0x11;
1178 dynamic_response_info
.response_n
= 2;
1182 memcpy(dynamic_response_info
.response
,"\xAB\x00",2);
1183 dynamic_response_info
.response_n
= 2;
1187 case 0xC2: { // Readers sends deselect command
1188 memcpy(dynamic_response_info
.response
,"\xCA\x00",2);
1189 dynamic_response_info
.response_n
= 2;
1193 // Never seen this command before
1194 Dbprintf("Received unknown command (len=%d):",len
);
1195 Dbhexdump(len
,receivedCmd
,false);
1197 dynamic_response_info
.response_n
= 0;
1201 if (dynamic_response_info
.response_n
> 0) {
1202 // Copy the CID from the reader query
1203 dynamic_response_info
.response
[1] = receivedCmd
[1];
1205 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1206 AppendCrc14443a(dynamic_response_info
.response
,dynamic_response_info
.response_n
);
1207 dynamic_response_info
.response_n
+= 2;
1209 if (prepare_tag_modulation(&dynamic_response_info
,DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
1210 Dbprintf("Error preparing tag response");
1213 p_response
= &dynamic_response_info
;
1217 // Count number of wakeups received after a halt
1218 if(order
== 6 && lastorder
== 5) { happened
++; }
1220 // Count number of other messages after a halt
1221 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1223 // Look at last parity bit to determine timing of answer
1224 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1225 // 1236, so correction bit needed
1229 if(cmdsRecvd
> 999) {
1230 DbpString("1000 commands later...");
1235 if (p_response
!= NULL
) {
1236 EmSendCmd14443aRaw(p_response
->modulation
, p_response
->modulation_n
, receivedCmd
[0] == 0x52);
1238 LogTrace(p_response
->response
,p_response
->response_n
,0,SwapBits(GetParity(p_response
->response
,p_response
->response_n
),p_response
->response_n
),FALSE
);
1239 if(traceLen
> TRACE_SIZE
) {
1240 DbpString("Trace full");
1247 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1252 // prepare a delayed transfer. This simply shifts ToSend[] by a number
1253 // of bits specified in the delay parameter.
1254 void PrepareDelayedTransfer(uint16_t delay
)
1256 uint8_t bitmask
= 0;
1257 uint8_t bits_to_shift
= 0;
1258 uint8_t bits_shifted
= 0;
1262 for (uint16_t i
= 0; i
< delay
; i
++) {
1263 bitmask
|= (0x01 << i
);
1265 ToSend
[++ToSendMax
] = 0x00;
1266 for (uint16_t i
= 0; i
< ToSendMax
; i
++) {
1267 bits_to_shift
= ToSend
[i
] & bitmask
;
1268 ToSend
[i
] = ToSend
[i
] >> delay
;
1269 ToSend
[i
] = ToSend
[i
] | (bits_shifted
<< (8 - delay
));
1270 bits_shifted
= bits_to_shift
;
1275 //-----------------------------------------------------------------------------
1276 // Transmit the command (to the tag) that was placed in ToSend[].
1277 // Parameter timing:
1279 // if == 0: return time of transfer
1280 // if != 0: delay transfer until time specified
1281 //-----------------------------------------------------------------------------
1282 static void TransmitFor14443a(const uint8_t *cmd
, int len
, uint32_t *timing
)
1286 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1290 if(*timing
== 0) { // Measure time
1291 *timing
= (GetCountMifare() + 8) & 0xfffffff8;
1293 PrepareDelayedTransfer(*timing
& 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
1295 if(MF_DBGLEVEL
>= 4 && GetCountMifare() >= (*timing
& 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
1296 while(GetCountMifare() < (*timing
& 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
1299 for(c
= 0; c
< 10;) { // standard delay for each transfer (allow tag to be ready after last transmission)
1300 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1301 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1308 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1309 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1319 //-----------------------------------------------------------------------------
1320 // Prepare reader command (in bits, support short frames) to send to FPGA
1321 //-----------------------------------------------------------------------------
1322 void CodeIso14443aBitsAsReaderPar(const uint8_t * cmd
, int bits
, uint32_t dwParity
)
1330 // Start of Communication (Seq. Z)
1331 ToSend
[++ToSendMax
] = SEC_Z
;
1334 size_t bytecount
= nbytes(bits
);
1335 // Generate send structure for the data bits
1336 for (i
= 0; i
< bytecount
; i
++) {
1337 // Get the current byte to send
1339 size_t bitsleft
= MIN((bits
-(i
*8)),8);
1341 for (j
= 0; j
< bitsleft
; j
++) {
1344 ToSend
[++ToSendMax
] = SEC_X
;
1349 ToSend
[++ToSendMax
] = SEC_Z
;
1352 ToSend
[++ToSendMax
] = SEC_Y
;
1359 // Only transmit (last) parity bit if we transmitted a complete byte
1361 // Get the parity bit
1362 if ((dwParity
>> i
) & 0x01) {
1364 ToSend
[++ToSendMax
] = SEC_X
;
1369 ToSend
[++ToSendMax
] = SEC_Z
;
1372 ToSend
[++ToSendMax
] = SEC_Y
;
1379 // End of Communication
1382 ToSend
[++ToSendMax
] = SEC_Z
;
1385 ToSend
[++ToSendMax
] = SEC_Y
;
1389 ToSend
[++ToSendMax
] = SEC_Y
;
1392 ToSend
[++ToSendMax
] = SEC_Y
;
1393 ToSend
[++ToSendMax
] = SEC_Y
;
1394 ToSend
[++ToSendMax
] = SEC_Y
;
1396 // Convert from last character reference to length
1400 //-----------------------------------------------------------------------------
1401 // Prepare reader command to send to FPGA
1402 //-----------------------------------------------------------------------------
1403 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1405 CodeIso14443aBitsAsReaderPar(cmd
,len
*8,dwParity
);
1408 //-----------------------------------------------------------------------------
1409 // Wait for commands from reader
1410 // Stop when button is pressed (return 1) or field was gone (return 2)
1411 // Or return 0 when command is captured
1412 //-----------------------------------------------------------------------------
1413 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1417 uint32_t timer
= 0, vtime
= 0;
1421 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1422 // only, since we are receiving, not transmitting).
1423 // Signal field is off with the appropriate LED
1425 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1427 // Set ADC to read field strength
1428 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1429 AT91C_BASE_ADC
->ADC_MR
=
1430 ADC_MODE_PRESCALE(32) |
1431 ADC_MODE_STARTUP_TIME(16) |
1432 ADC_MODE_SAMPLE_HOLD_TIME(8);
1433 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1435 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1437 // Now run a 'software UART' on the stream of incoming samples.
1438 Uart
.output
= received
;
1439 Uart
.byteCntMax
= maxLen
;
1440 Uart
.state
= STATE_UNSYNCD
;
1445 if (BUTTON_PRESS()) return 1;
1447 // test if the field exists
1448 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1450 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1451 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1452 if (analogCnt
>= 32) {
1453 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1454 vtime
= GetTickCount();
1455 if (!timer
) timer
= vtime
;
1456 // 50ms no field --> card to idle state
1457 if (vtime
- timer
> 50) return 2;
1459 if (timer
) timer
= 0;
1465 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1466 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1468 // receive and test the miller decoding
1469 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1470 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1471 if(MillerDecoding((b
& 0xf0) >> 4)) {
1472 *len
= Uart
.byteCnt
;
1473 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1476 if(MillerDecoding(b
& 0x0f)) {
1477 *len
= Uart
.byteCnt
;
1478 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1485 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1490 // Modulate Manchester
1491 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1492 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1495 // include correction bit
1497 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1498 // 1236, so correction bit needed
1504 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1505 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1508 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1510 b
= 0xff; // was 0x00
1516 AT91C_BASE_SSC
->SSC_THR
= b
;
1520 if(BUTTON_PRESS()) {
1528 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1529 Code4bitAnswerAsTag(resp
);
1530 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1531 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1535 int EmSend4bit(uint8_t resp
){
1536 return EmSend4bitEx(resp
, 0);
1539 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1540 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1541 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1542 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1546 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1547 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1550 int EmSendCmd(uint8_t *resp
, int respLen
){
1551 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1554 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1555 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1558 //-----------------------------------------------------------------------------
1559 // Wait a certain time for tag response
1560 // If a response is captured return TRUE
1561 // If it takes to long return FALSE
1562 //-----------------------------------------------------------------------------
1563 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1565 // buffer needs to be 512 bytes
1568 // Set FPGA mode to "reader listen mode", no modulation (listen
1569 // only, since we are receiving, not transmitting).
1570 // Signal field is on with the appropriate LED
1572 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1574 // Now get the answer from the card
1575 Demod
.output
= receivedResponse
;
1577 Demod
.state
= DEMOD_UNSYNCD
;
1580 if (elapsed
) *elapsed
= 0;
1586 // if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1587 // AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1588 // if (elapsed) (*elapsed)++;
1590 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1591 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1592 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1593 if(ManchesterDecoding((b
>>4) & 0xf)) {
1594 *samples
= ((c
- 1) << 3) + 4;
1597 if(ManchesterDecoding(b
& 0x0f)) {
1605 void ReaderTransmitBitsPar(uint8_t* frame
, int bits
, uint32_t par
, uint32_t *timing
)
1608 CodeIso14443aBitsAsReaderPar(frame
,bits
,par
);
1611 TransmitFor14443a(ToSend
, ToSendMax
, timing
);
1615 // Store reader command in buffer
1616 if (tracing
) LogTrace(frame
,nbytes(bits
),0,par
,TRUE
);
1619 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
, uint32_t *timing
)
1621 ReaderTransmitBitsPar(frame
,len
*8,par
, timing
);
1624 void ReaderTransmit(uint8_t* frame
, int len
, uint32_t *timing
)
1626 // Generate parity and redirect
1627 ReaderTransmitBitsPar(frame
,len
*8,GetParity(frame
,len
), timing
);
1630 int ReaderReceive(uint8_t* receivedAnswer
)
1633 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1634 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1635 if(samples
== 0) return FALSE
;
1639 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1642 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1643 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1644 *parptr
= Demod
.parityBits
;
1645 if(samples
== 0) return FALSE
;
1649 /* performs iso14443a anticolision procedure
1650 * fills the uid pointer unless NULL
1651 * fills resp_data unless NULL */
1652 int iso14443a_select_card(byte_t
* uid_ptr
, iso14a_card_select_t
* p_hi14a_card
, uint32_t* cuid_ptr
) {
1653 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1654 uint8_t sel_all
[] = { 0x93,0x20 };
1655 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1656 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1657 uint8_t* resp
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
); // was 3560 - tied to other size changes
1659 size_t uid_resp_len
;
1661 uint8_t sak
= 0x04; // cascade uid
1662 int cascade_level
= 0;
1665 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1666 ReaderTransmitBitsPar(wupa
,7,0, NULL
);
1668 if(!ReaderReceive(resp
)) return 0;
1669 // Dbprintf("atqa: %02x %02x",resp[0],resp[1]);
1672 memcpy(p_hi14a_card
->atqa
, resp
, 2);
1673 p_hi14a_card
->uidlen
= 0;
1674 memset(p_hi14a_card
->uid
,0,10);
1679 memset(uid_ptr
,0,10);
1682 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1683 // which case we need to make a cascade 2 request and select - this is a long UID
1684 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1685 for(; sak
& 0x04; cascade_level
++) {
1686 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1687 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1690 ReaderTransmit(sel_all
,sizeof(sel_all
), NULL
);
1691 if (!ReaderReceive(resp
)) return 0;
1693 // First backup the current uid
1694 memcpy(uid_resp
,resp
,4);
1696 // Dbprintf("uid: %02x %02x %02x %02x",uid_resp[0],uid_resp[1],uid_resp[2],uid_resp[3]);
1698 // calculate crypto UID. Always use last 4 Bytes.
1700 *cuid_ptr
= bytes_to_num(uid_resp
, 4);
1703 // Construct SELECT UID command
1704 memcpy(sel_uid
+2,resp
,5);
1705 AppendCrc14443a(sel_uid
,7);
1706 ReaderTransmit(sel_uid
,sizeof(sel_uid
), NULL
);
1709 if (!ReaderReceive(resp
)) return 0;
1712 // Test if more parts of the uid are comming
1713 if ((sak
& 0x04) && uid_resp
[0] == 0x88) {
1714 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
1715 // http://www.nxp.com/documents/application_note/AN10927.pdf
1716 memcpy(uid_resp
, uid_resp
+ 1, 3);
1721 memcpy(uid_ptr
+ (cascade_level
*3), uid_resp
, uid_resp_len
);
1725 memcpy(p_hi14a_card
->uid
+ (cascade_level
*3), uid_resp
, uid_resp_len
);
1726 p_hi14a_card
->uidlen
+= uid_resp_len
;
1731 p_hi14a_card
->sak
= sak
;
1732 p_hi14a_card
->ats_len
= 0;
1735 if( (sak
& 0x20) == 0) {
1736 return 2; // non iso14443a compliant tag
1739 // Request for answer to select
1740 AppendCrc14443a(rats
, 2);
1741 ReaderTransmit(rats
, sizeof(rats
), NULL
);
1743 if (!(len
= ReaderReceive(resp
))) return 0;
1746 memcpy(p_hi14a_card
->ats
, resp
, sizeof(p_hi14a_card
->ats
));
1747 p_hi14a_card
->ats_len
= len
;
1750 // reset the PCB block number
1751 iso14_pcb_blocknum
= 0;
1755 void iso14443a_setup() {
1756 // Set up the synchronous serial port
1758 // Start from off (no field generated)
1759 // Signal field is off with the appropriate LED
1761 // FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1764 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1766 // Now give it time to spin up.
1767 // Signal field is on with the appropriate LED
1769 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1770 SpinDelay(7); // iso14443-3 specifies 5ms max.
1772 iso14a_timeout
= 2048; //default
1775 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1776 uint8_t real_cmd
[cmd_len
+4];
1777 real_cmd
[0] = 0x0a; //I-Block
1778 // put block number into the PCB
1779 real_cmd
[0] |= iso14_pcb_blocknum
;
1780 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1781 memcpy(real_cmd
+2, cmd
, cmd_len
);
1782 AppendCrc14443a(real_cmd
,cmd_len
+2);
1784 ReaderTransmit(real_cmd
, cmd_len
+4, NULL
);
1785 size_t len
= ReaderReceive(data
);
1786 uint8_t * data_bytes
= (uint8_t *) data
;
1788 return 0; //DATA LINK ERROR
1789 // if we received an I- or R(ACK)-Block with a block number equal to the
1790 // current block number, toggle the current block number
1791 else if (len
>= 4 // PCB+CID+CRC = 4 bytes
1792 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
1793 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1794 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) // equal block numbers
1796 iso14_pcb_blocknum
^= 1;
1802 //-----------------------------------------------------------------------------
1803 // Read an ISO 14443a tag. Send out commands and store answers.
1805 //-----------------------------------------------------------------------------
1806 void ReaderIso14443a(UsbCommand
* c
)
1808 iso14a_command_t param
= c
->arg
[0];
1809 uint8_t * cmd
= c
->d
.asBytes
;
1810 size_t len
= c
->arg
[1];
1811 size_t lenbits
= c
->arg
[2];
1813 byte_t buf
[USB_CMD_DATA_SIZE
];
1815 if(param
& ISO14A_CONNECT
) {
1816 iso14a_clear_trace();
1818 iso14a_set_tracing(true);
1820 if(param
& ISO14A_REQUEST_TRIGGER
) {
1821 iso14a_set_trigger(1);
1824 if(param
& ISO14A_CONNECT
) {
1826 if(!(param
& ISO14A_NO_SELECT
)) {
1827 iso14a_card_select_t
*card
= (iso14a_card_select_t
*)buf
;
1828 arg0
= iso14443a_select_card(NULL
,card
,NULL
);
1829 cmd_send(CMD_ACK
,arg0
,card
->uidlen
,0,buf
,sizeof(iso14a_card_select_t
));
1833 if(param
& ISO14A_SET_TIMEOUT
) {
1834 iso14a_timeout
= c
->arg
[2];
1837 if(param
& ISO14A_SET_TIMEOUT
) {
1838 iso14a_timeout
= c
->arg
[2];
1841 if(param
& ISO14A_APDU
) {
1842 arg0
= iso14_apdu(cmd
, len
, buf
);
1843 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(buf
));
1846 if(param
& ISO14A_RAW
) {
1847 if(param
& ISO14A_APPEND_CRC
) {
1848 AppendCrc14443a(cmd
,len
);
1852 ReaderTransmitBitsPar(cmd
,lenbits
,GetParity(cmd
,lenbits
/8), NULL
);
1854 ReaderTransmit(cmd
,len
, NULL
);
1856 arg0
= ReaderReceive(buf
);
1857 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(buf
));
1860 if(param
& ISO14A_REQUEST_TRIGGER
) {
1861 iso14a_set_trigger(0);
1864 if(param
& ISO14A_NO_DISCONNECT
) {
1868 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1873 // Determine the distance between two nonces.
1874 // Assume that the difference is small, but we don't know which is first.
1875 // Therefore try in alternating directions.
1876 int32_t dist_nt(uint32_t nt1
, uint32_t nt2
) {
1879 uint32_t nttmp1
, nttmp2
;
1881 if (nt1
== nt2
) return 0;
1886 for (i
= 1; i
< 32768; i
++) {
1887 nttmp1
= prng_successor(nttmp1
, 1);
1888 if (nttmp1
== nt2
) return i
;
1889 nttmp2
= prng_successor(nttmp2
, 1);
1890 if (nttmp2
== nt1
) return -i
;
1893 return(-99999); // either nt1 or nt2 are invalid nonces
1897 //-----------------------------------------------------------------------------
1898 // Recover several bits of the cypher stream. This implements (first stages of)
1899 // the algorithm described in "The Dark Side of Security by Obscurity and
1900 // Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
1901 // (article by Nicolas T. Courtois, 2009)
1902 //-----------------------------------------------------------------------------
1903 void ReaderMifare(bool first_try
)
1906 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1907 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1908 static uint8_t mf_nr_ar3
;
1910 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
1916 //byte_t par_mask = 0xff;
1917 static byte_t par_low
= 0;
1922 uint32_t nt
, previous_nt
;
1923 static uint32_t nt_attacked
= 0;
1924 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1925 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1927 static uint32_t sync_time
;
1928 static uint32_t sync_cycles
;
1929 int catch_up_cycles
= 0;
1930 int last_catch_up
= 0;
1931 uint16_t consecutive_resyncs
= 0;
1940 while((GetCountMifare() & 0xffff0000) != 0x10000); // wait for counter to reset and "warm up"
1941 sync_time
= GetCountMifare() & 0xfffffff8;
1942 sync_cycles
= 65536; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
1948 // we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same)
1949 // nt_attacked = prng_successor(nt_attacked, 1);
1951 mf_nr_ar
[3] = mf_nr_ar3
;
1960 for(uint16_t i
= 0; TRUE
; i
++) {
1964 // Test if the action was cancelled
1965 if(BUTTON_PRESS()) {
1971 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
1972 if (MF_DBGLEVEL
>= 1) Dbprintf("Mifare: Can't select card");
1976 //keep the card active
1977 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1979 // CodeIso14443aBitsAsReaderPar(mf_auth, sizeof(mf_auth)*8, GetParity(mf_auth, sizeof(mf_auth)*8));
1981 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
1982 catch_up_cycles
= 0;
1984 // if we missed the sync time already, advance to the next nonce repeat
1985 while(GetCountMifare() > sync_time
) {
1986 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
1989 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
1990 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
1992 // Receive the (4 Byte) "random" nonce
1993 if (!ReaderReceive(receivedAnswer
)) {
1994 if (MF_DBGLEVEL
>= 1) Dbprintf("Mifare: Couldn't receive tag nonce");
1999 nt
= bytes_to_num(receivedAnswer
, 4);
2001 // Transmit reader nonce with fake par
2002 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
2004 if (first_try
&& previous_nt
&& !nt_attacked
) { // we didn't calibrate our clock yet
2005 int nt_distance
= dist_nt(previous_nt
, nt
);
2006 if (nt_distance
== 0) {
2010 if (nt_distance
== -99999) { // invalid nonce received, try again
2013 sync_cycles
= (sync_cycles
- nt_distance
);
2014 if (MF_DBGLEVEL
>= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i
, nt_distance
, sync_cycles
);
2019 if ((nt
!= nt_attacked
) && nt_attacked
) { // we somehow lost sync. Try to catch up again...
2020 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
2021 if (catch_up_cycles
== 99999) { // invalid nonce received. Don't resync on that one.
2022 catch_up_cycles
= 0;
2025 if (catch_up_cycles
== last_catch_up
) {
2026 consecutive_resyncs
++;
2029 last_catch_up
= catch_up_cycles
;
2030 consecutive_resyncs
= 0;
2032 if (consecutive_resyncs
< 3) {
2033 if (MF_DBGLEVEL
>= 3) Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, -catch_up_cycles
, consecutive_resyncs
);
2036 sync_cycles
= sync_cycles
+ catch_up_cycles
;
2037 if (MF_DBGLEVEL
>= 3) Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i
, -catch_up_cycles
, sync_cycles
);
2042 consecutive_resyncs
= 0;
2044 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
2045 if (ReaderReceive(receivedAnswer
))
2047 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
2051 par_low
= par
& 0x07; // there is no need to check all parities for other nt_diff. Parity Bits for mf_nr_ar[0..2] won't change
2055 if(led_on
) LED_B_ON(); else LED_B_OFF();
2057 par_list
[nt_diff
] = par
;
2058 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
2060 // Test if the information is complete
2061 if (nt_diff
== 0x07) {
2066 nt_diff
= (nt_diff
+ 1) & 0x07;
2067 mf_nr_ar
[3] = (mf_nr_ar
[3] & 0x1F) | (nt_diff
<< 5);
2070 if (nt_diff
== 0 && first_try
)
2074 par
= (((par
>> 3) + 1) << 3) | par_low
;
2079 LogTrace((const uint8_t *)&nt
, 4, 0, GetParity((const uint8_t *)&nt
, 4), TRUE
);
2080 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
2081 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
2083 mf_nr_ar
[3] &= 0x1F;
2086 memcpy(buf
+ 0, uid
, 4);
2087 num_to_bytes(nt
, 4, buf
+ 4);
2088 memcpy(buf
+ 8, par_list
, 8);
2089 memcpy(buf
+ 16, ks_list
, 8);
2090 memcpy(buf
+ 24, mf_nr_ar
, 4);
2092 cmd_send(CMD_ACK
,isOK
,0,0,buf
,28);
2095 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2100 //-----------------------------------------------------------------------------
2101 // MIFARE 1K simulate.
2103 //-----------------------------------------------------------------------------
2104 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2106 int cardSTATE
= MFEMUL_NOFIELD
;
2108 int vHf
= 0; // in mV
2109 //int nextCycleTimeout = 0;
2111 // uint32_t timer = 0;
2112 uint32_t selTimer
= 0;
2113 uint32_t authTimer
= 0;
2116 uint8_t cardWRBL
= 0;
2117 uint8_t cardAUTHSC
= 0;
2118 uint8_t cardAUTHKEY
= 0xff; // no authentication
2119 //uint32_t cardRn = 0;
2120 uint32_t cardRr
= 0;
2122 //uint32_t rn_enc = 0;
2124 uint32_t cardINTREG
= 0;
2125 uint8_t cardINTBLOCK
= 0;
2126 struct Crypto1State mpcs
= {0, 0};
2127 struct Crypto1State
*pcs
;
2130 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
2131 uint8_t *response
= eml_get_bigbufptr_sendbuf();
2133 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2135 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2136 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2138 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2139 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
2141 static uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
2142 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
2143 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2149 // Authenticate response - nonce
2150 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2152 // get UID from emul memory
2153 emlGetMemBt(receivedCmd
, 7, 1);
2154 _7BUID
= !(receivedCmd
[0] == 0x00);
2155 if (!_7BUID
) { // ---------- 4BUID
2158 emlGetMemBt(rUIDBCC1
, 0, 4);
2159 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2160 } else { // ---------- 7BUID
2164 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2165 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2166 emlGetMemBt(rUIDBCC2
, 3, 4);
2167 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2170 // -------------------------------------- test area
2172 // -------------------------------------- END test area
2173 // start mkseconds counter
2176 // We need to listen to the high-frequency, peak-detected path.
2177 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2180 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2183 if (MF_DBGLEVEL
>= 1) Dbprintf("Started. 7buid=%d", _7BUID
);
2184 // calibrate mkseconds counter
2189 if(BUTTON_PRESS()) {
2193 // find reader field
2194 // Vref = 3300mV, and an 10:1 voltage divider on the input
2195 // can measure voltages up to 33000 mV
2196 if (cardSTATE
== MFEMUL_NOFIELD
) {
2197 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2198 if (vHf
> MF_MINFIELDV
) {
2199 cardSTATE_TO_IDLE();
2204 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2205 res
= EmGetCmd(receivedCmd
, &len
, RECV_CMD_SIZE
); // (+ nextCycleTimeout)
2207 cardSTATE
= MFEMUL_NOFIELD
;
2214 //nextCycleTimeout = 0;
2216 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2218 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2219 // REQ or WUP request in ANY state and WUP in HALTED state
2220 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2221 selTimer
= GetTickCount();
2222 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2223 cardSTATE
= MFEMUL_SELECT1
;
2225 // init crypto block
2228 crypto1_destroy(pcs
);
2233 switch (cardSTATE
) {
2234 case MFEMUL_NOFIELD
:{
2237 case MFEMUL_HALTED
:{
2243 case MFEMUL_SELECT1
:{
2245 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2246 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2252 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2254 EmSendCmd(rSAK
, sizeof(rSAK
));
2256 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2258 cuid
= bytes_to_num(rUIDBCC1
, 4);
2260 cardSTATE
= MFEMUL_WORK
;
2262 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2265 cardSTATE
= MFEMUL_SELECT2
;
2272 case MFEMUL_SELECT2
:{
2275 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2276 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2282 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2283 EmSendCmd(rSAK
, sizeof(rSAK
));
2285 cuid
= bytes_to_num(rUIDBCC2
, 4);
2286 cardSTATE
= MFEMUL_WORK
;
2288 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2292 // i guess there is a command). go into the work state.
2293 if (len
!= 4) break;
2294 cardSTATE
= MFEMUL_WORK
;
2300 //rn_enc = bytes_to_num(receivedCmd, 4);
2301 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2302 cardRr
= bytes_to_num(&receivedCmd
[4], 4) ^ crypto1_word(pcs
, 0, 0);
2304 if (cardRr
!= prng_successor(nonce
, 64)){
2305 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr
, prng_successor(nonce
, 64));
2306 cardSTATE_TO_IDLE();
2309 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2310 num_to_bytes(ans
, 4, rAUTH_AT
);
2312 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2313 cardSTATE
= MFEMUL_AUTH2
;
2315 cardSTATE_TO_IDLE();
2317 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2321 cardSTATE
= MFEMUL_WORK
;
2322 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2326 lbWORK
: if (len
== 0) break;
2328 if (cardAUTHKEY
== 0xff) {
2329 // first authentication
2330 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2331 authTimer
= GetTickCount();
2333 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2334 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2337 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2338 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2339 num_to_bytes(nonce
, 4, rAUTH_AT
);
2340 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2343 // last working revision
2344 // EmSendCmd14443aRaw(resp1, resp1Len, 0);
2345 // LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2347 cardSTATE
= MFEMUL_AUTH1
;
2348 //nextCycleTimeout = 10;
2353 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2355 // nested authentication
2356 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2357 authTimer
= GetTickCount();
2359 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2360 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2363 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2364 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2365 num_to_bytes(ans
, 4, rAUTH_AT
);
2366 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2369 cardSTATE
= MFEMUL_AUTH1
;
2370 //nextCycleTimeout = 10;
2375 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2376 // BUT... ACK --> NACK
2377 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2378 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2382 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2383 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2384 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2389 if (len
== 4 && receivedCmd
[0] == 0x30) {
2390 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2391 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2394 emlGetMem(response
, receivedCmd
[1], 1);
2395 AppendCrc14443a(response
, 16);
2396 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2397 EmSendCmdPar(response
, 18, par
);
2402 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2403 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2404 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2407 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2408 //nextCycleTimeout = 50;
2409 cardSTATE
= MFEMUL_WRITEBL2
;
2410 cardWRBL
= receivedCmd
[1];
2414 // works with cardINTREG
2416 // increment, decrement, restore
2417 if (len
== 4 && (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2)) {
2418 if (receivedCmd
[1] >= 16 * 4 ||
2419 receivedCmd
[1] / 4 != cardAUTHSC
||
2420 emlCheckValBl(receivedCmd
[1])) {
2421 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2424 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2425 if (receivedCmd
[0] == 0xC1)
2426 cardSTATE
= MFEMUL_INTREG_INC
;
2427 if (receivedCmd
[0] == 0xC0)
2428 cardSTATE
= MFEMUL_INTREG_DEC
;
2429 if (receivedCmd
[0] == 0xC2)
2430 cardSTATE
= MFEMUL_INTREG_REST
;
2431 cardWRBL
= receivedCmd
[1];
2438 if (len
== 4 && receivedCmd
[0] == 0xB0) {
2439 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2440 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2444 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2445 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2447 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2453 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2456 cardSTATE
= MFEMUL_HALTED
;
2457 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2461 // command not allowed
2463 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2470 case MFEMUL_WRITEBL2
:{
2472 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2473 emlSetMem(receivedCmd
, cardWRBL
, 1);
2474 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2475 cardSTATE
= MFEMUL_WORK
;
2478 cardSTATE_TO_IDLE();
2484 case MFEMUL_INTREG_INC
:{
2485 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2486 memcpy(&ans
, receivedCmd
, 4);
2487 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2488 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2489 cardSTATE_TO_IDLE();
2492 cardINTREG
= cardINTREG
+ ans
;
2493 cardSTATE
= MFEMUL_WORK
;
2496 case MFEMUL_INTREG_DEC
:{
2497 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2498 memcpy(&ans
, receivedCmd
, 4);
2499 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2500 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2501 cardSTATE_TO_IDLE();
2504 cardINTREG
= cardINTREG
- ans
;
2505 cardSTATE
= MFEMUL_WORK
;
2508 case MFEMUL_INTREG_REST
:{
2509 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2510 memcpy(&ans
, receivedCmd
, 4);
2511 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2512 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2513 cardSTATE_TO_IDLE();
2516 cardSTATE
= MFEMUL_WORK
;
2522 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2525 // add trace trailer
2526 memset(rAUTH_NT
, 0x44, 4);
2527 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2529 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);
2532 //-----------------------------------------------------------------------------
2535 //-----------------------------------------------------------------------------
2536 void RAMFUNC
SniffMifare(uint8_t param
) {
2538 // bit 0 - trigger from first card answer
2539 // bit 1 - trigger from first reader 7-bit request
2541 // C(red) A(yellow) B(green)
2543 // init trace buffer
2544 iso14a_clear_trace();
2546 // The command (reader -> tag) that we're receiving.
2547 // The length of a received command will in most cases be no more than 18 bytes.
2548 // So 32 should be enough!
2549 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
2550 // The response (tag -> reader) that we're receiving.
2551 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
2553 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2554 // into trace, along with its length and other annotations.
2555 //uint8_t *trace = (uint8_t *)BigBuf;
2557 // The DMA buffer, used to stream samples from the FPGA
2558 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
2559 int8_t *data
= dmaBuf
;
2563 // Set up the demodulator for tag -> reader responses.
2564 Demod
.output
= receivedResponse
;
2566 Demod
.state
= DEMOD_UNSYNCD
;
2568 // Set up the demodulator for the reader -> tag commands
2569 memset(&Uart
, 0, sizeof(Uart
));
2570 Uart
.output
= receivedCmd
;
2571 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
2572 Uart
.state
= STATE_UNSYNCD
;
2574 // Setup for the DMA.
2576 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
2578 // And put the FPGA in the appropriate mode
2579 // Signal field is off with the appropriate LED
2581 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
2582 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2586 int sniffCounter
= 0;
2588 // And now we loop, receiving samples.
2590 if(BUTTON_PRESS()) {
2591 DbpString("cancelled by button");
2598 if (++sniffCounter
> 65) {
2599 if (MfSniffSend(2000)) {
2605 int register readBufDataP
= data
- dmaBuf
;
2606 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
2607 if (readBufDataP
<= dmaBufDataP
){
2608 dataLen
= dmaBufDataP
- readBufDataP
;
2610 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
2612 // test for length of buffer
2613 if(dataLen
> maxDataLen
) {
2614 maxDataLen
= dataLen
;
2616 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
2620 if(dataLen
< 1) continue;
2622 // primary buffer was stopped( <-- we lost data!
2623 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
2624 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
2625 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
2626 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen
); // temporary
2628 // secondary buffer sets as primary, secondary buffer was stopped
2629 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
2630 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
2631 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
2636 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
2638 // check - if there is a short 7bit request from reader
2639 if (MfSniffLogic(receivedCmd
, Uart
.byteCnt
, Uart
.parityBits
, Uart
.bitCnt
, TRUE
)) break;
2641 /* And ready to receive another command. */
2642 Uart
.state
= STATE_UNSYNCD
;
2644 /* And also reset the demod code */
2645 Demod
.state
= DEMOD_UNSYNCD
;
2648 if(ManchesterDecoding(data
[0] & 0x0F)) {
2651 if (MfSniffLogic(receivedResponse
, Demod
.len
, Demod
.parityBits
, Demod
.bitCount
, FALSE
)) break;
2653 // And ready to receive another response.
2654 memset(&Demod
, 0, sizeof(Demod
));
2655 Demod
.output
= receivedResponse
;
2656 Demod
.state
= DEMOD_UNSYNCD
;
2658 /* And also reset the uart code */
2659 Uart
.state
= STATE_UNSYNCD
;
2663 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
2668 DbpString("COMMAND FINISHED");
2671 FpgaDisableSscDma();
2674 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);