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 parity bits
100 for (i
= 0; i
< iLen
; i
++) {
101 // and save them to a 32Bit word
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 decoder
379 //=============================================================================
381 // The tag will modulate the reader field by asserting different loads to it. As a consequence, the voltage
382 // at the reader antenna will be modulated as well. The FPGA detects the modulation for us and would deliver e.g. the following:
383 // ........ 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .......
384 // The Manchester decoder needs to identify the following sequences:
385 // 4 ticks modulated followed by 4 ticks unmodulated: Sequence D = 1 (also used as "start of communication")
386 // 4 ticks unmodulated followed by 4 ticks modulated: Sequence E = 0
387 // 8 ticks unmodulated: Sequence F = end of communication
388 // 8 ticks modulated: A collision. Save the collision position and treat as Sequence D
389 // Note 1: the bitstream may start at any time (either in first or second nibble within the parameter bit). We therefore need to sync.
390 // Note 2: parameter offset is used to determine the position of the parity bits (required for the anticollision command only)
393 inline RAMFUNC
bool IsModulation(byte_t b
)
395 if (b
>= 5 || b
== 3) // majority decision: 2 or more bits are set
402 inline RAMFUNC
bool IsModulationNibble1(byte_t b
)
404 return IsModulation((b
& 0xE0) >> 5);
407 inline RAMFUNC
bool IsModulationNibble2(byte_t b
)
409 return IsModulation((b
& 0x0E) >> 1);
412 static RAMFUNC
int ManchesterDecoding(int bit
, uint16_t offset
)
415 switch (Demod
.state
) {
417 case DEMOD_UNSYNCD
: // not yet synced
418 Demod
.len
= 0; // initialize number of decoded data bytes
419 Demod
.bitCount
= offset
; // initialize number of decoded data bits
420 Demod
.shiftReg
= 0; // initialize shiftreg to hold decoded data bits
421 Demod
.parityBits
= 0; // initialize parity bits
422 Demod
.collisionPos
= 0; // Position of collision bit
424 if (IsModulationNibble1(bit
)
425 && !IsModulationNibble2(bit
)) { // this is the start bit
427 if(trigger
) LED_A_OFF();
428 Demod
.state
= DEMOD_MANCHESTER_DATA
;
429 } else if (!IsModulationNibble1(bit
) && IsModulationNibble2(bit
)) { // this may be the first half of the start bit
431 Demod
.state
= DEMOD_HALF_SYNCD
;
436 case DEMOD_HALF_SYNCD
:
438 if (IsModulationNibble1(bit
)) { // error: this was not a start bit.
439 Demod
.state
= DEMOD_UNSYNCD
;
441 if (IsModulationNibble2(bit
)) { // modulation in first half
442 Demod
.state
= DEMOD_MOD_FIRST_HALF
;
443 } else { // no modulation in first half
444 Demod
.state
= DEMOD_NOMOD_FIRST_HALF
;
450 case DEMOD_MOD_FIRST_HALF
:
453 if (IsModulationNibble1(bit
)) { // modulation in both halfs - collision
454 if (!Demod
.collisionPos
) {
455 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
457 } // modulation in first half only - Sequence D = 1
458 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) | 0x100; // add a 1 to the shiftreg
459 if(Demod
.bitCount
>= 9) { // if we decoded a full byte (including parity)
460 Demod
.parityBits
<<= 1; // make room for the parity bit
461 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
462 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
466 if (IsModulationNibble2(bit
)) { // modulation in first half
467 Demod
.state
= DEMOD_MOD_FIRST_HALF
;
468 } else { // no modulation in first half
469 Demod
.state
= DEMOD_NOMOD_FIRST_HALF
;
474 case DEMOD_NOMOD_FIRST_HALF
:
475 if (IsModulationNibble1(bit
)) { // modulation in second half only - Sequence E = 0
478 Demod
.shiftReg
= (Demod
.shiftReg
>> 1); // add a 0 to the shiftreg
479 if(Demod
.bitCount
>= 9) { // if we decoded a full byte (including parity)
480 Demod
.parityBits
<<= 1; // make room for the new parity bit
481 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
482 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
486 } else { // no modulation in both halves - End of communication
488 if(Demod
.bitCount
> 0) { // if we decoded bits
489 Demod
.shiftReg
>>= (9 - Demod
.bitCount
); // add the remaining decoded bits to the output
490 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff;
491 // No parity bit, so just shift a 0
492 Demod
.parityBits
<<= 1;
494 Demod
.state
= DEMOD_UNSYNCD
; // start from the beginning
495 return TRUE
; // we are finished with decoding the raw data sequence
497 if (IsModulationNibble2(bit
)) { // modulation in first half
498 Demod
.state
= DEMOD_MOD_FIRST_HALF
;
499 } else { // no modulation in first half
500 Demod
.state
= DEMOD_NOMOD_FIRST_HALF
;
505 case DEMOD_MANCHESTER_DATA
:
507 if (IsModulationNibble1(bit
)) { // modulation in first half
508 if (IsModulationNibble2(bit
) & 0x0f) { // ... and in second half = collision
509 if (!Demod
.collisionPos
) {
510 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
512 } // modulation in first half only - Sequence D = 1
514 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) | 0x100; // in both cases, add a 1 to the shiftreg
515 if(Demod
.bitCount
>= 9) { // if we decoded a full byte (including parity)
516 Demod
.parityBits
<<= 1; // make room for the parity bit
517 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
518 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
522 } else { // no modulation in first half
523 if (IsModulationNibble2(bit
)) { // and modulation in second half = Sequence E = 0
525 Demod
.shiftReg
= (Demod
.shiftReg
>> 1); // add a 0 to the shiftreg
526 if(Demod
.bitCount
>= 9) { // if we decoded a full byte (including parity)
527 Demod
.parityBits
<<= 1; // make room for the new parity bit
528 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
529 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
533 } else { // no modulation in both halves - End of communication
534 if(Demod
.bitCount
> 0) { // if we decoded bits
535 Demod
.shiftReg
>>= (9 - Demod
.bitCount
); // add the remaining decoded bits to the output
536 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff;
537 // No parity bit, so just shift a 0
538 Demod
.parityBits
<<= 1;
540 Demod
.state
= DEMOD_UNSYNCD
; // start from the beginning
541 return TRUE
; // we are finished with decoding the raw data sequence
547 return FALSE
; // not finished yet, need more data
550 //=============================================================================
551 // Finally, a `sniffer' for ISO 14443 Type A
552 // Both sides of communication!
553 //=============================================================================
555 //-----------------------------------------------------------------------------
556 // Record the sequence of commands sent by the reader to the tag, with
557 // triggering so that we start recording at the point that the tag is moved
559 //-----------------------------------------------------------------------------
560 void RAMFUNC
SnoopIso14443a(uint8_t param
) {
562 // bit 0 - trigger from first card answer
563 // bit 1 - trigger from first reader 7-bit request
567 iso14a_clear_trace();
569 // We won't start recording the frames that we acquire until we trigger;
570 // a good trigger condition to get started is probably when we see a
571 // response from the tag.
572 // triggered == FALSE -- to wait first for card
573 int triggered
= !(param
& 0x03);
575 // The command (reader -> tag) that we're receiving.
576 // The length of a received command will in most cases be no more than 18 bytes.
577 // So 32 should be enough!
578 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
579 // The response (tag -> reader) that we're receiving.
580 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
582 // As we receive stuff, we copy it from receivedCmd or receivedResponse
583 // into trace, along with its length and other annotations.
584 //uint8_t *trace = (uint8_t *)BigBuf;
586 // The DMA buffer, used to stream samples from the FPGA
587 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
588 int8_t *data
= dmaBuf
;
592 // Set up the demodulator for tag -> reader responses.
593 Demod
.output
= receivedResponse
;
595 Demod
.state
= DEMOD_UNSYNCD
;
597 // Set up the demodulator for the reader -> tag commands
598 memset(&Uart
, 0, sizeof(Uart
));
599 Uart
.output
= receivedCmd
;
600 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
601 Uart
.state
= STATE_UNSYNCD
;
603 // Setup for the DMA.
605 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
607 // And put the FPGA in the appropriate mode
608 // Signal field is off with the appropriate LED
610 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
611 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
613 // Count of samples received so far, so that we can include timing
614 // information in the trace buffer.
616 // And now we loop, receiving samples.
619 DbpString("cancelled by button");
626 int register readBufDataP
= data
- dmaBuf
;
627 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
628 if (readBufDataP
<= dmaBufDataP
){
629 dataLen
= dmaBufDataP
- readBufDataP
;
631 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
633 // test for length of buffer
634 if(dataLen
> maxDataLen
) {
635 maxDataLen
= dataLen
;
637 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
641 if(dataLen
< 1) continue;
643 // primary buffer was stopped( <-- we lost data!
644 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
645 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
646 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
648 // secondary buffer sets as primary, secondary buffer was stopped
649 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
650 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
651 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
657 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
660 // check - if there is a short 7bit request from reader
661 if ((!triggered
) && (param
& 0x02) && (Uart
.byteCnt
== 1) && (Uart
.bitCnt
= 9)) triggered
= TRUE
;
664 if (!LogTrace(receivedCmd
, Uart
.byteCnt
, 0 - Uart
.samples
, Uart
.parityBits
, TRUE
)) break;
666 /* And ready to receive another command. */
667 Uart
.state
= STATE_UNSYNCD
;
668 /* And also reset the demod code, which might have been */
669 /* false-triggered by the commands from the reader. */
670 Demod
.state
= DEMOD_UNSYNCD
;
674 if(ManchesterDecoding(data
[0], 0)) {
677 if (!LogTrace(receivedResponse
, Demod
.len
, 0 - Demod
.samples
, Demod
.parityBits
, FALSE
)) break;
679 if ((!triggered
) && (param
& 0x01)) triggered
= TRUE
;
681 // And ready to receive another response.
682 memset(&Demod
, 0, sizeof(Demod
));
683 Demod
.output
= receivedResponse
;
684 Demod
.state
= DEMOD_UNSYNCD
;
689 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
694 DbpString("COMMAND FINISHED");
697 AT91C_BASE_PDC_SSC
->PDC_PTCR
= AT91C_PDC_RXTDIS
;
698 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
);
699 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart
.byteCntMax
, traceLen
, (int)Uart
.output
[0]);
703 //-----------------------------------------------------------------------------
704 // Prepare tag messages
705 //-----------------------------------------------------------------------------
706 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, int len
, uint32_t dwParity
)
712 // Correction bit, might be removed when not needed
717 ToSendStuffBit(1); // 1
723 ToSend
[++ToSendMax
] = SEC_D
;
725 for(i
= 0; i
< len
; i
++) {
730 for(j
= 0; j
< 8; j
++) {
732 ToSend
[++ToSendMax
] = SEC_D
;
734 ToSend
[++ToSendMax
] = SEC_E
;
739 // Get the parity bit
740 if ((dwParity
>> i
) & 0x01) {
741 ToSend
[++ToSendMax
] = SEC_D
;
743 ToSend
[++ToSendMax
] = SEC_E
;
748 ToSend
[++ToSendMax
] = SEC_F
;
750 // Convert from last byte pos to length
754 static void CodeIso14443aAsTag(const uint8_t *cmd
, int len
){
755 CodeIso14443aAsTagPar(cmd
, len
, GetParity(cmd
, len
));
758 ////-----------------------------------------------------------------------------
759 //// This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
760 ////-----------------------------------------------------------------------------
761 //static void CodeStrangeAnswerAsTag()
767 // // Correction bit, might be removed when not needed
768 // ToSendStuffBit(0);
769 // ToSendStuffBit(0);
770 // ToSendStuffBit(0);
771 // ToSendStuffBit(0);
772 // ToSendStuffBit(1); // 1
773 // ToSendStuffBit(0);
774 // ToSendStuffBit(0);
775 // ToSendStuffBit(0);
778 // ToSend[++ToSendMax] = SEC_D;
781 // ToSend[++ToSendMax] = SEC_E;
784 // ToSend[++ToSendMax] = SEC_E;
787 // ToSend[++ToSendMax] = SEC_D;
790 // ToSend[++ToSendMax] = SEC_F;
792 // // Flush the buffer in FPGA!!
793 // for(i = 0; i < 5; i++) {
794 // ToSend[++ToSendMax] = SEC_F;
797 // // Convert from last byte pos to length
801 static void Code4bitAnswerAsTag(uint8_t cmd
)
807 // Correction bit, might be removed when not needed
812 ToSendStuffBit(1); // 1
818 ToSend
[++ToSendMax
] = SEC_D
;
821 for(i
= 0; i
< 4; i
++) {
823 ToSend
[++ToSendMax
] = SEC_D
;
825 ToSend
[++ToSendMax
] = SEC_E
;
831 ToSend
[++ToSendMax
] = SEC_F
;
833 // Flush the buffer in FPGA!!
834 for(i
= 0; i
< 5; i
++) {
835 ToSend
[++ToSendMax
] = SEC_F
;
838 // Convert from last byte pos to length
842 //-----------------------------------------------------------------------------
843 // Wait for commands from reader
844 // Stop when button is pressed
845 // Or return TRUE when command is captured
846 //-----------------------------------------------------------------------------
847 static int GetIso14443aCommandFromReader(uint8_t *received
, int *len
, int maxLen
)
849 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
850 // only, since we are receiving, not transmitting).
851 // Signal field is off with the appropriate LED
853 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
855 // Now run a `software UART' on the stream of incoming samples.
856 Uart
.output
= received
;
857 Uart
.byteCntMax
= maxLen
;
858 Uart
.state
= STATE_UNSYNCD
;
863 if(BUTTON_PRESS()) return FALSE
;
865 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
866 AT91C_BASE_SSC
->SSC_THR
= 0x00;
868 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
869 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
870 if(MillerDecoding((b
& 0xf0) >> 4)) {
874 if(MillerDecoding(b
& 0x0f)) {
882 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
);
883 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
);
884 int EmSend4bit(uint8_t resp
);
885 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
);
886 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
);
887 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
);
888 int EmSendCmd(uint8_t *resp
, int respLen
);
889 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
);
891 static uint8_t* free_buffer_pointer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
898 } tag_response_info_t
;
900 void reset_free_buffer() {
901 free_buffer_pointer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
904 bool prepare_tag_modulation(tag_response_info_t
* response_info
, size_t max_buffer_size
) {
905 // Exmaple response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
906 // This will need the following byte array for a modulation sequence
907 // 144 data bits (18 * 8)
910 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
911 // 1 just for the case
913 // 166 bytes, since every bit that needs to be send costs us a byte
916 // Prepare the tag modulation bits from the message
917 CodeIso14443aAsTag(response_info
->response
,response_info
->response_n
);
919 // Make sure we do not exceed the free buffer space
920 if (ToSendMax
> max_buffer_size
) {
921 Dbprintf("Out of memory, when modulating bits for tag answer:");
922 Dbhexdump(response_info
->response_n
,response_info
->response
,false);
926 // Copy the byte array, used for this modulation to the buffer position
927 memcpy(response_info
->modulation
,ToSend
,ToSendMax
);
929 // Store the number of bytes that were used for encoding/modulation
930 response_info
->modulation_n
= ToSendMax
;
935 bool prepare_allocated_tag_modulation(tag_response_info_t
* response_info
) {
936 // Retrieve and store the current buffer index
937 response_info
->modulation
= free_buffer_pointer
;
939 // Determine the maximum size we can use from our buffer
940 size_t max_buffer_size
= (((uint8_t *)BigBuf
)+FREE_BUFFER_OFFSET
+FREE_BUFFER_SIZE
)-free_buffer_pointer
;
942 // Forward the prepare tag modulation function to the inner function
943 if (prepare_tag_modulation(response_info
,max_buffer_size
)) {
944 // Update the free buffer offset
945 free_buffer_pointer
+= ToSendMax
;
952 //-----------------------------------------------------------------------------
953 // Main loop of simulated tag: receive commands from reader, decide what
954 // response to send, and send it.
955 //-----------------------------------------------------------------------------
956 void SimulateIso14443aTag(int tagType
, int uid_1st
, int uid_2nd
, byte_t
* data
)
958 // Enable and clear the trace
960 iso14a_clear_trace();
962 // This function contains the tag emulation
965 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
966 uint8_t response1
[2];
969 case 1: { // MIFARE Classic
970 // Says: I am Mifare 1k - original line
975 case 2: { // MIFARE Ultralight
976 // Says: I am a stupid memory tag, no crypto
981 case 3: { // MIFARE DESFire
982 // Says: I am a DESFire tag, ph33r me
987 case 4: { // ISO/IEC 14443-4
988 // Says: I am a javacard (JCOP)
994 Dbprintf("Error: unkown tagtype (%d)",tagType
);
999 // The second response contains the (mandatory) first 24 bits of the UID
1000 uint8_t response2
[5];
1002 // Check if the uid uses the (optional) part
1003 uint8_t response2a
[5];
1005 response2
[0] = 0x88;
1006 num_to_bytes(uid_1st
,3,response2
+1);
1007 num_to_bytes(uid_2nd
,4,response2a
);
1008 response2a
[4] = response2a
[0] ^ response2a
[1] ^ response2a
[2] ^ response2a
[3];
1010 // Configure the ATQA and SAK accordingly
1011 response1
[0] |= 0x40;
1014 num_to_bytes(uid_1st
,4,response2
);
1015 // Configure the ATQA and SAK accordingly
1016 response1
[0] &= 0xBF;
1020 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
1021 response2
[4] = response2
[0] ^ response2
[1] ^ response2
[2] ^ response2
[3];
1023 // Prepare the mandatory SAK (for 4 and 7 byte UID)
1024 uint8_t response3
[3];
1026 ComputeCrc14443(CRC_14443_A
, response3
, 1, &response3
[1], &response3
[2]);
1028 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
1029 uint8_t response3a
[3];
1030 response3a
[0] = sak
& 0xFB;
1031 ComputeCrc14443(CRC_14443_A
, response3a
, 1, &response3a
[1], &response3a
[2]);
1033 uint8_t response5
[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
1034 uint8_t response6
[] = { 0x04, 0x58, 0x00, 0x02, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
1035 ComputeCrc14443(CRC_14443_A
, response6
, 4, &response6
[4], &response6
[5]);
1037 #define TAG_RESPONSE_COUNT 7
1038 tag_response_info_t responses
[TAG_RESPONSE_COUNT
] = {
1039 { .response
= response1
, .response_n
= sizeof(response1
) }, // Answer to request - respond with card type
1040 { .response
= response2
, .response_n
= sizeof(response2
) }, // Anticollision cascade1 - respond with uid
1041 { .response
= response2a
, .response_n
= sizeof(response2a
) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1042 { .response
= response3
, .response_n
= sizeof(response3
) }, // Acknowledge select - cascade 1
1043 { .response
= response3a
, .response_n
= sizeof(response3a
) }, // Acknowledge select - cascade 2
1044 { .response
= response5
, .response_n
= sizeof(response5
) }, // Authentication answer (random nonce)
1045 { .response
= response6
, .response_n
= sizeof(response6
) }, // dummy ATS (pseudo-ATR), answer to RATS
1048 // Allocate 512 bytes for the dynamic modulation, created when the reader querries for it
1049 // Such a response is less time critical, so we can prepare them on the fly
1050 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1051 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1052 uint8_t dynamic_response_buffer
[DYNAMIC_RESPONSE_BUFFER_SIZE
];
1053 uint8_t dynamic_modulation_buffer
[DYNAMIC_MODULATION_BUFFER_SIZE
];
1054 tag_response_info_t dynamic_response_info
= {
1055 .response
= dynamic_response_buffer
,
1057 .modulation
= dynamic_modulation_buffer
,
1061 // Reset the offset pointer of the free buffer
1062 reset_free_buffer();
1064 // Prepare the responses of the anticollision phase
1065 // there will be not enough time to do this at the moment the reader sends it REQA
1066 for (size_t i
=0; i
<TAG_RESPONSE_COUNT
; i
++) {
1067 prepare_allocated_tag_modulation(&responses
[i
]);
1070 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
1073 // To control where we are in the protocol
1077 // Just to allow some checks
1082 // We need to listen to the high-frequency, peak-detected path.
1083 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1087 tag_response_info_t
* p_response
;
1091 // Clean receive command buffer
1092 memset(receivedCmd
, 0x44, RECV_CMD_SIZE
);
1094 if(!GetIso14443aCommandFromReader(receivedCmd
, &len
, RECV_CMD_SIZE
)) {
1095 DbpString("Button press");
1100 LogTrace(receivedCmd
,len
, 0, Uart
.parityBits
, TRUE
);
1105 // 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
1106 // Okay, look at the command now.
1108 if(receivedCmd
[0] == 0x26) { // Received a REQUEST
1109 p_response
= &responses
[0]; order
= 1;
1110 } else if(receivedCmd
[0] == 0x52) { // Received a WAKEUP
1111 p_response
= &responses
[0]; order
= 6;
1112 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x93) { // Received request for UID (cascade 1)
1113 p_response
= &responses
[1]; order
= 2;
1114 } else if(receivedCmd
[1] == 0x20 && receivedCmd
[0] == 0x95) { // Received request for UID (cascade 2)
1115 p_response
= &responses
[2]; order
= 20;
1116 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x93) { // Received a SELECT (cascade 1)
1117 p_response
= &responses
[3]; order
= 3;
1118 } else if(receivedCmd
[1] == 0x70 && receivedCmd
[0] == 0x95) { // Received a SELECT (cascade 2)
1119 p_response
= &responses
[4]; order
= 30;
1120 } else if(receivedCmd
[0] == 0x30) { // Received a (plain) READ
1121 EmSendCmdEx(data
+(4*receivedCmd
[0]),16,false);
1122 Dbprintf("Read request from reader: %x %x",receivedCmd
[0],receivedCmd
[1]);
1123 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1125 } else if(receivedCmd
[0] == 0x50) { // Received a HALT
1126 // DbpString("Reader requested we HALT!:");
1128 } else if(receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61) { // Received an authentication request
1129 p_response
= &responses
[5]; order
= 7;
1130 } else if(receivedCmd
[0] == 0xE0) { // Received a RATS request
1131 p_response
= &responses
[6]; order
= 70;
1132 } else if (order
== 7 && len
==8) { // Received authentication request
1133 uint32_t nr
= bytes_to_num(receivedCmd
,4);
1134 uint32_t ar
= bytes_to_num(receivedCmd
+4,4);
1135 Dbprintf("Auth attempt {nr}{ar}: %08x %08x",nr
,ar
);
1137 // Check for ISO 14443A-4 compliant commands, look at left nibble
1138 switch (receivedCmd
[0]) {
1141 case 0x0A: { // IBlock (command)
1142 dynamic_response_info
.response
[0] = receivedCmd
[0];
1143 dynamic_response_info
.response
[1] = 0x00;
1144 dynamic_response_info
.response
[2] = 0x90;
1145 dynamic_response_info
.response
[3] = 0x00;
1146 dynamic_response_info
.response_n
= 4;
1150 case 0x1B: { // Chaining command
1151 dynamic_response_info
.response
[0] = 0xaa | ((receivedCmd
[0]) & 1);
1152 dynamic_response_info
.response_n
= 2;
1157 dynamic_response_info
.response
[0] = receivedCmd
[0] ^ 0x11;
1158 dynamic_response_info
.response_n
= 2;
1162 memcpy(dynamic_response_info
.response
,"\xAB\x00",2);
1163 dynamic_response_info
.response_n
= 2;
1167 case 0xC2: { // Readers sends deselect command
1168 memcpy(dynamic_response_info
.response
,"\xCA\x00",2);
1169 dynamic_response_info
.response_n
= 2;
1173 // Never seen this command before
1174 Dbprintf("Received unknown command (len=%d):",len
);
1175 Dbhexdump(len
,receivedCmd
,false);
1177 dynamic_response_info
.response_n
= 0;
1181 if (dynamic_response_info
.response_n
> 0) {
1182 // Copy the CID from the reader query
1183 dynamic_response_info
.response
[1] = receivedCmd
[1];
1185 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1186 AppendCrc14443a(dynamic_response_info
.response
,dynamic_response_info
.response_n
);
1187 dynamic_response_info
.response_n
+= 2;
1189 if (prepare_tag_modulation(&dynamic_response_info
,DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
1190 Dbprintf("Error preparing tag response");
1193 p_response
= &dynamic_response_info
;
1197 // Count number of wakeups received after a halt
1198 if(order
== 6 && lastorder
== 5) { happened
++; }
1200 // Count number of other messages after a halt
1201 if(order
!= 6 && lastorder
== 5) { happened2
++; }
1203 // Look at last parity bit to determine timing of answer
1204 if((Uart
.parityBits
& 0x01) || receivedCmd
[0] == 0x52) {
1205 // 1236, so correction bit needed
1209 if(cmdsRecvd
> 999) {
1210 DbpString("1000 commands later...");
1215 if (p_response
!= NULL
) {
1216 EmSendCmd14443aRaw(p_response
->modulation
, p_response
->modulation_n
, receivedCmd
[0] == 0x52);
1218 LogTrace(p_response
->response
,p_response
->response_n
,0,SwapBits(GetParity(p_response
->response
,p_response
->response_n
),p_response
->response_n
),FALSE
);
1219 if(traceLen
> TRACE_SIZE
) {
1220 DbpString("Trace full");
1227 Dbprintf("%x %x %x", happened
, happened2
, cmdsRecvd
);
1232 // prepare a delayed transfer. This simply shifts ToSend[] by a number
1233 // of bits specified in the delay parameter.
1234 void PrepareDelayedTransfer(uint16_t delay
)
1236 uint8_t bitmask
= 0;
1237 uint8_t bits_to_shift
= 0;
1238 uint8_t bits_shifted
= 0;
1242 for (uint16_t i
= 0; i
< delay
; i
++) {
1243 bitmask
|= (0x01 << i
);
1245 ToSend
[++ToSendMax
] = 0x00;
1246 for (uint16_t i
= 0; i
< ToSendMax
; i
++) {
1247 bits_to_shift
= ToSend
[i
] & bitmask
;
1248 ToSend
[i
] = ToSend
[i
] >> delay
;
1249 ToSend
[i
] = ToSend
[i
] | (bits_shifted
<< (8 - delay
));
1250 bits_shifted
= bits_to_shift
;
1255 //-----------------------------------------------------------------------------
1256 // Transmit the command (to the tag) that was placed in ToSend[].
1257 // Parameter timing:
1259 // if == 0: return time of transfer
1260 // if != 0: delay transfer until time specified
1261 //-----------------------------------------------------------------------------
1262 static void TransmitFor14443a(const uint8_t *cmd
, int len
, uint32_t *timing
)
1266 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1270 if(*timing
== 0) { // Measure time
1271 *timing
= (GetCountMifare() + 8) & 0xfffffff8;
1273 PrepareDelayedTransfer(*timing
& 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
1275 if(MF_DBGLEVEL
>= 4 && GetCountMifare() >= (*timing
& 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
1276 while(GetCountMifare() < (*timing
& 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
1279 for(c
= 0; c
< 10;) { // standard delay for each transfer (allow tag to be ready after last transmission?)
1280 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1281 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1288 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1289 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1299 //-----------------------------------------------------------------------------
1300 // Prepare reader command (in bits, support short frames) to send to FPGA
1301 //-----------------------------------------------------------------------------
1302 void CodeIso14443aBitsAsReaderPar(const uint8_t * cmd
, int bits
, uint32_t dwParity
)
1310 // Start of Communication (Seq. Z)
1311 ToSend
[++ToSendMax
] = SEC_Z
;
1314 size_t bytecount
= nbytes(bits
);
1315 // Generate send structure for the data bits
1316 for (i
= 0; i
< bytecount
; i
++) {
1317 // Get the current byte to send
1319 size_t bitsleft
= MIN((bits
-(i
*8)),8);
1321 for (j
= 0; j
< bitsleft
; j
++) {
1324 ToSend
[++ToSendMax
] = SEC_X
;
1329 ToSend
[++ToSendMax
] = SEC_Z
;
1332 ToSend
[++ToSendMax
] = SEC_Y
;
1339 // Only transmit (last) parity bit if we transmitted a complete byte
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
;
1359 // End of Communication
1362 ToSend
[++ToSendMax
] = SEC_Z
;
1365 ToSend
[++ToSendMax
] = SEC_Y
;
1369 ToSend
[++ToSendMax
] = SEC_Y
;
1372 ToSend
[++ToSendMax
] = SEC_Y
;
1373 ToSend
[++ToSendMax
] = SEC_Y
;
1374 ToSend
[++ToSendMax
] = SEC_Y
;
1376 // Convert from last character reference to length
1380 //-----------------------------------------------------------------------------
1381 // Prepare reader command to send to FPGA
1382 //-----------------------------------------------------------------------------
1383 void CodeIso14443aAsReaderPar(const uint8_t * cmd
, int len
, uint32_t dwParity
)
1385 CodeIso14443aBitsAsReaderPar(cmd
,len
*8,dwParity
);
1388 //-----------------------------------------------------------------------------
1389 // Wait for commands from reader
1390 // Stop when button is pressed (return 1) or field was gone (return 2)
1391 // Or return 0 when command is captured
1392 //-----------------------------------------------------------------------------
1393 static int EmGetCmd(uint8_t *received
, int *len
, int maxLen
)
1397 uint32_t timer
= 0, vtime
= 0;
1401 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1402 // only, since we are receiving, not transmitting).
1403 // Signal field is off with the appropriate LED
1405 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1407 // Set ADC to read field strength
1408 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1409 AT91C_BASE_ADC
->ADC_MR
=
1410 ADC_MODE_PRESCALE(32) |
1411 ADC_MODE_STARTUP_TIME(16) |
1412 ADC_MODE_SAMPLE_HOLD_TIME(8);
1413 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1415 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1417 // Now run a 'software UART' on the stream of incoming samples.
1418 Uart
.output
= received
;
1419 Uart
.byteCntMax
= maxLen
;
1420 Uart
.state
= STATE_UNSYNCD
;
1425 if (BUTTON_PRESS()) return 1;
1427 // test if the field exists
1428 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
1430 analogAVG
+= AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
];
1431 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1432 if (analogCnt
>= 32) {
1433 if ((33000 * (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
1434 vtime
= GetTickCount();
1435 if (!timer
) timer
= vtime
;
1436 // 50ms no field --> card to idle state
1437 if (vtime
- timer
> 50) return 2;
1439 if (timer
) timer
= 0;
1445 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1446 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1448 // receive and test the miller decoding
1449 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1450 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1451 if(MillerDecoding((b
& 0xf0) >> 4)) {
1452 *len
= Uart
.byteCnt
;
1453 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1456 if(MillerDecoding(b
& 0x0f)) {
1457 *len
= Uart
.byteCnt
;
1458 if (tracing
) LogTrace(received
, *len
, GetDeltaCountUS(), Uart
.parityBits
, TRUE
);
1465 static int EmSendCmd14443aRaw(uint8_t *resp
, int respLen
, int correctionNeeded
)
1470 // Modulate Manchester
1471 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
1472 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1475 // include correction bit
1477 if((Uart
.parityBits
& 0x01) || correctionNeeded
) {
1478 // 1236, so correction bit needed
1484 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1485 volatile uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1488 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1490 b
= 0xff; // was 0x00
1496 AT91C_BASE_SSC
->SSC_THR
= b
;
1500 if(BUTTON_PRESS()) {
1508 int EmSend4bitEx(uint8_t resp
, int correctionNeeded
){
1509 Code4bitAnswerAsTag(resp
);
1510 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1511 if (tracing
) LogTrace(&resp
, 1, GetDeltaCountUS(), GetParity(&resp
, 1), FALSE
);
1515 int EmSend4bit(uint8_t resp
){
1516 return EmSend4bitEx(resp
, 0);
1519 int EmSendCmdExPar(uint8_t *resp
, int respLen
, int correctionNeeded
, uint32_t par
){
1520 CodeIso14443aAsTagPar(resp
, respLen
, par
);
1521 int res
= EmSendCmd14443aRaw(ToSend
, ToSendMax
, correctionNeeded
);
1522 if (tracing
) LogTrace(resp
, respLen
, GetDeltaCountUS(), par
, FALSE
);
1526 int EmSendCmdEx(uint8_t *resp
, int respLen
, int correctionNeeded
){
1527 return EmSendCmdExPar(resp
, respLen
, correctionNeeded
, GetParity(resp
, respLen
));
1530 int EmSendCmd(uint8_t *resp
, int respLen
){
1531 return EmSendCmdExPar(resp
, respLen
, 0, GetParity(resp
, respLen
));
1534 int EmSendCmdPar(uint8_t *resp
, int respLen
, uint32_t par
){
1535 return EmSendCmdExPar(resp
, respLen
, 0, par
);
1538 //-----------------------------------------------------------------------------
1539 // Wait a certain time for tag response
1540 // If a response is captured return TRUE
1541 // If it takes too long return FALSE
1542 //-----------------------------------------------------------------------------
1543 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, uint16_t offset
, int maxLen
, int *samples
)
1547 // Set FPGA mode to "reader listen mode", no modulation (listen
1548 // only, since we are receiving, not transmitting).
1549 // Signal field is on with the appropriate LED
1551 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1553 // Now get the answer from the card
1554 Demod
.output
= receivedResponse
;
1556 Demod
.state
= DEMOD_UNSYNCD
;
1564 // if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1565 // AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1566 // if (elapsed) (*elapsed)++;
1568 if(AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1569 if(c
< iso14a_timeout
) { c
++; } else { return FALSE
; }
1570 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1571 if(ManchesterDecoding(b
, offset
)) {
1572 *samples
= Demod
.samples
;
1579 void ReaderTransmitBitsPar(uint8_t* frame
, int bits
, uint32_t par
, uint32_t *timing
)
1582 CodeIso14443aBitsAsReaderPar(frame
,bits
,par
);
1584 // Send command to tag
1585 TransmitFor14443a(ToSend
, ToSendMax
, timing
);
1589 // Log reader command in trace buffer
1590 if (tracing
) LogTrace(frame
,nbytes(bits
),0,par
,TRUE
);
1593 void ReaderTransmitPar(uint8_t* frame
, int len
, uint32_t par
, uint32_t *timing
)
1595 ReaderTransmitBitsPar(frame
,len
*8,par
, timing
);
1598 void ReaderTransmitBits(uint8_t* frame
, int len
, uint32_t *timing
)
1600 // Generate parity and redirect
1601 ReaderTransmitBitsPar(frame
,len
,GetParity(frame
,len
/8), timing
);
1604 void ReaderTransmit(uint8_t* frame
, int len
, uint32_t *timing
)
1606 // Generate parity and redirect
1607 ReaderTransmitBitsPar(frame
,len
*8,GetParity(frame
,len
), timing
);
1610 int ReaderReceiveOffset(uint8_t* receivedAnswer
, uint16_t offset
)
1613 if (!GetIso14443aAnswerFromTag(receivedAnswer
,offset
,160,&samples
)) return FALSE
;
1614 if (tracing
) LogTrace(receivedAnswer
,Demod
.len
,samples
,Demod
.parityBits
,FALSE
);
1615 if(samples
== 0) return FALSE
;
1619 int ReaderReceive(uint8_t* receivedAnswer
)
1621 return ReaderReceiveOffset(receivedAnswer
, 0);
1624 int ReaderReceivePar(uint8_t *receivedAnswer
, uint32_t *parptr
)
1627 if (!GetIso14443aAnswerFromTag(receivedAnswer
,0,160,&samples
)) 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 anticollision procedure
1635 * fills the uid pointer unless NULL
1636 * fills resp_data unless NULL */
1637 int iso14443a_select_card(byte_t
* uid_ptr
, iso14a_card_select_t
* p_hi14a_card
, 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
1642 uint8_t* resp
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
); // was 3560 - tied to other size changes
1644 size_t uid_resp_len
;
1646 uint8_t sak
= 0x04; // cascade uid
1647 int cascade_level
= 0;
1650 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1651 ReaderTransmitBitsPar(wupa
,7,0, NULL
);
1653 if(!ReaderReceive(resp
)) return 0;
1654 // Dbprintf("atqa: %02x %02x",resp[0],resp[1]);
1657 memcpy(p_hi14a_card
->atqa
, resp
, 2);
1658 p_hi14a_card
->uidlen
= 0;
1659 memset(p_hi14a_card
->uid
,0,10);
1664 memset(uid_ptr
,0,10);
1667 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1668 // which case we need to make a cascade 2 request and select - this is a long UID
1669 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1670 for(; sak
& 0x04; cascade_level
++) {
1671 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1672 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
1675 ReaderTransmit(sel_all
,sizeof(sel_all
), NULL
);
1676 if (!ReaderReceive(resp
)) return 0;
1678 if (Demod
.collisionPos
) { // we had a collision and need to construct the UID bit by bit
1679 memset(uid_resp
, 0, 4);
1680 uint16_t uid_resp_bits
= 0;
1681 uint16_t collision_answer_offset
= 0;
1682 // anti-collision-loop:
1683 while (Demod
.collisionPos
) {
1684 Dbprintf("Multiple tags detected. Collision after Bit %d", Demod
.collisionPos
);
1685 for (uint16_t i
= collision_answer_offset
; i
< Demod
.collisionPos
; i
++, uid_resp_bits
++) { // add valid UID bits before collision point
1686 uint16_t UIDbit
= (resp
[i
/8] >> (i
% 8)) & 0x01;
1687 uid_resp
[uid_resp_bits
& 0xf8] |= UIDbit
<< (uid_resp_bits
% 8);
1689 uid_resp
[uid_resp_bits
/8] |= 1 << (uid_resp_bits
% 8); // next time select the card(s) with a 1 in the collision position
1691 // construct anticollosion command:
1692 sel_uid
[1] = ((2 + uid_resp_bits
/8) << 4) | (uid_resp_bits
& 0x07); // length of data in bytes and bits
1693 for (uint16_t i
= 0; i
<= uid_resp_bits
/8; i
++) {
1694 sel_uid
[2+i
] = uid_resp
[i
];
1696 collision_answer_offset
= uid_resp_bits
%8;
1697 ReaderTransmitBits(sel_uid
, 16 + uid_resp_bits
, NULL
);
1698 if (!ReaderReceiveOffset(resp
, collision_answer_offset
)) return 0;
1700 // finally, add the last bits and BCC of the UID
1701 for (uint16_t i
= collision_answer_offset
; i
< (Demod
.len
-1)*8; i
++, uid_resp_bits
++) {
1702 uint16_t UIDbit
= (resp
[i
/8] >> (i
%8)) & 0x01;
1703 uid_resp
[uid_resp_bits
/8] |= UIDbit
<< (uid_resp_bits
% 8);
1706 } else { // no collision, use the response to SELECT_ALL as current uid
1707 memcpy(uid_resp
,resp
,4);
1710 // Dbprintf("uid: %02x %02x %02x %02x",uid_resp[0],uid_resp[1],uid_resp[2],uid_resp[3]);
1712 // calculate crypto UID. Always use last 4 Bytes.
1714 *cuid_ptr
= bytes_to_num(uid_resp
, 4);
1717 // Construct SELECT UID command
1718 sel_uid
[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
1719 memcpy(sel_uid
+2,uid_resp
,4); // the UID
1720 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
1721 AppendCrc14443a(sel_uid
,7); // calculate and add CRC
1722 ReaderTransmit(sel_uid
,sizeof(sel_uid
), NULL
);
1725 if (!ReaderReceive(resp
)) return 0;
1728 // Test if more parts of the uid are comming
1729 if ((sak
& 0x04) /* && uid_resp[0] == 0x88 */) {
1730 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
1731 // http://www.nxp.com/documents/application_note/AN10927.pdf
1732 memcpy(uid_resp
, uid_resp
+ 1, 3);
1737 memcpy(uid_ptr
+ (cascade_level
*3), uid_resp
, uid_resp_len
);
1741 memcpy(p_hi14a_card
->uid
+ (cascade_level
*3), uid_resp
, uid_resp_len
);
1742 p_hi14a_card
->uidlen
+= uid_resp_len
;
1747 p_hi14a_card
->sak
= sak
;
1748 p_hi14a_card
->ats_len
= 0;
1751 if( (sak
& 0x20) == 0) {
1752 return 2; // non iso14443a compliant tag
1755 // Request for answer to select
1756 AppendCrc14443a(rats
, 2);
1757 ReaderTransmit(rats
, sizeof(rats
), NULL
);
1759 if (!(len
= ReaderReceive(resp
))) return 0;
1762 memcpy(p_hi14a_card
->ats
, resp
, sizeof(p_hi14a_card
->ats
));
1763 p_hi14a_card
->ats_len
= len
;
1766 // reset the PCB block number
1767 iso14_pcb_blocknum
= 0;
1771 void iso14443a_setup() {
1772 // Set up the synchronous serial port
1774 // Start from off (no field generated)
1775 // Signal field is off with the appropriate LED
1777 // FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1780 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1782 // Now give it time to spin up.
1783 // Signal field is on with the appropriate LED
1785 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1786 SpinDelay(7); // iso14443-3 specifies 5ms max.
1788 Demod
.state
= DEMOD_UNSYNCD
;
1789 iso14a_timeout
= 2048; //default
1792 int iso14_apdu(uint8_t * cmd
, size_t cmd_len
, void * data
) {
1793 uint8_t real_cmd
[cmd_len
+4];
1794 real_cmd
[0] = 0x0a; //I-Block
1795 // put block number into the PCB
1796 real_cmd
[0] |= iso14_pcb_blocknum
;
1797 real_cmd
[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1798 memcpy(real_cmd
+2, cmd
, cmd_len
);
1799 AppendCrc14443a(real_cmd
,cmd_len
+2);
1801 ReaderTransmit(real_cmd
, cmd_len
+4, NULL
);
1802 size_t len
= ReaderReceive(data
);
1803 uint8_t * data_bytes
= (uint8_t *) data
;
1805 return 0; //DATA LINK ERROR
1806 // if we received an I- or R(ACK)-Block with a block number equal to the
1807 // current block number, toggle the current block number
1808 else if (len
>= 4 // PCB+CID+CRC = 4 bytes
1809 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
1810 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1811 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) // equal block numbers
1813 iso14_pcb_blocknum
^= 1;
1819 //-----------------------------------------------------------------------------
1820 // Read an ISO 14443a tag. Send out commands and store answers.
1822 //-----------------------------------------------------------------------------
1823 void ReaderIso14443a(UsbCommand
* c
)
1825 iso14a_command_t param
= c
->arg
[0];
1826 uint8_t * cmd
= c
->d
.asBytes
;
1827 size_t len
= c
->arg
[1];
1828 size_t lenbits
= c
->arg
[2];
1830 byte_t buf
[USB_CMD_DATA_SIZE
];
1832 if(param
& ISO14A_CONNECT
) {
1833 iso14a_clear_trace();
1836 iso14a_set_tracing(true);
1838 if(param
& ISO14A_REQUEST_TRIGGER
) {
1839 iso14a_set_trigger(1);
1842 if(param
& ISO14A_CONNECT
) {
1844 if(!(param
& ISO14A_NO_SELECT
)) {
1845 iso14a_card_select_t
*card
= (iso14a_card_select_t
*)buf
;
1846 arg0
= iso14443a_select_card(NULL
,card
,NULL
);
1847 cmd_send(CMD_ACK
,arg0
,card
->uidlen
,0,buf
,sizeof(iso14a_card_select_t
));
1851 if(param
& ISO14A_SET_TIMEOUT
) {
1852 iso14a_timeout
= c
->arg
[2];
1855 if(param
& ISO14A_SET_TIMEOUT
) {
1856 iso14a_timeout
= c
->arg
[2];
1859 if(param
& ISO14A_APDU
) {
1860 arg0
= iso14_apdu(cmd
, len
, buf
);
1861 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(buf
));
1864 if(param
& ISO14A_RAW
) {
1865 if(param
& ISO14A_APPEND_CRC
) {
1866 AppendCrc14443a(cmd
,len
);
1870 ReaderTransmitBitsPar(cmd
,lenbits
,GetParity(cmd
,lenbits
/8), NULL
);
1872 ReaderTransmit(cmd
,len
, NULL
);
1874 arg0
= ReaderReceive(buf
);
1875 cmd_send(CMD_ACK
,arg0
,0,0,buf
,sizeof(buf
));
1878 if(param
& ISO14A_REQUEST_TRIGGER
) {
1879 iso14a_set_trigger(0);
1882 if(param
& ISO14A_NO_DISCONNECT
) {
1886 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1891 // Determine the distance between two nonces.
1892 // Assume that the difference is small, but we don't know which is first.
1893 // Therefore try in alternating directions.
1894 int32_t dist_nt(uint32_t nt1
, uint32_t nt2
) {
1897 uint32_t nttmp1
, nttmp2
;
1899 if (nt1
== nt2
) return 0;
1904 for (i
= 1; i
< 32768; i
++) {
1905 nttmp1
= prng_successor(nttmp1
, 1);
1906 if (nttmp1
== nt2
) return i
;
1907 nttmp2
= prng_successor(nttmp2
, 1);
1908 if (nttmp2
== nt1
) return -i
;
1911 return(-99999); // either nt1 or nt2 are invalid nonces
1915 //-----------------------------------------------------------------------------
1916 // Recover several bits of the cypher stream. This implements (first stages of)
1917 // the algorithm described in "The Dark Side of Security by Obscurity and
1918 // Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
1919 // (article by Nicolas T. Courtois, 2009)
1920 //-----------------------------------------------------------------------------
1921 void ReaderMifare(bool first_try
)
1924 uint8_t mf_auth
[] = { 0x60,0x00,0xf5,0x7b };
1925 uint8_t mf_nr_ar
[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1926 static uint8_t mf_nr_ar3
;
1928 uint8_t* receivedAnswer
= (((uint8_t *)BigBuf
) + FREE_BUFFER_OFFSET
);
1929 iso14a_clear_trace();
1934 //byte_t par_mask = 0xff;
1935 static byte_t par_low
= 0;
1940 uint32_t nt
, previous_nt
;
1941 static uint32_t nt_attacked
= 0;
1942 byte_t par_list
[8] = {0,0,0,0,0,0,0,0};
1943 byte_t ks_list
[8] = {0,0,0,0,0,0,0,0};
1945 static uint32_t sync_time
;
1946 static uint32_t sync_cycles
;
1947 int catch_up_cycles
= 0;
1948 int last_catch_up
= 0;
1949 uint16_t consecutive_resyncs
= 0;
1958 while((GetCountMifare() & 0xffff0000) != 0x10000); // wait for counter to reset and "warm up"
1959 sync_time
= GetCountMifare() & 0xfffffff8;
1960 sync_cycles
= 65536; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
1966 // we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same)
1967 // nt_attacked = prng_successor(nt_attacked, 1);
1969 mf_nr_ar
[3] = mf_nr_ar3
;
1978 for(uint16_t i
= 0; TRUE
; i
++) {
1982 // Test if the action was cancelled
1983 if(BUTTON_PRESS()) {
1989 if(!iso14443a_select_card(uid
, NULL
, &cuid
)) {
1990 if (MF_DBGLEVEL
>= 1) Dbprintf("Mifare: Can't select card");
1994 //keep the card active
1995 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1997 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
1998 catch_up_cycles
= 0;
2000 // if we missed the sync time already, advance to the next nonce repeat
2001 while(GetCountMifare() > sync_time
) {
2002 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
2005 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
2006 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
2008 // Receive the (4 Byte) "random" nonce
2009 if (!ReaderReceive(receivedAnswer
)) {
2010 if (MF_DBGLEVEL
>= 1) Dbprintf("Mifare: Couldn't receive tag nonce");
2015 nt
= bytes_to_num(receivedAnswer
, 4);
2017 // Transmit reader nonce with fake par
2018 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
2020 if (first_try
&& previous_nt
&& !nt_attacked
) { // we didn't calibrate our clock yet
2021 int nt_distance
= dist_nt(previous_nt
, nt
);
2022 if (nt_distance
== 0) {
2026 if (nt_distance
== -99999) { // invalid nonce received, try again
2029 sync_cycles
= (sync_cycles
- nt_distance
);
2030 if (MF_DBGLEVEL
>= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i
, nt_distance
, sync_cycles
);
2035 if ((nt
!= nt_attacked
) && nt_attacked
) { // we somehow lost sync. Try to catch up again...
2036 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
2037 if (catch_up_cycles
== 99999) { // invalid nonce received. Don't resync on that one.
2038 catch_up_cycles
= 0;
2041 if (catch_up_cycles
== last_catch_up
) {
2042 consecutive_resyncs
++;
2045 last_catch_up
= catch_up_cycles
;
2046 consecutive_resyncs
= 0;
2048 if (consecutive_resyncs
< 3) {
2049 if (MF_DBGLEVEL
>= 3) Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, -catch_up_cycles
, consecutive_resyncs
);
2052 sync_cycles
= sync_cycles
+ catch_up_cycles
;
2053 if (MF_DBGLEVEL
>= 3) Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i
, -catch_up_cycles
, sync_cycles
);
2058 consecutive_resyncs
= 0;
2060 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
2061 if (ReaderReceive(receivedAnswer
))
2063 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
2067 par_low
= par
& 0x07; // there is no need to check all parities for other nt_diff. Parity Bits for mf_nr_ar[0..2] won't change
2071 if(led_on
) LED_B_ON(); else LED_B_OFF();
2073 par_list
[nt_diff
] = par
;
2074 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05;
2076 // Test if the information is complete
2077 if (nt_diff
== 0x07) {
2082 nt_diff
= (nt_diff
+ 1) & 0x07;
2083 mf_nr_ar
[3] = (mf_nr_ar
[3] & 0x1F) | (nt_diff
<< 5);
2086 if (nt_diff
== 0 && first_try
)
2090 par
= (((par
>> 3) + 1) << 3) | par_low
;
2095 LogTrace((const uint8_t *)&nt
, 4, 0, GetParity((const uint8_t *)&nt
, 4), TRUE
);
2096 LogTrace(par_list
, 8, 0, GetParity(par_list
, 8), TRUE
);
2097 LogTrace(ks_list
, 8, 0, GetParity(ks_list
, 8), TRUE
);
2099 mf_nr_ar
[3] &= 0x1F;
2102 memcpy(buf
+ 0, uid
, 4);
2103 num_to_bytes(nt
, 4, buf
+ 4);
2104 memcpy(buf
+ 8, par_list
, 8);
2105 memcpy(buf
+ 16, ks_list
, 8);
2106 memcpy(buf
+ 24, mf_nr_ar
, 4);
2108 cmd_send(CMD_ACK
,isOK
,0,0,buf
,28);
2111 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2117 *MIFARE 1K simulate.
2120 * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
2121 * 4B_FLAG_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
2122 * 7B_FLAG_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
2123 * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
2124 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is inifite
2126 void Mifare1ksim(uint8_t flags
, uint8_t exitAfterNReads
, uint8_t arg2
, uint8_t *datain
)
2128 int cardSTATE
= MFEMUL_NOFIELD
;
2130 int vHf
= 0; // in mV
2132 uint32_t selTimer
= 0;
2133 uint32_t authTimer
= 0;
2136 uint8_t cardWRBL
= 0;
2137 uint8_t cardAUTHSC
= 0;
2138 uint8_t cardAUTHKEY
= 0xff; // no authentication
2139 uint32_t cardRr
= 0;
2141 //uint32_t rn_enc = 0;
2143 uint32_t cardINTREG
= 0;
2144 uint8_t cardINTBLOCK
= 0;
2145 struct Crypto1State mpcs
= {0, 0};
2146 struct Crypto1State
*pcs
;
2148 uint32_t numReads
= 0;//Counts numer of times reader read a block
2149 uint8_t* receivedCmd
= eml_get_bigbufptr_recbuf();
2150 uint8_t *response
= eml_get_bigbufptr_sendbuf();
2152 uint8_t rATQA
[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2153 uint8_t rUIDBCC1
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2154 uint8_t rUIDBCC2
[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2155 uint8_t rSAK
[] = {0x08, 0xb6, 0xdd};
2156 uint8_t rSAK1
[] = {0x04, 0xda, 0x17};
2158 uint8_t rAUTH_NT
[] = {0x01, 0x02, 0x03, 0x04};
2159 uint8_t rAUTH_AT
[] = {0x00, 0x00, 0x00, 0x00};
2161 //Here, we collect UID,NT,AR,NR,UID2,NT2,AR2,NR2
2162 // This can be used in a reader-only attack.
2163 // (it can also be retrieved via 'hf 14a list', but hey...
2164 uint32_t ar_nr_responses
[] = {0,0,0,0,0,0,0,0};
2165 uint8_t ar_nr_collected
= 0;
2168 iso14a_clear_trace();
2172 // Authenticate response - nonce
2173 uint32_t nonce
= bytes_to_num(rAUTH_NT
, 4);
2175 //-- Determine the UID
2176 // Can be set from emulator memory, incoming data
2177 // and can be 7 or 4 bytes long
2178 if(flags
& FLAG_4B_UID_IN_DATA
)
2180 // 4B uid comes from data-portion of packet
2181 memcpy(rUIDBCC1
,datain
,4);
2182 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2184 }else if(flags
& FLAG_7B_UID_IN_DATA
)
2186 // 7B uid comes from data-portion of packet
2187 memcpy(&rUIDBCC1
[1],datain
,3);
2188 memcpy(rUIDBCC2
, datain
+3, 4);
2193 // get UID from emul memory
2194 emlGetMemBt(receivedCmd
, 7, 1);
2195 _7BUID
= !(receivedCmd
[0] == 0x00);
2196 if (!_7BUID
) { // ---------- 4BUID
2197 emlGetMemBt(rUIDBCC1
, 0, 4);
2198 } else { // ---------- 7BUID
2199 emlGetMemBt(&rUIDBCC1
[1], 0, 3);
2200 emlGetMemBt(rUIDBCC2
, 3, 4);
2204 * Regardless of what method was used to set the UID, set fifth byte and modify
2205 * the ATQA for 4 or 7-byte UID
2208 rUIDBCC1
[4] = rUIDBCC1
[0] ^ rUIDBCC1
[1] ^ rUIDBCC1
[2] ^ rUIDBCC1
[3];
2213 rUIDBCC2
[4] = rUIDBCC2
[0] ^ rUIDBCC2
[1] ^ rUIDBCC2
[2] ^ rUIDBCC2
[3];
2216 // start mkseconds counter
2219 // We need to listen to the high-frequency, peak-detected path.
2220 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2223 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2226 if (MF_DBGLEVEL
>= 1) {
2228 Dbprintf("4B UID: %02x%02x%02x%02x",rUIDBCC1
[0] , rUIDBCC1
[1] , rUIDBCC1
[2] , rUIDBCC1
[3]);
2231 Dbprintf("7B UID: (%02x)%02x%02x%02x%02x%02x%02x%02x",rUIDBCC1
[0] , rUIDBCC1
[1] , rUIDBCC1
[2] , rUIDBCC1
[3],rUIDBCC2
[0],rUIDBCC2
[1] ,rUIDBCC2
[2] , rUIDBCC2
[3]);
2234 // calibrate mkseconds counter
2236 bool finished
= false;
2237 while (!BUTTON_PRESS() && !finished
) {
2240 // find reader field
2241 // Vref = 3300mV, and an 10:1 voltage divider on the input
2242 // can measure voltages up to 33000 mV
2243 if (cardSTATE
== MFEMUL_NOFIELD
) {
2244 vHf
= (33000 * AvgAdc(ADC_CHAN_HF
)) >> 10;
2245 if (vHf
> MF_MINFIELDV
) {
2246 cardSTATE_TO_IDLE();
2250 if(cardSTATE
== MFEMUL_NOFIELD
) continue;
2254 res
= EmGetCmd(receivedCmd
, &len
, RECV_CMD_SIZE
); // (+ nextCycleTimeout)
2255 if (res
== 2) { //Field is off!
2256 cardSTATE
= MFEMUL_NOFIELD
;
2259 }else if(res
== 1) break;//return value 1 means button press
2262 // REQ or WUP request in ANY state and WUP in HALTED state
2263 if (len
== 1 && ((receivedCmd
[0] == 0x26 && cardSTATE
!= MFEMUL_HALTED
) || receivedCmd
[0] == 0x52)) {
2264 selTimer
= GetTickCount();
2265 EmSendCmdEx(rATQA
, sizeof(rATQA
), (receivedCmd
[0] == 0x52));
2266 cardSTATE
= MFEMUL_SELECT1
;
2268 // init crypto block
2271 crypto1_destroy(pcs
);
2276 switch (cardSTATE
) {
2277 case MFEMUL_NOFIELD
:
2282 case MFEMUL_SELECT1
:{
2284 if (len
== 2 && (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x20)) {
2285 if (MF_DBGLEVEL
>= 4) Dbprintf("SELECT ALL received");
2286 EmSendCmd(rUIDBCC1
, sizeof(rUIDBCC1
));
2290 if (MF_DBGLEVEL
>= 4 && len
== 9 && receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 )
2292 Dbprintf("SELECT %02x%02x%02x%02x received",receivedCmd
[2],receivedCmd
[3],receivedCmd
[4],receivedCmd
[5]);
2296 (receivedCmd
[0] == 0x93 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC1
, 4) == 0)) {
2299 EmSendCmd(rSAK
, sizeof(rSAK
));
2301 EmSendCmd(rSAK1
, sizeof(rSAK1
));
2303 cuid
= bytes_to_num(rUIDBCC1
, 4);
2305 cardSTATE
= MFEMUL_WORK
;
2307 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer
);
2310 cardSTATE
= MFEMUL_SELECT2
;
2320 cardSTATE_TO_IDLE();
2323 uint32_t ar
= bytes_to_num(receivedCmd
, 4);
2324 uint32_t nr
= bytes_to_num(&receivedCmd
[4], 4);
2327 if(ar_nr_collected
< 2){
2328 if(ar_nr_responses
[ar_nr_collected
*4+2] != ar
)
2329 {// Avoid duplicates
2331 ar_nr_responses
[ar_nr_collected
*4] = cuid
;
2332 ar_nr_responses
[ar_nr_collected
*4+1] = nonce
;
2333 ar_nr_responses
[ar_nr_collected
*4+2] = ar
;
2334 ar_nr_responses
[ar_nr_collected
*4+3] = nr
;
2339 crypto1_word(pcs
, ar
, 1);
2340 cardRr
= nr
^ crypto1_word(pcs
, 0, 0);
2343 if (cardRr
!= prng_successor(nonce
, 64)){
2344 if (MF_DBGLEVEL
>= 2) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x",cardRr
, prng_successor(nonce
, 64));
2345 //Shouldn't we respond anything here?
2346 // Right now, we don't nack or anything, which causes the
2347 // reader to do a WUPA after a while. /Martin
2348 cardSTATE_TO_IDLE();
2352 ans
= prng_successor(nonce
, 96) ^ crypto1_word(pcs
, 0, 0);
2354 num_to_bytes(ans
, 4, rAUTH_AT
);
2356 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2358 cardSTATE
= MFEMUL_WORK
;
2359 if (MF_DBGLEVEL
>= 4) Dbprintf("AUTH COMPLETED. sector=%d, key=%d time=%d", cardAUTHSC
, cardAUTHKEY
, GetTickCount() - authTimer
);
2362 case MFEMUL_SELECT2
:{
2365 if (len
== 2 && (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x20)) {
2366 EmSendCmd(rUIDBCC2
, sizeof(rUIDBCC2
));
2372 (receivedCmd
[0] == 0x95 && receivedCmd
[1] == 0x70 && memcmp(&receivedCmd
[2], rUIDBCC2
, 4) == 0)) {
2373 EmSendCmd(rSAK
, sizeof(rSAK
));
2375 cuid
= bytes_to_num(rUIDBCC2
, 4);
2376 cardSTATE
= MFEMUL_WORK
;
2378 if (MF_DBGLEVEL
>= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer
);
2382 // i guess there is a command). go into the work state.
2383 if (len
!= 4) break;
2384 cardSTATE
= MFEMUL_WORK
;
2386 //intentional fall-through to the next case-stmt
2389 if (len
== 0) break;
2391 bool encrypted_data
= (cardAUTHKEY
!= 0xFF) ;
2396 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2399 if (len
== 4 && (receivedCmd
[0] == 0x60 || receivedCmd
[0] == 0x61)) {
2400 authTimer
= GetTickCount();
2401 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
2402 cardAUTHKEY
= receivedCmd
[0] - 0x60;
2403 crypto1_destroy(pcs
);//Added by martin
2404 crypto1_create(pcs
, emlGetKey(cardAUTHSC
, cardAUTHKEY
));
2406 if (!encrypted_data
) { // first authentication
2407 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader authenticating for block %d (0x%02x) with key %d",receivedCmd
[1] ,receivedCmd
[1],cardAUTHKEY
);
2409 crypto1_word(pcs
, cuid
^ nonce
, 0);//Update crypto state
2410 num_to_bytes(nonce
, 4, rAUTH_AT
); // Send nonce
2412 else{ // nested authentication
2413 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader doing nested authentication for block %d (0x%02x) with key %d",receivedCmd
[1] ,receivedCmd
[1],cardAUTHKEY
);
2414 ans
= nonce
^ crypto1_word(pcs
, cuid
^ nonce
, 0);
2415 num_to_bytes(ans
, 4, rAUTH_AT
);
2417 EmSendCmd(rAUTH_AT
, sizeof(rAUTH_AT
));
2418 //Dbprintf("Sending rAUTH %02x%02x%02x%02x", rAUTH_AT[0],rAUTH_AT[1],rAUTH_AT[2],rAUTH_AT[3]);
2419 cardSTATE
= MFEMUL_AUTH1
;
2423 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2424 // BUT... ACK --> NACK
2425 if (len
== 1 && receivedCmd
[0] == CARD_ACK
) {
2426 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2430 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2431 if (len
== 1 && receivedCmd
[0] == CARD_NACK_NA
) {
2432 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2438 if(receivedCmd
[0] == 0x30 // read block
2439 || receivedCmd
[0] == 0xA0 // write block
2440 || receivedCmd
[0] == 0xC0
2441 || receivedCmd
[0] == 0xC1
2442 || receivedCmd
[0] == 0xC2 // inc dec restore
2443 || receivedCmd
[0] == 0xB0) // transfer
2445 if (receivedCmd
[1] >= 16 * 4)
2448 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2449 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking",receivedCmd
[0],receivedCmd
[1],receivedCmd
[1]);
2453 if (receivedCmd
[1] / 4 != cardAUTHSC
)
2455 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2456 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate (0x%02) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd
[0],receivedCmd
[1],cardAUTHSC
);
2461 if (receivedCmd
[0] == 0x30) {
2462 if (MF_DBGLEVEL
>= 2) {
2463 Dbprintf("Reader reading block %d (0x%02x)",receivedCmd
[1],receivedCmd
[1]);
2465 emlGetMem(response
, receivedCmd
[1], 1);
2466 AppendCrc14443a(response
, 16);
2467 mf_crypto1_encrypt(pcs
, response
, 18, &par
);
2468 EmSendCmdPar(response
, 18, par
);
2470 if(exitAfterNReads
> 0 && numReads
== exitAfterNReads
)
2472 Dbprintf("%d reads done, exiting", numReads
);
2478 if (receivedCmd
[0] == 0xA0) {
2479 if (MF_DBGLEVEL
>= 2) Dbprintf("RECV 0xA0 write block %d (%02x)",receivedCmd
[1],receivedCmd
[1]);
2481 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2482 //nextCycleTimeout = 50;
2483 cardSTATE
= MFEMUL_WRITEBL2
;
2484 cardWRBL
= receivedCmd
[1];
2487 // increment, decrement, restore
2488 if (receivedCmd
[0] == 0xC0 || receivedCmd
[0] == 0xC1 || receivedCmd
[0] == 0xC2) {
2489 if (MF_DBGLEVEL
>= 2) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd
[0],receivedCmd
[1],receivedCmd
[1]);
2491 if (emlCheckValBl(receivedCmd
[1])) {
2492 if (MF_DBGLEVEL
>= 2) Dbprintf("Reader tried to operate on block, but emlCheckValBl failed, nacking");
2493 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2496 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2497 if (receivedCmd
[0] == 0xC1)
2498 cardSTATE
= MFEMUL_INTREG_INC
;
2499 if (receivedCmd
[0] == 0xC0)
2500 cardSTATE
= MFEMUL_INTREG_DEC
;
2501 if (receivedCmd
[0] == 0xC2)
2502 cardSTATE
= MFEMUL_INTREG_REST
;
2503 cardWRBL
= receivedCmd
[1];
2509 if (receivedCmd
[0] == 0xB0) {
2510 if (MF_DBGLEVEL
>= 2) Dbprintf("RECV 0x%02x transfer block %d (%02x)",receivedCmd
[0],receivedCmd
[1],receivedCmd
[1]);
2512 if (emlSetValBl(cardINTREG
, cardINTBLOCK
, receivedCmd
[1]))
2513 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2515 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2521 if (receivedCmd
[0] == 0x50 && receivedCmd
[1] == 0x00) {
2524 cardSTATE
= MFEMUL_HALTED
;
2525 if (MF_DBGLEVEL
>= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer
);
2529 if (receivedCmd
[0] == 0xe0) {//RATS
2530 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2534 // command not allowed
2535 if (MF_DBGLEVEL
>= 4) Dbprintf("Received command not allowed, nacking");
2536 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2541 case MFEMUL_WRITEBL2
:{
2543 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2544 emlSetMem(receivedCmd
, cardWRBL
, 1);
2545 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_ACK
));
2546 cardSTATE
= MFEMUL_WORK
;
2549 cardSTATE_TO_IDLE();
2555 case MFEMUL_INTREG_INC
:{
2556 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2557 memcpy(&ans
, receivedCmd
, 4);
2558 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2559 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2560 cardSTATE_TO_IDLE();
2563 cardINTREG
= cardINTREG
+ ans
;
2564 cardSTATE
= MFEMUL_WORK
;
2567 case MFEMUL_INTREG_DEC
:{
2568 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2569 memcpy(&ans
, receivedCmd
, 4);
2570 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2571 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2572 cardSTATE_TO_IDLE();
2575 cardINTREG
= cardINTREG
- ans
;
2576 cardSTATE
= MFEMUL_WORK
;
2579 case MFEMUL_INTREG_REST
:{
2580 mf_crypto1_decrypt(pcs
, receivedCmd
, len
);
2581 memcpy(&ans
, receivedCmd
, 4);
2582 if (emlGetValBl(&cardINTREG
, &cardINTBLOCK
, cardWRBL
)) {
2583 EmSend4bit(mf_crypto1_encrypt4bit(pcs
, CARD_NACK_NA
));
2584 cardSTATE_TO_IDLE();
2587 cardSTATE
= MFEMUL_WORK
;
2593 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
2596 // add trace trailer
2597 memset(rAUTH_NT
, 0x44, 4);
2598 LogTrace(rAUTH_NT
, 4, 0, 0, TRUE
);
2599 if(flags
& FLAG_INTERACTIVE
)// Interactive mode flag, means we need to send ACK
2601 //May just aswell send the collected ar_nr in the response aswell
2602 cmd_send(CMD_ACK
,CMD_SIMULATE_MIFARE_CARD
,0,0,&ar_nr_responses
,ar_nr_collected
*4*4);
2604 if(flags
& FLAG_NR_AR_ATTACK
)
2606 if(ar_nr_collected
> 1)
2608 Dbprintf("Collected two pairs of AR/NR which can be used to extract keys from reader:");
2609 Dbprintf("../tools/mfkey/mfkey32 %08x %08x %08x %08x",
2610 ar_nr_responses
[0], // UID
2611 ar_nr_responses
[1], //NT
2612 ar_nr_responses
[2], //AR1
2613 ar_nr_responses
[3], //NR1
2614 ar_nr_responses
[6], //AR2
2615 ar_nr_responses
[7] //NR2
2619 Dbprintf("Failed to obtain two AR/NR pairs!");
2620 if(ar_nr_collected
>0)
2622 Dbprintf("Only got these: UID=%08d, nonce=%08d, AR1=%08d, NR1=%08d",
2623 ar_nr_responses
[0], // UID
2624 ar_nr_responses
[1], //NT
2625 ar_nr_responses
[2], //AR1
2626 ar_nr_responses
[3] //NR1
2631 if (MF_DBGLEVEL
>= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing
, traceLen
);
2636 //-----------------------------------------------------------------------------
2639 //-----------------------------------------------------------------------------
2640 void RAMFUNC
SniffMifare(uint8_t param
) {
2642 // bit 0 - trigger from first card answer
2643 // bit 1 - trigger from first reader 7-bit request
2645 // C(red) A(yellow) B(green)
2647 // init trace buffer
2648 iso14a_clear_trace();
2650 // The command (reader -> tag) that we're receiving.
2651 // The length of a received command will in most cases be no more than 18 bytes.
2652 // So 32 should be enough!
2653 uint8_t *receivedCmd
= (((uint8_t *)BigBuf
) + RECV_CMD_OFFSET
);
2654 // The response (tag -> reader) that we're receiving.
2655 uint8_t *receivedResponse
= (((uint8_t *)BigBuf
) + RECV_RES_OFFSET
);
2657 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2658 // into trace, along with its length and other annotations.
2659 //uint8_t *trace = (uint8_t *)BigBuf;
2661 // The DMA buffer, used to stream samples from the FPGA
2662 int8_t *dmaBuf
= ((int8_t *)BigBuf
) + DMA_BUFFER_OFFSET
;
2663 int8_t *data
= dmaBuf
;
2667 // Set up the demodulator for tag -> reader responses.
2668 Demod
.output
= receivedResponse
;
2670 Demod
.state
= DEMOD_UNSYNCD
;
2672 // Set up the demodulator for the reader -> tag commands
2673 memset(&Uart
, 0, sizeof(Uart
));
2674 Uart
.output
= receivedCmd
;
2675 Uart
.byteCntMax
= 32; // was 100 (greg)//////////////////
2676 Uart
.state
= STATE_UNSYNCD
;
2678 // Setup for the DMA.
2680 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
2682 // And put the FPGA in the appropriate mode
2683 // Signal field is off with the appropriate LED
2685 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
2686 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2690 int sniffCounter
= 0;
2692 // And now we loop, receiving samples.
2694 if(BUTTON_PRESS()) {
2695 DbpString("cancelled by button");
2702 if (++sniffCounter
> 65) {
2703 if (MfSniffSend(2000)) {
2709 int register readBufDataP
= data
- dmaBuf
;
2710 int register dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
2711 if (readBufDataP
<= dmaBufDataP
){
2712 dataLen
= dmaBufDataP
- readBufDataP
;
2714 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
+ 1;
2716 // test for length of buffer
2717 if(dataLen
> maxDataLen
) {
2718 maxDataLen
= dataLen
;
2720 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen
);
2724 if(dataLen
< 1) continue;
2726 // primary buffer was stopped( <-- we lost data!
2727 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
2728 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dmaBuf
;
2729 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
2730 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen
); // temporary
2732 // secondary buffer sets as primary, secondary buffer was stopped
2733 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
2734 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dmaBuf
;
2735 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
2740 if(MillerDecoding((data
[0] & 0xF0) >> 4)) {
2742 // check - if there is a short 7bit request from reader
2743 if (MfSniffLogic(receivedCmd
, Uart
.byteCnt
, Uart
.parityBits
, Uart
.bitCnt
, TRUE
)) break;
2745 /* And ready to receive another command. */
2746 Uart
.state
= STATE_UNSYNCD
;
2748 /* And also reset the demod code */
2749 Demod
.state
= DEMOD_UNSYNCD
;
2752 if(ManchesterDecoding(data
[0], 0)) {
2755 if (MfSniffLogic(receivedResponse
, Demod
.len
, Demod
.parityBits
, Demod
.bitCount
, FALSE
)) break;
2757 // And ready to receive another response.
2758 memset(&Demod
, 0, sizeof(Demod
));
2759 Demod
.output
= receivedResponse
;
2760 Demod
.state
= DEMOD_UNSYNCD
;
2762 /* And also reset the uart code */
2763 Uart
.state
= STATE_UNSYNCD
;
2767 if(data
> dmaBuf
+ DMA_BUFFER_SIZE
) {
2772 DbpString("COMMAND FINISHED");
2775 FpgaDisableSscDma();
2778 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen
, Uart
.state
, Uart
.byteCnt
, Uart
.byteCntMax
);