1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
9 //-----------------------------------------------------------------------------
10 // Routines to support ISO 14443 type A.
11 //-----------------------------------------------------------------------------
13 #include "proxmark3.h"
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
+TRACE_OFFSET
;
29 // the block number for the ISO14443-4 PCB
30 static uint8_t iso14_pcb_blocknum
= 0;
32 // CARD TO READER - manchester
33 // Sequence D: 11110000 modulation with subcarrier during first half
34 // Sequence E: 00001111 modulation with subcarrier during second half
35 // Sequence F: 00000000 no modulation with subcarrier
36 // READER TO CARD - miller
37 // Sequence X: 00001100 drop after half a period
38 // Sequence Y: 00000000 no drop
39 // Sequence Z: 11000000 drop at start
47 const uint8_t OddByteParity
[256] = {
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 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 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
53 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
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 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 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
61 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
62 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
63 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
67 void iso14a_set_trigger(int enable
) {
71 void iso14a_clear_trace(void) {
72 memset(trace
, 0x44, TRACE_SIZE
);
76 void iso14a_set_tracing(int enable
) {
80 void iso14a_set_timeout(uint32_t timeout
) {
81 iso14a_timeout
= timeout
;
84 //-----------------------------------------------------------------------------
85 // Generate the parity value for a byte sequence
87 //-----------------------------------------------------------------------------
88 byte_t
oddparity (const byte_t bt
)
90 return OddByteParity
[bt
];
93 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
98 // Generate the encrypted data
99 for (i
= 0; i
< iLen
; i
++) {
100 // Save the encrypted parity bit
101 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
106 void AppendCrc14443a(uint8_t* data
, int len
)
108 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
111 // The function LogTrace() is also used by the iClass implementation in iClass.c
112 int RAMFUNC
LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
114 // Return when trace is full
115 if (traceLen
>= TRACE_SIZE
) return FALSE
;
117 // Trace the random, i'm curious
118 rsamples
+= iSamples
;
119 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
120 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
121 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
122 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
124 trace
[traceLen
- 1] |= 0x80;
126 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
127 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
128 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
129 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
130 trace
[traceLen
++] = iLen
;
131 memcpy(trace
+ traceLen
, btBytes
, iLen
);
136 //-----------------------------------------------------------------------------
137 // The software UART that receives commands from the reader, and its state
139 //-----------------------------------------------------------------------------
142 static RAMFUNC
int MillerDecoding(int bit
)
147 if(!Uart
.bitBuffer
) {
148 Uart
.bitBuffer
= bit
^ 0xFF0;
152 Uart
.bitBuffer
<<= 4;
153 Uart
.bitBuffer
^= bit
;
158 if(Uart
.state
!= STATE_UNSYNCD
) {
161 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
167 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
173 if(bit
!= bitright
) { bit
= bitright
; }
175 if(Uart
.posCnt
== 1) {
176 // measurement first half bitperiod
178 Uart
.drop
= DROP_FIRST_HALF
;
182 // measurement second half bitperiod
183 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
184 Uart
.drop
= DROP_SECOND_HALF
;
187 // measured a drop in first and second half
188 // which should not be possible
189 Uart
.state
= STATE_ERROR_WAIT
;
196 case STATE_START_OF_COMMUNICATION
:
198 if(Uart
.drop
== DROP_SECOND_HALF
) {
199 // error, should not happen in SOC
200 Uart
.state
= STATE_ERROR_WAIT
;
205 Uart
.state
= STATE_MILLER_Z
;
212 if(Uart
.drop
== DROP_NONE
) {
213 // logic '0' followed by sequence Y
214 // end of communication
215 Uart
.state
= STATE_UNSYNCD
;
218 // if(Uart.drop == DROP_FIRST_HALF) {
219 // Uart.state = STATE_MILLER_Z; stay the same
220 // we see a logic '0' }
221 if(Uart
.drop
== DROP_SECOND_HALF
) {
222 // we see a logic '1'
223 Uart
.shiftReg
|= 0x100;
224 Uart
.state
= STATE_MILLER_X
;
230 if(Uart
.drop
== DROP_NONE
) {
231 // sequence Y, we see a '0'
232 Uart
.state
= STATE_MILLER_Y
;
235 if(Uart
.drop
== DROP_FIRST_HALF
) {
236 // Would be STATE_MILLER_Z
237 // but Z does not follow X, so error
238 Uart
.state
= STATE_ERROR_WAIT
;
241 if(Uart
.drop
== DROP_SECOND_HALF
) {
242 // We see a '1' and stay in state X
243 Uart
.shiftReg
|= 0x100;
251 if(Uart
.drop
== DROP_NONE
) {
252 // logic '0' followed by sequence Y
253 // end of communication
254 Uart
.state
= STATE_UNSYNCD
;
257 if(Uart
.drop
== DROP_FIRST_HALF
) {
259 Uart
.state
= STATE_MILLER_Z
;
261 if(Uart
.drop
== DROP_SECOND_HALF
) {
262 // We see a '1' and go to state X
263 Uart
.shiftReg
|= 0x100;
264 Uart
.state
= STATE_MILLER_X
;
268 case STATE_ERROR_WAIT
:
269 // That went wrong. Now wait for at least two bit periods
270 // and try to sync again
271 if(Uart
.drop
== DROP_NONE
) {
273 Uart
.state
= STATE_UNSYNCD
;
278 Uart
.state
= STATE_UNSYNCD
;
283 Uart
.drop
= DROP_NONE
;
285 // should have received at least one whole byte...
286 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
290 if(Uart
.bitCnt
== 9) {
291 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
294 Uart
.parityBits
<<= 1;
295 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
298 // when End of Communication received and
299 // all data bits processed..
306 Uart.output[Uart.byteCnt] = 0xAA;
308 Uart.output[Uart.byteCnt] = error & 0xFF;
310 Uart.output[Uart.byteCnt] = 0xAA;
312 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
314 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
316 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
318 Uart.output[Uart.byteCnt] = 0xAA;
326 bit
= Uart
.bitBuffer
& 0xf0;
330 // should have been high or at least (4 * 128) / fc
331 // according to ISO this should be at least (9 * 128 + 20) / fc
332 if(Uart
.highCnt
== 8) {
333 // we went low, so this could be start of communication
334 // it turns out to be safer to choose a less significant
335 // syncbit... so we check whether the neighbour also represents the drop
336 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
337 Uart
.syncBit
= bit
& 8;
339 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
340 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
341 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
342 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
343 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
344 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
347 // the first half bit period is expected in next sample
352 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
355 Uart
.state
= STATE_START_OF_COMMUNICATION
;
356 Uart
.drop
= DROP_FIRST_HALF
;
367 if(Uart
.highCnt
< 8) {
376 //=============================================================================
377 // ISO 14443 Type A - Manchester
378 //=============================================================================
381 static RAMFUNC
int ManchesterDecoding(int v
)
397 if(Demod
.state
==DEMOD_UNSYNCD
) {
398 Demod
.output
[Demod
.len
] = 0xfa;
401 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
404 Demod
.syncBit
= 0x08;
411 Demod
.syncBit
= 0x04;
418 Demod
.syncBit
= 0x02;
421 if(bit
& 0x01 && Demod
.syncBit
) {
422 Demod
.syncBit
= 0x01;
427 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
428 Demod
.sub
= SUB_FIRST_HALF
;
431 Demod
.parityBits
= 0;
434 if(trigger
) LED_A_OFF();
435 switch(Demod
.syncBit
) {
436 case 0x08: Demod
.samples
= 3; break;
437 case 0x04: Demod
.samples
= 2; break;
438 case 0x02: Demod
.samples
= 1; break;
439 case 0x01: Demod
.samples
= 0; break;
446 //modulation = bit & Demod.syncBit;
447 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
451 if(Demod
.posCount
==0) {
454 Demod
.sub
= SUB_FIRST_HALF
;
457 Demod
.sub
= SUB_NONE
;
462 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
463 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
464 Demod
.state
= DEMOD_ERROR_WAIT
;
465 Demod
.output
[Demod
.len
] = 0xaa;
469 else if(modulation
) {
470 Demod
.sub
= SUB_SECOND_HALF
;
473 switch(Demod
.state
) {
474 case DEMOD_START_OF_COMMUNICATION
:
475 if(Demod
.sub
== SUB_FIRST_HALF
) {
476 Demod
.state
= DEMOD_MANCHESTER_D
;
479 Demod
.output
[Demod
.len
] = 0xab;
480 Demod
.state
= DEMOD_ERROR_WAIT
;
485 case DEMOD_MANCHESTER_D
:
486 case DEMOD_MANCHESTER_E
:
487 if(Demod
.sub
== SUB_FIRST_HALF
) {
489 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
490 Demod
.state
= DEMOD_MANCHESTER_D
;
492 else if(Demod
.sub
== SUB_SECOND_HALF
) {
494 Demod
.shiftReg
>>= 1;
495 Demod
.state
= DEMOD_MANCHESTER_E
;
498 Demod
.state
= DEMOD_MANCHESTER_F
;
502 case DEMOD_MANCHESTER_F
:
503 // Tag response does not need to be a complete byte!
504 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
505 if(Demod
.bitCount
> 0) {
506 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
507 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
509 // No parity bit, so just shift a 0
510 Demod
.parityBits
<<= 1;
513 Demod
.state
= DEMOD_UNSYNCD
;
517 Demod
.output
[Demod
.len
] = 0xad;
518 Demod
.state
= DEMOD_ERROR_WAIT
;
523 case DEMOD_ERROR_WAIT
:
524 Demod
.state
= DEMOD_UNSYNCD
;
528 Demod
.output
[Demod
.len
] = 0xdd;
529 Demod
.state
= DEMOD_UNSYNCD
;
533 if(Demod
.bitCount
>=9) {
534 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
537 Demod
.parityBits
<<= 1;
538 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
545 Demod.output[Demod.len] = 0xBB;
547 Demod.output[Demod.len] = error & 0xFF;
549 Demod.output[Demod.len] = 0xBB;
551 Demod.output[Demod.len] = bit & 0xFF;
553 Demod.output[Demod.len] = Demod.buffer & 0xFF;
555 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
557 Demod.output[Demod.len] = 0xBB;
564 } // end (state != UNSYNCED)
569 //=============================================================================
570 // Finally, a `sniffer' for ISO 14443 Type A
571 // Both sides of communication!
572 //=============================================================================
574 //-----------------------------------------------------------------------------
575 // Record the sequence of commands sent by the reader to the tag, with
576 // triggering so that we start recording at the point that the tag is moved
578 //-----------------------------------------------------------------------------
579 void RAMFUNC
SnoopIso14443a(uint8_t param
) {
581 // bit 0 - trigger from first card answer
582 // bit 1 - trigger from first reader 7-bit request
586 iso14a_clear_trace();
588 // We won't start recording the frames that we acquire until we trigger;
589 // a good trigger condition to get started is probably when we see a
590 // response from the tag.
591 // triggered == FALSE -- to wait first for card
592 int triggered
= !(param
& 0x03);
594 // The command (reader -> tag) that we're receiving.
595 // The length of a received command will in most cases be no more than 18 bytes.
596 // So 32 should be enough!
597 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
598 // The response (tag -> reader) that we're receiving.
599 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
601 // As we receive stuff, we copy it from receivedCmd or receivedResponse
602 // into trace, along with its length and other annotations.
603 //uint8_t *trace = (uint8_t *)BigBuf;
605 // The DMA buffer, used to stream samples from the FPGA
606 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
607 int8_t *data
= dmaBuf
;
611 // Set up the demodulator for tag -> reader responses.
612 Demod
.output
= receivedResponse
;
614 Demod
.state
= DEMOD_UNSYNCD
;
616 // Set up the demodulator for the reader -> tag commands
617 memset(&Uart
, 0, sizeof(Uart
));
618 Uart
.output
= receivedCmd
;
619 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
620 Uart
.state
= STATE_UNSYNCD
;
622 // Setup for the DMA.
624 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
626 // And put the FPGA in the appropriate mode
627 // Signal field is off with the appropriate LED
629 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
630 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
632 // Count of samples received so far, so that we can include timing
633 // information in the trace buffer.
635 // And now we loop, receiving samples.
638 DbpString("cancelled by button");
645 int register readBufDataP
= data
- dmaBuf
;
646 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
647 if (readBufDataP
<= dmaBufDataP
){
648 dataLen
= dmaBufDataP
- readBufDataP
;
650 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
652 // test for length of buffer
653 if(dataLen
> maxDataLen
) {
654 maxDataLen
= dataLen
;
656 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
660 if(dataLen
< 1) continue;
662 // primary buffer was stopped( <-- we lost data!
663 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
664 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
665 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
667 // secondary buffer sets as primary, secondary buffer was stopped
668 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
669 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
670 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
676 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
679 // check - if there is a short 7bit request from reader
680 if ((!triggered
) && (param
& 0x02) && (Uart
.byteCnt
== 1) && (Uart
.bitCnt
= 9)) triggered
= TRUE
;
683 if (!LogTrace(receivedCmd
, Uart
.byteCnt
, 0 - Uart
.samples
, Uart
.parityBits
, TRUE
)) break;
685 /* And ready to receive another command. */
686 Uart
.state
= STATE_UNSYNCD
;
687 /* And also reset the demod code, which might have been */
688 /* false-triggered by the commands from the reader. */
689 Demod
.state
= DEMOD_UNSYNCD
;
693 if(ManchesterDecoding(data
[0] & 0x0F)) {
696 if (!LogTrace(receivedResponse
, Demod
.len
, 0 - Demod
.samples
, Demod
.parityBits
, FALSE
)) break;
698 if ((!triggered
) && (param
& 0x01)) triggered
= TRUE
;
700 // And ready to receive another response.
701 memset(&Demod
, 0, sizeof(Demod
));
702 Demod
.output
= receivedResponse
;
703 Demod
.state
= DEMOD_UNSYNCD
;
708 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
713 DbpString("COMMAND FINISHED");
716 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
717 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
);
718 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
722 //-----------------------------------------------------------------------------
723 // Prepare tag messages
724 //-----------------------------------------------------------------------------
725 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
731 // Correction bit, might be removed when not needed
736 ToSendStuffBit(1); // 1
742 ToSend
[++ToSendMax
] = SEC_D
;
744 for(i
= 0; i
< len
; i
++) {
749 for(j
= 0; j
< 8; j
++) {
751 ToSend
[++ToSendMax
] = SEC_D
;
753 ToSend
[++ToSendMax
] = SEC_E
;
758 // Get the parity bit
759 if ((dwParity
>> i
) & 0x01) {
760 ToSend
[++ToSendMax
] = SEC_D
;
762 ToSend
[++ToSendMax
] = SEC_E
;
767 ToSend
[++ToSendMax
] = SEC_F
;
769 // Convert from last byte pos to length
773 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
774 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
777 //-----------------------------------------------------------------------------
778 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
779 //-----------------------------------------------------------------------------
780 static void CodeStrangeAnswerAsTag()
786 // Correction bit, might be removed when not needed
791 ToSendStuffBit(1); // 1
797 ToSend
[++ToSendMax
] = SEC_D
;
800 ToSend
[++ToSendMax
] = SEC_E
;
803 ToSend
[++ToSendMax
] = SEC_E
;
806 ToSend
[++ToSendMax
] = SEC_D
;
809 ToSend
[++ToSendMax
] = SEC_F
;
811 // Flush the buffer in FPGA!!
812 for(i
= 0; i
< 5; i
++) {
813 ToSend
[++ToSendMax
] = SEC_F
;
816 // Convert from last byte pos to length
820 static void Code4bitAnswerAsTag(uint8_t cmd
)
826 // Correction bit, might be removed when not needed
831 ToSendStuffBit(1); // 1
837 ToSend
[++ToSendMax
] = SEC_D
;
840 for(i
= 0; i
< 4; i
++) {
842 ToSend
[++ToSendMax
] = SEC_D
;
844 ToSend
[++ToSendMax
] = SEC_E
;
850 ToSend
[++ToSendMax
] = SEC_F
;
852 // Flush the buffer in FPGA!!
853 for(i
= 0; i
< 5; i
++) {
854 ToSend
[++ToSendMax
] = SEC_F
;
857 // Convert from last byte pos to length
861 //-----------------------------------------------------------------------------
862 // Wait for commands from reader
863 // Stop when button is pressed
864 // Or return TRUE when command is captured
865 //-----------------------------------------------------------------------------
866 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
868 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
869 // only, since we are receiving, not transmitting).
870 // Signal field is off with the appropriate LED
872 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
874 // Now run a `software UART' on the stream of incoming samples.
875 Uart
.output
= received
;
876 Uart
.byteCntMax
= maxLen
;
877 Uart
.state
= STATE_UNSYNCD
;
882 if(BUTTON_PRESS()) return FALSE
;
884 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
885 AT91C_BASE_SSC
->SSC_THR
= 0x00;
887 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
888 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
889 if(MillerDecoding((b
& 0xf0) >> 4)) {
893 if(MillerDecoding(b
& 0x0f)) {
900 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
902 //-----------------------------------------------------------------------------
903 // Main loop of simulated tag: receive commands from reader, decide what
904 // response to send, and send it.
905 //-----------------------------------------------------------------------------
906 void SimulateIso14443aTag(int tagType
, int uid_1st
, int uid_2nd
)
908 // Enable and clear the trace
910 iso14a_clear_trace();
912 // This function contains the tag emulation
915 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
916 uint8_t response1
[2];
919 case 1: { // MIFARE Classic
920 // Says: I am Mifare 1k - original line
925 case 2: { // MIFARE Ultralight
926 // Says: I am a stupid memory tag, no crypto
931 case 3: { // MIFARE DESFire
932 // Says: I am a DESFire tag, ph33r me
937 case 4: { // ISO/IEC 14443-4
938 // Says: I am a javacard (JCOP)
944 Dbprintf("Error: unkown tagtype (%d)",tagType
);
949 // The second response contains the (mandatory) first 24 bits of the UID
950 uint8_t response2
[5];
952 // Check if the uid uses the (optional) part
953 uint8_t response2a
[5];
956 num_to_bytes(uid_1st
,3,response2
+1);
957 num_to_bytes(uid_2nd
,4,response2a
);
958 response2a
[4] = response2a
[0] ^ response2a
[1] ^ response2a
[2] ^ response2a
[3];
960 // Configure the ATQA and SAK accordingly
961 response1
[0] |= 0x40;
964 num_to_bytes(uid_1st
,4,response2
);
965 // Configure the ATQA and SAK accordingly
966 response1
[0] &= 0xBF;
970 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
971 response2
[4] = response2
[0] ^ response2
[1] ^ response2
[2] ^ response2
[3];
973 // Prepare the mandatory SAK (for 4 and 7 byte UID)
974 uint8_t response3
[3];
976 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
978 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
979 uint8_t response3a
[3];
980 response3a
[0] = sak
& 0xFB;
981 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
983 uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
984 uint8_t response6
[] = { 0x03, 0x3B, 0x00, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
985 ComputeCrc14443(CRC_14443_A
, response6
, 3, &response6
[3], &response6
[4]);
990 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
992 // 144 data bits (18 * 8)
995 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
996 // 1 just for the case
1000 // 166 bytes, since every bit that needs to be send costs us a byte
1003 // Respond with card type
1004 uint8_t *resp1
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
1007 // Anticollision cascade1 - respond with uid
1008 uint8_t *resp2
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ 166);
1011 // Anticollision cascade2 - respond with 2nd half of uid if asked
1012 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1013 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1016 // Acknowledge select - cascade 1
1017 uint8_t *resp3
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*2));
1020 // Acknowledge select - cascade 2
1021 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*3));
1024 // Response to a read request - not implemented atm
1025 uint8_t *resp4
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*4));
1028 // Authenticate response - nonce
1029 uint8_t *resp5
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*5));
1032 // Authenticate response - nonce
1033 uint8_t *resp6
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*6));
1036 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
1039 // To control where we are in the protocol
1043 // Just to allow some checks
1048 uint8_t* respdata
= NULL
;
1050 uint8_t nack
= 0x04;
1052 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1054 // Prepare the responses of the anticollision phase
1055 // there will be not enough time to do this at the moment the reader sends it REQA
1057 // Answer to request
1058 CodeIso14443aAsTag(response1
, sizeof(response1
));
1059 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1061 // Send our UID (cascade 1)
1062 CodeIso14443aAsTag(response2
, sizeof(response2
));
1063 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1065 // Answer to select (cascade1)
1066 CodeIso14443aAsTag(response3
, sizeof(response3
));
1067 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1069 // Send the cascade 2 2nd part of the uid
1070 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1071 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1073 // Answer to select (cascade 2)
1074 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1075 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1077 // Strange answer is an example of rare message size (3 bits)
1078 CodeStrangeAnswerAsTag();
1079 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1081 // Authentication answer (random nonce)
1082 CodeIso14443aAsTag(response5
, sizeof(response5
));
1083 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1085 // dummy ATS (pseudo-ATR), answer to RATS
1086 CodeIso14443aAsTag(response6
, sizeof(response6
));
1087 memcpy(resp6
, ToSend
, ToSendMax
); resp6Len
= ToSendMax
;
1089 // We need to listen to the high-frequency, peak-detected path.
1090 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1098 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, RECV_CMD_SIZE
)) {
1099 DbpString("button press");
1102 // 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
1103 // Okay, look at the command now.
1105 if(receivedCmd
[0] == 0x26) { // Received a REQUEST
1106 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1107 respdata
= response1
;
1108 respsize
= sizeof(response1
);
1109 } else if(receivedCmd
[0] == 0x52) { // Received a WAKEUP
1110 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1111 respdata
= response1
;
1112 respsize
= sizeof(response1
);
1113 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // Received request for UID (cascade 1)
1114 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1115 respdata
= response2
;
1116 respsize
= sizeof(response2
);
1117 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x95) { // Received request for UID (cascade 2)
1118 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1119 respdata
= response2a
;
1120 respsize
= sizeof(response2a
);
1121 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x93) { // Received a SELECT (cascade 1)
1122 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1123 respdata
= response3
;
1124 respsize
= sizeof(response3
);
1125 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x95) { // Received a SELECT (cascade 2)
1126 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1127 respdata
= response3a
;
1128 respsize
= sizeof(response3a
);
1129 } else if(receivedCmd
[0] == 0x30) { // Received a (plain) READ
1130 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1131 Dbprintf("Read request from reader: %x %x",receivedCmd
[0],receivedCmd
[1]);
1133 respsize
= sizeof(nack
); // 4-bit answer
1134 } else if(receivedCmd
[0] == 0x50) { // Received a HALT
1135 DbpString("Reader requested we HALT!:");
1137 resp
= resp1
; respLen
= 0; order
= 0;
1140 } else if(receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61) { // Received an authentication request
1141 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1142 respdata
= response5
;
1143 respsize
= sizeof(response5
);
1144 } else if(receivedCmd
[0] == 0xE0) { // Received a RATS request
1145 resp
= resp6
; respLen
= resp6Len
; order
= 70;
1146 respdata
= response6
;
1147 respsize
= sizeof(response6
);
1149 // Never seen this command before
1150 Dbprintf("Received (len=%d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1152 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2],
1153 receivedCmd
[3], receivedCmd
[4], receivedCmd
[5],
1154 receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1156 resp
= resp1
; respLen
= 0; order
= 0;
1161 // Count number of wakeups received after a halt
1162 if(order
== 6 && lastorder
== 5) { happened
++; }
1164 // Count number of other messages after a halt
1165 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1167 // Look at last parity bit to determine timing of answer
1168 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1169 // 1236, so correction bit needed
1173 if(cmdsRecvd
> 999) {
1174 DbpString("1000 commands later...");
1181 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1185 LogTrace(receivedCmd
,len
, 0, Uart
.parityBits
, TRUE
);
1186 if (respdata
!= NULL
) {
1187 LogTrace(respdata
,respsize
, 0, SwapBits(GetParity(respdata
,respsize
),respsize
), FALSE
);
1189 if(traceLen
> TRACE_SIZE
) {
1190 DbpString("Trace full");
1195 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1198 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1202 //-----------------------------------------------------------------------------
1203 // Transmit the command (to the tag) that was placed in ToSend[].
1204 //-----------------------------------------------------------------------------
1205 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1209 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1215 for(c
= 0; c
< *wait
;) {
1216 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1217 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1220 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1221 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1229 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1230 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1236 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1237 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1242 if (samples
) *samples
= (c
+ *wait
) << 3;
1245 //-----------------------------------------------------------------------------
1246 // Code a 7-bit command without parity bit
1247 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1248 //-----------------------------------------------------------------------------
1249 void ShortFrameFromReader(const uint8_t bt
)
1257 // Start of Communication (Seq. Z)
1258 ToSend
[++ToSendMax
] = SEC_Z
;
1262 for(j
= 0; j
< 7; j
++) {
1265 ToSend
[++ToSendMax
] = SEC_X
;
1270 ToSend
[++ToSendMax
] = SEC_Z
;
1274 ToSend
[++ToSendMax
] = SEC_Y
;
1281 // End of Communication
1284 ToSend
[++ToSendMax
] = SEC_Z
;
1288 ToSend
[++ToSendMax
] = SEC_Y
;
1292 ToSend
[++ToSendMax
] = SEC_Y
;
1295 ToSend
[++ToSendMax
] = SEC_Y
;
1296 ToSend
[++ToSendMax
] = SEC_Y
;
1297 ToSend
[++ToSendMax
] = SEC_Y
;
1299 // Convert from last character reference to length
1303 //-----------------------------------------------------------------------------
1304 // Prepare reader command to send to FPGA
1306 //-----------------------------------------------------------------------------
1307 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1315 // Start of Communication (Seq. Z)
1316 ToSend
[++ToSendMax
] = SEC_Z
;
1319 // Generate send structure for the data bits
1320 for (i
= 0; i
< len
; i
++) {
1321 // Get the current byte to send
1324 for (j
= 0; j
< 8; j
++) {
1327 ToSend
[++ToSendMax
] = SEC_X
;
1332 ToSend
[++ToSendMax
] = SEC_Z
;
1335 ToSend
[++ToSendMax
] = SEC_Y
;
1342 // Get the parity bit
1343 if ((dwParity
>> i
) & 0x01) {
1345 ToSend
[++ToSendMax
] = SEC_X
;
1350 ToSend
[++ToSendMax
] = SEC_Z
;
1353 ToSend
[++ToSendMax
] = SEC_Y
;
1359 // End of Communication
1362 ToSend
[++ToSendMax
] = SEC_Z
;
1365 ToSend
[++ToSendMax
] = SEC_Y
;
1369 ToSend
[++ToSendMax
] = SEC_Y
;
1372 ToSend
[++ToSendMax
] = SEC_Y
;
1373 ToSend
[++ToSendMax
] = SEC_Y
;
1374 ToSend
[++ToSendMax
] = SEC_Y
;
1376 // Convert from last character reference to length
1380 //-----------------------------------------------------------------------------
1381 // Wait for commands from reader
1382 // Stop when button is pressed (return 1) or field was gone (return 2)
1383 // Or return 0 when command is captured
1384 //-----------------------------------------------------------------------------
1385 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1389 uint32_t timer
= 0, vtime
= 0;
1393 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1394 // only, since we are receiving, not transmitting).
1395 // Signal field is off with the appropriate LED
1397 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1399 // Set ADC to read field strength
1400 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1401 AT91C_BASE_ADC
->ADC_MR
=
1402 ADC_MODE_PRESCALE(32) |
1403 ADC_MODE_STARTUP_TIME(16) |
1404 ADC_MODE_SAMPLE_HOLD_TIME(8);
1405 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1407 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1409 // Now run a 'software UART' on the stream of incoming samples.
1410 Uart
.output
= received
;
1411 Uart
.byteCntMax
= maxLen
;
1412 Uart
.state
= STATE_UNSYNCD
;
1417 if (BUTTON_PRESS()) return 1;
1419 // test if the field exists
1420 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1422 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1423 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1424 if (analogCnt
>= 32) {
1425 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1426 vtime
= GetTickCount();
1427 if (!timer
) timer
= vtime
;
1428 // 50ms no field --> card to idle state
1429 if (vtime
- timer
> 50) return 2;
1431 if (timer
) timer
= 0;
1437 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1438 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1440 // receive and test the miller decoding
1441 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1442 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1443 if(MillerDecoding((b
& 0xf0) >> 4)) {
1444 *len
= Uart
.byteCnt
;
1445 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1448 if(MillerDecoding(b
& 0x0f)) {
1449 *len
= Uart
.byteCnt
;
1450 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1457 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1462 // Modulate Manchester
1463 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1464 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1467 // include correction bit
1469 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1470 // 1236, so correction bit needed
1476 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1477 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1480 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1482 b
= 0xff; // was 0x00
1488 AT91C_BASE_SSC
->SSC_THR
= b
;
1492 if(BUTTON_PRESS()) {
1500 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1501 Code4bitAnswerAsTag(resp
);
1502 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1503 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1507 int EmSend4bit(uint8_t resp
){
1508 return EmSend4bitEx(resp
, 0);
1511 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1512 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1513 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1514 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1518 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1519 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1522 int EmSendCmd(uint8_t *resp
, int respLen
){
1523 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1526 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1527 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1530 //-----------------------------------------------------------------------------
1531 // Wait a certain time for tag response
1532 // If a response is captured return TRUE
1533 // If it takes to long return FALSE
1534 //-----------------------------------------------------------------------------
1535 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1537 // buffer needs to be 512 bytes
1540 // Set FPGA mode to "reader listen mode", no modulation (listen
1541 // only, since we are receiving, not transmitting).
1542 // Signal field is on with the appropriate LED
1544 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1546 // Now get the answer from the card
1547 Demod
.output
= receivedResponse
;
1549 Demod
.state
= DEMOD_UNSYNCD
;
1552 if (elapsed
) *elapsed
= 0;
1558 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1559 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1560 if (elapsed
) (*elapsed
)++;
1562 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1563 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1564 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1565 if(ManchesterDecoding((b
>>4) & 0xf)) {
1566 *samples
= ((c
- 1) << 3) + 4;
1569 if(ManchesterDecoding(b
& 0x0f)) {
1577 void ReaderTransmitShort(const uint8_t* bt
)
1582 ShortFrameFromReader(*bt
);
1585 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1587 // Store reader command in buffer
1588 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1591 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1596 // This is tied to other size changes
1597 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1598 CodeIso14443aAsReaderPar(frame
,len
,par
);
1601 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1605 // Store reader command in buffer
1606 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1610 void ReaderTransmit(uint8_t* frame
, int len
)
1612 // Generate parity and redirect
1613 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1616 int ReaderReceive(uint8_t* receivedAnswer
)
1619 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1620 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1621 if(samples
== 0) return FALSE
;
1625 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1628 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1629 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1630 *parptr
= Demod
.parityBits
;
1631 if(samples
== 0) return FALSE
;
1635 /* performs iso14443a anticolision procedure
1636 * fills the uid pointer unless NULL
1637 * fills resp_data unless NULL */
1638 int iso14443a_select_card(uint8_t * uid_ptr
, iso14a_card_select_t
* resp_data
, uint32_t * cuid_ptr
) {
1639 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1640 uint8_t sel_all
[] = { 0x93,0x20 };
1641 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1642 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1644 uint8_t* resp
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1646 uint8_t sak
= 0x04; // cascade uid
1647 int cascade_level
= 0;
1652 memset(uid_ptr
, 0, 8);
1654 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1655 ReaderTransmitShort(wupa
);
1657 if(!ReaderReceive(resp
)) return 0;
1660 memcpy(resp_data
->atqa
, resp
, 2);
1662 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1663 // which case we need to make a cascade 2 request and select - this is a long UID
1664 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1665 for(; sak
& 0x04; cascade_level
++)
1667 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1668 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1671 ReaderTransmit(sel_all
,sizeof(sel_all
));
1672 if (!ReaderReceive(resp
)) return 0;
1673 if(uid_ptr
) memcpy(uid_ptr
+ cascade_level
*4, resp
, 4);
1675 // calculate crypto UID
1676 if(cuid_ptr
) *cuid_ptr
= bytes_to_num(resp
, 4);
1678 // Construct SELECT UID command
1679 memcpy(sel_uid
+2,resp
,5);
1680 AppendCrc14443a(sel_uid
,7);
1681 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1684 if (!ReaderReceive(resp
)) return 0;
1688 resp_data
->sak
= sak
;
1689 resp_data
->ats_len
= 0;
1691 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1692 if (uid_ptr
[0] == 0x88) {
1693 memcpy(uid_ptr
, uid_ptr
+ 1, 7);
1697 if( (sak
& 0x20) == 0)
1698 return 2; // non iso14443a compliant tag
1700 // Request for answer to select
1701 if(resp_data
) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1702 AppendCrc14443a(rats
, 2);
1703 ReaderTransmit(rats
, sizeof(rats
));
1705 if (!(len
= ReaderReceive(resp
))) return 0;
1707 memcpy(resp_data
->ats
, resp
, sizeof(resp_data
->ats
));
1708 resp_data
->ats_len
= len
;
1711 // reset the PCB block number
1712 iso14_pcb_blocknum
= 0;
1717 void iso14443a_setup() {
1720 // Start from off (no field generated)
1721 // Signal field is off with the appropriate LED
1723 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1726 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1728 // Now give it time to spin up.
1729 // Signal field is on with the appropriate LED
1731 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1734 iso14a_timeout
= 2048; //default
1737 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1738 uint8_t real_cmd
[cmd_len
+4];
1739 real_cmd
[0] = 0x0a; //I-Block
1740 // put block number into the PCB
1741 real_cmd
[0] |= iso14_pcb_blocknum
;
1742 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1743 memcpy(real_cmd
+2, cmd
, cmd_len
);
1744 AppendCrc14443a(real_cmd
,cmd_len
+2);
1746 ReaderTransmit(real_cmd
, cmd_len
+4);
1747 size_t len
= ReaderReceive(data
);
1748 uint8_t * data_bytes
= (uint8_t *) data
;
1750 return 0; //DATA LINK ERROR
1751 // if we received an I- or R(ACK)-Block with a block number equal to the
1752 // current block number, toggle the current block number
1753 else if (len
>= 4 // PCB+CID+CRC = 4 bytes
1754 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
1755 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1756 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) // equal block numbers
1758 iso14_pcb_blocknum
^= 1;
1764 //-----------------------------------------------------------------------------
1765 // Read an ISO 14443a tag. Send out commands and store answers.
1767 //-----------------------------------------------------------------------------
1768 void ReaderIso14443a(UsbCommand
* c
, UsbCommand
* ack
)
1770 iso14a_command_t param
= c
->arg
[0];
1771 uint8_t * cmd
= c
->d
.asBytes
;
1772 size_t len
= c
->arg
[1];
1774 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(1);
1776 if(param
& ISO14A_CONNECT
) {
1778 ack
->arg
[0] = iso14443a_select_card(ack
->d
.asBytes
, (iso14a_card_select_t
*) (ack
->d
.asBytes
+12), NULL
);
1779 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1782 if(param
& ISO14A_SET_TIMEOUT
) {
1783 iso14a_timeout
= c
->arg
[2];
1786 if(param
& ISO14A_SET_TIMEOUT
) {
1787 iso14a_timeout
= c
->arg
[2];
1790 if(param
& ISO14A_APDU
) {
1791 ack
->arg
[0] = iso14_apdu(cmd
, len
, ack
->d
.asBytes
);
1792 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1795 if(param
& ISO14A_RAW
) {
1796 if(param
& ISO14A_APPEND_CRC
) {
1797 AppendCrc14443a(cmd
,len
);
1800 ReaderTransmit(cmd
,len
);
1801 ack
->arg
[0] = ReaderReceive(ack
->d
.asBytes
);
1802 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1805 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(0);
1807 if(param
& ISO14A_NO_DISCONNECT
)
1810 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1814 //-----------------------------------------------------------------------------
1815 // Read an ISO 14443a tag. Send out commands and store answers.
1817 //-----------------------------------------------------------------------------
1818 void ReaderMifare(uint32_t parameter
)
1821 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1822 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1824 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1837 //byte_t par_mask = 0xff;
1844 byte_t nt
[4] = {0,0,0,0};
1845 byte_t nt_attacked
[4], nt_noattack
[4];
1846 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1847 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1848 num_to_bytes(parameter
, 4, nt_noattack
);
1849 int isOK
= 0, isNULL
= 0;
1854 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1856 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1860 // Test if the action was cancelled
1861 if(BUTTON_PRESS()) {
1865 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1867 // Transmit MIFARE_CLASSIC_AUTH
1868 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1870 // Receive the (16 bit) "random" nonce
1871 if (!ReaderReceive(receivedAnswer
)) continue;
1872 memcpy(nt
, receivedAnswer
, 4);
1874 // Transmit reader nonce and reader answer
1875 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1877 // Receive 4 bit answer
1878 if (ReaderReceive(receivedAnswer
))
1880 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1882 isNULL
= !(nt_attacked
[0] == 0) && (nt_attacked
[1] == 0) && (nt_attacked
[2] == 0) && (nt_attacked
[3] == 0);
1883 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1888 memcpy(nt_attacked
, nt
, 4);
1890 par_low
= par
& 0x07;
1894 if(led_on
) LED_B_ON(); else LED_B_OFF();
1895 par_list
[nt_diff
] = par
;
1896 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1898 // Test if the information is complete
1899 if (nt_diff
== 0x07) {
1904 nt_diff
= (nt_diff
+ 1) & 0x07;
1905 mf_nr_ar
[3] = nt_diff
<< 5;
1912 par
= (((par
>> 3) + 1) << 3) | par_low
;
1917 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1918 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1919 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1921 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
1922 memcpy(ack
.d
.asBytes
+ 0, uid
, 4);
1923 memcpy(ack
.d
.asBytes
+ 4, nt
, 4);
1924 memcpy(ack
.d
.asBytes
+ 8, par_list
, 8);
1925 memcpy(ack
.d
.asBytes
+ 16, ks_list
, 8);
1928 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
1932 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1936 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1940 //-----------------------------------------------------------------------------
1941 // MIFARE 1K simulate.
1943 //-----------------------------------------------------------------------------
1944 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
1946 int cardSTATE
= MFEMUL_NOFIELD
;
1948 int vHf
= 0; // in mV
1949 //int nextCycleTimeout = 0;
1951 // uint32_t timer = 0;
1952 uint32_t selTimer
= 0;
1953 uint32_t authTimer
= 0;
1956 uint8_t cardWRBL
= 0;
1957 uint8_t cardAUTHSC
= 0;
1958 uint8_t cardAUTHKEY
= 0xff; // no authentication
1959 //uint32_t cardRn = 0;
1960 uint32_t cardRr
= 0;
1962 //uint32_t rn_enc = 0;
1964 uint32_t cardINTREG
= 0;
1965 uint8_t cardINTBLOCK
= 0;
1966 struct Crypto1State mpcs
= {0, 0};
1967 struct Crypto1State
*pcs
;
1970 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
1971 uint8_t *response
= eml_get_bigbufptr_sendbuf();
1973 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
1975 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
1976 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
1978 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
1979 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
1981 static uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
1982 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
1983 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
1989 // Authenticate response - nonce
1990 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
1992 // get UID from emul memory
1993 emlGetMemBt(receivedCmd
, 7, 1);
1994 _7BUID
= !(receivedCmd
[0] == 0x00);
1995 if (!_7BUID
) { // ---------- 4BUID
1998 emlGetMemBt(rUIDBCC1
, 0, 4);
1999 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2000 } else { // ---------- 7BUID
2004 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2005 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2006 emlGetMemBt(rUIDBCC2
, 3, 4);
2007 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2010 // -------------------------------------- test area
2012 // -------------------------------------- END test area
2013 // start mkseconds counter
2016 // We need to listen to the high-frequency, peak-detected path.
2017 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2020 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2023 if (MF_DBGLEVEL
>= 1) Dbprintf("Started. 7buid=%d", _7BUID
);
2024 // calibrate mkseconds counter
2029 if(BUTTON_PRESS()) {
2033 // find reader field
2034 // Vref = 3300mV, and an 10:1 voltage divider on the input
2035 // can measure voltages up to 33000 mV
2036 if (cardSTATE
== MFEMUL_NOFIELD
) {
2037 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2038 if (vHf
> MF_MINFIELDV
) {
2039 cardSTATE_TO_IDLE();
2044 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2045 res
= EmGetCmd(receivedCmd
, &len
, RECV_CMD_SIZE
); // (+ nextCycleTimeout)
2047 cardSTATE
= MFEMUL_NOFIELD
;
2054 //nextCycleTimeout = 0;
2056 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2058 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2059 // REQ or WUP request in ANY state and WUP in HALTED state
2060 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2061 selTimer
= GetTickCount();
2062 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2063 cardSTATE
= MFEMUL_SELECT1
;
2065 // init crypto block
2068 crypto1_destroy(pcs
);
2073 switch (cardSTATE
) {
2074 case MFEMUL_NOFIELD
:{
2077 case MFEMUL_HALTED
:{
2083 case MFEMUL_SELECT1
:{
2085 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2086 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2092 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2094 EmSendCmd(rSAK
, sizeof(rSAK
));
2096 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2098 cuid
= bytes_to_num(rUIDBCC1
, 4);
2100 cardSTATE
= MFEMUL_WORK
;
2102 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2105 cardSTATE
= MFEMUL_SELECT2
;
2112 case MFEMUL_SELECT2
:{
2115 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2116 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2122 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2123 EmSendCmd(rSAK
, sizeof(rSAK
));
2125 cuid
= bytes_to_num(rUIDBCC2
, 4);
2126 cardSTATE
= MFEMUL_WORK
;
2128 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2132 // i guess there is a command). go into the work state.
2133 if (len
!= 4) break;
2134 cardSTATE
= MFEMUL_WORK
;
2140 //rn_enc = bytes_to_num(receivedCmd, 4);
2141 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2142 cardRr
= bytes_to_num(&receivedCmd
[4], 4) ^ crypto1_word(pcs
, 0, 0);
2144 if (cardRr
!= prng_successor(nonce
, 64)){
2145 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr
, prng_successor(nonce
, 64));
2146 cardSTATE_TO_IDLE();
2149 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2150 num_to_bytes(ans
, 4, rAUTH_AT
);
2152 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2153 cardSTATE
= MFEMUL_AUTH2
;
2155 cardSTATE_TO_IDLE();
2157 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2161 cardSTATE
= MFEMUL_WORK
;
2162 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2166 lbWORK
: if (len
== 0) break;
2168 if (cardAUTHKEY
== 0xff) {
2169 // first authentication
2170 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2171 authTimer
= GetTickCount();
2173 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2174 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2177 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2178 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2179 num_to_bytes(nonce
, 4, rAUTH_AT
);
2180 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2183 // last working revision
2184 // EmSendCmd14443aRaw(resp1, resp1Len, 0);
2185 // LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2187 cardSTATE
= MFEMUL_AUTH1
;
2188 //nextCycleTimeout = 10;
2193 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2195 // nested authentication
2196 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2197 authTimer
= GetTickCount();
2199 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2200 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2203 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2204 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2205 num_to_bytes(ans
, 4, rAUTH_AT
);
2206 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2209 cardSTATE
= MFEMUL_AUTH1
;
2210 //nextCycleTimeout = 10;
2215 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2216 // BUT... ACK --> NACK
2217 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2218 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2222 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2223 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2224 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2229 if (len
== 4 && receivedCmd
[0] == 0x30) {
2230 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2231 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2234 emlGetMem(response
, receivedCmd
[1], 1);
2235 AppendCrc14443a(response
, 16);
2236 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2237 EmSendCmdPar(response
, 18, par
);
2242 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2243 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2244 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2247 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2248 //nextCycleTimeout = 50;
2249 cardSTATE
= MFEMUL_WRITEBL2
;
2250 cardWRBL
= receivedCmd
[1];
2254 // works with cardINTREG
2256 // increment, decrement, restore
2257 if (len
== 4 && (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2)) {
2258 if (receivedCmd
[1] >= 16 * 4 ||
2259 receivedCmd
[1] / 4 != cardAUTHSC
||
2260 emlCheckValBl(receivedCmd
[1])) {
2261 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2264 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2265 if (receivedCmd
[0] == 0xC1)
2266 cardSTATE
= MFEMUL_INTREG_INC
;
2267 if (receivedCmd
[0] == 0xC0)
2268 cardSTATE
= MFEMUL_INTREG_DEC
;
2269 if (receivedCmd
[0] == 0xC2)
2270 cardSTATE
= MFEMUL_INTREG_REST
;
2271 cardWRBL
= receivedCmd
[1];
2278 if (len
== 4 && receivedCmd
[0] == 0xB0) {
2279 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2280 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2284 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2285 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2287 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2293 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2296 cardSTATE
= MFEMUL_HALTED
;
2297 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2301 // command not allowed
2303 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2310 case MFEMUL_WRITEBL2
:{
2312 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2313 emlSetMem(receivedCmd
, cardWRBL
, 1);
2314 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2315 cardSTATE
= MFEMUL_WORK
;
2318 cardSTATE_TO_IDLE();
2324 case MFEMUL_INTREG_INC
:{
2325 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2326 memcpy(&ans
, receivedCmd
, 4);
2327 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2328 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2329 cardSTATE_TO_IDLE();
2332 cardINTREG
= cardINTREG
+ ans
;
2333 cardSTATE
= MFEMUL_WORK
;
2336 case MFEMUL_INTREG_DEC
:{
2337 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2338 memcpy(&ans
, receivedCmd
, 4);
2339 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2340 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2341 cardSTATE_TO_IDLE();
2344 cardINTREG
= cardINTREG
- ans
;
2345 cardSTATE
= MFEMUL_WORK
;
2348 case MFEMUL_INTREG_REST
:{
2349 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2350 memcpy(&ans
, receivedCmd
, 4);
2351 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2352 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2353 cardSTATE_TO_IDLE();
2356 cardSTATE
= MFEMUL_WORK
;
2362 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2365 // add trace trailer
2366 memset(rAUTH_NT
, 0x44, 4);
2367 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2369 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);
2372 //-----------------------------------------------------------------------------
2375 //-----------------------------------------------------------------------------
2376 void RAMFUNC
SniffMifare(uint8_t param
) {
2378 // bit 0 - trigger from first card answer
2379 // bit 1 - trigger from first reader 7-bit request
2381 // C(red) A(yellow) B(green)
2383 // init trace buffer
2384 iso14a_clear_trace();
2386 // The command (reader -> tag) that we're receiving.
2387 // The length of a received command will in most cases be no more than 18 bytes.
2388 // So 32 should be enough!
2389 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
2390 // The response (tag -> reader) that we're receiving.
2391 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
2393 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2394 // into trace, along with its length and other annotations.
2395 //uint8_t *trace = (uint8_t *)BigBuf;
2397 // The DMA buffer, used to stream samples from the FPGA
2398 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
2399 int8_t *data
= dmaBuf
;
2403 // Set up the demodulator for tag -> reader responses.
2404 Demod
.output
= receivedResponse
;
2406 Demod
.state
= DEMOD_UNSYNCD
;
2408 // Set up the demodulator for the reader -> tag commands
2409 memset(&Uart
, 0, sizeof(Uart
));
2410 Uart
.output
= receivedCmd
;
2411 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
2412 Uart
.state
= STATE_UNSYNCD
;
2414 // Setup for the DMA.
2416 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
2418 // And put the FPGA in the appropriate mode
2419 // Signal field is off with the appropriate LED
2421 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
2422 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2426 int sniffCounter
= 0;
2428 // And now we loop, receiving samples.
2430 if(BUTTON_PRESS()) {
2431 DbpString("cancelled by button");
2438 if (++sniffCounter
> 65) {
2439 if (MfSniffSend(2000)) {
2445 int register readBufDataP
= data
- dmaBuf
;
2446 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
2447 if (readBufDataP
<= dmaBufDataP
){
2448 dataLen
= dmaBufDataP
- readBufDataP
;
2450 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
2452 // test for length of buffer
2453 if(dataLen
> maxDataLen
) {
2454 maxDataLen
= dataLen
;
2456 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
2460 if(dataLen
< 1) continue;
2462 // primary buffer was stopped( <-- we lost data!
2463 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
2464 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
2465 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
2466 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen
); // temporary
2468 // secondary buffer sets as primary, secondary buffer was stopped
2469 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
2470 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
2471 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
2476 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
2478 // check - if there is a short 7bit request from reader
2479 if (MfSniffLogic(receivedCmd
, Uart
.byteCnt
, Uart
.parityBits
, Uart
.bitCnt
, TRUE
)) break;
2481 /* And ready to receive another command. */
2482 Uart
.state
= STATE_UNSYNCD
;
2484 /* And also reset the demod code */
2485 Demod
.state
= DEMOD_UNSYNCD
;
2488 if(ManchesterDecoding(data
[0] & 0x0F)) {
2491 if (MfSniffLogic(receivedResponse
, Demod
.len
, Demod
.parityBits
, Demod
.bitCount
, FALSE
)) break;
2493 // And ready to receive another response.
2494 memset(&Demod
, 0, sizeof(Demod
));
2495 Demod
.output
= receivedResponse
;
2496 Demod
.state
= DEMOD_UNSYNCD
;
2498 /* And also reset the uart code */
2499 Uart
.state
= STATE_UNSYNCD
;
2503 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
2508 DbpString("COMMAND FINISHED");
2511 FpgaDisableSscDma();
2514 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);