1 //-----------------------------------------------------------------------------
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
9 //-----------------------------------------------------------------------------
10 // Routines to support ISO 14443 type A.
11 //-----------------------------------------------------------------------------
13 #include "proxmark3.h"
18 #include "iso14443crc.h"
19 #include "iso14443a.h"
21 #include "mifareutil.h"
23 static uint8_t *trace
= (uint8_t *) BigBuf
;
24 static int traceLen
= 0;
25 static int rsamples
= 0;
26 static int tracing
= TRUE
;
27 static uint32_t iso14a_timeout
;
29 // CARD TO READER - manchester
30 // Sequence D: 11110000 modulation with subcarrier during first half
31 // Sequence E: 00001111 modulation with subcarrier during second half
32 // Sequence F: 00000000 no modulation with subcarrier
33 // READER TO CARD - miller
34 // Sequence X: 00001100 drop after half a period
35 // Sequence Y: 00000000 no drop
36 // Sequence Z: 11000000 drop at start
44 static const uint8_t OddByteParity
[256] = {
45 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
46 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
47 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
48 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
49 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
50 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
51 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
52 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
57 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
58 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
59 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
60 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
64 void iso14a_set_trigger(int enable
) {
68 void iso14a_clear_tracelen(void) {
71 void iso14a_set_tracing(int enable
) {
75 //-----------------------------------------------------------------------------
76 // Generate the parity value for a byte sequence
78 //-----------------------------------------------------------------------------
79 byte_t
oddparity (const byte_t bt
)
81 return OddByteParity
[bt
];
84 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
89 // Generate the encrypted data
90 for (i
= 0; i
< iLen
; i
++) {
91 // Save the encrypted parity bit
92 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
97 void AppendCrc14443a(uint8_t* data
, int len
)
99 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
102 int LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
104 // Return when trace is full
105 if (traceLen
>= TRACE_LENGTH
) return FALSE
;
107 // Trace the random, i'm curious
108 rsamples
+= iSamples
;
109 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
110 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
111 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
112 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
114 trace
[traceLen
- 1] |= 0x80;
116 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
117 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
118 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
119 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
120 trace
[traceLen
++] = iLen
;
121 memcpy(trace
+ traceLen
, btBytes
, iLen
);
126 //-----------------------------------------------------------------------------
127 // The software UART that receives commands from the reader, and its state
129 //-----------------------------------------------------------------------------
133 STATE_START_OF_COMMUNICATION
,
157 static RAMFUNC
int MillerDecoding(int bit
)
162 if(!Uart
.bitBuffer
) {
163 Uart
.bitBuffer
= bit
^ 0xFF0;
167 Uart
.bitBuffer
<<= 4;
168 Uart
.bitBuffer
^= bit
;
173 if(Uart
.state
!= STATE_UNSYNCD
) {
176 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
182 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
188 if(bit
!= bitright
) { bit
= bitright
; }
190 if(Uart
.posCnt
== 1) {
191 // measurement first half bitperiod
193 Uart
.drop
= DROP_FIRST_HALF
;
197 // measurement second half bitperiod
198 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
199 Uart
.drop
= DROP_SECOND_HALF
;
202 // measured a drop in first and second half
203 // which should not be possible
204 Uart
.state
= STATE_ERROR_WAIT
;
211 case STATE_START_OF_COMMUNICATION
:
213 if(Uart
.drop
== DROP_SECOND_HALF
) {
214 // error, should not happen in SOC
215 Uart
.state
= STATE_ERROR_WAIT
;
220 Uart
.state
= STATE_MILLER_Z
;
227 if(Uart
.drop
== DROP_NONE
) {
228 // logic '0' followed by sequence Y
229 // end of communication
230 Uart
.state
= STATE_UNSYNCD
;
233 // if(Uart.drop == DROP_FIRST_HALF) {
234 // Uart.state = STATE_MILLER_Z; stay the same
235 // we see a logic '0' }
236 if(Uart
.drop
== DROP_SECOND_HALF
) {
237 // we see a logic '1'
238 Uart
.shiftReg
|= 0x100;
239 Uart
.state
= STATE_MILLER_X
;
245 if(Uart
.drop
== DROP_NONE
) {
246 // sequence Y, we see a '0'
247 Uart
.state
= STATE_MILLER_Y
;
250 if(Uart
.drop
== DROP_FIRST_HALF
) {
251 // Would be STATE_MILLER_Z
252 // but Z does not follow X, so error
253 Uart
.state
= STATE_ERROR_WAIT
;
256 if(Uart
.drop
== DROP_SECOND_HALF
) {
257 // We see a '1' and stay in state X
258 Uart
.shiftReg
|= 0x100;
266 if(Uart
.drop
== DROP_NONE
) {
267 // logic '0' followed by sequence Y
268 // end of communication
269 Uart
.state
= STATE_UNSYNCD
;
272 if(Uart
.drop
== DROP_FIRST_HALF
) {
274 Uart
.state
= STATE_MILLER_Z
;
276 if(Uart
.drop
== DROP_SECOND_HALF
) {
277 // We see a '1' and go to state X
278 Uart
.shiftReg
|= 0x100;
279 Uart
.state
= STATE_MILLER_X
;
283 case STATE_ERROR_WAIT
:
284 // That went wrong. Now wait for at least two bit periods
285 // and try to sync again
286 if(Uart
.drop
== DROP_NONE
) {
288 Uart
.state
= STATE_UNSYNCD
;
293 Uart
.state
= STATE_UNSYNCD
;
298 Uart
.drop
= DROP_NONE
;
300 // should have received at least one whole byte...
301 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
305 if(Uart
.bitCnt
== 9) {
306 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
309 Uart
.parityBits
<<= 1;
310 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
313 // when End of Communication received and
314 // all data bits processed..
321 Uart.output[Uart.byteCnt] = 0xAA;
323 Uart.output[Uart.byteCnt] = error & 0xFF;
325 Uart.output[Uart.byteCnt] = 0xAA;
327 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
329 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
331 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
333 Uart.output[Uart.byteCnt] = 0xAA;
341 bit
= Uart
.bitBuffer
& 0xf0;
345 // should have been high or at least (4 * 128) / fc
346 // according to ISO this should be at least (9 * 128 + 20) / fc
347 if(Uart
.highCnt
== 8) {
348 // we went low, so this could be start of communication
349 // it turns out to be safer to choose a less significant
350 // syncbit... so we check whether the neighbour also represents the drop
351 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
352 Uart
.syncBit
= bit
& 8;
354 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
355 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
356 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
357 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
358 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
359 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
362 // the first half bit period is expected in next sample
367 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
370 Uart
.state
= STATE_START_OF_COMMUNICATION
;
371 Uart
.drop
= DROP_FIRST_HALF
;
382 if(Uart
.highCnt
< 8) {
391 //=============================================================================
392 // ISO 14443 Type A - Manchester
393 //=============================================================================
398 DEMOD_START_OF_COMMUNICATION
,
421 static RAMFUNC
int ManchesterDecoding(int v
)
437 if(Demod
.state
==DEMOD_UNSYNCD
) {
438 Demod
.output
[Demod
.len
] = 0xfa;
441 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
444 Demod
.syncBit
= 0x08;
451 Demod
.syncBit
= 0x04;
458 Demod
.syncBit
= 0x02;
461 if(bit
& 0x01 && Demod
.syncBit
) {
462 Demod
.syncBit
= 0x01;
467 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
468 Demod
.sub
= SUB_FIRST_HALF
;
471 Demod
.parityBits
= 0;
474 if(trigger
) LED_A_OFF();
475 switch(Demod
.syncBit
) {
476 case 0x08: Demod
.samples
= 3; break;
477 case 0x04: Demod
.samples
= 2; break;
478 case 0x02: Demod
.samples
= 1; break;
479 case 0x01: Demod
.samples
= 0; break;
486 //modulation = bit & Demod.syncBit;
487 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
491 if(Demod
.posCount
==0) {
494 Demod
.sub
= SUB_FIRST_HALF
;
497 Demod
.sub
= SUB_NONE
;
502 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
503 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
504 Demod
.state
= DEMOD_ERROR_WAIT
;
505 Demod
.output
[Demod
.len
] = 0xaa;
509 else if(modulation
) {
510 Demod
.sub
= SUB_SECOND_HALF
;
513 switch(Demod
.state
) {
514 case DEMOD_START_OF_COMMUNICATION
:
515 if(Demod
.sub
== SUB_FIRST_HALF
) {
516 Demod
.state
= DEMOD_MANCHESTER_D
;
519 Demod
.output
[Demod
.len
] = 0xab;
520 Demod
.state
= DEMOD_ERROR_WAIT
;
525 case DEMOD_MANCHESTER_D
:
526 case DEMOD_MANCHESTER_E
:
527 if(Demod
.sub
== SUB_FIRST_HALF
) {
529 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
530 Demod
.state
= DEMOD_MANCHESTER_D
;
532 else if(Demod
.sub
== SUB_SECOND_HALF
) {
534 Demod
.shiftReg
>>= 1;
535 Demod
.state
= DEMOD_MANCHESTER_E
;
538 Demod
.state
= DEMOD_MANCHESTER_F
;
542 case DEMOD_MANCHESTER_F
:
543 // Tag response does not need to be a complete byte!
544 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
545 if(Demod
.bitCount
> 0) {
546 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
547 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
549 // No parity bit, so just shift a 0
550 Demod
.parityBits
<<= 1;
553 Demod
.state
= DEMOD_UNSYNCD
;
557 Demod
.output
[Demod
.len
] = 0xad;
558 Demod
.state
= DEMOD_ERROR_WAIT
;
563 case DEMOD_ERROR_WAIT
:
564 Demod
.state
= DEMOD_UNSYNCD
;
568 Demod
.output
[Demod
.len
] = 0xdd;
569 Demod
.state
= DEMOD_UNSYNCD
;
573 if(Demod
.bitCount
>=9) {
574 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
577 Demod
.parityBits
<<= 1;
578 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
585 Demod.output[Demod.len] = 0xBB;
587 Demod.output[Demod.len] = error & 0xFF;
589 Demod.output[Demod.len] = 0xBB;
591 Demod.output[Demod.len] = bit & 0xFF;
593 Demod.output[Demod.len] = Demod.buffer & 0xFF;
595 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
597 Demod.output[Demod.len] = 0xBB;
604 } // end (state != UNSYNCED)
609 //=============================================================================
610 // Finally, a `sniffer' for ISO 14443 Type A
611 // Both sides of communication!
612 //=============================================================================
614 //-----------------------------------------------------------------------------
615 // Record the sequence of commands sent by the reader to the tag, with
616 // triggering so that we start recording at the point that the tag is moved
618 //-----------------------------------------------------------------------------
619 void RAMFUNC
SnoopIso14443a(void)
621 // #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
622 // #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
623 // #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
624 // #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
625 // #define TRACE_LENGTH 2000 // original (working as of 21/2/09) values
627 // We won't start recording the frames that we acquire until we trigger;
628 // a good trigger condition to get started is probably when we see a
629 // response from the tag.
630 int triggered
= FALSE
; // FALSE to wait first for card
632 // The command (reader -> tag) that we're receiving.
633 // The length of a received command will in most cases be no more than 18 bytes.
634 // So 32 should be enough!
635 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
636 // The response (tag -> reader) that we're receiving.
637 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
639 // As we receive stuff, we copy it from receivedCmd or receivedResponse
640 // into trace, along with its length and other annotations.
641 //uint8_t *trace = (uint8_t *)BigBuf;
643 traceLen
= 0; // uncommented to fix ISSUE 15 - gerhard - jan2011
645 // The DMA buffer, used to stream samples from the FPGA
646 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
652 // Count of samples received so far, so that we can include timing
653 // information in the trace buffer.
657 memset(trace
, 0x44, RECV_CMD_OFFSET
);
659 // Set up the demodulator for tag -> reader responses.
660 Demod
.output
= receivedResponse
;
662 Demod
.state
= DEMOD_UNSYNCD
;
664 // Setup for the DMA.
667 lastRxCounter
= DMA_BUFFER_SIZE
;
668 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
670 // And the reader -> tag commands
671 memset(&Uart
, 0, sizeof(Uart
));
672 Uart
.output
= receivedCmd
;
673 Uart
.byteCntMax
= 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
674 Uart
.state
= STATE_UNSYNCD
;
676 // And put the FPGA in the appropriate mode
677 // Signal field is off with the appropriate LED
679 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
680 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
683 // And now we loop, receiving samples.
687 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) &
689 if(behindBy
> maxBehindBy
) {
690 maxBehindBy
= behindBy
;
692 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy
);
696 if(behindBy
< 1) continue;
702 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
703 upTo
-= DMA_BUFFER_SIZE
;
704 lastRxCounter
+= DMA_BUFFER_SIZE
;
705 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
706 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
710 if(MillerDecoding((smpl
& 0xF0) >> 4)) {
711 rsamples
= samples
- Uart
.samples
;
714 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
715 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
716 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
717 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
718 trace
[traceLen
++] = ((Uart
.parityBits
>> 0) & 0xff);
719 trace
[traceLen
++] = ((Uart
.parityBits
>> 8) & 0xff);
720 trace
[traceLen
++] = ((Uart
.parityBits
>> 16) & 0xff);
721 trace
[traceLen
++] = ((Uart
.parityBits
>> 24) & 0xff);
722 trace
[traceLen
++] = Uart
.byteCnt
;
723 memcpy(trace
+traceLen
, receivedCmd
, Uart
.byteCnt
);
724 traceLen
+= Uart
.byteCnt
;
725 if(traceLen
> TRACE_LENGTH
) break;
727 /* And ready to receive another command. */
728 Uart
.state
= STATE_UNSYNCD
;
729 /* And also reset the demod code, which might have been */
730 /* false-triggered by the commands from the reader. */
731 Demod
.state
= DEMOD_UNSYNCD
;
735 if(ManchesterDecoding(smpl
& 0x0F)) {
736 rsamples
= samples
- Demod
.samples
;
739 // timestamp, as a count of samples
740 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
741 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
742 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
743 trace
[traceLen
++] = 0x80 | ((rsamples
>> 24) & 0xff);
744 trace
[traceLen
++] = ((Demod
.parityBits
>> 0) & 0xff);
745 trace
[traceLen
++] = ((Demod
.parityBits
>> 8) & 0xff);
746 trace
[traceLen
++] = ((Demod
.parityBits
>> 16) & 0xff);
747 trace
[traceLen
++] = ((Demod
.parityBits
>> 24) & 0xff);
749 trace
[traceLen
++] = Demod
.len
;
750 memcpy(trace
+traceLen
, receivedResponse
, Demod
.len
);
751 traceLen
+= Demod
.len
;
752 if(traceLen
> TRACE_LENGTH
) break;
756 // And ready to receive another response.
757 memset(&Demod
, 0, sizeof(Demod
));
758 Demod
.output
= receivedResponse
;
759 Demod
.state
= DEMOD_UNSYNCD
;
764 DbpString("cancelled_a");
769 DbpString("COMMAND FINISHED");
772 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
773 Dbprintf("maxBehindBy=%x, Uart.state=%x, Uart.byteCnt=%x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
774 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
781 //-----------------------------------------------------------------------------
782 // Prepare tag messages
783 //-----------------------------------------------------------------------------
784 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
790 // Correction bit, might be removed when not needed
795 ToSendStuffBit(1); // 1
801 ToSend
[++ToSendMax
] = SEC_D
;
803 for(i
= 0; i
< len
; i
++) {
808 for(j
= 0; j
< 8; j
++) {
810 ToSend
[++ToSendMax
] = SEC_D
;
812 ToSend
[++ToSendMax
] = SEC_E
;
817 // Get the parity bit
818 if ((dwParity
>> i
) & 0x01) {
819 ToSend
[++ToSendMax
] = SEC_D
;
821 ToSend
[++ToSendMax
] = SEC_E
;
826 ToSend
[++ToSendMax
] = SEC_F
;
828 // Convert from last byte pos to length
832 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
833 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
836 //-----------------------------------------------------------------------------
837 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
838 //-----------------------------------------------------------------------------
839 static void CodeStrangeAnswerAsTag()
845 // Correction bit, might be removed when not needed
850 ToSendStuffBit(1); // 1
856 ToSend
[++ToSendMax
] = SEC_D
;
859 ToSend
[++ToSendMax
] = SEC_E
;
862 ToSend
[++ToSendMax
] = SEC_E
;
865 ToSend
[++ToSendMax
] = SEC_D
;
868 ToSend
[++ToSendMax
] = SEC_F
;
870 // Flush the buffer in FPGA!!
871 for(i
= 0; i
< 5; i
++) {
872 ToSend
[++ToSendMax
] = SEC_F
;
875 // Convert from last byte pos to length
879 static void Code4bitAnswerAsTag(uint8_t cmd
)
885 // Correction bit, might be removed when not needed
890 ToSendStuffBit(1); // 1
896 ToSend
[++ToSendMax
] = SEC_D
;
899 for(i
= 0; i
< 4; i
++) {
901 ToSend
[++ToSendMax
] = SEC_D
;
903 ToSend
[++ToSendMax
] = SEC_E
;
909 ToSend
[++ToSendMax
] = SEC_F
;
911 // Flush the buffer in FPGA!!
912 for(i
= 0; i
< 5; i
++) {
913 ToSend
[++ToSendMax
] = SEC_F
;
916 // Convert from last byte pos to length
920 //-----------------------------------------------------------------------------
921 // Wait for commands from reader
922 // Stop when button is pressed
923 // Or return TRUE when command is captured
924 //-----------------------------------------------------------------------------
925 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
927 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
928 // only, since we are receiving, not transmitting).
929 // Signal field is off with the appropriate LED
931 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
933 // Now run a `software UART' on the stream of incoming samples.
934 Uart
.output
= received
;
935 Uart
.byteCntMax
= maxLen
;
936 Uart
.state
= STATE_UNSYNCD
;
941 if(BUTTON_PRESS()) return FALSE
;
943 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
944 AT91C_BASE_SSC
->SSC_THR
= 0x00;
946 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
947 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
948 if(MillerDecoding((b
& 0xf0) >> 4)) {
952 if(MillerDecoding(b
& 0x0f)) {
959 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
961 //-----------------------------------------------------------------------------
962 // Main loop of simulated tag: receive commands from reader, decide what
963 // response to send, and send it.
964 //-----------------------------------------------------------------------------
965 void SimulateIso14443aTag(int tagType
, int TagUid
)
967 // This function contains the tag emulation
969 // Prepare protocol messages
970 // static const uint8_t cmd1[] = { 0x26 };
971 // static const uint8_t response1[] = { 0x02, 0x00 }; // Says: I am Mifare 4k - original line - greg
973 static const uint8_t response1
[] = { 0x44, 0x03 }; // Says: I am a DESFire Tag, ph33r me
974 // static const uint8_t response1[] = { 0x44, 0x00 }; // Says: I am a ULTRALITE Tag, 0wn me
977 // static const uint8_t cmd2[] = { 0x93, 0x20 };
978 //static const uint8_t response2[] = { 0x9a, 0xe5, 0xe4, 0x43, 0xd8 }; // original value - greg
981 static const uint8_t response2
[] = { 0x88, 0x04, 0x21, 0x3f, 0x4d }; // known uid - note cascade (0x88), 2nd byte (0x04) = NXP/Phillips
984 // When reader selects us during cascade1 it will send cmd3
985 //uint8_t response3[] = { 0x04, 0x00, 0x00 }; // SAK Select (cascade1) successful response (ULTRALITE)
986 uint8_t response3
[] = { 0x24, 0x00, 0x00 }; // SAK Select (cascade1) successful response (DESFire)
987 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
989 // send cascade2 2nd half of UID
990 static const uint8_t response2a
[] = { 0x51, 0x48, 0x1d, 0x80, 0x84 }; // uid - cascade2 - 2nd half (4 bytes) of UID+ BCCheck
991 // NOTE : THE CRC on the above may be wrong as I have obfuscated the actual UID
993 // When reader selects us during cascade2 it will send cmd3a
994 //uint8_t response3a[] = { 0x00, 0x00, 0x00 }; // SAK Select (cascade2) successful response (ULTRALITE)
995 uint8_t response3a
[] = { 0x20, 0x00, 0x00 }; // SAK Select (cascade2) successful response (DESFire)
996 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
998 static const uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
1003 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
1005 // 144 data bits (18 * 8)
1008 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
1009 // 1 just for the case
1013 // 166 bytes, since every bit that needs to be send costs us a byte
1016 // Respond with card type
1017 uint8_t *resp1
= (((uint8_t *)BigBuf
) + 800);
1020 // Anticollision cascade1 - respond with uid
1021 uint8_t *resp2
= (((uint8_t *)BigBuf
) + 970);
1024 // Anticollision cascade2 - respond with 2nd half of uid if asked
1025 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1026 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1029 // Acknowledge select - cascade 1
1030 uint8_t *resp3
= (((uint8_t *)BigBuf
) + 1310);
1033 // Acknowledge select - cascade 2
1034 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + 1480);
1037 // Response to a read request - not implemented atm
1038 uint8_t *resp4
= (((uint8_t *)BigBuf
) + 1550);
1041 // Authenticate response - nonce
1042 uint8_t *resp5
= (((uint8_t *)BigBuf
) + 1720);
1045 uint8_t *receivedCmd
= (uint8_t *)BigBuf
;
1052 // To control where we are in the protocol
1056 // Just to allow some checks
1062 //int fdt_indicator;
1064 memset(receivedCmd
, 0x44, 400);
1066 // Prepare the responses of the anticollision phase
1067 // there will be not enough time to do this at the moment the reader sends it REQA
1069 // Answer to request
1070 CodeIso14443aAsTag(response1
, sizeof(response1
));
1071 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1073 // Send our UID (cascade 1)
1074 CodeIso14443aAsTag(response2
, sizeof(response2
));
1075 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1077 // Answer to select (cascade1)
1078 CodeIso14443aAsTag(response3
, sizeof(response3
));
1079 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1081 // Send the cascade 2 2nd part of the uid
1082 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1083 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1085 // Answer to select (cascade 2)
1086 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1087 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1089 // Strange answer is an example of rare message size (3 bits)
1090 CodeStrangeAnswerAsTag();
1091 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1093 // Authentication answer (random nonce)
1094 CodeIso14443aAsTag(response5
, sizeof(response5
));
1095 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1097 // We need to listen to the high-frequency, peak-detected path.
1098 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1106 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, 100)) {
1107 DbpString("button press");
1110 // 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
1111 // Okay, look at the command now.
1113 //i = 1; // first byte transmitted
1114 if(receivedCmd
[0] == 0x26) {
1115 // Received a REQUEST
1116 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1117 //DbpString("Hello request from reader:");
1118 } else if(receivedCmd
[0] == 0x52) {
1119 // Received a WAKEUP
1120 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1121 // //DbpString("Wakeup request from reader:");
1123 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // greg - cascade 1 anti-collision
1124 // Received request for UID (cascade 1)
1125 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1126 // DbpString("UID (cascade 1) request from reader:");
1127 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1130 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] ==0x95) { // greg - cascade 2 anti-collision
1131 // Received request for UID (cascade 2)
1132 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1133 // DbpString("UID (cascade 2) request from reader:");
1134 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1137 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x93) { // greg - cascade 1 select
1138 // Received a SELECT
1139 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1140 // DbpString("Select (cascade 1) request from reader:");
1141 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1144 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] ==0x95) { // greg - cascade 2 select
1145 // Received a SELECT
1146 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1147 // DbpString("Select (cascade 2) request from reader:");
1148 // DbpIntegers(receivedCmd[0], receivedCmd[1], receivedCmd[2]);
1151 } else if(receivedCmd
[0] == 0x30) {
1153 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1154 Dbprintf("Read request from reader: %x %x %x",
1155 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1158 } else if(receivedCmd
[0] == 0x50) {
1160 resp
= resp1
; respLen
= 0; order
= 5; // Do nothing
1161 DbpString("Reader requested we HALT!:");
1163 } else if(receivedCmd
[0] == 0x60) {
1164 // Received an authentication request
1165 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1166 Dbprintf("Authenticate request from reader: %x %x %x",
1167 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1169 } else if(receivedCmd
[0] == 0xE0) {
1170 // Received a RATS request
1171 resp
= resp1
; respLen
= 0;order
= 70;
1172 Dbprintf("RATS request from reader: %x %x %x",
1173 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2]);
1175 // Never seen this command before
1176 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1178 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2],
1179 receivedCmd
[3], receivedCmd
[4], receivedCmd
[5],
1180 receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1182 resp
= resp1
; respLen
= 0; order
= 0;
1185 // Count number of wakeups received after a halt
1186 if(order
== 6 && lastorder
== 5) { happened
++; }
1188 // Count number of other messages after a halt
1189 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1191 // Look at last parity bit to determine timing of answer
1192 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1193 // 1236, so correction bit needed
1197 memset(receivedCmd
, 0x44, 32);
1199 if(cmdsRecvd
> 999) {
1200 DbpString("1000 commands later...");
1207 if(respLen
<= 0) continue;
1208 //----------------------------
1211 //fdt_indicator = FALSE;
1213 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1214 /* // Modulate Manchester
1215 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1216 AT91C_BASE_SSC->SSC_THR = 0x00;
1219 // ### Transmit the response ###
1222 fdt_indicator = FALSE;
1224 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1225 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1228 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1236 AT91C_BASE_SSC->SSC_THR = b;
1242 if(BUTTON_PRESS()) {
1249 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1253 //-----------------------------------------------------------------------------
1254 // Transmit the command (to the tag) that was placed in ToSend[].
1255 //-----------------------------------------------------------------------------
1256 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1260 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1266 for(c
= 0; c
< *wait
;) {
1267 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1268 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1271 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1272 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1280 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1281 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1287 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1288 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1293 if (samples
) *samples
= (c
+ *wait
) << 3;
1296 //-----------------------------------------------------------------------------
1297 // Code a 7-bit command without parity bit
1298 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1299 //-----------------------------------------------------------------------------
1300 void ShortFrameFromReader(const uint8_t bt
)
1308 // Start of Communication (Seq. Z)
1309 ToSend
[++ToSendMax
] = SEC_Z
;
1313 for(j
= 0; j
< 7; j
++) {
1316 ToSend
[++ToSendMax
] = SEC_X
;
1321 ToSend
[++ToSendMax
] = SEC_Z
;
1325 ToSend
[++ToSendMax
] = SEC_Y
;
1332 // End of Communication
1335 ToSend
[++ToSendMax
] = SEC_Z
;
1339 ToSend
[++ToSendMax
] = SEC_Y
;
1343 ToSend
[++ToSendMax
] = SEC_Y
;
1346 ToSend
[++ToSendMax
] = SEC_Y
;
1347 ToSend
[++ToSendMax
] = SEC_Y
;
1348 ToSend
[++ToSendMax
] = SEC_Y
;
1350 // Convert from last character reference to length
1354 //-----------------------------------------------------------------------------
1355 // Prepare reader command to send to FPGA
1357 //-----------------------------------------------------------------------------
1358 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1366 // Start of Communication (Seq. Z)
1367 ToSend
[++ToSendMax
] = SEC_Z
;
1370 // Generate send structure for the data bits
1371 for (i
= 0; i
< len
; i
++) {
1372 // Get the current byte to send
1375 for (j
= 0; j
< 8; j
++) {
1378 ToSend
[++ToSendMax
] = SEC_X
;
1383 ToSend
[++ToSendMax
] = SEC_Z
;
1386 ToSend
[++ToSendMax
] = SEC_Y
;
1393 // Get the parity bit
1394 if ((dwParity
>> i
) & 0x01) {
1396 ToSend
[++ToSendMax
] = SEC_X
;
1401 ToSend
[++ToSendMax
] = SEC_Z
;
1404 ToSend
[++ToSendMax
] = SEC_Y
;
1410 // End of Communication
1413 ToSend
[++ToSendMax
] = SEC_Z
;
1416 ToSend
[++ToSendMax
] = SEC_Y
;
1420 ToSend
[++ToSendMax
] = SEC_Y
;
1423 ToSend
[++ToSendMax
] = SEC_Y
;
1424 ToSend
[++ToSendMax
] = SEC_Y
;
1425 ToSend
[++ToSendMax
] = SEC_Y
;
1427 // Convert from last character reference to length
1431 //-----------------------------------------------------------------------------
1432 // Wait for commands from reader
1433 // Stop when button is pressed (return 1) or field was gone (return 2)
1434 // Or return 0 when command is captured
1435 //-----------------------------------------------------------------------------
1436 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1440 uint32_t timer
= 0, vtime
= 0;
1444 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1445 // only, since we are receiving, not transmitting).
1446 // Signal field is off with the appropriate LED
1448 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1450 // Set ADC to read field strength
1451 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1452 AT91C_BASE_ADC
->ADC_MR
=
1453 ADC_MODE_PRESCALE(32) |
1454 ADC_MODE_STARTUP_TIME(16) |
1455 ADC_MODE_SAMPLE_HOLD_TIME(8);
1456 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1458 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1460 // Now run a 'software UART' on the stream of incoming samples.
1461 Uart
.output
= received
;
1462 Uart
.byteCntMax
= maxLen
;
1463 Uart
.state
= STATE_UNSYNCD
;
1468 if (BUTTON_PRESS()) return 1;
1470 // test if the field exists
1471 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1473 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1474 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1475 if (analogCnt
>= 32) {
1476 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1477 vtime
= GetTickCount();
1478 if (!timer
) timer
= vtime
;
1479 // 50ms no field --> card to idle state
1480 if (vtime
- timer
> 50) return 2;
1482 if (timer
) timer
= 0;
1488 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1489 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1491 // receive and test the miller decoding
1492 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1493 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1494 if(MillerDecoding((b
& 0xf0) >> 4)) {
1495 *len
= Uart
.byteCnt
;
1496 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1499 if(MillerDecoding(b
& 0x0f)) {
1500 *len
= Uart
.byteCnt
;
1501 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1508 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1513 // Modulate Manchester
1514 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1515 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1518 // include correction bit
1520 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1521 // 1236, so correction bit needed
1527 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1528 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1531 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1533 b
= 0xff; // was 0x00
1539 AT91C_BASE_SSC
->SSC_THR
= b
;
1543 if(BUTTON_PRESS()) {
1551 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1552 Code4bitAnswerAsTag(resp
);
1553 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1554 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1558 int EmSend4bit(uint8_t resp
){
1559 return EmSend4bitEx(resp
, 0);
1562 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1563 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1564 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1565 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1569 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1570 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1573 int EmSendCmd(uint8_t *resp
, int respLen
){
1574 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1577 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1578 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1581 //-----------------------------------------------------------------------------
1582 // Wait a certain time for tag response
1583 // If a response is captured return TRUE
1584 // If it takes to long return FALSE
1585 //-----------------------------------------------------------------------------
1586 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1588 // buffer needs to be 512 bytes
1591 // Set FPGA mode to "reader listen mode", no modulation (listen
1592 // only, since we are receiving, not transmitting).
1593 // Signal field is on with the appropriate LED
1595 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1597 // Now get the answer from the card
1598 Demod
.output
= receivedResponse
;
1600 Demod
.state
= DEMOD_UNSYNCD
;
1603 if (elapsed
) *elapsed
= 0;
1609 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1610 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1611 if (elapsed
) (*elapsed
)++;
1613 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1614 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1615 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1616 if(ManchesterDecoding((b
>>4) & 0xf)) {
1617 *samples
= ((c
- 1) << 3) + 4;
1620 if(ManchesterDecoding(b
& 0x0f)) {
1628 void ReaderTransmitShort(const uint8_t* bt
)
1633 ShortFrameFromReader(*bt
);
1636 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1638 // Store reader command in buffer
1639 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1642 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1647 // This is tied to other size changes
1648 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1649 CodeIso14443aAsReaderPar(frame
,len
,par
);
1652 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1656 // Store reader command in buffer
1657 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1661 void ReaderTransmit(uint8_t* frame
, int len
)
1663 // Generate parity and redirect
1664 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1667 int ReaderReceive(uint8_t* receivedAnswer
)
1670 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1671 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1672 if(samples
== 0) return FALSE
;
1676 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1679 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1680 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1681 *parptr
= Demod
.parityBits
;
1682 if(samples
== 0) return FALSE
;
1686 /* performs iso14443a anticolision procedure
1687 * fills the uid pointer unless NULL
1688 * fills resp_data unless NULL */
1689 int iso14443a_select_card(uint8_t * uid_ptr
, iso14a_card_select_t
* resp_data
, uint32_t * cuid_ptr
) {
1690 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1691 uint8_t sel_all
[] = { 0x93,0x20 };
1692 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1693 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1695 uint8_t* resp
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1697 uint8_t sak
= 0x04; // cascade uid
1698 int cascade_level
= 0;
1703 memset(uid_ptr
, 0, 8);
1705 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1706 ReaderTransmitShort(wupa
);
1708 if(!ReaderReceive(resp
)) return 0;
1711 memcpy(resp_data
->atqa
, resp
, 2);
1713 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1714 // which case we need to make a cascade 2 request and select - this is a long UID
1715 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1716 for(; sak
& 0x04; cascade_level
++)
1718 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1719 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1722 ReaderTransmit(sel_all
,sizeof(sel_all
));
1723 if (!ReaderReceive(resp
)) return 0;
1724 if(uid_ptr
) memcpy(uid_ptr
+ cascade_level
*4, resp
, 4);
1726 // calculate crypto UID
1727 if(cuid_ptr
) *cuid_ptr
= bytes_to_num(resp
, 4);
1729 // Construct SELECT UID command
1730 memcpy(sel_uid
+2,resp
,5);
1731 AppendCrc14443a(sel_uid
,7);
1732 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1735 if (!ReaderReceive(resp
)) return 0;
1739 resp_data
->sak
= sak
;
1740 resp_data
->ats_len
= 0;
1742 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1743 if (uid_ptr
[0] == 0x88) {
1744 memcpy(uid_ptr
, uid_ptr
+ 1, 7);
1748 if( (sak
& 0x20) == 0)
1749 return 2; // non iso14443a compliant tag
1751 // Request for answer to select
1752 if(resp_data
) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1753 AppendCrc14443a(rats
, 2);
1754 ReaderTransmit(rats
, sizeof(rats
));
1756 if (!(len
= ReaderReceive(resp
))) return 0;
1758 memcpy(resp_data
->ats
, resp
, sizeof(resp_data
->ats
));
1759 resp_data
->ats_len
= len
;
1765 void iso14443a_setup() {
1768 // Start from off (no field generated)
1769 // Signal field is off with the appropriate LED
1771 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1774 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1776 // Now give it time to spin up.
1777 // Signal field is on with the appropriate LED
1779 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1782 iso14a_timeout
= 2048; //default
1785 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1786 uint8_t real_cmd
[cmd_len
+4];
1787 real_cmd
[0] = 0x0a; //I-Block
1788 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1789 memcpy(real_cmd
+2, cmd
, cmd_len
);
1790 AppendCrc14443a(real_cmd
,cmd_len
+2);
1792 ReaderTransmit(real_cmd
, cmd_len
+4);
1793 size_t len
= ReaderReceive(data
);
1795 return -1; //DATA LINK ERROR
1801 //-----------------------------------------------------------------------------
1802 // Read an ISO 14443a tag. Send out commands and store answers.
1804 //-----------------------------------------------------------------------------
1805 void ReaderIso14443a(UsbCommand
* c
, UsbCommand
* ack
)
1807 iso14a_command_t param
= c
->arg
[0];
1808 uint8_t * cmd
= c
->d
.asBytes
;
1809 size_t len
= c
->arg
[1];
1811 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(1);
1813 if(param
& ISO14A_CONNECT
) {
1815 ack
->arg
[0] = iso14443a_select_card(ack
->d
.asBytes
, (iso14a_card_select_t
*) (ack
->d
.asBytes
+12), NULL
);
1816 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1819 if(param
& ISO14A_SET_TIMEOUT
) {
1820 iso14a_timeout
= c
->arg
[2];
1823 if(param
& ISO14A_SET_TIMEOUT
) {
1824 iso14a_timeout
= c
->arg
[2];
1827 if(param
& ISO14A_APDU
) {
1828 ack
->arg
[0] = iso14_apdu(cmd
, len
, ack
->d
.asBytes
);
1829 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1832 if(param
& ISO14A_RAW
) {
1833 if(param
& ISO14A_APPEND_CRC
) {
1834 AppendCrc14443a(cmd
,len
);
1837 ReaderTransmit(cmd
,len
);
1838 ack
->arg
[0] = ReaderReceive(ack
->d
.asBytes
);
1839 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1842 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(0);
1844 if(param
& ISO14A_NO_DISCONNECT
)
1847 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1850 //-----------------------------------------------------------------------------
1851 // Read an ISO 14443a tag. Send out commands and store answers.
1853 //-----------------------------------------------------------------------------
1854 void ReaderMifare(uint32_t parameter
)
1857 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1858 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1860 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1873 //byte_t par_mask = 0xff;
1880 byte_t nt
[4] = {0,0,0,0};
1881 byte_t nt_attacked
[4], nt_noattack
[4];
1882 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1883 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1884 num_to_bytes(parameter
, 4, nt_noattack
);
1885 int isOK
= 0, isNULL
= 0;
1890 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1892 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1895 // Test if the action was cancelled
1896 if(BUTTON_PRESS()) {
1900 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1902 // Transmit MIFARE_CLASSIC_AUTH
1903 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1905 // Receive the (16 bit) "random" nonce
1906 if (!ReaderReceive(receivedAnswer
)) continue;
1907 memcpy(nt
, receivedAnswer
, 4);
1909 // Transmit reader nonce and reader answer
1910 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1912 // Receive 4 bit answer
1913 if (ReaderReceive(receivedAnswer
))
1915 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1917 isNULL
= (nt_attacked
[0] == 0) && (nt_attacked
[1] == 0) && (nt_attacked
[2] == 0) && (nt_attacked
[3] == 0);
1918 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1923 memcpy(nt_attacked
, nt
, 4);
1925 par_low
= par
& 0x07;
1929 if(led_on
) LED_B_ON(); else LED_B_OFF();
1930 par_list
[nt_diff
] = par
;
1931 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1933 // Test if the information is complete
1934 if (nt_diff
== 0x07) {
1939 nt_diff
= (nt_diff
+ 1) & 0x07;
1940 mf_nr_ar
[3] = nt_diff
<< 5;
1947 par
= (((par
>> 3) + 1) << 3) | par_low
;
1952 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1953 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1954 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1956 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
1957 memcpy(ack
.d
.asBytes
+ 0, uid
, 4);
1958 memcpy(ack
.d
.asBytes
+ 4, nt
, 4);
1959 memcpy(ack
.d
.asBytes
+ 8, par_list
, 8);
1960 memcpy(ack
.d
.asBytes
+ 16, ks_list
, 8);
1963 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
1967 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1971 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1975 //-----------------------------------------------------------------------------
1976 // MIFARE 1K simulate.
1978 //-----------------------------------------------------------------------------
1979 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
1981 int cardSTATE
= MFEMUL_NOFIELD
;
1983 int vHf
= 0; // in mV
1984 //int nextCycleTimeout = 0;
1986 // uint32_t timer = 0;
1987 uint32_t selTimer
= 0;
1988 uint32_t authTimer
= 0;
1991 uint8_t cardWRBL
= 0;
1992 uint8_t cardAUTHSC
= 0;
1993 uint8_t cardAUTHKEY
= 0xff; // no authentication
1994 //uint32_t cardRn = 0;
1995 uint32_t cardRr
= 0;
1997 //uint32_t rn_enc = 0;
1999 uint32_t cardINTREG
= 0;
2000 uint8_t cardINTBLOCK
= 0;
2001 struct Crypto1State mpcs
= {0, 0};
2002 struct Crypto1State
*pcs
;
2005 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
2006 uint8_t *response
= eml_get_bigbufptr_sendbuf();
2008 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2010 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2011 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2013 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2014 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
2016 static uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
2017 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
2018 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2024 // Authenticate response - nonce
2025 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2027 // get UID from emul memory
2028 emlGetMemBt(receivedCmd
, 7, 1);
2029 _7BUID
= !(receivedCmd
[0] == 0x00);
2030 if (!_7BUID
) { // ---------- 4BUID
2033 emlGetMemBt(rUIDBCC1
, 0, 4);
2034 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2035 } else { // ---------- 7BUID
2039 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2040 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2041 emlGetMemBt(rUIDBCC2
, 3, 4);
2042 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2045 // -------------------------------------- test area
2047 // -------------------------------------- END test area
2048 // start mkseconds counter
2051 // We need to listen to the high-frequency, peak-detected path.
2052 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2055 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2058 if (MF_DBGLEVEL
>= 1) Dbprintf("Started. 7buid=%d", _7BUID
);
2059 // calibrate mkseconds counter
2064 if(BUTTON_PRESS()) {
2068 // find reader field
2069 // Vref = 3300mV, and an 10:1 voltage divider on the input
2070 // can measure voltages up to 33000 mV
2071 if (cardSTATE
== MFEMUL_NOFIELD
) {
2072 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2073 if (vHf
> MF_MINFIELDV
) {
2074 cardSTATE_TO_IDLE();
2079 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2080 res
= EmGetCmd(receivedCmd
, &len
, 100); // (+ nextCycleTimeout)
2082 cardSTATE
= MFEMUL_NOFIELD
;
2089 //nextCycleTimeout = 0;
2091 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2093 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2094 // REQ or WUP request in ANY state and WUP in HALTED state
2095 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2096 selTimer
= GetTickCount();
2097 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2098 cardSTATE
= MFEMUL_SELECT1
;
2100 // init crypto block
2103 crypto1_destroy(pcs
);
2108 switch (cardSTATE
) {
2109 case MFEMUL_NOFIELD
:{
2112 case MFEMUL_HALTED
:{
2118 case MFEMUL_SELECT1
:{
2120 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2121 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2127 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2129 EmSendCmd(rSAK
, sizeof(rSAK
));
2131 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2133 cuid
= bytes_to_num(rUIDBCC1
, 4);
2135 cardSTATE
= MFEMUL_WORK
;
2137 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2140 cardSTATE
= MFEMUL_SELECT2
;
2147 case MFEMUL_SELECT2
:{
2150 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2151 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2157 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2158 EmSendCmd(rSAK
, sizeof(rSAK
));
2160 cuid
= bytes_to_num(rUIDBCC2
, 4);
2161 cardSTATE
= MFEMUL_WORK
;
2163 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2167 // i guess there is a command). go into the work state.
2168 if (len
!= 4) break;
2169 cardSTATE
= MFEMUL_WORK
;
2175 //rn_enc = bytes_to_num(receivedCmd, 4);
2176 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2177 cardRr
= bytes_to_num(&receivedCmd
[4], 4) ^ crypto1_word(pcs
, 0, 0);
2179 if (cardRr
!= prng_successor(nonce
, 64)){
2180 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr
, prng_successor(nonce
, 64));
2181 cardSTATE_TO_IDLE();
2184 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2185 num_to_bytes(ans
, 4, rAUTH_AT
);
2187 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2188 cardSTATE
= MFEMUL_AUTH2
;
2190 cardSTATE_TO_IDLE();
2192 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2196 cardSTATE
= MFEMUL_WORK
;
2197 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2201 lbWORK
: if (len
== 0) break;
2203 if (cardAUTHKEY
== 0xff) {
2204 // first authentication
2205 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2206 authTimer
= GetTickCount();
2208 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2209 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2212 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2213 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2214 num_to_bytes(nonce
, 4, rAUTH_AT
);
2215 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2218 // last working revision
2219 // EmSendCmd14443aRaw(resp1, resp1Len, 0);
2220 // LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2222 cardSTATE
= MFEMUL_AUTH1
;
2223 //nextCycleTimeout = 10;
2228 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2230 // nested authentication
2231 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2232 authTimer
= GetTickCount();
2234 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2235 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2238 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2239 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2240 num_to_bytes(ans
, 4, rAUTH_AT
);
2241 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2244 cardSTATE
= MFEMUL_AUTH1
;
2245 //nextCycleTimeout = 10;
2250 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2251 // BUT... ACK --> NACK
2252 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2253 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2257 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2258 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2259 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2264 if (len
== 4 && receivedCmd
[0] == 0x30) {
2265 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2266 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2269 emlGetMem(response
, receivedCmd
[1], 1);
2270 AppendCrc14443a(response
, 16);
2271 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2272 EmSendCmdPar(response
, 18, par
);
2277 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2278 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2279 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2282 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2283 //nextCycleTimeout = 50;
2284 cardSTATE
= MFEMUL_WRITEBL2
;
2285 cardWRBL
= receivedCmd
[1];
2289 // works with cardINTREG
2291 // increment, decrement, restore
2292 if (len
== 4 && (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2)) {
2293 if (receivedCmd
[1] >= 16 * 4 ||
2294 receivedCmd
[1] / 4 != cardAUTHSC
||
2295 emlCheckValBl(receivedCmd
[1])) {
2296 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2299 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2300 if (receivedCmd
[0] == 0xC1)
2301 cardSTATE
= MFEMUL_INTREG_INC
;
2302 if (receivedCmd
[0] == 0xC0)
2303 cardSTATE
= MFEMUL_INTREG_DEC
;
2304 if (receivedCmd
[0] == 0xC2)
2305 cardSTATE
= MFEMUL_INTREG_REST
;
2306 cardWRBL
= receivedCmd
[1];
2313 if (len
== 4 && receivedCmd
[0] == 0xB0) {
2314 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2315 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2319 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2320 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2322 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2328 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2331 cardSTATE
= MFEMUL_HALTED
;
2332 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2336 // command not allowed
2338 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2345 case MFEMUL_WRITEBL2
:{
2347 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2348 emlSetMem(receivedCmd
, cardWRBL
, 1);
2349 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2350 cardSTATE
= MFEMUL_WORK
;
2353 cardSTATE_TO_IDLE();
2359 case MFEMUL_INTREG_INC
:{
2360 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2361 memcpy(&ans
, receivedCmd
, 4);
2362 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2363 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2364 cardSTATE_TO_IDLE();
2367 cardINTREG
= cardINTREG
+ ans
;
2368 cardSTATE
= MFEMUL_WORK
;
2371 case MFEMUL_INTREG_DEC
:{
2372 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2373 memcpy(&ans
, receivedCmd
, 4);
2374 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2375 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2376 cardSTATE_TO_IDLE();
2379 cardINTREG
= cardINTREG
- ans
;
2380 cardSTATE
= MFEMUL_WORK
;
2383 case MFEMUL_INTREG_REST
:{
2384 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2385 memcpy(&ans
, receivedCmd
, 4);
2386 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2387 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2388 cardSTATE_TO_IDLE();
2391 cardSTATE
= MFEMUL_WORK
;
2399 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2402 // add trace trailer
2403 memset(rAUTH_NT
, 0x44, 4);
2404 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2406 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);