1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
6 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
7 // at your option, any later version. See the LICENSE.txt file for the text of
9 //-----------------------------------------------------------------------------
10 // Routines to support ISO 14443 type A.
11 //-----------------------------------------------------------------------------
13 #include "proxmark3.h"
19 #include "iso14443crc.h"
20 #include "iso14443a.h"
22 #include "mifareutil.h"
24 static uint32_t iso14a_timeout
;
25 uint8_t *trace
= (uint8_t *) BigBuf
+TRACE_OFFSET
;
30 // the block number for the ISO14443-4 PCB
31 static uint8_t iso14_pcb_blocknum
= 0;
33 // CARD TO READER - manchester
34 // Sequence D: 11110000 modulation with subcarrier during first half
35 // Sequence E: 00001111 modulation with subcarrier during second half
36 // Sequence F: 00000000 no modulation with subcarrier
37 // READER TO CARD - miller
38 // Sequence X: 00001100 drop after half a period
39 // Sequence Y: 00000000 no drop
40 // Sequence Z: 11000000 drop at start
48 const uint8_t OddByteParity
[256] = {
49 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
50 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
51 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
52 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
57 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
58 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
59 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
60 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
61 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
62 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
63 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
64 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
68 void iso14a_set_trigger(bool enable
) {
72 void iso14a_clear_trace() {
73 memset(trace
, 0x44, TRACE_SIZE
);
77 void iso14a_set_tracing(bool enable
) {
81 void iso14a_set_timeout(uint32_t timeout
) {
82 iso14a_timeout
= timeout
;
85 //-----------------------------------------------------------------------------
86 // Generate the parity value for a byte sequence
88 //-----------------------------------------------------------------------------
89 byte_t
oddparity (const byte_t bt
)
91 return OddByteParity
[bt
];
94 uint32_t GetParity(const uint8_t * pbtCmd
, int iLen
)
99 // Generate the encrypted data
100 for (i
= 0; i
< iLen
; i
++) {
101 // Save the encrypted parity bit
102 dwPar
|= ((OddByteParity
[pbtCmd
[i
]]) << i
);
107 void AppendCrc14443a(uint8_t* data
, int len
)
109 ComputeCrc14443(CRC_14443_A
,data
,len
,data
+len
,data
+len
+1);
112 // The function LogTrace() is also used by the iClass implementation in iClass.c
113 int RAMFUNC
LogTrace(const uint8_t * btBytes
, int iLen
, int iSamples
, uint32_t dwParity
, int bReader
)
115 // Return when trace is full
116 if (traceLen
>= TRACE_SIZE
) return FALSE
;
118 // Trace the random, i'm curious
119 rsamples
+= iSamples
;
120 trace
[traceLen
++] = ((rsamples
>> 0) & 0xff);
121 trace
[traceLen
++] = ((rsamples
>> 8) & 0xff);
122 trace
[traceLen
++] = ((rsamples
>> 16) & 0xff);
123 trace
[traceLen
++] = ((rsamples
>> 24) & 0xff);
125 trace
[traceLen
- 1] |= 0x80;
127 trace
[traceLen
++] = ((dwParity
>> 0) & 0xff);
128 trace
[traceLen
++] = ((dwParity
>> 8) & 0xff);
129 trace
[traceLen
++] = ((dwParity
>> 16) & 0xff);
130 trace
[traceLen
++] = ((dwParity
>> 24) & 0xff);
131 trace
[traceLen
++] = iLen
;
132 memcpy(trace
+ traceLen
, btBytes
, iLen
);
137 //-----------------------------------------------------------------------------
138 // The software UART that receives commands from the reader, and its state
140 //-----------------------------------------------------------------------------
143 static RAMFUNC
int MillerDecoding(int bit
)
148 if(!Uart
.bitBuffer
) {
149 Uart
.bitBuffer
= bit
^ 0xFF0;
153 Uart
.bitBuffer
<<= 4;
154 Uart
.bitBuffer
^= bit
;
159 if(Uart
.state
!= STATE_UNSYNCD
) {
162 if((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
168 if(((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
174 if(bit
!= bitright
) { bit
= bitright
; }
176 if(Uart
.posCnt
== 1) {
177 // measurement first half bitperiod
179 Uart
.drop
= DROP_FIRST_HALF
;
183 // measurement second half bitperiod
184 if(!bit
& (Uart
.drop
== DROP_NONE
)) {
185 Uart
.drop
= DROP_SECOND_HALF
;
188 // measured a drop in first and second half
189 // which should not be possible
190 Uart
.state
= STATE_ERROR_WAIT
;
197 case STATE_START_OF_COMMUNICATION
:
199 if(Uart
.drop
== DROP_SECOND_HALF
) {
200 // error, should not happen in SOC
201 Uart
.state
= STATE_ERROR_WAIT
;
206 Uart
.state
= STATE_MILLER_Z
;
213 if(Uart
.drop
== DROP_NONE
) {
214 // logic '0' followed by sequence Y
215 // end of communication
216 Uart
.state
= STATE_UNSYNCD
;
219 // if(Uart.drop == DROP_FIRST_HALF) {
220 // Uart.state = STATE_MILLER_Z; stay the same
221 // we see a logic '0' }
222 if(Uart
.drop
== DROP_SECOND_HALF
) {
223 // we see a logic '1'
224 Uart
.shiftReg
|= 0x100;
225 Uart
.state
= STATE_MILLER_X
;
231 if(Uart
.drop
== DROP_NONE
) {
232 // sequence Y, we see a '0'
233 Uart
.state
= STATE_MILLER_Y
;
236 if(Uart
.drop
== DROP_FIRST_HALF
) {
237 // Would be STATE_MILLER_Z
238 // but Z does not follow X, so error
239 Uart
.state
= STATE_ERROR_WAIT
;
242 if(Uart
.drop
== DROP_SECOND_HALF
) {
243 // We see a '1' and stay in state X
244 Uart
.shiftReg
|= 0x100;
252 if(Uart
.drop
== DROP_NONE
) {
253 // logic '0' followed by sequence Y
254 // end of communication
255 Uart
.state
= STATE_UNSYNCD
;
258 if(Uart
.drop
== DROP_FIRST_HALF
) {
260 Uart
.state
= STATE_MILLER_Z
;
262 if(Uart
.drop
== DROP_SECOND_HALF
) {
263 // We see a '1' and go to state X
264 Uart
.shiftReg
|= 0x100;
265 Uart
.state
= STATE_MILLER_X
;
269 case STATE_ERROR_WAIT
:
270 // That went wrong. Now wait for at least two bit periods
271 // and try to sync again
272 if(Uart
.drop
== DROP_NONE
) {
274 Uart
.state
= STATE_UNSYNCD
;
279 Uart
.state
= STATE_UNSYNCD
;
284 Uart
.drop
= DROP_NONE
;
286 // should have received at least one whole byte...
287 if((Uart
.bitCnt
== 2) && EOC
&& (Uart
.byteCnt
> 0)) {
291 if(Uart
.bitCnt
== 9) {
292 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
295 Uart
.parityBits
<<= 1;
296 Uart
.parityBits
^= ((Uart
.shiftReg
>> 8) & 0x01);
299 // when End of Communication received and
300 // all data bits processed..
307 Uart.output[Uart.byteCnt] = 0xAA;
309 Uart.output[Uart.byteCnt] = error & 0xFF;
311 Uart.output[Uart.byteCnt] = 0xAA;
313 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
315 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
317 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
319 Uart.output[Uart.byteCnt] = 0xAA;
327 bit
= Uart
.bitBuffer
& 0xf0;
331 // should have been high or at least (4 * 128) / fc
332 // according to ISO this should be at least (9 * 128 + 20) / fc
333 if(Uart
.highCnt
== 8) {
334 // we went low, so this could be start of communication
335 // it turns out to be safer to choose a less significant
336 // syncbit... so we check whether the neighbour also represents the drop
337 Uart
.posCnt
= 1; // apparently we are busy with our first half bit period
338 Uart
.syncBit
= bit
& 8;
340 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; }
341 else if(bit
& 4) { Uart
.syncBit
= bit
& 4; Uart
.samples
= 2; bit
<<= 2; }
342 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; }
343 else if(bit
& 2) { Uart
.syncBit
= bit
& 2; Uart
.samples
= 1; bit
<<= 1; }
344 if(!Uart
.syncBit
) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0;
345 if(Uart
.syncBit
&& (Uart
.bitBuffer
& 8)) {
348 // the first half bit period is expected in next sample
353 else if(bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
356 Uart
.state
= STATE_START_OF_COMMUNICATION
;
357 Uart
.drop
= DROP_FIRST_HALF
;
368 if(Uart
.highCnt
< 8) {
377 //=============================================================================
378 // ISO 14443 Type A - Manchester
379 //=============================================================================
382 static RAMFUNC
int ManchesterDecoding(int v
)
398 if(Demod
.state
==DEMOD_UNSYNCD
) {
399 Demod
.output
[Demod
.len
] = 0xfa;
402 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
405 Demod
.syncBit
= 0x08;
412 Demod
.syncBit
= 0x04;
419 Demod
.syncBit
= 0x02;
422 if(bit
& 0x01 && Demod
.syncBit
) {
423 Demod
.syncBit
= 0x01;
428 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
429 Demod
.sub
= SUB_FIRST_HALF
;
432 Demod
.parityBits
= 0;
435 if(trigger
) LED_A_OFF();
436 switch(Demod
.syncBit
) {
437 case 0x08: Demod
.samples
= 3; break;
438 case 0x04: Demod
.samples
= 2; break;
439 case 0x02: Demod
.samples
= 1; break;
440 case 0x01: Demod
.samples
= 0; break;
447 //modulation = bit & Demod.syncBit;
448 modulation
= ((bit
<< 1) ^ ((Demod
.buffer
& 0x08) >> 3)) & Demod
.syncBit
;
452 if(Demod
.posCount
==0) {
455 Demod
.sub
= SUB_FIRST_HALF
;
458 Demod
.sub
= SUB_NONE
;
463 if(modulation
&& (Demod
.sub
== SUB_FIRST_HALF
)) {
464 if(Demod
.state
!=DEMOD_ERROR_WAIT
) {
465 Demod
.state
= DEMOD_ERROR_WAIT
;
466 Demod
.output
[Demod
.len
] = 0xaa;
470 else if(modulation
) {
471 Demod
.sub
= SUB_SECOND_HALF
;
474 switch(Demod
.state
) {
475 case DEMOD_START_OF_COMMUNICATION
:
476 if(Demod
.sub
== SUB_FIRST_HALF
) {
477 Demod
.state
= DEMOD_MANCHESTER_D
;
480 Demod
.output
[Demod
.len
] = 0xab;
481 Demod
.state
= DEMOD_ERROR_WAIT
;
486 case DEMOD_MANCHESTER_D
:
487 case DEMOD_MANCHESTER_E
:
488 if(Demod
.sub
== SUB_FIRST_HALF
) {
490 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
491 Demod
.state
= DEMOD_MANCHESTER_D
;
493 else if(Demod
.sub
== SUB_SECOND_HALF
) {
495 Demod
.shiftReg
>>= 1;
496 Demod
.state
= DEMOD_MANCHESTER_E
;
499 Demod
.state
= DEMOD_MANCHESTER_F
;
503 case DEMOD_MANCHESTER_F
:
504 // Tag response does not need to be a complete byte!
505 if(Demod
.len
> 0 || Demod
.bitCount
> 0) {
506 if(Demod
.bitCount
> 0) {
507 Demod
.shiftReg
>>= (9 - Demod
.bitCount
);
508 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
510 // No parity bit, so just shift a 0
511 Demod
.parityBits
<<= 1;
514 Demod
.state
= DEMOD_UNSYNCD
;
518 Demod
.output
[Demod
.len
] = 0xad;
519 Demod
.state
= DEMOD_ERROR_WAIT
;
524 case DEMOD_ERROR_WAIT
:
525 Demod
.state
= DEMOD_UNSYNCD
;
529 Demod
.output
[Demod
.len
] = 0xdd;
530 Demod
.state
= DEMOD_UNSYNCD
;
534 if(Demod
.bitCount
>=9) {
535 Demod
.output
[Demod
.len
] = Demod
.shiftReg
& 0xff;
538 Demod
.parityBits
<<= 1;
539 Demod
.parityBits
^= ((Demod
.shiftReg
>> 8) & 0x01);
546 Demod.output[Demod.len] = 0xBB;
548 Demod.output[Demod.len] = error & 0xFF;
550 Demod.output[Demod.len] = 0xBB;
552 Demod.output[Demod.len] = bit & 0xFF;
554 Demod.output[Demod.len] = Demod.buffer & 0xFF;
556 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
558 Demod.output[Demod.len] = 0xBB;
565 } // end (state != UNSYNCED)
570 //=============================================================================
571 // Finally, a `sniffer' for ISO 14443 Type A
572 // Both sides of communication!
573 //=============================================================================
575 //-----------------------------------------------------------------------------
576 // Record the sequence of commands sent by the reader to the tag, with
577 // triggering so that we start recording at the point that the tag is moved
579 //-----------------------------------------------------------------------------
580 void RAMFUNC
SnoopIso14443a(uint8_t param
) {
582 // bit 0 - trigger from first card answer
583 // bit 1 - trigger from first reader 7-bit request
587 iso14a_clear_trace();
589 // We won't start recording the frames that we acquire until we trigger;
590 // a good trigger condition to get started is probably when we see a
591 // response from the tag.
592 // triggered == FALSE -- to wait first for card
593 int triggered
= !(param
& 0x03);
595 // The command (reader -> tag) that we're receiving.
596 // The length of a received command will in most cases be no more than 18 bytes.
597 // So 32 should be enough!
598 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
599 // The response (tag -> reader) that we're receiving.
600 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
602 // As we receive stuff, we copy it from receivedCmd or receivedResponse
603 // into trace, along with its length and other annotations.
604 //uint8_t *trace = (uint8_t *)BigBuf;
606 // The DMA buffer, used to stream samples from the FPGA
607 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
608 int8_t *data
= dmaBuf
;
612 // Set up the demodulator for tag -> reader responses.
613 Demod
.output
= receivedResponse
;
615 Demod
.state
= DEMOD_UNSYNCD
;
617 // Set up the demodulator for the reader -> tag commands
618 memset(&Uart
, 0, sizeof(Uart
));
619 Uart
.output
= receivedCmd
;
620 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
621 Uart
.state
= STATE_UNSYNCD
;
623 // Setup for the DMA.
625 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
627 // And put the FPGA in the appropriate mode
628 // Signal field is off with the appropriate LED
630 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
631 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
633 // Count of samples received so far, so that we can include timing
634 // information in the trace buffer.
636 // And now we loop, receiving samples.
639 DbpString("cancelled by button");
646 int register readBufDataP
= data
- dmaBuf
;
647 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
648 if (readBufDataP
<= dmaBufDataP
){
649 dataLen
= dmaBufDataP
- readBufDataP
;
651 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
653 // test for length of buffer
654 if(dataLen
> maxDataLen
) {
655 maxDataLen
= dataLen
;
657 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
661 if(dataLen
< 1) continue;
663 // primary buffer was stopped( <-- we lost data!
664 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
665 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
666 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
668 // secondary buffer sets as primary, secondary buffer was stopped
669 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
670 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
671 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
677 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
680 // check - if there is a short 7bit request from reader
681 if ((!triggered
) && (param
& 0x02) && (Uart
.byteCnt
== 1) && (Uart
.bitCnt
= 9)) triggered
= TRUE
;
684 if (!LogTrace(receivedCmd
, Uart
.byteCnt
, 0 - Uart
.samples
, Uart
.parityBits
, TRUE
)) break;
686 /* And ready to receive another command. */
687 Uart
.state
= STATE_UNSYNCD
;
688 /* And also reset the demod code, which might have been */
689 /* false-triggered by the commands from the reader. */
690 Demod
.state
= DEMOD_UNSYNCD
;
694 if(ManchesterDecoding(data
[0] & 0x0F)) {
697 if (!LogTrace(receivedResponse
, Demod
.len
, 0 - Demod
.samples
, Demod
.parityBits
, FALSE
)) break;
699 if ((!triggered
) && (param
& 0x01)) triggered
= TRUE
;
701 // And ready to receive another response.
702 memset(&Demod
, 0, sizeof(Demod
));
703 Demod
.output
= receivedResponse
;
704 Demod
.state
= DEMOD_UNSYNCD
;
709 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
714 DbpString("COMMAND FINISHED");
717 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
718 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
);
719 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
723 //-----------------------------------------------------------------------------
724 // Prepare tag messages
725 //-----------------------------------------------------------------------------
726 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
732 // Correction bit, might be removed when not needed
737 ToSendStuffBit(1); // 1
743 ToSend
[++ToSendMax
] = SEC_D
;
745 for(i
= 0; i
< len
; i
++) {
750 for(j
= 0; j
< 8; j
++) {
752 ToSend
[++ToSendMax
] = SEC_D
;
754 ToSend
[++ToSendMax
] = SEC_E
;
759 // Get the parity bit
760 if ((dwParity
>> i
) & 0x01) {
761 ToSend
[++ToSendMax
] = SEC_D
;
763 ToSend
[++ToSendMax
] = SEC_E
;
768 ToSend
[++ToSendMax
] = SEC_F
;
770 // Convert from last byte pos to length
774 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
775 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
778 //-----------------------------------------------------------------------------
779 // This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
780 //-----------------------------------------------------------------------------
781 static void CodeStrangeAnswerAsTag()
787 // Correction bit, might be removed when not needed
792 ToSendStuffBit(1); // 1
798 ToSend
[++ToSendMax
] = SEC_D
;
801 ToSend
[++ToSendMax
] = SEC_E
;
804 ToSend
[++ToSendMax
] = SEC_E
;
807 ToSend
[++ToSendMax
] = SEC_D
;
810 ToSend
[++ToSendMax
] = SEC_F
;
812 // Flush the buffer in FPGA!!
813 for(i
= 0; i
< 5; i
++) {
814 ToSend
[++ToSendMax
] = SEC_F
;
817 // Convert from last byte pos to length
821 static void Code4bitAnswerAsTag(uint8_t cmd
)
827 // Correction bit, might be removed when not needed
832 ToSendStuffBit(1); // 1
838 ToSend
[++ToSendMax
] = SEC_D
;
841 for(i
= 0; i
< 4; i
++) {
843 ToSend
[++ToSendMax
] = SEC_D
;
845 ToSend
[++ToSendMax
] = SEC_E
;
851 ToSend
[++ToSendMax
] = SEC_F
;
853 // Flush the buffer in FPGA!!
854 for(i
= 0; i
< 5; i
++) {
855 ToSend
[++ToSendMax
] = SEC_F
;
858 // Convert from last byte pos to length
862 //-----------------------------------------------------------------------------
863 // Wait for commands from reader
864 // Stop when button is pressed
865 // Or return TRUE when command is captured
866 //-----------------------------------------------------------------------------
867 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
869 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
870 // only, since we are receiving, not transmitting).
871 // Signal field is off with the appropriate LED
873 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
875 // Now run a `software UART' on the stream of incoming samples.
876 Uart
.output
= received
;
877 Uart
.byteCntMax
= maxLen
;
878 Uart
.state
= STATE_UNSYNCD
;
883 if(BUTTON_PRESS()) return FALSE
;
885 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
886 AT91C_BASE_SSC
->SSC_THR
= 0x00;
888 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
889 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
890 if(MillerDecoding((b
& 0xf0) >> 4)) {
894 if(MillerDecoding(b
& 0x0f)) {
902 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
903 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
);
904 int EmSend4bit(uint8_t resp
);
905 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
);
906 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
);
907 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
);
908 int EmSendCmd(uint8_t *resp
, int respLen
);
909 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
);
911 //-----------------------------------------------------------------------------
912 // Main loop of simulated tag: receive commands from reader, decide what
913 // response to send, and send it.
914 //-----------------------------------------------------------------------------
915 void SimulateIso14443aTag(int tagType
, int uid_1st
, int uid_2nd
, byte_t
* data
)
917 // Enable and clear the trace
919 iso14a_clear_trace();
921 // This function contains the tag emulation
924 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
925 uint8_t response1
[2];
928 case 1: { // MIFARE Classic
929 // Says: I am Mifare 1k - original line
934 case 2: { // MIFARE Ultralight
935 // Says: I am a stupid memory tag, no crypto
940 case 3: { // MIFARE DESFire
941 // Says: I am a DESFire tag, ph33r me
946 case 4: { // ISO/IEC 14443-4
947 // Says: I am a javacard (JCOP)
953 Dbprintf("Error: unkown tagtype (%d)",tagType
);
958 // The second response contains the (mandatory) first 24 bits of the UID
959 uint8_t response2
[5];
961 // Check if the uid uses the (optional) part
962 uint8_t response2a
[5];
965 num_to_bytes(uid_1st
,3,response2
+1);
966 num_to_bytes(uid_2nd
,4,response2a
);
967 response2a
[4] = response2a
[0] ^ response2a
[1] ^ response2a
[2] ^ response2a
[3];
969 // Configure the ATQA and SAK accordingly
970 response1
[0] |= 0x40;
973 num_to_bytes(uid_1st
,4,response2
);
974 // Configure the ATQA and SAK accordingly
975 response1
[0] &= 0xBF;
979 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
980 response2
[4] = response2
[0] ^ response2
[1] ^ response2
[2] ^ response2
[3];
982 // Prepare the mandatory SAK (for 4 and 7 byte UID)
983 uint8_t response3
[3];
985 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
987 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
988 uint8_t response3a
[3];
989 response3a
[0] = sak
& 0xFB;
990 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
992 uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
993 uint8_t response6
[] = { 0x03, 0x3B, 0x00, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
994 ComputeCrc14443(CRC_14443_A
, response6
, 3, &response6
[3], &response6
[4]);
999 // Longest possible response will be 16 bytes + 2 CRC = 18 bytes
1001 // 144 data bits (18 * 8)
1004 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
1005 // 1 just for the case
1009 // 166 bytes, since every bit that needs to be send costs us a byte
1012 // Respond with card type
1013 uint8_t *resp1
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
1016 // Anticollision cascade1 - respond with uid
1017 uint8_t *resp2
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ 166);
1020 // Anticollision cascade2 - respond with 2nd half of uid if asked
1021 // we're only going to be asked if we set the 1st byte of the UID (during cascade1) to 0x88
1022 uint8_t *resp2a
= (((uint8_t *)BigBuf
) + 1140);
1025 // Acknowledge select - cascade 1
1026 uint8_t *resp3
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*2));
1029 // Acknowledge select - cascade 2
1030 uint8_t *resp3a
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*3));
1033 // Response to a read request - not implemented atm
1034 uint8_t *resp4
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*4));
1037 // Authenticate response - nonce
1038 uint8_t *resp5
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*5));
1041 // Authenticate response - nonce
1042 uint8_t *resp6
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
+ (166*6));
1045 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
1048 // To control where we are in the protocol
1052 // Just to allow some checks
1057 uint8_t* respdata
= NULL
;
1059 // uint8_t nack = 0x04;
1061 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1063 // Prepare the responses of the anticollision phase
1064 // there will be not enough time to do this at the moment the reader sends it REQA
1066 // Answer to request
1067 CodeIso14443aAsTag(response1
, sizeof(response1
));
1068 memcpy(resp1
, ToSend
, ToSendMax
); resp1Len
= ToSendMax
;
1070 // Send our UID (cascade 1)
1071 CodeIso14443aAsTag(response2
, sizeof(response2
));
1072 memcpy(resp2
, ToSend
, ToSendMax
); resp2Len
= ToSendMax
;
1074 // Answer to select (cascade1)
1075 CodeIso14443aAsTag(response3
, sizeof(response3
));
1076 memcpy(resp3
, ToSend
, ToSendMax
); resp3Len
= ToSendMax
;
1078 // Send the cascade 2 2nd part of the uid
1079 CodeIso14443aAsTag(response2a
, sizeof(response2a
));
1080 memcpy(resp2a
, ToSend
, ToSendMax
); resp2aLen
= ToSendMax
;
1082 // Answer to select (cascade 2)
1083 CodeIso14443aAsTag(response3a
, sizeof(response3a
));
1084 memcpy(resp3a
, ToSend
, ToSendMax
); resp3aLen
= ToSendMax
;
1086 // Strange answer is an example of rare message size (3 bits)
1087 CodeStrangeAnswerAsTag();
1088 memcpy(resp4
, ToSend
, ToSendMax
);// resp4Len = ToSendMax;
1090 // Authentication answer (random nonce)
1091 CodeIso14443aAsTag(response5
, sizeof(response5
));
1092 memcpy(resp5
, ToSend
, ToSendMax
); resp5Len
= ToSendMax
;
1094 // dummy ATS (pseudo-ATR), answer to RATS
1095 CodeIso14443aAsTag(response6
, sizeof(response6
));
1096 memcpy(resp6
, ToSend
, ToSendMax
); resp6Len
= ToSendMax
;
1098 // We need to listen to the high-frequency, peak-detected path.
1099 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1107 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, RECV_CMD_SIZE
)) {
1108 DbpString("button press");
1113 LogTrace(receivedCmd
,len
, 0, Uart
.parityBits
, TRUE
);
1116 // 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
1117 // Okay, look at the command now.
1119 if(receivedCmd
[0] == 0x26) { // Received a REQUEST
1120 resp
= resp1
; respLen
= resp1Len
; order
= 1;
1121 respdata
= response1
;
1122 respsize
= sizeof(response1
);
1123 } else if(receivedCmd
[0] == 0x52) { // Received a WAKEUP
1124 resp
= resp1
; respLen
= resp1Len
; order
= 6;
1125 respdata
= response1
;
1126 respsize
= sizeof(response1
);
1127 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // Received request for UID (cascade 1)
1128 resp
= resp2
; respLen
= resp2Len
; order
= 2;
1129 respdata
= response2
;
1130 respsize
= sizeof(response2
);
1131 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x95) { // Received request for UID (cascade 2)
1132 resp
= resp2a
; respLen
= resp2aLen
; order
= 20;
1133 respdata
= response2a
;
1134 respsize
= sizeof(response2a
);
1135 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x93) { // Received a SELECT (cascade 1)
1136 resp
= resp3
; respLen
= resp3Len
; order
= 3;
1137 respdata
= response3
;
1138 respsize
= sizeof(response3
);
1139 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x95) { // Received a SELECT (cascade 2)
1140 resp
= resp3a
; respLen
= resp3aLen
; order
= 30;
1141 respdata
= response3a
;
1142 respsize
= sizeof(response3a
);
1143 } else if(receivedCmd
[0] == 0x30) { // Received a (plain) READ
1144 // resp = resp4; respLen = resp4Len; order = 4; // Do nothing
1145 // respdata = &nack;
1146 // respsize = sizeof(nack); // 4-bit answer
1147 EmSendCmdEx(data
+(4*receivedCmd
[0]),16,false);
1148 Dbprintf("Read request from reader: %x %x",receivedCmd
[0],receivedCmd
[1]);
1149 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1151 } else if(receivedCmd
[0] == 0x50) { // Received a HALT
1152 // DbpString("Reader requested we HALT!:");
1154 resp
= resp1
; respLen
= 0; order
= 0;
1157 } else if(receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61) { // Received an authentication request
1158 resp
= resp5
; respLen
= resp5Len
; order
= 7;
1159 respdata
= response5
;
1160 respsize
= sizeof(response5
);
1161 } else if(receivedCmd
[0] == 0xE0) { // Received a RATS request
1162 resp
= resp6
; respLen
= resp6Len
; order
= 70;
1163 respdata
= response6
;
1164 respsize
= sizeof(response6
);
1166 if (order
== 7 && len
==8) {
1167 uint32_t nr
= bytes_to_num(receivedCmd
,4);
1168 uint32_t ar
= bytes_to_num(receivedCmd
+4,4);
1169 Dbprintf("Auth attempt {nr}{ar}: %08x %08x",nr
,ar
);
1171 // Never seen this command before
1172 Dbprintf("Received unknown command (len=%d):",len
);
1173 Dbhexdump(len
,receivedCmd
,false);
1176 resp
= resp1
; respLen
= 0; order
= 0;
1181 // Count number of wakeups received after a halt
1182 if(order
== 6 && lastorder
== 5) { happened
++; }
1184 // Count number of other messages after a halt
1185 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1187 // Look at last parity bit to determine timing of answer
1188 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1189 // 1236, so correction bit needed
1193 if(cmdsRecvd
> 999) {
1194 DbpString("1000 commands later...");
1201 EmSendCmd14443aRaw(resp
, respLen
, receivedCmd
[0] == 0x52);
1205 if (respdata
!= NULL
) {
1206 LogTrace(respdata
,respsize
, 0, SwapBits(GetParity(respdata
,respsize
),respsize
), FALSE
);
1208 if(traceLen
> TRACE_SIZE
) {
1209 DbpString("Trace full");
1214 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1217 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1221 //-----------------------------------------------------------------------------
1222 // Transmit the command (to the tag) that was placed in ToSend[].
1223 //-----------------------------------------------------------------------------
1224 static void TransmitFor14443a(const uint8_t *cmd
, int len
, int *samples
, int *wait
)
1228 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1234 for(c
= 0; c
< *wait
;) {
1235 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1236 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1239 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1240 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1248 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1249 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1255 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1256 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1261 if (samples
) *samples
= (c
+ *wait
) << 3;
1264 //-----------------------------------------------------------------------------
1265 // Code a 7-bit command without parity bit
1266 // This is especially for 0x26 and 0x52 (REQA and WUPA)
1267 //-----------------------------------------------------------------------------
1268 void ShortFrameFromReader(const uint8_t bt
)
1276 // Start of Communication (Seq. Z)
1277 ToSend
[++ToSendMax
] = SEC_Z
;
1281 for(j
= 0; j
< 7; j
++) {
1284 ToSend
[++ToSendMax
] = SEC_X
;
1289 ToSend
[++ToSendMax
] = SEC_Z
;
1293 ToSend
[++ToSendMax
] = SEC_Y
;
1300 // End of Communication
1303 ToSend
[++ToSendMax
] = SEC_Z
;
1307 ToSend
[++ToSendMax
] = SEC_Y
;
1311 ToSend
[++ToSendMax
] = SEC_Y
;
1314 ToSend
[++ToSendMax
] = SEC_Y
;
1315 ToSend
[++ToSendMax
] = SEC_Y
;
1316 ToSend
[++ToSendMax
] = SEC_Y
;
1318 // Convert from last character reference to length
1322 //-----------------------------------------------------------------------------
1323 // Prepare reader command to send to FPGA
1325 //-----------------------------------------------------------------------------
1326 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1334 // Start of Communication (Seq. Z)
1335 ToSend
[++ToSendMax
] = SEC_Z
;
1338 // Generate send structure for the data bits
1339 for (i
= 0; i
< len
; i
++) {
1340 // Get the current byte to send
1343 for (j
= 0; j
< 8; j
++) {
1346 ToSend
[++ToSendMax
] = SEC_X
;
1351 ToSend
[++ToSendMax
] = SEC_Z
;
1354 ToSend
[++ToSendMax
] = SEC_Y
;
1361 // Get the parity bit
1362 if ((dwParity
>> i
) & 0x01) {
1364 ToSend
[++ToSendMax
] = SEC_X
;
1369 ToSend
[++ToSendMax
] = SEC_Z
;
1372 ToSend
[++ToSendMax
] = SEC_Y
;
1378 // End of Communication
1381 ToSend
[++ToSendMax
] = SEC_Z
;
1384 ToSend
[++ToSendMax
] = SEC_Y
;
1388 ToSend
[++ToSendMax
] = SEC_Y
;
1391 ToSend
[++ToSendMax
] = SEC_Y
;
1392 ToSend
[++ToSendMax
] = SEC_Y
;
1393 ToSend
[++ToSendMax
] = SEC_Y
;
1395 // Convert from last character reference to length
1399 //-----------------------------------------------------------------------------
1400 // Wait for commands from reader
1401 // Stop when button is pressed (return 1) or field was gone (return 2)
1402 // Or return 0 when command is captured
1403 //-----------------------------------------------------------------------------
1404 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1408 uint32_t timer
= 0, vtime
= 0;
1412 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1413 // only, since we are receiving, not transmitting).
1414 // Signal field is off with the appropriate LED
1416 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1418 // Set ADC to read field strength
1419 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1420 AT91C_BASE_ADC
->ADC_MR
=
1421 ADC_MODE_PRESCALE(32) |
1422 ADC_MODE_STARTUP_TIME(16) |
1423 ADC_MODE_SAMPLE_HOLD_TIME(8);
1424 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1426 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1428 // Now run a 'software UART' on the stream of incoming samples.
1429 Uart
.output
= received
;
1430 Uart
.byteCntMax
= maxLen
;
1431 Uart
.state
= STATE_UNSYNCD
;
1436 if (BUTTON_PRESS()) return 1;
1438 // test if the field exists
1439 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1441 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1442 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1443 if (analogCnt
>= 32) {
1444 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1445 vtime
= GetTickCount();
1446 if (!timer
) timer
= vtime
;
1447 // 50ms no field --> card to idle state
1448 if (vtime
- timer
> 50) return 2;
1450 if (timer
) timer
= 0;
1456 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1457 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1459 // receive and test the miller decoding
1460 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1461 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1462 if(MillerDecoding((b
& 0xf0) >> 4)) {
1463 *len
= Uart
.byteCnt
;
1464 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1467 if(MillerDecoding(b
& 0x0f)) {
1468 *len
= Uart
.byteCnt
;
1469 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1476 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1481 // Modulate Manchester
1482 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1483 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1486 // include correction bit
1488 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1489 // 1236, so correction bit needed
1495 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1496 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1499 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1501 b
= 0xff; // was 0x00
1507 AT91C_BASE_SSC
->SSC_THR
= b
;
1511 if(BUTTON_PRESS()) {
1519 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1520 Code4bitAnswerAsTag(resp
);
1521 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1522 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1526 int EmSend4bit(uint8_t resp
){
1527 return EmSend4bitEx(resp
, 0);
1530 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1531 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1532 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1533 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1537 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1538 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1541 int EmSendCmd(uint8_t *resp
, int respLen
){
1542 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1545 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1546 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1549 //-----------------------------------------------------------------------------
1550 // Wait a certain time for tag response
1551 // If a response is captured return TRUE
1552 // If it takes to long return FALSE
1553 //-----------------------------------------------------------------------------
1554 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) //uint8_t *buffer
1556 // buffer needs to be 512 bytes
1559 // Set FPGA mode to "reader listen mode", no modulation (listen
1560 // only, since we are receiving, not transmitting).
1561 // Signal field is on with the appropriate LED
1563 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1565 // Now get the answer from the card
1566 Demod
.output
= receivedResponse
;
1568 Demod
.state
= DEMOD_UNSYNCD
;
1571 if (elapsed
) *elapsed
= 0;
1577 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1578 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1579 if (elapsed
) (*elapsed
)++;
1581 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1582 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1583 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1584 if(ManchesterDecoding((b
>>4) & 0xf)) {
1585 *samples
= ((c
- 1) << 3) + 4;
1588 if(ManchesterDecoding(b
& 0x0f)) {
1596 void ReaderTransmitShort(const uint8_t* bt
)
1601 ShortFrameFromReader(*bt
);
1604 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1606 // Store reader command in buffer
1607 if (tracing
) LogTrace(bt
,1,0,GetParity(bt
,1),TRUE
);
1610 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
)
1615 // This is tied to other size changes
1616 // uint8_t* frame_addr = ((uint8_t*)BigBuf) + 2024;
1617 CodeIso14443aAsReaderPar(frame
,len
,par
);
1620 TransmitFor14443a(ToSend
, ToSendMax
, &samples
, &wait
);
1624 // Store reader command in buffer
1625 if (tracing
) LogTrace(frame
,len
,0,par
,TRUE
);
1629 void ReaderTransmit(uint8_t* frame
, int len
)
1631 // Generate parity and redirect
1632 ReaderTransmitPar(frame
,len
,GetParity(frame
,len
));
1635 int ReaderReceive(uint8_t* receivedAnswer
)
1638 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1639 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1640 if(samples
== 0) return FALSE
;
1644 int ReaderReceivePar(uint8_t* receivedAnswer
, uint32_t * parptr
)
1647 if (!GetIso14443aAnswerFromTag(receivedAnswer
,160,&samples
,0)) return FALSE
;
1648 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1649 *parptr
= Demod
.parityBits
;
1650 if(samples
== 0) return FALSE
;
1654 /* performs iso14443a anticolision procedure
1655 * fills the uid pointer unless NULL
1656 * fills resp_data unless NULL */
1657 int iso14443a_select_card(byte_t
* uid_ptr
, iso14a_card_select_t
* p_hi14a_card
, uint32_t* cuid_ptr
) {
1658 uint8_t wupa
[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1659 uint8_t sel_all
[] = { 0x93,0x20 };
1660 uint8_t sel_uid
[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1661 uint8_t rats
[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1662 uint8_t* resp
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
); // was 3560 - tied to other size changes
1664 size_t uid_resp_len
;
1666 uint8_t sak
= 0x04; // cascade uid
1667 int cascade_level
= 0;
1670 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1671 ReaderTransmitShort(wupa
);
1673 if(!ReaderReceive(resp
)) return 0;
1674 // Dbprintf("atqa: %02x %02x",resp[0],resp[1]);
1677 memcpy(p_hi14a_card
->atqa
, resp
, 2);
1678 p_hi14a_card
->uidlen
= 0;
1679 memset(p_hi14a_card
->uid
,0,10);
1684 memset(uid_ptr
,0,10);
1687 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1688 // which case we need to make a cascade 2 request and select - this is a long UID
1689 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1690 for(; sak
& 0x04; cascade_level
++)
1692 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1693 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1696 ReaderTransmit(sel_all
,sizeof(sel_all
));
1697 if (!ReaderReceive(resp
)) return 0;
1699 // First backup the current uid
1700 memcpy(uid_resp
,resp
,4);
1702 // Dbprintf("uid: %02x %02x %02x %02x",uid_resp[0],uid_resp[1],uid_resp[2],uid_resp[3]);
1704 // calculate crypto UID
1706 *cuid_ptr
= bytes_to_num(uid_resp
, 4);
1709 // Construct SELECT UID command
1710 memcpy(sel_uid
+2,resp
,5);
1711 AppendCrc14443a(sel_uid
,7);
1712 ReaderTransmit(sel_uid
,sizeof(sel_uid
));
1715 if (!ReaderReceive(resp
)) return 0;
1718 // Test if more parts of the uid are comming
1719 if ((sak
& 0x04) && uid_resp
[0] == 0x88) {
1720 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
1721 // http://www.nxp.com/documents/application_note/AN10927.pdf
1722 memcpy(uid_ptr
, uid_ptr
+ 1, 3);
1727 memcpy(uid_ptr
+ (cascade_level
*3), uid_resp
, uid_resp_len
);
1731 memcpy(p_hi14a_card
->uid
+ (cascade_level
*3), uid_resp
, uid_resp_len
);
1732 p_hi14a_card
->uidlen
+= uid_resp_len
;
1737 p_hi14a_card
->sak
= sak
;
1738 p_hi14a_card
->ats_len
= 0;
1741 if( (sak
& 0x20) == 0) {
1742 return 2; // non iso14443a compliant tag
1745 // Request for answer to select
1746 AppendCrc14443a(rats
, 2);
1747 ReaderTransmit(rats
, sizeof(rats
));
1749 if (!(len
= ReaderReceive(resp
))) return 0;
1752 memcpy(p_hi14a_card
->ats
, resp
, sizeof(p_hi14a_card
->ats
));
1753 p_hi14a_card
->ats_len
= len
;
1756 // reset the PCB block number
1757 iso14_pcb_blocknum
= 0;
1761 void iso14443a_setup() {
1762 // Set up the synchronous serial port
1764 // Start from off (no field generated)
1765 // Signal field is off with the appropriate LED
1767 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1770 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1772 // Now give it time to spin up.
1773 // Signal field is on with the appropriate LED
1775 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1778 iso14a_timeout
= 2048; //default
1781 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1782 uint8_t real_cmd
[cmd_len
+4];
1783 real_cmd
[0] = 0x0a; //I-Block
1784 // put block number into the PCB
1785 real_cmd
[0] |= iso14_pcb_blocknum
;
1786 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1787 memcpy(real_cmd
+2, cmd
, cmd_len
);
1788 AppendCrc14443a(real_cmd
,cmd_len
+2);
1790 ReaderTransmit(real_cmd
, cmd_len
+4);
1791 size_t len
= ReaderReceive(data
);
1792 uint8_t * data_bytes
= (uint8_t *) data
;
1794 return 0; //DATA LINK ERROR
1795 // if we received an I- or R(ACK)-Block with a block number equal to the
1796 // current block number, toggle the current block number
1797 else if (len
>= 4 // PCB+CID+CRC = 4 bytes
1798 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
1799 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1800 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) // equal block numbers
1802 iso14_pcb_blocknum
^= 1;
1808 //-----------------------------------------------------------------------------
1809 // Read an ISO 14443a tag. Send out commands and store answers.
1811 //-----------------------------------------------------------------------------
1812 void ReaderIso14443a(UsbCommand
* c
)
1814 iso14a_command_t param
= c
->arg
[0];
1815 uint8_t * cmd
= c
->d
.asBytes
;
1816 size_t len
= c
->arg
[1];
1818 byte_t buf
[USB_CMD_DATA_SIZE
];
1820 iso14a_clear_trace();
1821 iso14a_set_tracing(true);
1823 if(param
& ISO14A_REQUEST_TRIGGER
) {
1824 iso14a_set_trigger(1);
1827 if(param
& ISO14A_CONNECT
) {
1829 arg0
= iso14443a_select_card(NULL
,(iso14a_card_select_t
*)buf
,NULL
);
1830 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(iso14a_card_select_t
));
1831 // UsbSendPacket((void *)ack, sizeof(UsbCommand));
1834 if(param
& ISO14A_SET_TIMEOUT
) {
1835 iso14a_timeout
= c
->arg
[2];
1838 if(param
& ISO14A_SET_TIMEOUT
) {
1839 iso14a_timeout
= c
->arg
[2];
1842 if(param
& ISO14A_APDU
) {
1843 arg0
= iso14_apdu(cmd
, len
, buf
);
1844 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(buf
));
1845 // UsbSendPacket((void *)ack, sizeof(UsbCommand));
1848 if(param
& ISO14A_RAW
) {
1849 if(param
& ISO14A_APPEND_CRC
) {
1850 AppendCrc14443a(cmd
,len
);
1853 ReaderTransmit(cmd
,len
);
1854 arg0
= ReaderReceive(buf
);
1855 // UsbSendPacket((void *)ack, sizeof(UsbCommand));
1856 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(buf
));
1859 if(param
& ISO14A_REQUEST_TRIGGER
) {
1860 iso14a_set_trigger(0);
1863 if(param
& ISO14A_NO_DISCONNECT
) {
1867 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1871 //-----------------------------------------------------------------------------
1872 // Read an ISO 14443a tag. Send out commands and store answers.
1874 //-----------------------------------------------------------------------------
1875 void ReaderMifare(uint32_t parameter
)
1878 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1879 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1881 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
); // was 3560 - tied to other size changes
1894 //byte_t par_mask = 0xff;
1901 byte_t nt
[4] = {0,0,0,0};
1902 byte_t nt_attacked
[4], nt_noattack
[4];
1903 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1904 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1905 num_to_bytes(parameter
, 4, nt_noattack
);
1906 int isOK
= 0, isNULL
= 0;
1911 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1913 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1917 // Test if the action was cancelled
1918 if(BUTTON_PRESS()) {
1922 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) continue;
1924 // Transmit MIFARE_CLASSIC_AUTH
1925 ReaderTransmit(mf_auth
, sizeof(mf_auth
));
1927 // Receive the (16 bit) "random" nonce
1928 if (!ReaderReceive(receivedAnswer
)) continue;
1929 memcpy(nt
, receivedAnswer
, 4);
1931 // Transmit reader nonce and reader answer
1932 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
),par
);
1934 // Receive 4 bit answer
1935 if (ReaderReceive(receivedAnswer
))
1937 if ( (parameter
!= 0) && (memcmp(nt
, nt_noattack
, 4) == 0) ) continue;
1939 isNULL
= !(nt_attacked
[0] == 0) && (nt_attacked
[1] == 0) && (nt_attacked
[2] == 0) && (nt_attacked
[3] == 0);
1940 if ( (isNULL
!= 0 ) && (memcmp(nt
, nt_attacked
, 4) != 0) ) continue;
1945 memcpy(nt_attacked
, nt
, 4);
1947 par_low
= par
& 0x07;
1951 if(led_on
) LED_B_ON(); else LED_B_OFF();
1952 par_list
[nt_diff
] = par
;
1953 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
1955 // Test if the information is complete
1956 if (nt_diff
== 0x07) {
1961 nt_diff
= (nt_diff
+ 1) & 0x07;
1962 mf_nr_ar
[3] = nt_diff
<< 5;
1969 par
= (((par
>> 3) + 1) << 3) | par_low
;
1974 LogTrace(nt
, 4, 0, GetParity(nt
, 4), TRUE
);
1975 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
1976 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
1979 // UsbCommand ack = {CMD_ACK, {isOK, 0, 0}};
1980 memcpy(buf
+ 0, uid
, 4);
1981 memcpy(buf
+ 4, nt
, 4);
1982 memcpy(buf
+ 8, par_list
, 8);
1983 memcpy(buf
+ 16, ks_list
, 8);
1986 cmd_send(CMD_ACK
,isOK
,0,0,buf
,48);
1987 // UsbSendPacket((uint8_t *)&ack, sizeof(UsbCommand));
1991 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1995 if (MF_DBGLEVEL
>= 1) DbpString("COMMAND mifare FINISHED");
1999 //-----------------------------------------------------------------------------
2000 // MIFARE 1K simulate.
2002 //-----------------------------------------------------------------------------
2003 void Mifare1ksim(uint8_t arg0
, uint8_t arg1
, uint8_t arg2
, uint8_t *datain
)
2005 int cardSTATE
= MFEMUL_NOFIELD
;
2007 int vHf
= 0; // in mV
2008 //int nextCycleTimeout = 0;
2010 // uint32_t timer = 0;
2011 uint32_t selTimer
= 0;
2012 uint32_t authTimer
= 0;
2015 uint8_t cardWRBL
= 0;
2016 uint8_t cardAUTHSC
= 0;
2017 uint8_t cardAUTHKEY
= 0xff; // no authentication
2018 //uint32_t cardRn = 0;
2019 uint32_t cardRr
= 0;
2021 //uint32_t rn_enc = 0;
2023 uint32_t cardINTREG
= 0;
2024 uint8_t cardINTBLOCK
= 0;
2025 struct Crypto1State mpcs
= {0, 0};
2026 struct Crypto1State
*pcs
;
2029 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
2030 uint8_t *response
= eml_get_bigbufptr_sendbuf();
2032 static uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2034 static uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2035 static uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2037 static uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2038 static uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
2040 static uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
2041 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
2042 static uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2048 // Authenticate response - nonce
2049 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2051 // get UID from emul memory
2052 emlGetMemBt(receivedCmd
, 7, 1);
2053 _7BUID
= !(receivedCmd
[0] == 0x00);
2054 if (!_7BUID
) { // ---------- 4BUID
2057 emlGetMemBt(rUIDBCC1
, 0, 4);
2058 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2059 } else { // ---------- 7BUID
2063 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2064 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2065 emlGetMemBt(rUIDBCC2
, 3, 4);
2066 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2069 // -------------------------------------- test area
2071 // -------------------------------------- END test area
2072 // start mkseconds counter
2075 // We need to listen to the high-frequency, peak-detected path.
2076 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2079 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2082 if (MF_DBGLEVEL
>= 1) Dbprintf("Started. 7buid=%d", _7BUID
);
2083 // calibrate mkseconds counter
2088 if(BUTTON_PRESS()) {
2092 // find reader field
2093 // Vref = 3300mV, and an 10:1 voltage divider on the input
2094 // can measure voltages up to 33000 mV
2095 if (cardSTATE
== MFEMUL_NOFIELD
) {
2096 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2097 if (vHf
> MF_MINFIELDV
) {
2098 cardSTATE_TO_IDLE();
2103 if (cardSTATE
!= MFEMUL_NOFIELD
) {
2104 res
= EmGetCmd(receivedCmd
, &len
, RECV_CMD_SIZE
); // (+ nextCycleTimeout)
2106 cardSTATE
= MFEMUL_NOFIELD
;
2113 //nextCycleTimeout = 0;
2115 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2117 if (len
!= 4 && cardSTATE
!= MFEMUL_NOFIELD
) { // len != 4 <---- speed up the code 4 authentication
2118 // REQ or WUP request in ANY state and WUP in HALTED state
2119 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2120 selTimer
= GetTickCount();
2121 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2122 cardSTATE
= MFEMUL_SELECT1
;
2124 // init crypto block
2127 crypto1_destroy(pcs
);
2132 switch (cardSTATE
) {
2133 case MFEMUL_NOFIELD
:{
2136 case MFEMUL_HALTED
:{
2142 case MFEMUL_SELECT1
:{
2144 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2145 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2151 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2153 EmSendCmd(rSAK
, sizeof(rSAK
));
2155 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2157 cuid
= bytes_to_num(rUIDBCC1
, 4);
2159 cardSTATE
= MFEMUL_WORK
;
2161 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2164 cardSTATE
= MFEMUL_SELECT2
;
2171 case MFEMUL_SELECT2
:{
2174 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2175 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2181 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2182 EmSendCmd(rSAK
, sizeof(rSAK
));
2184 cuid
= bytes_to_num(rUIDBCC2
, 4);
2185 cardSTATE
= MFEMUL_WORK
;
2187 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2191 // i guess there is a command). go into the work state.
2192 if (len
!= 4) break;
2193 cardSTATE
= MFEMUL_WORK
;
2199 //rn_enc = bytes_to_num(receivedCmd, 4);
2200 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
2201 cardRr
= bytes_to_num(&receivedCmd
[4], 4) ^ crypto1_word(pcs
, 0, 0);
2203 if (cardRr
!= prng_successor(nonce
, 64)){
2204 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr
, prng_successor(nonce
, 64));
2205 cardSTATE_TO_IDLE();
2208 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2209 num_to_bytes(ans
, 4, rAUTH_AT
);
2211 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2212 cardSTATE
= MFEMUL_AUTH2
;
2214 cardSTATE_TO_IDLE();
2216 if (cardSTATE
!= MFEMUL_AUTH2
) break;
2220 cardSTATE
= MFEMUL_WORK
;
2221 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2225 lbWORK
: if (len
== 0) break;
2227 if (cardAUTHKEY
== 0xff) {
2228 // first authentication
2229 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2230 authTimer
= GetTickCount();
2232 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2233 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2236 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2237 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2238 num_to_bytes(nonce
, 4, rAUTH_AT
);
2239 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2242 // last working revision
2243 // EmSendCmd14443aRaw(resp1, resp1Len, 0);
2244 // LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2246 cardSTATE
= MFEMUL_AUTH1
;
2247 //nextCycleTimeout = 10;
2252 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2254 // nested authentication
2255 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2256 authTimer
= GetTickCount();
2258 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2259 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2262 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2263 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2264 num_to_bytes(ans
, 4, rAUTH_AT
);
2265 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2268 cardSTATE
= MFEMUL_AUTH1
;
2269 //nextCycleTimeout = 10;
2274 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2275 // BUT... ACK --> NACK
2276 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2277 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2281 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2282 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2283 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2288 if (len
== 4 && receivedCmd
[0] == 0x30) {
2289 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2290 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2293 emlGetMem(response
, receivedCmd
[1], 1);
2294 AppendCrc14443a(response
, 16);
2295 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2296 EmSendCmdPar(response
, 18, par
);
2301 if (len
== 4 && receivedCmd
[0] == 0xA0) {
2302 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2303 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2306 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2307 //nextCycleTimeout = 50;
2308 cardSTATE
= MFEMUL_WRITEBL2
;
2309 cardWRBL
= receivedCmd
[1];
2313 // works with cardINTREG
2315 // increment, decrement, restore
2316 if (len
== 4 && (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2)) {
2317 if (receivedCmd
[1] >= 16 * 4 ||
2318 receivedCmd
[1] / 4 != cardAUTHSC
||
2319 emlCheckValBl(receivedCmd
[1])) {
2320 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2323 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2324 if (receivedCmd
[0] == 0xC1)
2325 cardSTATE
= MFEMUL_INTREG_INC
;
2326 if (receivedCmd
[0] == 0xC0)
2327 cardSTATE
= MFEMUL_INTREG_DEC
;
2328 if (receivedCmd
[0] == 0xC2)
2329 cardSTATE
= MFEMUL_INTREG_REST
;
2330 cardWRBL
= receivedCmd
[1];
2337 if (len
== 4 && receivedCmd
[0] == 0xB0) {
2338 if (receivedCmd
[1] >= 16 * 4 || receivedCmd
[1] / 4 != cardAUTHSC
) {
2339 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2343 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2344 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2346 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2352 if (len
== 4 && (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00)) {
2355 cardSTATE
= MFEMUL_HALTED
;
2356 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2360 // command not allowed
2362 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2369 case MFEMUL_WRITEBL2
:{
2371 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2372 emlSetMem(receivedCmd
, cardWRBL
, 1);
2373 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2374 cardSTATE
= MFEMUL_WORK
;
2377 cardSTATE_TO_IDLE();
2383 case MFEMUL_INTREG_INC
:{
2384 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2385 memcpy(&ans
, receivedCmd
, 4);
2386 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2387 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2388 cardSTATE_TO_IDLE();
2391 cardINTREG
= cardINTREG
+ ans
;
2392 cardSTATE
= MFEMUL_WORK
;
2395 case MFEMUL_INTREG_DEC
:{
2396 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2397 memcpy(&ans
, receivedCmd
, 4);
2398 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2399 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2400 cardSTATE_TO_IDLE();
2403 cardINTREG
= cardINTREG
- ans
;
2404 cardSTATE
= MFEMUL_WORK
;
2407 case MFEMUL_INTREG_REST
:{
2408 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2409 memcpy(&ans
, receivedCmd
, 4);
2410 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2411 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2412 cardSTATE_TO_IDLE();
2415 cardSTATE
= MFEMUL_WORK
;
2421 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2424 // add trace trailer
2425 memset(rAUTH_NT
, 0x44, 4);
2426 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2428 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);
2431 //-----------------------------------------------------------------------------
2434 //-----------------------------------------------------------------------------
2435 void RAMFUNC
SniffMifare(uint8_t param
) {
2437 // bit 0 - trigger from first card answer
2438 // bit 1 - trigger from first reader 7-bit request
2440 // C(red) A(yellow) B(green)
2442 // init trace buffer
2443 iso14a_clear_trace();
2445 // The command (reader -> tag) that we're receiving.
2446 // The length of a received command will in most cases be no more than 18 bytes.
2447 // So 32 should be enough!
2448 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
2449 // The response (tag -> reader) that we're receiving.
2450 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
2452 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2453 // into trace, along with its length and other annotations.
2454 //uint8_t *trace = (uint8_t *)BigBuf;
2456 // The DMA buffer, used to stream samples from the FPGA
2457 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
2458 int8_t *data
= dmaBuf
;
2462 // Set up the demodulator for tag -> reader responses.
2463 Demod
.output
= receivedResponse
;
2465 Demod
.state
= DEMOD_UNSYNCD
;
2467 // Set up the demodulator for the reader -> tag commands
2468 memset(&Uart
, 0, sizeof(Uart
));
2469 Uart
.output
= receivedCmd
;
2470 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
2471 Uart
.state
= STATE_UNSYNCD
;
2473 // Setup for the DMA.
2475 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
2477 // And put the FPGA in the appropriate mode
2478 // Signal field is off with the appropriate LED
2480 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
2481 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2485 int sniffCounter
= 0;
2487 // And now we loop, receiving samples.
2489 if(BUTTON_PRESS()) {
2490 DbpString("cancelled by button");
2497 if (++sniffCounter
> 65) {
2498 if (MfSniffSend(2000)) {
2504 int register readBufDataP
= data
- dmaBuf
;
2505 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
2506 if (readBufDataP
<= dmaBufDataP
){
2507 dataLen
= dmaBufDataP
- readBufDataP
;
2509 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
2511 // test for length of buffer
2512 if(dataLen
> maxDataLen
) {
2513 maxDataLen
= dataLen
;
2515 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
2519 if(dataLen
< 1) continue;
2521 // primary buffer was stopped( <-- we lost data!
2522 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
2523 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
2524 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
2525 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen
); // temporary
2527 // secondary buffer sets as primary, secondary buffer was stopped
2528 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
2529 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
2530 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
2535 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
2537 // check - if there is a short 7bit request from reader
2538 if (MfSniffLogic(receivedCmd
, Uart
.byteCnt
, Uart
.parityBits
, Uart
.bitCnt
, TRUE
)) break;
2540 /* And ready to receive another command. */
2541 Uart
.state
= STATE_UNSYNCD
;
2543 /* And also reset the demod code */
2544 Demod
.state
= DEMOD_UNSYNCD
;
2547 if(ManchesterDecoding(data
[0] & 0x0F)) {
2550 if (MfSniffLogic(receivedResponse
, Demod
.len
, Demod
.parityBits
, Demod
.bitCount
, FALSE
)) break;
2552 // And ready to receive another response.
2553 memset(&Demod
, 0, sizeof(Demod
));
2554 Demod
.output
= receivedResponse
;
2555 Demod
.state
= DEMOD_UNSYNCD
;
2557 /* And also reset the uart code */
2558 Uart
.state
= STATE_UNSYNCD
;
2562 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
2567 DbpString("COMMAND FINISHED");
2570 FpgaDisableSscDma();
2573 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);