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 uint32_t iso14a_timeout
;
24 uint8_t *trace
= (uint8_t *) BigBuf
;
30 // CARD TO READER - manchester
31 // Sequence D: 11110000 modulation with subcarrier during first half
32 // Sequence E: 00001111 modulation with subcarrier during second half
33 // Sequence F: 00000000 no modulation with subcarrier
34 // READER TO CARD - miller
35 // Sequence X: 00001100 drop after half a period
36 // Sequence Y: 00000000 no drop
37 // Sequence Z: 11000000 drop at start
45 const uint8_t OddByteParity
[256] = {
46 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
47 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
48 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
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 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
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 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
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 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
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
65 void iso14a_set_trigger(int enable
) {
69 void iso14a_clear_tracelen(void) {
72 void iso14a_set_tracing(int enable
) {
76 //-----------------------------------------------------------------------------
77 // Generate the parity value for a byte sequence
79 //-----------------------------------------------------------------------------
80 byte_t
oddparity (const byte_t bt
)
82 return OddByteParity
[bt
];
85 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
90 // Generate the encrypted data
91 for (i
= 0; i
< iLen
; i
++) {
92 // Save the encrypted parity bit
93 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
98 void AppendCrc14443a(uint8_t* data
, int len
)
100 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
103 // The function LogTrace() is also used by the iClass implementation in iClass.c
104 int LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
106 // Return when trace is full
107 if (traceLen
>= TRACE_SIZE
) return FALSE
;
109 // Trace the random, i'm curious
110 rsamples
+= iSamples
;
111 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
112 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
113 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
114 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
116 trace
[traceLen
- 1] |= 0x80;
118 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
119 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
120 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
121 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
122 trace
[traceLen
++] = iLen
;
123 memcpy(trace
+ traceLen
, btBytes
, iLen
);
128 //-----------------------------------------------------------------------------
129 // The software UART that receives commands from the reader, and its state
131 //-----------------------------------------------------------------------------
135 STATE_START_OF_COMMUNICATION
,
159 static RAMFUNC
int MillerDecoding(int bit
)
164 if(!Uart
.bitBuffer
) {
165 Uart
.bitBuffer
= bit
^ 0xFF0;
169 Uart
.bitBuffer
<<= 4;
170 Uart
.bitBuffer
^= bit
;
175 if(Uart
.state
!= STATE_UNSYNCD
) {
178 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
184 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
190 if(bit
!= bitright
) { bit
= bitright
; }
192 if(Uart
.posCnt
== 1) {
193 // measurement first half bitperiod
195 Uart
.drop
= DROP_FIRST_HALF
;
199 // measurement second half bitperiod
200 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
201 Uart
.drop
= DROP_SECOND_HALF
;
204 // measured a drop in first and second half
205 // which should not be possible
206 Uart
.state
= STATE_ERROR_WAIT
;
213 case STATE_START_OF_COMMUNICATION
:
215 if(Uart
.drop
== DROP_SECOND_HALF
) {
216 // error, should not happen in SOC
217 Uart
.state
= STATE_ERROR_WAIT
;
222 Uart
.state
= STATE_MILLER_Z
;
229 if(Uart
.drop
== DROP_NONE
) {
230 // logic '0' followed by sequence Y
231 // end of communication
232 Uart
.state
= STATE_UNSYNCD
;
235 // if(Uart.drop == DROP_FIRST_HALF) {
236 // Uart.state = STATE_MILLER_Z; stay the same
237 // we see a logic '0' }
238 if(Uart
.drop
== DROP_SECOND_HALF
) {
239 // we see a logic '1'
240 Uart
.shiftReg
|= 0x100;
241 Uart
.state
= STATE_MILLER_X
;
247 if(Uart
.drop
== DROP_NONE
) {
248 // sequence Y, we see a '0'
249 Uart
.state
= STATE_MILLER_Y
;
252 if(Uart
.drop
== DROP_FIRST_HALF
) {
253 // Would be STATE_MILLER_Z
254 // but Z does not follow X, so error
255 Uart
.state
= STATE_ERROR_WAIT
;
258 if(Uart
.drop
== DROP_SECOND_HALF
) {
259 // We see a '1' and stay in state X
260 Uart
.shiftReg
|= 0x100;
268 if(Uart
.drop
== DROP_NONE
) {
269 // logic '0' followed by sequence Y
270 // end of communication
271 Uart
.state
= STATE_UNSYNCD
;
274 if(Uart
.drop
== DROP_FIRST_HALF
) {
276 Uart
.state
= STATE_MILLER_Z
;
278 if(Uart
.drop
== DROP_SECOND_HALF
) {
279 // We see a '1' and go to state X
280 Uart
.shiftReg
|= 0x100;
281 Uart
.state
= STATE_MILLER_X
;
285 case STATE_ERROR_WAIT
:
286 // That went wrong. Now wait for at least two bit periods
287 // and try to sync again
288 if(Uart
.drop
== DROP_NONE
) {
290 Uart
.state
= STATE_UNSYNCD
;
295 Uart
.state
= STATE_UNSYNCD
;
300 Uart
.drop
= DROP_NONE
;
302 // should have received at least one whole byte...
303 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
307 if(Uart
.bitCnt
== 9) {
308 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
311 Uart
.parityBits
<<= 1;
312 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
315 // when End of Communication received and
316 // all data bits processed..
323 Uart.output[Uart.byteCnt] = 0xAA;
325 Uart.output[Uart.byteCnt] = error & 0xFF;
327 Uart.output[Uart.byteCnt] = 0xAA;
329 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
331 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
333 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
335 Uart.output[Uart.byteCnt] = 0xAA;
343 bit
= Uart
.bitBuffer
& 0xf0;
347 // should have been high or at least (4 * 128) / fc
348 // according to ISO this should be at least (9 * 128 + 20) / fc
349 if(Uart
.highCnt
== 8) {
350 // we went low, so this could be start of communication
351 // it turns out to be safer to choose a less significant
352 // syncbit... so we check whether the neighbour also represents the drop
353 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
354 Uart
.syncBit
= bit
& 8;
356 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
357 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
358 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
359 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
360 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
361 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
364 // the first half bit period is expected in next sample
369 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
372 Uart
.state
= STATE_START_OF_COMMUNICATION
;
373 Uart
.drop
= DROP_FIRST_HALF
;
384 if(Uart
.highCnt
< 8) {
393 //=============================================================================
394 // ISO 14443 Type A - Manchester
395 //=============================================================================
400 DEMOD_START_OF_COMMUNICATION
,
423 static RAMFUNC
int ManchesterDecoding(int v
)
439 if(Demod
.state
==DEMOD_UNSYNCD
) {
440 Demod
.output
[Demod
.len
] = 0xfa;
443 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
446 Demod
.syncBit
= 0x08;
453 Demod
.syncBit
= 0x04;
460 Demod
.syncBit
= 0x02;
463 if(bit
& 0x01 && Demod
.syncBit
) {
464 Demod
.syncBit
= 0x01;
469 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
470 Demod
.sub
= SUB_FIRST_HALF
;
473 Demod
.parityBits
= 0;
476 if(trigger
) LED_A_OFF();
477 switch(Demod
.syncBit
) {
478 case 0x08: Demod
.samples
= 3; break;
479 case 0x04: Demod
.samples
= 2; break;
480 case 0x02: Demod
.samples
= 1; break;
481 case 0x01: Demod
.samples
= 0; break;
488 //modulation = bit & Demod.syncBit;
489 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
493 if(Demod
.posCount
==0) {
496 Demod
.sub
= SUB_FIRST_HALF
;
499 Demod
.sub
= SUB_NONE
;
504 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
505 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
506 Demod
.state
= DEMOD_ERROR_WAIT
;
507 Demod
.output
[Demod
.len
] = 0xaa;
511 else if(modulation
) {
512 Demod
.sub
= SUB_SECOND_HALF
;
515 switch(Demod
.state
) {
516 case DEMOD_START_OF_COMMUNICATION
:
517 if(Demod
.sub
== SUB_FIRST_HALF
) {
518 Demod
.state
= DEMOD_MANCHESTER_D
;
521 Demod
.output
[Demod
.len
] = 0xab;
522 Demod
.state
= DEMOD_ERROR_WAIT
;
527 case DEMOD_MANCHESTER_D
:
528 case DEMOD_MANCHESTER_E
:
529 if(Demod
.sub
== SUB_FIRST_HALF
) {
531 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
532 Demod
.state
= DEMOD_MANCHESTER_D
;
534 else if(Demod
.sub
== SUB_SECOND_HALF
) {
536 Demod
.shiftReg
>>= 1;
537 Demod
.state
= DEMOD_MANCHESTER_E
;
540 Demod
.state
= DEMOD_MANCHESTER_F
;
544 case DEMOD_MANCHESTER_F
:
545 // Tag response does not need to be a complete byte!
546 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
547 if(Demod
.bitCount
> 0) {
548 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
549 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
551 // No parity bit, so just shift a 0
552 Demod
.parityBits
<<= 1;
555 Demod
.state
= DEMOD_UNSYNCD
;
559 Demod
.output
[Demod
.len
] = 0xad;
560 Demod
.state
= DEMOD_ERROR_WAIT
;
565 case DEMOD_ERROR_WAIT
:
566 Demod
.state
= DEMOD_UNSYNCD
;
570 Demod
.output
[Demod
.len
] = 0xdd;
571 Demod
.state
= DEMOD_UNSYNCD
;
575 if(Demod
.bitCount
>=9) {
576 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
579 Demod
.parityBits
<<= 1;
580 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
587 Demod.output[Demod.len] = 0xBB;
589 Demod.output[Demod.len] = error & 0xFF;
591 Demod.output[Demod.len] = 0xBB;
593 Demod.output[Demod.len] = bit & 0xFF;
595 Demod.output[Demod.len] = Demod.buffer & 0xFF;
597 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
599 Demod.output[Demod.len] = 0xBB;
606 } // end (state != UNSYNCED)
611 //=============================================================================
612 // Finally, a `sniffer' for ISO 14443 Type A
613 // Both sides of communication!
614 //=============================================================================
616 //-----------------------------------------------------------------------------
617 // Record the sequence of commands sent by the reader to the tag, with
618 // triggering so that we start recording at the point that the tag is moved
620 //-----------------------------------------------------------------------------
621 void RAMFUNC
SnoopIso14443a(void)
623 // #define RECV_CMD_OFFSET 2032 // original (working as of 21/2/09) values
624 // #define RECV_RES_OFFSET 2096 // original (working as of 21/2/09) values
625 // #define DMA_BUFFER_OFFSET 2160 // original (working as of 21/2/09) values
626 // #define DMA_BUFFER_SIZE 4096 // original (working as of 21/2/09) values
627 // #define TRACE_SIZE 2000 // original (working as of 21/2/09) values
629 // We won't start recording the frames that we acquire until we trigger;
630 // a good trigger condition to get started is probably when we see a
631 // response from the tag.
632 int triggered
= FALSE
; // FALSE to wait first for card
634 // The command (reader -> tag) that we're receiving.
635 // The length of a received command will in most cases be no more than 18 bytes.
636 // So 32 should be enough!
637 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
638 // The response (tag -> reader) that we're receiving.
639 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
641 // As we receive stuff, we copy it from receivedCmd or receivedResponse
642 // into trace, along with its length and other annotations.
643 //uint8_t *trace = (uint8_t *)BigBuf;
645 traceLen
= 0; // uncommented to fix ISSUE 15 - gerhard - jan2011
647 // The DMA buffer, used to stream samples from the FPGA
648 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
654 // Count of samples received so far, so that we can include timing
655 // information in the trace buffer.
659 memset(trace
, 0x44, TRACE_SIZE
);
661 // Set up the demodulator for tag -> reader responses.
662 Demod
.output
= receivedResponse
;
664 Demod
.state
= DEMOD_UNSYNCD
;
666 // Setup for the DMA.
669 lastRxCounter
= DMA_BUFFER_SIZE
;
670 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
672 // And the reader -> tag commands
673 memset(&Uart
, 0, sizeof(Uart
));
674 Uart
.output
= receivedCmd
;
675 Uart
.byteCntMax
= 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
676 Uart
.state
= STATE_UNSYNCD
;
678 // And put the FPGA in the appropriate mode
679 // Signal field is off with the appropriate LED
681 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
682 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
685 // And now we loop, receiving samples.
689 int behindBy
= (lastRxCounter
- AT91C_BASE_PDC_SSC
->PDC_RCR
) &
691 if(behindBy
> maxBehindBy
) {
692 maxBehindBy
= behindBy
;
694 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy
);
698 if(behindBy
< 1) continue;
704 if(upTo
- dmaBuf
> DMA_BUFFER_SIZE
) {
705 upTo
-= DMA_BUFFER_SIZE
;
706 lastRxCounter
+= DMA_BUFFER_SIZE
;
707 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) upTo
;
708 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
712 if(MillerDecoding((smpl
& 0xF0) >> 4)) {
713 rsamples
= samples
- Uart
.samples
;
716 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
717 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
718 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
719 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
720 trace
[traceLen
++] = ((Uart
.parityBits
>> 0) & 0xff);
721 trace
[traceLen
++] = ((Uart
.parityBits
>> 8) & 0xff);
722 trace
[traceLen
++] = ((Uart
.parityBits
>> 16) & 0xff);
723 trace
[traceLen
++] = ((Uart
.parityBits
>> 24) & 0xff);
724 trace
[traceLen
++] = Uart
.byteCnt
;
725 memcpy(trace
+traceLen
, receivedCmd
, Uart
.byteCnt
);
726 traceLen
+= Uart
.byteCnt
;
727 if(traceLen
> TRACE_SIZE
) break;
729 /* And ready to receive another command. */
730 Uart
.state
= STATE_UNSYNCD
;
731 /* And also reset the demod code, which might have been */
732 /* false-triggered by the commands from the reader. */
733 Demod
.state
= DEMOD_UNSYNCD
;
737 if(ManchesterDecoding(smpl
& 0x0F)) {
738 rsamples
= samples
- Demod
.samples
;
741 // timestamp, as a count of samples
742 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
743 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
744 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
745 trace
[traceLen
++] = 0x80 | ((rsamples
>> 24) & 0xff);
746 trace
[traceLen
++] = ((Demod
.parityBits
>> 0) & 0xff);
747 trace
[traceLen
++] = ((Demod
.parityBits
>> 8) & 0xff);
748 trace
[traceLen
++] = ((Demod
.parityBits
>> 16) & 0xff);
749 trace
[traceLen
++] = ((Demod
.parityBits
>> 24) & 0xff);
751 trace
[traceLen
++] = Demod
.len
;
752 memcpy(trace
+traceLen
, receivedResponse
, Demod
.len
);
753 traceLen
+= Demod
.len
;
754 if(traceLen
> TRACE_SIZE
) break;
758 // And ready to receive another response.
759 memset(&Demod
, 0, sizeof(Demod
));
760 Demod
.output
= receivedResponse
;
761 Demod
.state
= DEMOD_UNSYNCD
;
766 DbpString("cancelled_a");
771 DbpString("COMMAND FINISHED");
774 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
775 Dbprintf("maxBehindBy=%x, Uart.state=%x, Uart.byteCnt=%x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
776 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
783 //-----------------------------------------------------------------------------
784 // Prepare tag messages
785 //-----------------------------------------------------------------------------
786 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
792 // Correction bit, might be removed when not needed
797 ToSendStuffBit(1); // 1
803 ToSend
[++ToSendMax
] = SEC_D
;
805 for(i
= 0; i
< len
; i
++) {
810 for(j
= 0; j
< 8; j
++) {
812 ToSend
[++ToSendMax
] = SEC_D
;
814 ToSend
[++ToSendMax
] = SEC_E
;
819 // Get the parity bit
820 if ((dwParity
>> i
) & 0x01) {
821 ToSend
[++ToSendMax
] = SEC_D
;
823 ToSend
[++ToSendMax
] = SEC_E
;
828 ToSend
[++ToSendMax
] = SEC_F
;
830 // Convert from last byte pos to length
834 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
835 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
838 //-----------------------------------------------------------------------------
839 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
840 //-----------------------------------------------------------------------------
841 static void CodeStrangeAnswerAsTag()
847 // Correction bit, might be removed when not needed
852 ToSendStuffBit(1); // 1
858 ToSend
[++ToSendMax
] = SEC_D
;
861 ToSend
[++ToSendMax
] = SEC_E
;
864 ToSend
[++ToSendMax
] = SEC_E
;
867 ToSend
[++ToSendMax
] = SEC_D
;
870 ToSend
[++ToSendMax
] = SEC_F
;
872 // Flush the buffer in FPGA!!
873 for(i
= 0; i
< 5; i
++) {
874 ToSend
[++ToSendMax
] = SEC_F
;
877 // Convert from last byte pos to length
881 static void Code4bitAnswerAsTag(uint8_t cmd
)
887 // Correction bit, might be removed when not needed
892 ToSendStuffBit(1); // 1
898 ToSend
[++ToSendMax
] = SEC_D
;
901 for(i
= 0; i
< 4; i
++) {
903 ToSend
[++ToSendMax
] = SEC_D
;
905 ToSend
[++ToSendMax
] = SEC_E
;
911 ToSend
[++ToSendMax
] = SEC_F
;
913 // Flush the buffer in FPGA!!
914 for(i
= 0; i
< 5; i
++) {
915 ToSend
[++ToSendMax
] = SEC_F
;
918 // Convert from last byte pos to length
922 //-----------------------------------------------------------------------------
923 // Wait for commands from reader
924 // Stop when button is pressed
925 // Or return TRUE when command is captured
926 //-----------------------------------------------------------------------------
927 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
929 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
930 // only, since we are receiving, not transmitting).
931 // Signal field is off with the appropriate LED
933 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
935 // Now run a `software UART' on the stream of incoming samples.
936 Uart
.output
= received
;
937 Uart
.byteCntMax
= maxLen
;
938 Uart
.state
= STATE_UNSYNCD
;
943 if(BUTTON_PRESS()) return FALSE
;
945 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
946 AT91C_BASE_SSC
->SSC_THR
= 0x00;
948 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
949 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
950 if(MillerDecoding((b
& 0xf0) >> 4)) {
954 if(MillerDecoding(b
& 0x0f)) {
961 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
963 //-----------------------------------------------------------------------------
964 // Main loop of simulated tag: receive commands from reader, decide what
965 // response to send, and send it.
966 //-----------------------------------------------------------------------------
967 void SimulateIso14443aTag(int tagType
, int uid_1st
, int uid_2nd
)
969 // Enable and clear the trace
972 memset(trace
, 0x44, TRACE_SIZE
);
974 // This function contains the tag emulation
977 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
978 uint8_t response1
[2];
981 case 1: { // MIFARE Classic
982 // Says: I am Mifare 1k - original line
987 case 2: { // MIFARE Ultralight
988 // Says: I am a stupid memory tag, no crypto
993 case 3: { // MIFARE DESFire
994 // Says: I am a DESFire tag, ph33r me
999 case 4: { // ISO/IEC 14443-4
1000 // Says: I am a javacard (JCOP)
1001 response1
[0] = 0x04;
1002 response1
[1] = 0x00;
1006 Dbprintf("Error: unkown tagtype (%d)",tagType
);
1011 // The second response contains the (mandatory) first 24 bits of the UID
1012 uint8_t response2
[5];
1014 // Check if the uid uses the (optional) part
1015 uint8_t response2a
[5];
1017 response2
[0] = 0x88;
1018 num_to_bytes(uid_1st
,3,response2
+1);
1019 num_to_bytes(uid_2nd
,4,response2a
);
1020 response2a
[4] = response2a
[0] ^ response2a
[1] ^ response2a
[2] ^ response2a
[3];
1022 // Configure the ATQA and SAK accordingly
1023 response1
[0] |= 0x40;
1026 num_to_bytes(uid_1st
,4,response2
);
1027 // Configure the ATQA and SAK accordingly
1028 response1
[0] &= 0xBF;
1032 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
1033 response2
[4] = response2
[0] ^ response2
[1] ^ response2
[2] ^ response2
[3];
1035 // Prepare the mandatory SAK (for 4 and 7 byte UID)
1036 uint8_t response3
[3];
1038 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
1040 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
1041 uint8_t response3a
[3];
1042 response3a
[0] = sak
& 0xFB;
1043 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
1045 uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
1046 uint8_t response6
[] = { 0x03, 0x3B, 0x00, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
1047 ComputeCrc14443(CRC_14443_A
, response6
, 3, &response6
[3], &response6
[4]);
1052 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
1054 // 144 data bits (18 * 8)
1057 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
1058 // 1 just for the case
1062 // 166 bytes, since every bit that needs to be send costs us a byte
1065 // Respond with card type
1066 uint8_t *resp1
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
1069 // Anticollision cascade1 - respond with uid
1070 uint8_t *resp2
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ 166);
1073 // Anticollision cascade2 - respond with 2nd half of uid if asked
1074 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1075 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1078 // Acknowledge select - cascade 1
1079 uint8_t *resp3
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*2));
1082 // Acknowledge select - cascade 2
1083 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*3));
1086 // Response to a read request - not implemented atm
1087 uint8_t *resp4
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*4));
1090 // Authenticate response - nonce
1091 uint8_t *resp5
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*5));
1094 // Authenticate response - nonce
1095 uint8_t *resp6
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*6));
1098 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
1101 // To control where we are in the protocol
1105 // Just to allow some checks
1110 uint8_t* respdata
= NULL
;
1112 uint8_t nack
= 0x04;
1114 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1116 // Prepare the responses of the anticollision phase
1117 // there will be not enough time to do this at the moment the reader sends it REQA
1119 // Answer to request
1120 CodeIso14443aAsTag(response1
, sizeof(response1
));
1121 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1123 // Send our UID (cascade 1)
1124 CodeIso14443aAsTag(response2
, sizeof(response2
));
1125 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1127 // Answer to select (cascade1)
1128 CodeIso14443aAsTag(response3
, sizeof(response3
));
1129 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1131 // Send the cascade 2 2nd part of the uid
1132 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1133 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1135 // Answer to select (cascade 2)
1136 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1137 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1139 // Strange answer is an example of rare message size (3 bits)
1140 CodeStrangeAnswerAsTag();
1141 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1143 // Authentication answer (random nonce)
1144 CodeIso14443aAsTag(response5
, sizeof(response5
));
1145 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1147 // dummy ATS (pseudo-ATR), answer to RATS
1148 CodeIso14443aAsTag(response6
, sizeof(response6
));
1149 memcpy(resp6
, ToSend
, ToSendMax
); resp6Len
= ToSendMax
;
1151 // We need to listen to the high-frequency, peak-detected path.
1152 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1160 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, RECV_CMD_SIZE
)) {
1161 DbpString("button press");
1164 // 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
1165 // Okay, look at the command now.
1167 if(receivedCmd
[0] == 0x26) { // Received a REQUEST
1168 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1169 respdata
= response1
;
1170 respsize
= sizeof(response1
);
1171 } else if(receivedCmd
[0] == 0x52) { // Received a WAKEUP
1172 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1173 respdata
= response1
;
1174 respsize
= sizeof(response1
);
1175 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // Received request for UID (cascade 1)
1176 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1177 respdata
= response2
;
1178 respsize
= sizeof(response2
);
1179 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x95) { // Received request for UID (cascade 2)
1180 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1181 respdata
= response2a
;
1182 respsize
= sizeof(response2a
);
1183 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x93) { // Received a SELECT (cascade 1)
1184 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1185 respdata
= response3
;
1186 respsize
= sizeof(response3
);
1187 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x95) { // Received a SELECT (cascade 2)
1188 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1189 respdata
= response3a
;
1190 respsize
= sizeof(response3a
);
1191 } else if(receivedCmd
[0] == 0x30) { // Received a (plain) READ
1192 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1193 Dbprintf("Read request from reader: %x %x",receivedCmd
[0],receivedCmd
[1]);
1195 respsize
= sizeof(nack
); // 4-bit answer
1196 } else if(receivedCmd
[0] == 0x50) { // Received a HALT
1197 DbpString("Reader requested we HALT!:");
1199 resp
= resp1
; respLen
= 0; order
= 0;
1202 } else if(receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61) { // Received an authentication request
1203 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1204 respdata
= response5
;
1205 respsize
= sizeof(response5
);
1206 } else if(receivedCmd
[0] == 0xE0) { // Received a RATS request
1207 resp
= resp6
; respLen
= resp6Len
; order
= 70;
1208 respdata
= response6
;
1209 respsize
= sizeof(response6
);
1211 // Never seen this command before
1212 Dbprintf("Received (len=%d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1214 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2],
1215 receivedCmd
[3], receivedCmd
[4], receivedCmd
[5],
1216 receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1218 resp
= resp1
; respLen
= 0; order
= 0;
1223 // Count number of wakeups received after a halt
1224 if(order
== 6 && lastorder
== 5) { happened
++; }
1226 // Count number of other messages after a halt
1227 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1229 // Look at last parity bit to determine timing of answer
1230 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1231 // 1236, so correction bit needed
1235 if(cmdsRecvd
> 999) {
1236 DbpString("1000 commands later...");
1243 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1247 LogTrace(receivedCmd
,len
, 0, Uart
.parityBits
, TRUE
);
1248 if (respdata
!= NULL
) {
1249 LogTrace(respdata
,respsize
, 0, SwapBits(GetParity(respdata
,respsize
),respsize
), FALSE
);
1251 if(traceLen
> TRACE_SIZE
) {
1252 DbpString("Trace full");
1257 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1260 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1264 //-----------------------------------------------------------------------------
1265 // Transmit the command (to the tag) that was placed in ToSend[].
1266 //-----------------------------------------------------------------------------
1267 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1271 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1277 for(c
= 0; c
< *wait
;) {
1278 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1279 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1282 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1283 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1291 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1292 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1298 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1299 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1304 if (samples
) *samples
= (c
+ *wait
) << 3;
1307 //-----------------------------------------------------------------------------
1308 // Code a 7-bit command without parity bit
1309 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1310 //-----------------------------------------------------------------------------
1311 void ShortFrameFromReader(const uint8_t bt
)
1319 // Start of Communication (Seq. Z)
1320 ToSend
[++ToSendMax
] = SEC_Z
;
1324 for(j
= 0; j
< 7; j
++) {
1327 ToSend
[++ToSendMax
] = SEC_X
;
1332 ToSend
[++ToSendMax
] = SEC_Z
;
1336 ToSend
[++ToSendMax
] = SEC_Y
;
1343 // End of Communication
1346 ToSend
[++ToSendMax
] = SEC_Z
;
1350 ToSend
[++ToSendMax
] = SEC_Y
;
1354 ToSend
[++ToSendMax
] = SEC_Y
;
1357 ToSend
[++ToSendMax
] = SEC_Y
;
1358 ToSend
[++ToSendMax
] = SEC_Y
;
1359 ToSend
[++ToSendMax
] = SEC_Y
;
1361 // Convert from last character reference to length
1365 //-----------------------------------------------------------------------------
1366 // Prepare reader command to send to FPGA
1368 //-----------------------------------------------------------------------------
1369 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1377 // Start of Communication (Seq. Z)
1378 ToSend
[++ToSendMax
] = SEC_Z
;
1381 // Generate send structure for the data bits
1382 for (i
= 0; i
< len
; i
++) {
1383 // Get the current byte to send
1386 for (j
= 0; j
< 8; j
++) {
1389 ToSend
[++ToSendMax
] = SEC_X
;
1394 ToSend
[++ToSendMax
] = SEC_Z
;
1397 ToSend
[++ToSendMax
] = SEC_Y
;
1404 // Get the parity bit
1405 if ((dwParity
>> i
) & 0x01) {
1407 ToSend
[++ToSendMax
] = SEC_X
;
1412 ToSend
[++ToSendMax
] = SEC_Z
;
1415 ToSend
[++ToSendMax
] = SEC_Y
;
1421 // End of Communication
1424 ToSend
[++ToSendMax
] = SEC_Z
;
1427 ToSend
[++ToSendMax
] = SEC_Y
;
1431 ToSend
[++ToSendMax
] = SEC_Y
;
1434 ToSend
[++ToSendMax
] = SEC_Y
;
1435 ToSend
[++ToSendMax
] = SEC_Y
;
1436 ToSend
[++ToSendMax
] = SEC_Y
;
1438 // Convert from last character reference to length
1442 //-----------------------------------------------------------------------------
1443 // Wait for commands from reader
1444 // Stop when button is pressed (return 1) or field was gone (return 2)
1445 // Or return 0 when command is captured
1446 //-----------------------------------------------------------------------------
1447 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1451 uint32_t timer
= 0, vtime
= 0;
1455 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1456 // only, since we are receiving, not transmitting).
1457 // Signal field is off with the appropriate LED
1459 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1461 // Set ADC to read field strength
1462 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1463 AT91C_BASE_ADC
->ADC_MR
=
1464 ADC_MODE_PRESCALE(32) |
1465 ADC_MODE_STARTUP_TIME(16) |
1466 ADC_MODE_SAMPLE_HOLD_TIME(8);
1467 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1469 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1471 // Now run a 'software UART' on the stream of incoming samples.
1472 Uart
.output
= received
;
1473 Uart
.byteCntMax
= maxLen
;
1474 Uart
.state
= STATE_UNSYNCD
;
1479 if (BUTTON_PRESS()) return 1;
1481 // test if the field exists
1482 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1484 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1485 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1486 if (analogCnt
>= 32) {
1487 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1488 vtime
= GetTickCount();
1489 if (!timer
) timer
= vtime
;
1490 // 50ms no field --> card to idle state
1491 if (vtime
- timer
> 50) return 2;
1493 if (timer
) timer
= 0;
1499 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1500 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1502 // receive and test the miller decoding
1503 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1504 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1505 if(MillerDecoding((b
& 0xf0) >> 4)) {
1506 *len
= Uart
.byteCnt
;
1507 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1510 if(MillerDecoding(b
& 0x0f)) {
1511 *len
= Uart
.byteCnt
;
1512 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1519 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1524 // Modulate Manchester
1525 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1526 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1529 // include correction bit
1531 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1532 // 1236, so correction bit needed
1538 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1539 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1542 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1544 b
= 0xff; // was 0x00
1550 AT91C_BASE_SSC
->SSC_THR
= b
;
1554 if(BUTTON_PRESS()) {
1562 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1563 Code4bitAnswerAsTag(resp
);
1564 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1565 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1569 int EmSend4bit(uint8_t resp
){
1570 return EmSend4bitEx(resp
, 0);
1573 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1574 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1575 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1576 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1580 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1581 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1584 int EmSendCmd(uint8_t *resp
, int respLen
){
1585 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1588 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1589 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1592 //-----------------------------------------------------------------------------
1593 // Wait a certain time for tag response
1594 // If a response is captured return TRUE
1595 // If it takes to long return FALSE
1596 //-----------------------------------------------------------------------------
1597 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1599 // buffer needs to be 512 bytes
1602 // Set FPGA mode to "reader listen mode", no modulation (listen
1603 // only, since we are receiving, not transmitting).
1604 // Signal field is on with the appropriate LED
1606 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1608 // Now get the answer from the card
1609 Demod
.output
= receivedResponse
;
1611 Demod
.state
= DEMOD_UNSYNCD
;
1614 if (elapsed
) *elapsed
= 0;
1620 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1621 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1622 if (elapsed
) (*elapsed
)++;
1624 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1625 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1626 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1627 if(ManchesterDecoding((b
>>4) & 0xf)) {
1628 *samples
= ((c
- 1) << 3) + 4;
1631 if(ManchesterDecoding(b
& 0x0f)) {
1639 void ReaderTransmitShort(const uint8_t* bt
)
1644 ShortFrameFromReader(*bt
);
1647 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1649 // Store reader command in buffer
1650 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1653 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1658 // This is tied to other size changes
1659 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1660 CodeIso14443aAsReaderPar(frame
,len
,par
);
1663 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1667 // Store reader command in buffer
1668 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1672 void ReaderTransmit(uint8_t* frame
, int len
)
1674 // Generate parity and redirect
1675 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1678 int ReaderReceive(uint8_t* receivedAnswer
)
1681 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1682 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1683 if(samples
== 0) return FALSE
;
1687 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1690 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1691 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1692 *parptr
= Demod
.parityBits
;
1693 if(samples
== 0) return FALSE
;
1697 /* performs iso14443a anticolision procedure
1698 * fills the uid pointer unless NULL
1699 * fills resp_data unless NULL */
1700 int iso14443a_select_card(uint8_t * uid_ptr
, iso14a_card_select_t
* resp_data
, uint32_t * cuid_ptr
) {
1701 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1702 uint8_t sel_all
[] = { 0x93,0x20 };
1703 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1704 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1706 uint8_t* resp
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1708 uint8_t sak
= 0x04; // cascade uid
1709 int cascade_level
= 0;
1714 memset(uid_ptr
, 0, 8);
1716 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1717 ReaderTransmitShort(wupa
);
1719 if(!ReaderReceive(resp
)) return 0;
1722 memcpy(resp_data
->atqa
, resp
, 2);
1724 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1725 // which case we need to make a cascade 2 request and select - this is a long UID
1726 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1727 for(; sak
& 0x04; cascade_level
++)
1729 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1730 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1733 ReaderTransmit(sel_all
,sizeof(sel_all
));
1734 if (!ReaderReceive(resp
)) return 0;
1735 if(uid_ptr
) memcpy(uid_ptr
+ cascade_level
*4, resp
, 4);
1737 // calculate crypto UID
1738 if(cuid_ptr
) *cuid_ptr
= bytes_to_num(resp
, 4);
1740 // Construct SELECT UID command
1741 memcpy(sel_uid
+2,resp
,5);
1742 AppendCrc14443a(sel_uid
,7);
1743 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1746 if (!ReaderReceive(resp
)) return 0;
1750 resp_data
->sak
= sak
;
1751 resp_data
->ats_len
= 0;
1753 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1754 if (uid_ptr
[0] == 0x88) {
1755 memcpy(uid_ptr
, uid_ptr
+ 1, 7);
1759 if( (sak
& 0x20) == 0)
1760 return 2; // non iso14443a compliant tag
1762 // Request for answer to select
1763 if(resp_data
) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1764 AppendCrc14443a(rats
, 2);
1765 ReaderTransmit(rats
, sizeof(rats
));
1767 if (!(len
= ReaderReceive(resp
))) return 0;
1769 memcpy(resp_data
->ats
, resp
, sizeof(resp_data
->ats
));
1770 resp_data
->ats_len
= len
;
1776 void iso14443a_setup() {
1779 // Start from off (no field generated)
1780 // Signal field is off with the appropriate LED
1782 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1785 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1787 // Now give it time to spin up.
1788 // Signal field is on with the appropriate LED
1790 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1793 iso14a_timeout
= 2048; //default
1796 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1797 uint8_t real_cmd
[cmd_len
+4];
1798 real_cmd
[0] = 0x0a; //I-Block
1799 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1800 memcpy(real_cmd
+2, cmd
, cmd_len
);
1801 AppendCrc14443a(real_cmd
,cmd_len
+2);
1803 ReaderTransmit(real_cmd
, cmd_len
+4);
1804 size_t len
= ReaderReceive(data
);
1806 return -1; //DATA LINK ERROR
1812 //-----------------------------------------------------------------------------
1813 // Read an ISO 14443a tag. Send out commands and store answers.
1815 //-----------------------------------------------------------------------------
1816 void ReaderIso14443a(UsbCommand
* c
, UsbCommand
* ack
)
1818 iso14a_command_t param
= c
->arg
[0];
1819 uint8_t * cmd
= c
->d
.asBytes
;
1820 size_t len
= c
->arg
[1];
1822 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(1);
1824 if(param
& ISO14A_CONNECT
) {
1826 ack
->arg
[0] = iso14443a_select_card(ack
->d
.asBytes
, (iso14a_card_select_t
*) (ack
->d
.asBytes
+12), NULL
);
1827 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1830 if(param
& ISO14A_SET_TIMEOUT
) {
1831 iso14a_timeout
= c
->arg
[2];
1834 if(param
& ISO14A_SET_TIMEOUT
) {
1835 iso14a_timeout
= c
->arg
[2];
1838 if(param
& ISO14A_APDU
) {
1839 ack
->arg
[0] = iso14_apdu(cmd
, len
, ack
->d
.asBytes
);
1840 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1843 if(param
& ISO14A_RAW
) {
1844 if(param
& ISO14A_APPEND_CRC
) {
1845 AppendCrc14443a(cmd
,len
);
1848 ReaderTransmit(cmd
,len
);
1849 ack
->arg
[0] = ReaderReceive(ack
->d
.asBytes
);
1850 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1853 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(0);
1855 if(param
& ISO14A_NO_DISCONNECT
)
1858 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1861 //-----------------------------------------------------------------------------
1862 // Read an ISO 14443a tag. Send out commands and store answers.
1864 //-----------------------------------------------------------------------------
1865 void ReaderMifare(uint32_t parameter
)
1868 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1869 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1871 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1884 //byte_t par_mask = 0xff;
1891 byte_t nt
[4] = {0,0,0,0};
1892 byte_t nt_attacked
[4], nt_noattack
[4];
1893 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1894 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1895 num_to_bytes(parameter
, 4, nt_noattack
);
1896 int isOK
= 0, isNULL
= 0;
1901 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1903 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1906 // Test if the action was cancelled
1907 if(BUTTON_PRESS()) {
1911 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1913 // Transmit MIFARE_CLASSIC_AUTH
1914 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1916 // Receive the (16 bit) "random" nonce
1917 if (!ReaderReceive(receivedAnswer
)) continue;
1918 memcpy(nt
, receivedAnswer
, 4);
1920 // Transmit reader nonce and reader answer
1921 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1923 // Receive 4 bit answer
1924 if (ReaderReceive(receivedAnswer
))
1926 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1928 isNULL
= !(nt_attacked
[0] == 0) && (nt_attacked
[1] == 0) && (nt_attacked
[2] == 0) && (nt_attacked
[3] == 0);
1929 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1934 memcpy(nt_attacked
, nt
, 4);
1936 par_low
= par
& 0x07;
1940 if(led_on
) LED_B_ON(); else LED_B_OFF();
1941 par_list
[nt_diff
] = par
;
1942 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1944 // Test if the information is complete
1945 if (nt_diff
== 0x07) {
1950 nt_diff
= (nt_diff
+ 1) & 0x07;
1951 mf_nr_ar
[3] = nt_diff
<< 5;
1958 par
= (((par
>> 3) + 1) << 3) | par_low
;
1963 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1964 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1965 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1967 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
1968 memcpy(ack
.d
.asBytes
+ 0, uid
, 4);
1969 memcpy(ack
.d
.asBytes
+ 4, nt
, 4);
1970 memcpy(ack
.d
.asBytes
+ 8, par_list
, 8);
1971 memcpy(ack
.d
.asBytes
+ 16, ks_list
, 8);
1974 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
1978 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1982 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1986 //-----------------------------------------------------------------------------
1987 // MIFARE 1K simulate.
1989 //-----------------------------------------------------------------------------
1990 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
1992 int cardSTATE
= MFEMUL_NOFIELD
;
1994 int vHf
= 0; // in mV
1995 //int nextCycleTimeout = 0;
1997 // uint32_t timer = 0;
1998 uint32_t selTimer
= 0;
1999 uint32_t authTimer
= 0;
2002 uint8_t cardWRBL
= 0;
2003 uint8_t cardAUTHSC
= 0;
2004 uint8_t cardAUTHKEY
= 0xff; // no authentication
2005 //uint32_t cardRn = 0;
2006 uint32_t cardRr
= 0;
2008 //uint32_t rn_enc = 0;
2010 uint32_t cardINTREG
= 0;
2011 uint8_t cardINTBLOCK
= 0;
2012 struct Crypto1State mpcs
= {0, 0};
2013 struct Crypto1State
*pcs
;
2016 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
2017 uint8_t *response
= eml_get_bigbufptr_sendbuf();
2019 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2021 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2022 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2024 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2025 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
2027 static uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
2028 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
2029 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2035 // Authenticate response - nonce
2036 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2038 // get UID from emul memory
2039 emlGetMemBt(receivedCmd
, 7, 1);
2040 _7BUID
= !(receivedCmd
[0] == 0x00);
2041 if (!_7BUID
) { // ---------- 4BUID
2044 emlGetMemBt(rUIDBCC1
, 0, 4);
2045 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2046 } else { // ---------- 7BUID
2050 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2051 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2052 emlGetMemBt(rUIDBCC2
, 3, 4);
2053 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2056 // -------------------------------------- test area
2058 // -------------------------------------- END test area
2059 // start mkseconds counter
2062 // We need to listen to the high-frequency, peak-detected path.
2063 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2066 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2069 if (MF_DBGLEVEL
>= 1) Dbprintf("Started. 7buid=%d", _7BUID
);
2070 // calibrate mkseconds counter
2075 if(BUTTON_PRESS()) {
2079 // find reader field
2080 // Vref = 3300mV, and an 10:1 voltage divider on the input
2081 // can measure voltages up to 33000 mV
2082 if (cardSTATE
== MFEMUL_NOFIELD
) {
2083 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2084 if (vHf
> MF_MINFIELDV
) {
2085 cardSTATE_TO_IDLE();
2090 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2091 res
= EmGetCmd(receivedCmd
, &len
, RECV_CMD_SIZE
); // (+ nextCycleTimeout)
2093 cardSTATE
= MFEMUL_NOFIELD
;
2100 //nextCycleTimeout = 0;
2102 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2104 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2105 // REQ or WUP request in ANY state and WUP in HALTED state
2106 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2107 selTimer
= GetTickCount();
2108 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2109 cardSTATE
= MFEMUL_SELECT1
;
2111 // init crypto block
2114 crypto1_destroy(pcs
);
2119 switch (cardSTATE
) {
2120 case MFEMUL_NOFIELD
:{
2123 case MFEMUL_HALTED
:{
2129 case MFEMUL_SELECT1
:{
2131 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2132 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2138 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2140 EmSendCmd(rSAK
, sizeof(rSAK
));
2142 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2144 cuid
= bytes_to_num(rUIDBCC1
, 4);
2146 cardSTATE
= MFEMUL_WORK
;
2148 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2151 cardSTATE
= MFEMUL_SELECT2
;
2158 case MFEMUL_SELECT2
:{
2161 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2162 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2168 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2169 EmSendCmd(rSAK
, sizeof(rSAK
));
2171 cuid
= bytes_to_num(rUIDBCC2
, 4);
2172 cardSTATE
= MFEMUL_WORK
;
2174 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2178 // i guess there is a command). go into the work state.
2179 if (len
!= 4) break;
2180 cardSTATE
= MFEMUL_WORK
;
2186 //rn_enc = bytes_to_num(receivedCmd, 4);
2187 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2188 cardRr
= bytes_to_num(&receivedCmd
[4], 4) ^ crypto1_word(pcs
, 0, 0);
2190 if (cardRr
!= prng_successor(nonce
, 64)){
2191 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr
, prng_successor(nonce
, 64));
2192 cardSTATE_TO_IDLE();
2195 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2196 num_to_bytes(ans
, 4, rAUTH_AT
);
2198 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2199 cardSTATE
= MFEMUL_AUTH2
;
2201 cardSTATE_TO_IDLE();
2203 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2207 cardSTATE
= MFEMUL_WORK
;
2208 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2212 lbWORK
: if (len
== 0) break;
2214 if (cardAUTHKEY
== 0xff) {
2215 // first authentication
2216 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2217 authTimer
= GetTickCount();
2219 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2220 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2223 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2224 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2225 num_to_bytes(nonce
, 4, rAUTH_AT
);
2226 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2229 // last working revision
2230 // EmSendCmd14443aRaw(resp1, resp1Len, 0);
2231 // LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2233 cardSTATE
= MFEMUL_AUTH1
;
2234 //nextCycleTimeout = 10;
2239 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2241 // nested authentication
2242 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2243 authTimer
= GetTickCount();
2245 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2246 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2249 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2250 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2251 num_to_bytes(ans
, 4, rAUTH_AT
);
2252 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2255 cardSTATE
= MFEMUL_AUTH1
;
2256 //nextCycleTimeout = 10;
2261 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2262 // BUT... ACK --> NACK
2263 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2264 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2268 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2269 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2270 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2275 if (len
== 4 && receivedCmd
[0] == 0x30) {
2276 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2277 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2280 emlGetMem(response
, receivedCmd
[1], 1);
2281 AppendCrc14443a(response
, 16);
2282 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2283 EmSendCmdPar(response
, 18, par
);
2288 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2289 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2290 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2293 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2294 //nextCycleTimeout = 50;
2295 cardSTATE
= MFEMUL_WRITEBL2
;
2296 cardWRBL
= receivedCmd
[1];
2300 // works with cardINTREG
2302 // increment, decrement, restore
2303 if (len
== 4 && (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2)) {
2304 if (receivedCmd
[1] >= 16 * 4 ||
2305 receivedCmd
[1] / 4 != cardAUTHSC
||
2306 emlCheckValBl(receivedCmd
[1])) {
2307 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2310 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2311 if (receivedCmd
[0] == 0xC1)
2312 cardSTATE
= MFEMUL_INTREG_INC
;
2313 if (receivedCmd
[0] == 0xC0)
2314 cardSTATE
= MFEMUL_INTREG_DEC
;
2315 if (receivedCmd
[0] == 0xC2)
2316 cardSTATE
= MFEMUL_INTREG_REST
;
2317 cardWRBL
= receivedCmd
[1];
2324 if (len
== 4 && receivedCmd
[0] == 0xB0) {
2325 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2326 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2330 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2331 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2333 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2339 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2342 cardSTATE
= MFEMUL_HALTED
;
2343 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2347 // command not allowed
2349 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2356 case MFEMUL_WRITEBL2
:{
2358 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2359 emlSetMem(receivedCmd
, cardWRBL
, 1);
2360 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2361 cardSTATE
= MFEMUL_WORK
;
2364 cardSTATE_TO_IDLE();
2370 case MFEMUL_INTREG_INC
:{
2371 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2372 memcpy(&ans
, receivedCmd
, 4);
2373 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2374 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2375 cardSTATE_TO_IDLE();
2378 cardINTREG
= cardINTREG
+ ans
;
2379 cardSTATE
= MFEMUL_WORK
;
2382 case MFEMUL_INTREG_DEC
:{
2383 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2384 memcpy(&ans
, receivedCmd
, 4);
2385 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2386 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2387 cardSTATE_TO_IDLE();
2390 cardINTREG
= cardINTREG
- ans
;
2391 cardSTATE
= MFEMUL_WORK
;
2394 case MFEMUL_INTREG_REST
:{
2395 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2396 memcpy(&ans
, receivedCmd
, 4);
2397 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2398 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2399 cardSTATE_TO_IDLE();
2402 cardSTATE
= MFEMUL_WORK
;
2410 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2413 // add trace trailer
2414 memset(rAUTH_NT
, 0x44, 4);
2415 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2417 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);