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
;
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_tracelen(void) {
74 void iso14a_set_tracing(int enable
) {
77 void iso14a_set_timeout(uint32_t timeout
) {
78 iso14a_timeout
= timeout
;
81 //-----------------------------------------------------------------------------
82 // Generate the parity value for a byte sequence
84 //-----------------------------------------------------------------------------
85 byte_t
oddparity (const byte_t bt
)
87 return OddByteParity
[bt
];
90 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
95 // Generate the encrypted data
96 for (i
= 0; i
< iLen
; i
++) {
97 // Save the encrypted parity bit
98 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
103 void AppendCrc14443a(uint8_t* data
, int len
)
105 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
108 // The function LogTrace() is also used by the iClass implementation in iClass.c
109 int RAMFUNC
LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
111 // Return when trace is full
112 if (traceLen
>= TRACE_SIZE
) return FALSE
;
114 // Trace the random, i'm curious
115 rsamples
+= iSamples
;
116 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
117 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
118 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
119 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
121 trace
[traceLen
- 1] |= 0x80;
123 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
124 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
125 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
126 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
127 trace
[traceLen
++] = iLen
;
128 memcpy(trace
+ traceLen
, btBytes
, iLen
);
133 //-----------------------------------------------------------------------------
134 // The software UART that receives commands from the reader, and its state
136 //-----------------------------------------------------------------------------
139 static RAMFUNC
int MillerDecoding(int bit
)
144 if(!Uart
.bitBuffer
) {
145 Uart
.bitBuffer
= bit
^ 0xFF0;
149 Uart
.bitBuffer
<<= 4;
150 Uart
.bitBuffer
^= bit
;
155 if(Uart
.state
!= STATE_UNSYNCD
) {
158 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
164 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
170 if(bit
!= bitright
) { bit
= bitright
; }
172 if(Uart
.posCnt
== 1) {
173 // measurement first half bitperiod
175 Uart
.drop
= DROP_FIRST_HALF
;
179 // measurement second half bitperiod
180 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
181 Uart
.drop
= DROP_SECOND_HALF
;
184 // measured a drop in first and second half
185 // which should not be possible
186 Uart
.state
= STATE_ERROR_WAIT
;
193 case STATE_START_OF_COMMUNICATION
:
195 if(Uart
.drop
== DROP_SECOND_HALF
) {
196 // error, should not happen in SOC
197 Uart
.state
= STATE_ERROR_WAIT
;
202 Uart
.state
= STATE_MILLER_Z
;
209 if(Uart
.drop
== DROP_NONE
) {
210 // logic '0' followed by sequence Y
211 // end of communication
212 Uart
.state
= STATE_UNSYNCD
;
215 // if(Uart.drop == DROP_FIRST_HALF) {
216 // Uart.state = STATE_MILLER_Z; stay the same
217 // we see a logic '0' }
218 if(Uart
.drop
== DROP_SECOND_HALF
) {
219 // we see a logic '1'
220 Uart
.shiftReg
|= 0x100;
221 Uart
.state
= STATE_MILLER_X
;
227 if(Uart
.drop
== DROP_NONE
) {
228 // sequence Y, we see a '0'
229 Uart
.state
= STATE_MILLER_Y
;
232 if(Uart
.drop
== DROP_FIRST_HALF
) {
233 // Would be STATE_MILLER_Z
234 // but Z does not follow X, so error
235 Uart
.state
= STATE_ERROR_WAIT
;
238 if(Uart
.drop
== DROP_SECOND_HALF
) {
239 // We see a '1' and stay in state X
240 Uart
.shiftReg
|= 0x100;
248 if(Uart
.drop
== DROP_NONE
) {
249 // logic '0' followed by sequence Y
250 // end of communication
251 Uart
.state
= STATE_UNSYNCD
;
254 if(Uart
.drop
== DROP_FIRST_HALF
) {
256 Uart
.state
= STATE_MILLER_Z
;
258 if(Uart
.drop
== DROP_SECOND_HALF
) {
259 // We see a '1' and go to state X
260 Uart
.shiftReg
|= 0x100;
261 Uart
.state
= STATE_MILLER_X
;
265 case STATE_ERROR_WAIT
:
266 // That went wrong. Now wait for at least two bit periods
267 // and try to sync again
268 if(Uart
.drop
== DROP_NONE
) {
270 Uart
.state
= STATE_UNSYNCD
;
275 Uart
.state
= STATE_UNSYNCD
;
280 Uart
.drop
= DROP_NONE
;
282 // should have received at least one whole byte...
283 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
287 if(Uart
.bitCnt
== 9) {
288 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
291 Uart
.parityBits
<<= 1;
292 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
295 // when End of Communication received and
296 // all data bits processed..
303 Uart.output[Uart.byteCnt] = 0xAA;
305 Uart.output[Uart.byteCnt] = error & 0xFF;
307 Uart.output[Uart.byteCnt] = 0xAA;
309 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
311 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
313 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
315 Uart.output[Uart.byteCnt] = 0xAA;
323 bit
= Uart
.bitBuffer
& 0xf0;
327 // should have been high or at least (4 * 128) / fc
328 // according to ISO this should be at least (9 * 128 + 20) / fc
329 if(Uart
.highCnt
== 8) {
330 // we went low, so this could be start of communication
331 // it turns out to be safer to choose a less significant
332 // syncbit... so we check whether the neighbour also represents the drop
333 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
334 Uart
.syncBit
= bit
& 8;
336 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
337 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
338 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
339 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
340 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
341 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
344 // the first half bit period is expected in next sample
349 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
352 Uart
.state
= STATE_START_OF_COMMUNICATION
;
353 Uart
.drop
= DROP_FIRST_HALF
;
364 if(Uart
.highCnt
< 8) {
373 //=============================================================================
374 // ISO 14443 Type A - Manchester
375 //=============================================================================
378 static RAMFUNC
int ManchesterDecoding(int v
)
394 if(Demod
.state
==DEMOD_UNSYNCD
) {
395 Demod
.output
[Demod
.len
] = 0xfa;
398 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
401 Demod
.syncBit
= 0x08;
408 Demod
.syncBit
= 0x04;
415 Demod
.syncBit
= 0x02;
418 if(bit
& 0x01 && Demod
.syncBit
) {
419 Demod
.syncBit
= 0x01;
424 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
425 Demod
.sub
= SUB_FIRST_HALF
;
428 Demod
.parityBits
= 0;
431 if(trigger
) LED_A_OFF();
432 switch(Demod
.syncBit
) {
433 case 0x08: Demod
.samples
= 3; break;
434 case 0x04: Demod
.samples
= 2; break;
435 case 0x02: Demod
.samples
= 1; break;
436 case 0x01: Demod
.samples
= 0; break;
443 //modulation = bit & Demod.syncBit;
444 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
448 if(Demod
.posCount
==0) {
451 Demod
.sub
= SUB_FIRST_HALF
;
454 Demod
.sub
= SUB_NONE
;
459 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
460 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
461 Demod
.state
= DEMOD_ERROR_WAIT
;
462 Demod
.output
[Demod
.len
] = 0xaa;
466 else if(modulation
) {
467 Demod
.sub
= SUB_SECOND_HALF
;
470 switch(Demod
.state
) {
471 case DEMOD_START_OF_COMMUNICATION
:
472 if(Demod
.sub
== SUB_FIRST_HALF
) {
473 Demod
.state
= DEMOD_MANCHESTER_D
;
476 Demod
.output
[Demod
.len
] = 0xab;
477 Demod
.state
= DEMOD_ERROR_WAIT
;
482 case DEMOD_MANCHESTER_D
:
483 case DEMOD_MANCHESTER_E
:
484 if(Demod
.sub
== SUB_FIRST_HALF
) {
486 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
487 Demod
.state
= DEMOD_MANCHESTER_D
;
489 else if(Demod
.sub
== SUB_SECOND_HALF
) {
491 Demod
.shiftReg
>>= 1;
492 Demod
.state
= DEMOD_MANCHESTER_E
;
495 Demod
.state
= DEMOD_MANCHESTER_F
;
499 case DEMOD_MANCHESTER_F
:
500 // Tag response does not need to be a complete byte!
501 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
502 if(Demod
.bitCount
> 0) {
503 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
504 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
506 // No parity bit, so just shift a 0
507 Demod
.parityBits
<<= 1;
510 Demod
.state
= DEMOD_UNSYNCD
;
514 Demod
.output
[Demod
.len
] = 0xad;
515 Demod
.state
= DEMOD_ERROR_WAIT
;
520 case DEMOD_ERROR_WAIT
:
521 Demod
.state
= DEMOD_UNSYNCD
;
525 Demod
.output
[Demod
.len
] = 0xdd;
526 Demod
.state
= DEMOD_UNSYNCD
;
530 if(Demod
.bitCount
>=9) {
531 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
534 Demod
.parityBits
<<= 1;
535 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
542 Demod.output[Demod.len] = 0xBB;
544 Demod.output[Demod.len] = error & 0xFF;
546 Demod.output[Demod.len] = 0xBB;
548 Demod.output[Demod.len] = bit & 0xFF;
550 Demod.output[Demod.len] = Demod.buffer & 0xFF;
552 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
554 Demod.output[Demod.len] = 0xBB;
561 } // end (state != UNSYNCED)
566 //=============================================================================
567 // Finally, a `sniffer' for ISO 14443 Type A
568 // Both sides of communication!
569 //=============================================================================
571 //-----------------------------------------------------------------------------
572 // Record the sequence of commands sent by the reader to the tag, with
573 // triggering so that we start recording at the point that the tag is moved
575 //-----------------------------------------------------------------------------
576 void RAMFUNC
SnoopIso14443a(uint8_t param
) {
578 // bit 0 - trigger from first card answer
579 // bit 1 - trigger from first reader 7-bit request
584 memset(trace
, 0x44, TRACE_SIZE
);
586 // We won't start recording the frames that we acquire until we trigger;
587 // a good trigger condition to get started is probably when we see a
588 // response from the tag.
589 // triggered == FALSE -- to wait first for card
590 int triggered
= !(param
& 0x03);
592 // The command (reader -> tag) that we're receiving.
593 // The length of a received command will in most cases be no more than 18 bytes.
594 // So 32 should be enough!
595 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
596 // The response (tag -> reader) that we're receiving.
597 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
599 // As we receive stuff, we copy it from receivedCmd or receivedResponse
600 // into trace, along with its length and other annotations.
601 //uint8_t *trace = (uint8_t *)BigBuf;
603 // The DMA buffer, used to stream samples from the FPGA
604 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
605 int8_t *data
= dmaBuf
;
609 // Set up the demodulator for tag -> reader responses.
610 Demod
.output
= receivedResponse
;
612 Demod
.state
= DEMOD_UNSYNCD
;
614 // Set up the demodulator for the reader -> tag commands
615 memset(&Uart
, 0, sizeof(Uart
));
616 Uart
.output
= receivedCmd
;
617 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
618 Uart
.state
= STATE_UNSYNCD
;
620 // Setup for the DMA.
622 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
624 // And put the FPGA in the appropriate mode
625 // Signal field is off with the appropriate LED
627 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
628 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
630 // Count of samples received so far, so that we can include timing
631 // information in the trace buffer.
633 // And now we loop, receiving samples.
636 DbpString("cancelled by button");
643 int register readBufDataP
= data
- dmaBuf
;
644 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
645 if (readBufDataP
<= dmaBufDataP
){
646 dataLen
= dmaBufDataP
- readBufDataP
;
648 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
650 // test for length of buffer
651 if(dataLen
> maxDataLen
) {
652 maxDataLen
= dataLen
;
654 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
658 if(dataLen
< 1) continue;
660 // primary buffer was stopped( <-- we lost data!
661 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
662 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
663 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
665 // secondary buffer sets as primary, secondary buffer was stopped
666 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
667 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
668 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
674 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
677 // check - if there is a short 7bit request from reader
678 if ((!triggered
) && (param
& 0x02) && (Uart
.byteCnt
== 1) && (Uart
.bitCnt
= 9)) triggered
= TRUE
;
681 if (!LogTrace(receivedCmd
, Uart
.byteCnt
, 0 - Uart
.samples
, Uart
.parityBits
, TRUE
)) break;
683 /* And ready to receive another command. */
684 Uart
.state
= STATE_UNSYNCD
;
685 /* And also reset the demod code, which might have been */
686 /* false-triggered by the commands from the reader. */
687 Demod
.state
= DEMOD_UNSYNCD
;
691 if(ManchesterDecoding(data
[0] & 0x0F)) {
694 if (!LogTrace(receivedResponse
, Demod
.len
, 0 - Demod
.samples
, Demod
.parityBits
, FALSE
)) break;
696 if ((!triggered
) && (param
& 0x01)) triggered
= TRUE
;
698 // And ready to receive another response.
699 memset(&Demod
, 0, sizeof(Demod
));
700 Demod
.output
= receivedResponse
;
701 Demod
.state
= DEMOD_UNSYNCD
;
706 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
711 DbpString("COMMAND FINISHED");
714 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
715 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
);
716 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
720 //-----------------------------------------------------------------------------
721 // Prepare tag messages
722 //-----------------------------------------------------------------------------
723 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
729 // Correction bit, might be removed when not needed
734 ToSendStuffBit(1); // 1
740 ToSend
[++ToSendMax
] = SEC_D
;
742 for(i
= 0; i
< len
; i
++) {
747 for(j
= 0; j
< 8; j
++) {
749 ToSend
[++ToSendMax
] = SEC_D
;
751 ToSend
[++ToSendMax
] = SEC_E
;
756 // Get the parity bit
757 if ((dwParity
>> i
) & 0x01) {
758 ToSend
[++ToSendMax
] = SEC_D
;
760 ToSend
[++ToSendMax
] = SEC_E
;
765 ToSend
[++ToSendMax
] = SEC_F
;
767 // Convert from last byte pos to length
771 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
772 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
775 //-----------------------------------------------------------------------------
776 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
777 //-----------------------------------------------------------------------------
778 static void CodeStrangeAnswerAsTag()
784 // Correction bit, might be removed when not needed
789 ToSendStuffBit(1); // 1
795 ToSend
[++ToSendMax
] = SEC_D
;
798 ToSend
[++ToSendMax
] = SEC_E
;
801 ToSend
[++ToSendMax
] = SEC_E
;
804 ToSend
[++ToSendMax
] = SEC_D
;
807 ToSend
[++ToSendMax
] = SEC_F
;
809 // Flush the buffer in FPGA!!
810 for(i
= 0; i
< 5; i
++) {
811 ToSend
[++ToSendMax
] = SEC_F
;
814 // Convert from last byte pos to length
818 static void Code4bitAnswerAsTag(uint8_t cmd
)
824 // Correction bit, might be removed when not needed
829 ToSendStuffBit(1); // 1
835 ToSend
[++ToSendMax
] = SEC_D
;
838 for(i
= 0; i
< 4; i
++) {
840 ToSend
[++ToSendMax
] = SEC_D
;
842 ToSend
[++ToSendMax
] = SEC_E
;
848 ToSend
[++ToSendMax
] = SEC_F
;
850 // Flush the buffer in FPGA!!
851 for(i
= 0; i
< 5; i
++) {
852 ToSend
[++ToSendMax
] = SEC_F
;
855 // Convert from last byte pos to length
859 //-----------------------------------------------------------------------------
860 // Wait for commands from reader
861 // Stop when button is pressed
862 // Or return TRUE when command is captured
863 //-----------------------------------------------------------------------------
864 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
866 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
867 // only, since we are receiving, not transmitting).
868 // Signal field is off with the appropriate LED
870 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
872 // Now run a `software UART' on the stream of incoming samples.
873 Uart
.output
= received
;
874 Uart
.byteCntMax
= maxLen
;
875 Uart
.state
= STATE_UNSYNCD
;
880 if(BUTTON_PRESS()) return FALSE
;
882 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
883 AT91C_BASE_SSC
->SSC_THR
= 0x00;
885 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
886 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
887 if(MillerDecoding((b
& 0xf0) >> 4)) {
891 if(MillerDecoding(b
& 0x0f)) {
898 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
900 //-----------------------------------------------------------------------------
901 // Main loop of simulated tag: receive commands from reader, decide what
902 // response to send, and send it.
903 //-----------------------------------------------------------------------------
904 void SimulateIso14443aTag(int tagType
, int uid_1st
, int uid_2nd
)
906 // Enable and clear the trace
909 memset(trace
, 0x44, TRACE_SIZE
);
911 // This function contains the tag emulation
914 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
915 uint8_t response1
[2];
918 case 1: { // MIFARE Classic
919 // Says: I am Mifare 1k - original line
924 case 2: { // MIFARE Ultralight
925 // Says: I am a stupid memory tag, no crypto
930 case 3: { // MIFARE DESFire
931 // Says: I am a DESFire tag, ph33r me
936 case 4: { // ISO/IEC 14443-4
937 // Says: I am a javacard (JCOP)
943 Dbprintf("Error: unkown tagtype (%d)",tagType
);
948 // The second response contains the (mandatory) first 24 bits of the UID
949 uint8_t response2
[5];
951 // Check if the uid uses the (optional) part
952 uint8_t response2a
[5];
955 num_to_bytes(uid_1st
,3,response2
+1);
956 num_to_bytes(uid_2nd
,4,response2a
);
957 response2a
[4] = response2a
[0] ^ response2a
[1] ^ response2a
[2] ^ response2a
[3];
959 // Configure the ATQA and SAK accordingly
960 response1
[0] |= 0x40;
963 num_to_bytes(uid_1st
,4,response2
);
964 // Configure the ATQA and SAK accordingly
965 response1
[0] &= 0xBF;
969 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
970 response2
[4] = response2
[0] ^ response2
[1] ^ response2
[2] ^ response2
[3];
972 // Prepare the mandatory SAK (for 4 and 7 byte UID)
973 uint8_t response3
[3];
975 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
977 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
978 uint8_t response3a
[3];
979 response3a
[0] = sak
& 0xFB;
980 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
982 uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
983 uint8_t response6
[] = { 0x03, 0x3B, 0x00, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
984 ComputeCrc14443(CRC_14443_A
, response6
, 3, &response6
[3], &response6
[4]);
989 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
991 // 144 data bits (18 * 8)
994 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
995 // 1 just for the case
999 // 166 bytes, since every bit that needs to be send costs us a byte
1002 // Respond with card type
1003 uint8_t *resp1
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
1006 // Anticollision cascade1 - respond with uid
1007 uint8_t *resp2
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ 166);
1010 // Anticollision cascade2 - respond with 2nd half of uid if asked
1011 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1012 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1015 // Acknowledge select - cascade 1
1016 uint8_t *resp3
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*2));
1019 // Acknowledge select - cascade 2
1020 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*3));
1023 // Response to a read request - not implemented atm
1024 uint8_t *resp4
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*4));
1027 // Authenticate response - nonce
1028 uint8_t *resp5
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*5));
1031 // Authenticate response - nonce
1032 uint8_t *resp6
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*6));
1035 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
1038 // To control where we are in the protocol
1042 // Just to allow some checks
1047 uint8_t* respdata
= NULL
;
1049 uint8_t nack
= 0x04;
1051 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1053 // Prepare the responses of the anticollision phase
1054 // there will be not enough time to do this at the moment the reader sends it REQA
1056 // Answer to request
1057 CodeIso14443aAsTag(response1
, sizeof(response1
));
1058 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1060 // Send our UID (cascade 1)
1061 CodeIso14443aAsTag(response2
, sizeof(response2
));
1062 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1064 // Answer to select (cascade1)
1065 CodeIso14443aAsTag(response3
, sizeof(response3
));
1066 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1068 // Send the cascade 2 2nd part of the uid
1069 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1070 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1072 // Answer to select (cascade 2)
1073 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1074 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1076 // Strange answer is an example of rare message size (3 bits)
1077 CodeStrangeAnswerAsTag();
1078 memcpy(resp4
, ToSend
, ToSendMax
); resp4Len
= ToSendMax
;
1080 // Authentication answer (random nonce)
1081 CodeIso14443aAsTag(response5
, sizeof(response5
));
1082 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1084 // dummy ATS (pseudo-ATR), answer to RATS
1085 CodeIso14443aAsTag(response6
, sizeof(response6
));
1086 memcpy(resp6
, ToSend
, ToSendMax
); resp6Len
= ToSendMax
;
1088 // We need to listen to the high-frequency, peak-detected path.
1089 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1097 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, RECV_CMD_SIZE
)) {
1098 DbpString("button press");
1101 // 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
1102 // Okay, look at the command now.
1104 if(receivedCmd
[0] == 0x26) { // Received a REQUEST
1105 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1106 respdata
= response1
;
1107 respsize
= sizeof(response1
);
1108 } else if(receivedCmd
[0] == 0x52) { // Received a WAKEUP
1109 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1110 respdata
= response1
;
1111 respsize
= sizeof(response1
);
1112 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // Received request for UID (cascade 1)
1113 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1114 respdata
= response2
;
1115 respsize
= sizeof(response2
);
1116 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x95) { // Received request for UID (cascade 2)
1117 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1118 respdata
= response2a
;
1119 respsize
= sizeof(response2a
);
1120 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x93) { // Received a SELECT (cascade 1)
1121 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1122 respdata
= response3
;
1123 respsize
= sizeof(response3
);
1124 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x95) { // Received a SELECT (cascade 2)
1125 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1126 respdata
= response3a
;
1127 respsize
= sizeof(response3a
);
1128 } else if(receivedCmd
[0] == 0x30) { // Received a (plain) READ
1129 resp
= resp4
; respLen
= resp4Len
; order
= 4; // Do nothing
1130 Dbprintf("Read request from reader: %x %x",receivedCmd
[0],receivedCmd
[1]);
1132 respsize
= sizeof(nack
); // 4-bit answer
1133 } else if(receivedCmd
[0] == 0x50) { // Received a HALT
1134 DbpString("Reader requested we HALT!:");
1136 resp
= resp1
; respLen
= 0; order
= 0;
1139 } else if(receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61) { // Received an authentication request
1140 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1141 respdata
= response5
;
1142 respsize
= sizeof(response5
);
1143 } else if(receivedCmd
[0] == 0xE0) { // Received a RATS request
1144 resp
= resp6
; respLen
= resp6Len
; order
= 70;
1145 respdata
= response6
;
1146 respsize
= sizeof(response6
);
1148 // Never seen this command before
1149 Dbprintf("Received (len=%d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",
1151 receivedCmd
[0], receivedCmd
[1], receivedCmd
[2],
1152 receivedCmd
[3], receivedCmd
[4], receivedCmd
[5],
1153 receivedCmd
[6], receivedCmd
[7], receivedCmd
[8]);
1155 resp
= resp1
; respLen
= 0; order
= 0;
1160 // Count number of wakeups received after a halt
1161 if(order
== 6 && lastorder
== 5) { happened
++; }
1163 // Count number of other messages after a halt
1164 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1166 // Look at last parity bit to determine timing of answer
1167 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1168 // 1236, so correction bit needed
1172 if(cmdsRecvd
> 999) {
1173 DbpString("1000 commands later...");
1180 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1184 LogTrace(receivedCmd
,len
, 0, Uart
.parityBits
, TRUE
);
1185 if (respdata
!= NULL
) {
1186 LogTrace(respdata
,respsize
, 0, SwapBits(GetParity(respdata
,respsize
),respsize
), FALSE
);
1188 if(traceLen
> TRACE_SIZE
) {
1189 DbpString("Trace full");
1194 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1197 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1201 //-----------------------------------------------------------------------------
1202 // Transmit the command (to the tag) that was placed in ToSend[].
1203 //-----------------------------------------------------------------------------
1204 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1208 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1214 for(c
= 0; c
< *wait
;) {
1215 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1216 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1219 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1220 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1228 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1229 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1235 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1236 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1241 if (samples
) *samples
= (c
+ *wait
) << 3;
1244 //-----------------------------------------------------------------------------
1245 // Code a 7-bit command without parity bit
1246 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1247 //-----------------------------------------------------------------------------
1248 void ShortFrameFromReader(const uint8_t bt
)
1256 // Start of Communication (Seq. Z)
1257 ToSend
[++ToSendMax
] = SEC_Z
;
1261 for(j
= 0; j
< 7; j
++) {
1264 ToSend
[++ToSendMax
] = SEC_X
;
1269 ToSend
[++ToSendMax
] = SEC_Z
;
1273 ToSend
[++ToSendMax
] = SEC_Y
;
1280 // End of Communication
1283 ToSend
[++ToSendMax
] = SEC_Z
;
1287 ToSend
[++ToSendMax
] = SEC_Y
;
1291 ToSend
[++ToSendMax
] = SEC_Y
;
1294 ToSend
[++ToSendMax
] = SEC_Y
;
1295 ToSend
[++ToSendMax
] = SEC_Y
;
1296 ToSend
[++ToSendMax
] = SEC_Y
;
1298 // Convert from last character reference to length
1302 //-----------------------------------------------------------------------------
1303 // Prepare reader command to send to FPGA
1305 //-----------------------------------------------------------------------------
1306 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1314 // Start of Communication (Seq. Z)
1315 ToSend
[++ToSendMax
] = SEC_Z
;
1318 // Generate send structure for the data bits
1319 for (i
= 0; i
< len
; i
++) {
1320 // Get the current byte to send
1323 for (j
= 0; j
< 8; j
++) {
1326 ToSend
[++ToSendMax
] = SEC_X
;
1331 ToSend
[++ToSendMax
] = SEC_Z
;
1334 ToSend
[++ToSendMax
] = SEC_Y
;
1341 // Get the parity bit
1342 if ((dwParity
>> i
) & 0x01) {
1344 ToSend
[++ToSendMax
] = SEC_X
;
1349 ToSend
[++ToSendMax
] = SEC_Z
;
1352 ToSend
[++ToSendMax
] = SEC_Y
;
1358 // End of Communication
1361 ToSend
[++ToSendMax
] = SEC_Z
;
1364 ToSend
[++ToSendMax
] = SEC_Y
;
1368 ToSend
[++ToSendMax
] = SEC_Y
;
1371 ToSend
[++ToSendMax
] = SEC_Y
;
1372 ToSend
[++ToSendMax
] = SEC_Y
;
1373 ToSend
[++ToSendMax
] = SEC_Y
;
1375 // Convert from last character reference to length
1379 //-----------------------------------------------------------------------------
1380 // Wait for commands from reader
1381 // Stop when button is pressed (return 1) or field was gone (return 2)
1382 // Or return 0 when command is captured
1383 //-----------------------------------------------------------------------------
1384 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1388 uint32_t timer
= 0, vtime
= 0;
1392 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1393 // only, since we are receiving, not transmitting).
1394 // Signal field is off with the appropriate LED
1396 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1398 // Set ADC to read field strength
1399 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1400 AT91C_BASE_ADC
->ADC_MR
=
1401 ADC_MODE_PRESCALE(32) |
1402 ADC_MODE_STARTUP_TIME(16) |
1403 ADC_MODE_SAMPLE_HOLD_TIME(8);
1404 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1406 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1408 // Now run a 'software UART' on the stream of incoming samples.
1409 Uart
.output
= received
;
1410 Uart
.byteCntMax
= maxLen
;
1411 Uart
.state
= STATE_UNSYNCD
;
1416 if (BUTTON_PRESS()) return 1;
1418 // test if the field exists
1419 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1421 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1422 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1423 if (analogCnt
>= 32) {
1424 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1425 vtime
= GetTickCount();
1426 if (!timer
) timer
= vtime
;
1427 // 50ms no field --> card to idle state
1428 if (vtime
- timer
> 50) return 2;
1430 if (timer
) timer
= 0;
1436 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1437 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1439 // receive and test the miller decoding
1440 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1441 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1442 if(MillerDecoding((b
& 0xf0) >> 4)) {
1443 *len
= Uart
.byteCnt
;
1444 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1447 if(MillerDecoding(b
& 0x0f)) {
1448 *len
= Uart
.byteCnt
;
1449 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1456 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1461 // Modulate Manchester
1462 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1463 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1466 // include correction bit
1468 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1469 // 1236, so correction bit needed
1475 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1476 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1479 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1481 b
= 0xff; // was 0x00
1487 AT91C_BASE_SSC
->SSC_THR
= b
;
1491 if(BUTTON_PRESS()) {
1499 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1500 Code4bitAnswerAsTag(resp
);
1501 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1502 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1506 int EmSend4bit(uint8_t resp
){
1507 return EmSend4bitEx(resp
, 0);
1510 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1511 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1512 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1513 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1517 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1518 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1521 int EmSendCmd(uint8_t *resp
, int respLen
){
1522 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1525 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1526 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1529 //-----------------------------------------------------------------------------
1530 // Wait a certain time for tag response
1531 // If a response is captured return TRUE
1532 // If it takes to long return FALSE
1533 //-----------------------------------------------------------------------------
1534 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1536 // buffer needs to be 512 bytes
1539 // Set FPGA mode to "reader listen mode", no modulation (listen
1540 // only, since we are receiving, not transmitting).
1541 // Signal field is on with the appropriate LED
1543 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1545 // Now get the answer from the card
1546 Demod
.output
= receivedResponse
;
1548 Demod
.state
= DEMOD_UNSYNCD
;
1551 if (elapsed
) *elapsed
= 0;
1557 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1558 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1559 if (elapsed
) (*elapsed
)++;
1561 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1562 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1563 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1564 if(ManchesterDecoding((b
>>4) & 0xf)) {
1565 *samples
= ((c
- 1) << 3) + 4;
1568 if(ManchesterDecoding(b
& 0x0f)) {
1576 void ReaderTransmitShort(const uint8_t* bt
)
1581 ShortFrameFromReader(*bt
);
1584 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1586 // Store reader command in buffer
1587 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1590 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1595 // This is tied to other size changes
1596 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1597 CodeIso14443aAsReaderPar(frame
,len
,par
);
1600 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1604 // Store reader command in buffer
1605 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1609 void ReaderTransmit(uint8_t* frame
, int len
)
1611 // Generate parity and redirect
1612 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1615 int ReaderReceive(uint8_t* receivedAnswer
)
1618 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1619 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1620 if(samples
== 0) return FALSE
;
1624 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1627 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1628 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1629 *parptr
= Demod
.parityBits
;
1630 if(samples
== 0) return FALSE
;
1634 /* performs iso14443a anticolision procedure
1635 * fills the uid pointer unless NULL
1636 * fills resp_data unless NULL */
1637 int iso14443a_select_card(uint8_t * uid_ptr
, iso14a_card_select_t
* resp_data
, uint32_t * cuid_ptr
) {
1638 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1639 uint8_t sel_all
[] = { 0x93,0x20 };
1640 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1641 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1643 uint8_t* resp
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1645 uint8_t sak
= 0x04; // cascade uid
1646 int cascade_level
= 0;
1651 memset(uid_ptr
, 0, 8);
1653 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1654 ReaderTransmitShort(wupa
);
1656 if(!ReaderReceive(resp
)) return 0;
1659 memcpy(resp_data
->atqa
, resp
, 2);
1661 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1662 // which case we need to make a cascade 2 request and select - this is a long UID
1663 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1664 for(; sak
& 0x04; cascade_level
++)
1666 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1667 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1670 ReaderTransmit(sel_all
,sizeof(sel_all
));
1671 if (!ReaderReceive(resp
)) return 0;
1672 if(uid_ptr
) memcpy(uid_ptr
+ cascade_level
*4, resp
, 4);
1674 // calculate crypto UID
1675 if(cuid_ptr
) *cuid_ptr
= bytes_to_num(resp
, 4);
1677 // Construct SELECT UID command
1678 memcpy(sel_uid
+2,resp
,5);
1679 AppendCrc14443a(sel_uid
,7);
1680 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1683 if (!ReaderReceive(resp
)) return 0;
1687 resp_data
->sak
= sak
;
1688 resp_data
->ats_len
= 0;
1690 //-- this byte not UID, it CT. http://www.nxp.com/documents/application_note/AN10927.pdf page 3
1691 if (uid_ptr
[0] == 0x88) {
1692 memcpy(uid_ptr
, uid_ptr
+ 1, 7);
1696 if( (sak
& 0x20) == 0)
1697 return 2; // non iso14443a compliant tag
1699 // Request for answer to select
1700 if(resp_data
) { // JCOP cards - if reader sent RATS then there is no MIFARE session at all!!!
1701 AppendCrc14443a(rats
, 2);
1702 ReaderTransmit(rats
, sizeof(rats
));
1704 if (!(len
= ReaderReceive(resp
))) return 0;
1706 memcpy(resp_data
->ats
, resp
, sizeof(resp_data
->ats
));
1707 resp_data
->ats_len
= len
;
1710 // reset the PCB block number
1711 iso14_pcb_blocknum
= 0;
1716 void iso14443a_setup() {
1719 // Start from off (no field generated)
1720 // Signal field is off with the appropriate LED
1722 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1725 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1727 // Now give it time to spin up.
1728 // Signal field is on with the appropriate LED
1730 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1733 iso14a_timeout
= 2048; //default
1736 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1737 uint8_t real_cmd
[cmd_len
+4];
1738 real_cmd
[0] = 0x0a; //I-Block
1739 // put block number into the PCB
1740 real_cmd
[0] |= iso14_pcb_blocknum
;
1741 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1742 memcpy(real_cmd
+2, cmd
, cmd_len
);
1743 AppendCrc14443a(real_cmd
,cmd_len
+2);
1745 ReaderTransmit(real_cmd
, cmd_len
+4);
1746 size_t len
= ReaderReceive(data
);
1747 uint8_t * data_bytes
= (uint8_t *) data
;
1749 return 0; //DATA LINK ERROR
1750 // if we received an I- or R(ACK)-Block with a block number equal to the
1751 // current block number, toggle the current block number
1752 else if (len
>= 4 // PCB+CID+CRC = 4 bytes
1753 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
1754 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1755 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) // equal block numbers
1757 iso14_pcb_blocknum
^= 1;
1763 //-----------------------------------------------------------------------------
1764 // Read an ISO 14443a tag. Send out commands and store answers.
1766 //-----------------------------------------------------------------------------
1767 void ReaderIso14443a(UsbCommand
* c
, UsbCommand
* ack
)
1769 iso14a_command_t param
= c
->arg
[0];
1770 uint8_t * cmd
= c
->d
.asBytes
;
1771 size_t len
= c
->arg
[1];
1773 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(1);
1775 if(param
& ISO14A_CONNECT
) {
1777 ack
->arg
[0] = iso14443a_select_card(ack
->d
.asBytes
, (iso14a_card_select_t
*) (ack
->d
.asBytes
+12), NULL
);
1778 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1781 if(param
& ISO14A_SET_TIMEOUT
) {
1782 iso14a_timeout
= c
->arg
[2];
1785 if(param
& ISO14A_SET_TIMEOUT
) {
1786 iso14a_timeout
= c
->arg
[2];
1789 if(param
& ISO14A_APDU
) {
1790 ack
->arg
[0] = iso14_apdu(cmd
, len
, ack
->d
.asBytes
);
1791 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1794 if(param
& ISO14A_RAW
) {
1795 if(param
& ISO14A_APPEND_CRC
) {
1796 AppendCrc14443a(cmd
,len
);
1799 ReaderTransmit(cmd
,len
);
1800 ack
->arg
[0] = ReaderReceive(ack
->d
.asBytes
);
1801 UsbSendPacket((void *)ack
, sizeof(UsbCommand
));
1804 if(param
& ISO14A_REQUEST_TRIGGER
) iso14a_set_trigger(0);
1806 if(param
& ISO14A_NO_DISCONNECT
)
1809 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1813 //-----------------------------------------------------------------------------
1814 // Read an ISO 14443a tag. Send out commands and store answers.
1816 //-----------------------------------------------------------------------------
1817 void ReaderMifare(uint32_t parameter
)
1820 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1821 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1823 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + 3560); // was 3560 - tied to other size changes
1836 //byte_t par_mask = 0xff;
1843 byte_t nt
[4] = {0,0,0,0};
1844 byte_t nt_attacked
[4], nt_noattack
[4];
1845 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1846 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1847 num_to_bytes(parameter
, 4, nt_noattack
);
1848 int isOK
= 0, isNULL
= 0;
1853 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1855 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1858 // Test if the action was cancelled
1859 if(BUTTON_PRESS()) {
1863 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1865 // Transmit MIFARE_CLASSIC_AUTH
1866 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1868 // Receive the (16 bit) "random" nonce
1869 if (!ReaderReceive(receivedAnswer
)) continue;
1870 memcpy(nt
, receivedAnswer
, 4);
1872 // Transmit reader nonce and reader answer
1873 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1875 // Receive 4 bit answer
1876 if (ReaderReceive(receivedAnswer
))
1878 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1880 isNULL
= !(nt_attacked
[0] == 0) && (nt_attacked
[1] == 0) && (nt_attacked
[2] == 0) && (nt_attacked
[3] == 0);
1881 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1886 memcpy(nt_attacked
, nt
, 4);
1888 par_low
= par
& 0x07;
1892 if(led_on
) LED_B_ON(); else LED_B_OFF();
1893 par_list
[nt_diff
] = par
;
1894 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1896 // Test if the information is complete
1897 if (nt_diff
== 0x07) {
1902 nt_diff
= (nt_diff
+ 1) & 0x07;
1903 mf_nr_ar
[3] = nt_diff
<< 5;
1910 par
= (((par
>> 3) + 1) << 3) | par_low
;
1915 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1916 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1917 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1919 UsbCommand ack
= {CMD_ACK
, {isOK
, 0, 0}};
1920 memcpy(ack
.d
.asBytes
+ 0, uid
, 4);
1921 memcpy(ack
.d
.asBytes
+ 4, nt
, 4);
1922 memcpy(ack
.d
.asBytes
+ 8, par_list
, 8);
1923 memcpy(ack
.d
.asBytes
+ 16, ks_list
, 8);
1926 UsbSendPacket((uint8_t *)&ack
, sizeof(UsbCommand
));
1930 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1934 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1938 //-----------------------------------------------------------------------------
1939 // MIFARE 1K simulate.
1941 //-----------------------------------------------------------------------------
1942 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
1944 int cardSTATE
= MFEMUL_NOFIELD
;
1946 int vHf
= 0; // in mV
1947 //int nextCycleTimeout = 0;
1949 // uint32_t timer = 0;
1950 uint32_t selTimer
= 0;
1951 uint32_t authTimer
= 0;
1954 uint8_t cardWRBL
= 0;
1955 uint8_t cardAUTHSC
= 0;
1956 uint8_t cardAUTHKEY
= 0xff; // no authentication
1957 //uint32_t cardRn = 0;
1958 uint32_t cardRr
= 0;
1960 //uint32_t rn_enc = 0;
1962 uint32_t cardINTREG
= 0;
1963 uint8_t cardINTBLOCK
= 0;
1964 struct Crypto1State mpcs
= {0, 0};
1965 struct Crypto1State
*pcs
;
1968 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
1969 uint8_t *response
= eml_get_bigbufptr_sendbuf();
1971 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
1973 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
1974 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
1976 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
1977 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
1979 static uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
1980 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
1981 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
1987 // Authenticate response - nonce
1988 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
1990 // get UID from emul memory
1991 emlGetMemBt(receivedCmd
, 7, 1);
1992 _7BUID
= !(receivedCmd
[0] == 0x00);
1993 if (!_7BUID
) { // ---------- 4BUID
1996 emlGetMemBt(rUIDBCC1
, 0, 4);
1997 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
1998 } else { // ---------- 7BUID
2002 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2003 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2004 emlGetMemBt(rUIDBCC2
, 3, 4);
2005 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2008 // -------------------------------------- test area
2010 // -------------------------------------- END test area
2011 // start mkseconds counter
2014 // We need to listen to the high-frequency, peak-detected path.
2015 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2018 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2021 if (MF_DBGLEVEL
>= 1) Dbprintf("Started. 7buid=%d", _7BUID
);
2022 // calibrate mkseconds counter
2027 if(BUTTON_PRESS()) {
2031 // find reader field
2032 // Vref = 3300mV, and an 10:1 voltage divider on the input
2033 // can measure voltages up to 33000 mV
2034 if (cardSTATE
== MFEMUL_NOFIELD
) {
2035 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2036 if (vHf
> MF_MINFIELDV
) {
2037 cardSTATE_TO_IDLE();
2042 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2043 res
= EmGetCmd(receivedCmd
, &len
, RECV_CMD_SIZE
); // (+ nextCycleTimeout)
2045 cardSTATE
= MFEMUL_NOFIELD
;
2052 //nextCycleTimeout = 0;
2054 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2056 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2057 // REQ or WUP request in ANY state and WUP in HALTED state
2058 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2059 selTimer
= GetTickCount();
2060 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2061 cardSTATE
= MFEMUL_SELECT1
;
2063 // init crypto block
2066 crypto1_destroy(pcs
);
2071 switch (cardSTATE
) {
2072 case MFEMUL_NOFIELD
:{
2075 case MFEMUL_HALTED
:{
2081 case MFEMUL_SELECT1
:{
2083 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2084 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2090 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2092 EmSendCmd(rSAK
, sizeof(rSAK
));
2094 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2096 cuid
= bytes_to_num(rUIDBCC1
, 4);
2098 cardSTATE
= MFEMUL_WORK
;
2100 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2103 cardSTATE
= MFEMUL_SELECT2
;
2110 case MFEMUL_SELECT2
:{
2113 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2114 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2120 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2121 EmSendCmd(rSAK
, sizeof(rSAK
));
2123 cuid
= bytes_to_num(rUIDBCC2
, 4);
2124 cardSTATE
= MFEMUL_WORK
;
2126 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2130 // i guess there is a command). go into the work state.
2131 if (len
!= 4) break;
2132 cardSTATE
= MFEMUL_WORK
;
2138 //rn_enc = bytes_to_num(receivedCmd, 4);
2139 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2140 cardRr
= bytes_to_num(&receivedCmd
[4], 4) ^ crypto1_word(pcs
, 0, 0);
2142 if (cardRr
!= prng_successor(nonce
, 64)){
2143 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr
, prng_successor(nonce
, 64));
2144 cardSTATE_TO_IDLE();
2147 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2148 num_to_bytes(ans
, 4, rAUTH_AT
);
2150 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2151 cardSTATE
= MFEMUL_AUTH2
;
2153 cardSTATE_TO_IDLE();
2155 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2159 cardSTATE
= MFEMUL_WORK
;
2160 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2164 lbWORK
: if (len
== 0) break;
2166 if (cardAUTHKEY
== 0xff) {
2167 // first authentication
2168 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2169 authTimer
= GetTickCount();
2171 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2172 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2175 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2176 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2177 num_to_bytes(nonce
, 4, rAUTH_AT
);
2178 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2181 // last working revision
2182 // EmSendCmd14443aRaw(resp1, resp1Len, 0);
2183 // LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2185 cardSTATE
= MFEMUL_AUTH1
;
2186 //nextCycleTimeout = 10;
2191 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2193 // nested authentication
2194 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2195 authTimer
= GetTickCount();
2197 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2198 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2201 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2202 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2203 num_to_bytes(ans
, 4, rAUTH_AT
);
2204 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2207 cardSTATE
= MFEMUL_AUTH1
;
2208 //nextCycleTimeout = 10;
2213 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2214 // BUT... ACK --> NACK
2215 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2216 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2220 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2221 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2222 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2227 if (len
== 4 && receivedCmd
[0] == 0x30) {
2228 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2229 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2232 emlGetMem(response
, receivedCmd
[1], 1);
2233 AppendCrc14443a(response
, 16);
2234 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2235 EmSendCmdPar(response
, 18, par
);
2240 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2241 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2242 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2245 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2246 //nextCycleTimeout = 50;
2247 cardSTATE
= MFEMUL_WRITEBL2
;
2248 cardWRBL
= receivedCmd
[1];
2252 // works with cardINTREG
2254 // increment, decrement, restore
2255 if (len
== 4 && (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2)) {
2256 if (receivedCmd
[1] >= 16 * 4 ||
2257 receivedCmd
[1] / 4 != cardAUTHSC
||
2258 emlCheckValBl(receivedCmd
[1])) {
2259 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2262 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2263 if (receivedCmd
[0] == 0xC1)
2264 cardSTATE
= MFEMUL_INTREG_INC
;
2265 if (receivedCmd
[0] == 0xC0)
2266 cardSTATE
= MFEMUL_INTREG_DEC
;
2267 if (receivedCmd
[0] == 0xC2)
2268 cardSTATE
= MFEMUL_INTREG_REST
;
2269 cardWRBL
= receivedCmd
[1];
2276 if (len
== 4 && receivedCmd
[0] == 0xB0) {
2277 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2278 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2282 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2283 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2285 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2291 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2294 cardSTATE
= MFEMUL_HALTED
;
2295 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2299 // command not allowed
2301 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2308 case MFEMUL_WRITEBL2
:{
2310 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2311 emlSetMem(receivedCmd
, cardWRBL
, 1);
2312 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2313 cardSTATE
= MFEMUL_WORK
;
2316 cardSTATE_TO_IDLE();
2322 case MFEMUL_INTREG_INC
:{
2323 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2324 memcpy(&ans
, receivedCmd
, 4);
2325 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2326 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2327 cardSTATE_TO_IDLE();
2330 cardINTREG
= cardINTREG
+ ans
;
2331 cardSTATE
= MFEMUL_WORK
;
2334 case MFEMUL_INTREG_DEC
:{
2335 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2336 memcpy(&ans
, receivedCmd
, 4);
2337 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2338 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2339 cardSTATE_TO_IDLE();
2342 cardINTREG
= cardINTREG
- ans
;
2343 cardSTATE
= MFEMUL_WORK
;
2346 case MFEMUL_INTREG_REST
:{
2347 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2348 memcpy(&ans
, receivedCmd
, 4);
2349 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2350 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2351 cardSTATE_TO_IDLE();
2354 cardSTATE
= MFEMUL_WORK
;
2360 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2363 // add trace trailer
2364 memset(rAUTH_NT
, 0x44, 4);
2365 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2367 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);
2370 //-----------------------------------------------------------------------------
2373 //-----------------------------------------------------------------------------
2374 void RAMFUNC
SniffMifare(uint8_t param
) {
2376 // bit 0 - trigger from first card answer
2377 // bit 1 - trigger from first reader 7-bit request
2379 // C(red) A(yellow) B(green)
2381 // init trace buffer
2383 memset(trace
, 0x44, TRACE_SIZE
);
2385 // The command (reader -> tag) that we're receiving.
2386 // The length of a received command will in most cases be no more than 18 bytes.
2387 // So 32 should be enough!
2388 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
2389 // The response (tag -> reader) that we're receiving.
2390 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
2392 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2393 // into trace, along with its length and other annotations.
2394 //uint8_t *trace = (uint8_t *)BigBuf;
2396 // The DMA buffer, used to stream samples from the FPGA
2397 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
2398 int8_t *data
= dmaBuf
;
2402 // Set up the demodulator for tag -> reader responses.
2403 Demod
.output
= receivedResponse
;
2405 Demod
.state
= DEMOD_UNSYNCD
;
2407 // Set up the demodulator for the reader -> tag commands
2408 memset(&Uart
, 0, sizeof(Uart
));
2409 Uart
.output
= receivedCmd
;
2410 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
2411 Uart
.state
= STATE_UNSYNCD
;
2413 // Setup for the DMA.
2415 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
2417 // And put the FPGA in the appropriate mode
2418 // Signal field is off with the appropriate LED
2420 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
2421 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2425 int sniffCounter
= 0;
2427 // And now we loop, receiving samples.
2429 if(BUTTON_PRESS()) {
2430 DbpString("cancelled by button");
2437 if (++sniffCounter
> 65) {
2438 if (MfSniffSend(2000)) {
2444 int register readBufDataP
= data
- dmaBuf
;
2445 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
2446 if (readBufDataP
<= dmaBufDataP
){
2447 dataLen
= dmaBufDataP
- readBufDataP
;
2449 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
2451 // test for length of buffer
2452 if(dataLen
> maxDataLen
) {
2453 maxDataLen
= dataLen
;
2455 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
2459 if(dataLen
< 1) continue;
2461 // primary buffer was stopped( <-- we lost data!
2462 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
2463 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
2464 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
2465 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen
); // temporary
2467 // secondary buffer sets as primary, secondary buffer was stopped
2468 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
2469 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
2470 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
2475 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
2477 // check - if there is a short 7bit request from reader
2478 if (MfSniffLogic(receivedCmd
, Uart
.byteCnt
, Uart
.parityBits
, Uart
.bitCnt
, TRUE
)) break;
2480 /* And ready to receive another command. */
2481 Uart
.state
= STATE_UNSYNCD
;
2483 /* And also reset the demod code */
2484 Demod
.state
= DEMOD_UNSYNCD
;
2487 if(ManchesterDecoding(data
[0] & 0x0F)) {
2490 if (MfSniffLogic(receivedResponse
, Demod
.len
, Demod
.parityBits
, Demod
.bitCount
, FALSE
)) break;
2492 // And ready to receive another response.
2493 memset(&Demod
, 0, sizeof(Demod
));
2494 Demod
.output
= receivedResponse
;
2495 Demod
.state
= DEMOD_UNSYNCD
;
2497 /* And also reset the uart code */
2498 Uart
.state
= STATE_UNSYNCD
;
2502 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
2507 DbpString("COMMAND FINISHED");
2510 FpgaDisableSscDma();
2513 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);