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 //-----------------------------------------------------------------------------
12 #include "iso14443a.h"
15 #include "proxmark3_arm.h"
19 #include "fpgaloader.h"
25 #include "mifareutil.h"
26 #include "commonutil.h"
28 #include "protocols.h"
30 #define MAX_ISO14A_TIMEOUT 524288
32 // this timeout is in MS
33 static uint32_t iso14a_timeout
;
35 static uint8_t colpos
= 0;
37 // the block number for the ISO14443-4 PCB
38 static uint8_t iso14_pcb_blocknum
= 0;
43 // minimum time between the start bits of consecutive transfers from reader to tag: 7000 carrier (13.56MHz) cycles
44 #define REQUEST_GUARD_TIME (7000/16 + 1)
45 // minimum time between last modulation of tag and next start bit from reader to tag: 1172 carrier cycles
46 #define FRAME_DELAY_TIME_PICC_TO_PCD (1172/16 + 1)
47 // bool LastCommandWasRequest = false;
50 // Total delays including SSC-Transfers between ARM and FPGA. These are in carrier clock cycles (1/13,56MHz)
52 // When the PM acts as reader and is receiving tag data, it takes
53 // 3 ticks delay in the AD converter
54 // 16 ticks until the modulation detector completes and sets curbit
55 // 8 ticks until bit_to_arm is assigned from curbit
56 // 8*16 ticks for the transfer from FPGA to ARM
57 // 4*16 ticks until we measure the time
58 // - 8*16 ticks because we measure the time of the previous transfer
59 #define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16)
61 // When the PM acts as a reader and is sending, it takes
62 // 4*16 ticks until we can write data to the sending hold register
63 // 8*16 ticks until the SHR is transferred to the Sending Shift Register
64 // 8 ticks until the first transfer starts
65 // 8 ticks later the FPGA samples the data
66 // 1 tick to assign mod_sig_coil
67 #define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1)
69 // The FPGA will report its internal sending delay in
70 static uint16_t FpgaSendQueueDelay
;
71 // the 5 first bits are the number of bits buffered in mod_sig_buf
72 // the last three bits are the remaining ticks/2 after the mod_sig_buf shift
73 #define DELAY_FPGA_QUEUE (FpgaSendQueueDelay<<1)
75 // When the PM acts as tag and is sending, it takes
76 // 4*16 + 8 ticks until we can write data to the sending hold register
77 // 8*16 ticks until the SHR is transferred to the Sending Shift Register
78 // 8 ticks later the FPGA samples the first data
79 // + 16 ticks until assigned to mod_sig
80 // + 1 tick to assign mod_sig_coil
81 // + a varying number of ticks in the FPGA Delay Queue (mod_sig_buf)
82 #define DELAY_ARM2AIR_AS_TAG (4*16 + 8 + 8*16 + 8 + 16 + 1 + DELAY_FPGA_QUEUE)
84 // When the PM acts as sniffer and is receiving tag data, it takes
85 // 3 ticks A/D conversion
86 // 14 ticks to complete the modulation detection
87 // 8 ticks (on average) until the result is stored in to_arm
88 // + the delays in transferring data - which is the same for
89 // sniffing reader and tag data and therefore not relevant
90 #define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8)
92 // When the PM acts as sniffer and is receiving reader data, it takes
93 // 2 ticks delay in analogue RF receiver (for the falling edge of the
94 // start bit, which marks the start of the communication)
95 // 3 ticks A/D conversion
96 // 8 ticks on average until the data is stored in to_arm.
97 // + the delays in transferring data - which is the same for
98 // sniffing reader and tag data and therefore not relevant
99 #define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8)
101 //variables used for timing purposes:
102 //these are in ssp_clk cycles:
103 static uint32_t NextTransferTime
;
104 static uint32_t LastTimeProxToAirStart
;
105 static uint32_t LastProxToAirDuration
;
107 // CARD TO READER - manchester
108 // Sequence D: 11110000 modulation with subcarrier during first half
109 // Sequence E: 00001111 modulation with subcarrier during second half
110 // Sequence F: 00000000 no modulation with subcarrier
111 // Sequence COLL: 11111111 load modulation over the full bitlength.
112 // Tricks the reader to think that multiple cards answer.
113 // (at least one card with 1 and at least one card with 0)
114 // READER TO CARD - miller
115 // Sequence X: 00001100 drop after half a period
116 // Sequence Y: 00000000 no drop
117 // Sequence Z: 11000000 drop at start
121 #define SEC_COLL 0xff
127 Default HF 14a config is set to:
128 forceanticol = 0 (auto)
129 forcebcc = 0 (expect valid BCC)
134 static hf14a_config hf14aconfig
= { 0, 0, 0, 0, 0 } ;
136 void printHf14aConfig(void) {
137 DbpString(_CYAN_("HF 14a config"));
138 Dbprintf(" [a] Anticol override.... %s%s%s",
139 (hf14aconfig
.forceanticol
== 0) ? _GREEN_("std") " ( follow standard )" : "",
140 (hf14aconfig
.forceanticol
== 1) ? _RED_("force") " ( always do anticol )" : "",
141 (hf14aconfig
.forceanticol
== 2) ? _RED_("skip") " ( always skip anticol )" : ""
143 Dbprintf(" [b] BCC override........ %s%s%s",
144 (hf14aconfig
.forcebcc
== 0) ? _GREEN_("std") " ( follow standard )" : "",
145 (hf14aconfig
.forcebcc
== 1) ? _RED_("fix") " ( fix bad BCC )" : "",
146 (hf14aconfig
.forcebcc
== 2) ? _RED_("ignore") " ( ignore bad BCC, always use card BCC )" : ""
148 Dbprintf(" [2] CL2 override........ %s%s%s",
149 (hf14aconfig
.forcecl2
== 0) ? _GREEN_("std") " ( follow standard )" : "",
150 (hf14aconfig
.forcecl2
== 1) ? _RED_("force") " ( always do CL2 )" : "",
151 (hf14aconfig
.forcecl2
== 2) ? _RED_("skip") " ( always skip CL2 )" : ""
153 Dbprintf(" [3] CL3 override........ %s%s%s",
154 (hf14aconfig
.forcecl3
== 0) ? _GREEN_("std") " ( follow standard )" : "",
155 (hf14aconfig
.forcecl3
== 1) ? _RED_("force") " ( always do CL3 )" : "",
156 (hf14aconfig
.forcecl3
== 2) ? _RED_("skip") " ( always skip CL3 )" : ""
158 Dbprintf(" [r] RATS override....... %s%s%s",
159 (hf14aconfig
.forcerats
== 0) ? _GREEN_("std") " ( follow standard )" : "",
160 (hf14aconfig
.forcerats
== 1) ? _RED_("force") " ( always do RATS )" : "",
161 (hf14aconfig
.forcerats
== 2) ? _RED_("skip") " () always skip RATS )" : ""
166 * Called from the USB-handler to set the 14a configuration
167 * The 14a config is used for card selection sequence.
169 * Values set to '-1' implies no change
170 * @brief setSamplingConfig
173 void setHf14aConfig(hf14a_config
*hc
) {
175 if ((hc
->forceanticol
>= 0) && (hc
->forceanticol
<= 2))
176 hf14aconfig
.forceanticol
= hc
->forceanticol
;
177 if ((hc
->forcebcc
>= 0) && (hc
->forcebcc
<= 2))
178 hf14aconfig
.forcebcc
= hc
->forcebcc
;
179 if ((hc
->forcecl2
>= 0) && (hc
->forcecl2
<= 2))
180 hf14aconfig
.forcecl2
= hc
->forcecl2
;
181 if ((hc
->forcecl3
>= 0) && (hc
->forcecl3
<= 2))
182 hf14aconfig
.forcecl3
= hc
->forcecl3
;
183 if ((hc
->forcerats
>= 0) && (hc
->forcerats
<= 2))
184 hf14aconfig
.forcerats
= hc
->forcerats
;
187 hf14a_config
*getHf14aConfig(void) {
191 void iso14a_set_trigger(bool enable
) {
195 void iso14a_set_timeout(uint32_t timeout
) {
196 iso14a_timeout
= timeout
+ (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 128 + 2;
199 uint32_t iso14a_get_timeout(void) {
200 return iso14a_timeout
- (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 128 - 2;
203 //-----------------------------------------------------------------------------
204 // Generate the parity value for a byte sequence
205 //-----------------------------------------------------------------------------
206 void GetParity(const uint8_t *pbtCmd
, uint16_t len
, uint8_t *par
) {
207 uint16_t paritybit_cnt
= 0;
208 uint16_t paritybyte_cnt
= 0;
209 uint8_t parityBits
= 0;
211 for (uint16_t i
= 0; i
< len
; i
++) {
212 // Generate the parity bits
213 parityBits
|= ((oddparity8(pbtCmd
[i
])) << (7 - paritybit_cnt
));
214 if (paritybit_cnt
== 7) {
215 par
[paritybyte_cnt
] = parityBits
; // save 8 Bits parity
216 parityBits
= 0; // and advance to next Parity Byte
224 // save remaining parity bits
225 par
[paritybyte_cnt
] = parityBits
;
229 //=============================================================================
230 // ISO 14443 Type A - Miller decoder
231 //=============================================================================
233 // This decoder is used when the PM3 acts as a tag.
234 // The reader will generate "pauses" by temporarily switching of the field.
235 // At the PM3 antenna we will therefore measure a modulated antenna voltage.
236 // The FPGA does a comparison with a threshold and would deliver e.g.:
237 // ........ 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 .......
238 // The Miller decoder needs to identify the following sequences:
239 // 2 (or 3) ticks pause followed by 6 (or 5) ticks unmodulated: pause at beginning - Sequence Z ("start of communication" or a "0")
240 // 8 ticks without a modulation: no pause - Sequence Y (a "0" or "end of communication" or "no information")
241 // 4 ticks unmodulated followed by 2 (or 3) ticks pause: pause in second half - Sequence X (a "1")
242 // Note 1: the bitstream may start at any time. We therefore need to sync.
243 // Note 2: the interpretation of Sequence Y and Z depends on the preceding sequence.
244 //-----------------------------------------------------------------------------
245 static tUart14a Uart
;
247 // Lookup-Table to decide if 4 raw bits are a modulation.
248 // We accept the following:
249 // 0001 - a 3 tick wide pause
250 // 0011 - a 2 tick wide pause, or a three tick wide pause shifted left
251 // 0111 - a 2 tick wide pause shifted left
252 // 1001 - a 2 tick wide pause shifted right
253 static const bool Mod_Miller_LUT
[] = {
254 false, true, false, true, false, false, false, true,
255 false, true, false, false, false, false, false, false
257 #define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4])
258 #define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)])
260 tUart14a
*GetUart14a(void) {
264 void Uart14aReset(void) {
265 Uart
.state
= STATE_14A_UNSYNCD
;
267 Uart
.len
= 0; // number of decoded data bytes
268 Uart
.parityLen
= 0; // number of decoded parity bytes
269 Uart
.shiftReg
= 0; // shiftreg to hold decoded data bits
270 Uart
.parityBits
= 0; // holds 8 parity bits
273 Uart
.fourBits
= 0x00000000; // clear the buffer for 4 Bits
278 void Uart14aInit(uint8_t *data
, uint8_t *par
) {
284 // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
285 RAMFUNC
bool MillerDecoding(uint8_t bit
, uint32_t non_real_time
) {
286 Uart
.fourBits
= (Uart
.fourBits
<< 8) | bit
;
288 if (Uart
.state
== STATE_14A_UNSYNCD
) { // not yet synced
289 Uart
.syncBit
= 9999; // not set
291 // 00x11111 2|3 ticks pause followed by 6|5 ticks unmodulated Sequence Z (a "0" or "start of communication")
292 // 11111111 8 ticks unmodulation Sequence Y (a "0" or "end of communication" or "no information")
293 // 111100x1 4 ticks unmodulated followed by 2|3 ticks pause Sequence X (a "1")
295 // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from
296 // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111)
297 // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern
298 // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's)
299 #define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00000111 11111111 11101111 10000000
300 #define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00000111 11111111 10001111 10000000
301 if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 0)) == ISO14443A_STARTBIT_PATTERN
>> 0) Uart
.syncBit
= 7;
302 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 1)) == ISO14443A_STARTBIT_PATTERN
>> 1) Uart
.syncBit
= 6;
303 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 2)) == ISO14443A_STARTBIT_PATTERN
>> 2) Uart
.syncBit
= 5;
304 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 3)) == ISO14443A_STARTBIT_PATTERN
>> 3) Uart
.syncBit
= 4;
305 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 4)) == ISO14443A_STARTBIT_PATTERN
>> 4) Uart
.syncBit
= 3;
306 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 5)) == ISO14443A_STARTBIT_PATTERN
>> 5) Uart
.syncBit
= 2;
307 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 6)) == ISO14443A_STARTBIT_PATTERN
>> 6) Uart
.syncBit
= 1;
308 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 7)) == ISO14443A_STARTBIT_PATTERN
>> 7) Uart
.syncBit
= 0;
310 if (Uart
.syncBit
!= 9999) { // found a sync bit
311 Uart
.startTime
= non_real_time
? non_real_time
: (GetCountSspClk() & 0xfffffff8);
312 Uart
.startTime
-= Uart
.syncBit
;
313 Uart
.endTime
= Uart
.startTime
;
314 Uart
.state
= STATE_14A_START_OF_COMMUNICATION
;
318 if (IsMillerModulationNibble1(Uart
.fourBits
>> Uart
.syncBit
)) {
319 if (IsMillerModulationNibble2(Uart
.fourBits
>> Uart
.syncBit
)) { // Modulation in both halves - error
321 } else { // Modulation in first half = Sequence Z = logic "0"
322 if (Uart
.state
== STATE_14A_MILLER_X
) { // error - must not follow after X
326 Uart
.shiftReg
= (Uart
.shiftReg
>> 1); // add a 0 to the shiftreg
327 Uart
.state
= STATE_14A_MILLER_Z
;
328 Uart
.endTime
= Uart
.startTime
+ 8 * (9 * Uart
.len
+ Uart
.bitCount
+ 1) - 6;
329 if (Uart
.bitCount
>= 9) { // if we decoded a full byte (including parity)
330 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff);
331 Uart
.parityBits
<<= 1; // make room for the parity bit
332 Uart
.parityBits
|= ((Uart
.shiftReg
>> 8) & 0x01); // store parity bit
335 if ((Uart
.len
& 0x0007) == 0) { // every 8 data bytes
336 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // store 8 parity bits
343 if (IsMillerModulationNibble2(Uart
.fourBits
>> Uart
.syncBit
)) { // Modulation second half = Sequence X = logic "1"
345 Uart
.shiftReg
= (Uart
.shiftReg
>> 1) | 0x100; // add a 1 to the shiftreg
346 Uart
.state
= STATE_14A_MILLER_X
;
347 Uart
.endTime
= Uart
.startTime
+ 8 * (9 * Uart
.len
+ Uart
.bitCount
+ 1) - 2;
348 if (Uart
.bitCount
>= 9) { // if we decoded a full byte (including parity)
349 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff);
350 Uart
.parityBits
<<= 1; // make room for the new parity bit
351 Uart
.parityBits
|= ((Uart
.shiftReg
>> 8) & 0x01); // store parity bit
354 if ((Uart
.len
& 0x0007) == 0) { // every 8 data bytes
355 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // store 8 parity bits
359 } else { // no modulation in both halves - Sequence Y
360 if (Uart
.state
== STATE_14A_MILLER_Z
|| Uart
.state
== STATE_14A_MILLER_Y
) { // Y after logic "0" - End of Communication
361 Uart
.state
= STATE_14A_UNSYNCD
;
362 Uart
.bitCount
--; // last "0" was part of EOC sequence
363 Uart
.shiftReg
<<= 1; // drop it
364 if (Uart
.bitCount
> 0) { // if we decoded some bits
365 Uart
.shiftReg
>>= (9 - Uart
.bitCount
); // right align them
366 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff); // add last byte to the output
367 Uart
.parityBits
<<= 1; // add a (void) parity bit
368 Uart
.parityBits
<<= (8 - (Uart
.len
& 0x0007)); // left align parity bits
369 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // and store it
371 } else if (Uart
.len
& 0x0007) { // there are some parity bits to store
372 Uart
.parityBits
<<= (8 - (Uart
.len
& 0x0007)); // left align remaining parity bits
373 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // and store them
376 return true; // we are finished with decoding the raw data sequence
378 Uart14aReset(); // Nothing received - start over
382 if (Uart
.state
== STATE_14A_START_OF_COMMUNICATION
) { // error - must not follow directly after SOC
384 } else { // a logic "0"
386 Uart
.shiftReg
= (Uart
.shiftReg
>> 1); // add a 0 to the shiftreg
387 Uart
.state
= STATE_14A_MILLER_Y
;
388 if (Uart
.bitCount
>= 9) { // if we decoded a full byte (including parity)
389 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff);
390 Uart
.parityBits
<<= 1; // make room for the parity bit
391 Uart
.parityBits
|= ((Uart
.shiftReg
>> 8) & 0x01); // store parity bit
394 if ((Uart
.len
& 0x0007) == 0) { // every 8 data bytes
395 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // store 8 parity bits
403 return false; // not finished yet, need more data
406 //=============================================================================
407 // ISO 14443 Type A - Manchester decoder
408 //=============================================================================
410 // This decoder is used when the PM3 acts as a reader.
411 // The tag will modulate the reader field by asserting different loads to it. As a consequence, the voltage
412 // at the reader antenna will be modulated as well. The FPGA detects the modulation for us and would deliver e.g. the following:
413 // ........ 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 .......
414 // The Manchester decoder needs to identify the following sequences:
415 // 4 ticks modulated followed by 4 ticks unmodulated: Sequence D = 1 (also used as "start of communication")
416 // 4 ticks unmodulated followed by 4 ticks modulated: Sequence E = 0
417 // 8 ticks unmodulated: Sequence F = end of communication
418 // 8 ticks modulated: A collision. Save the collision position and treat as Sequence D
419 // Note 1: the bitstream may start at any time. We therefore need to sync.
420 // Note 2: parameter offset is used to determine the position of the parity bits (required for the anticollision command only)
421 static tDemod14a Demod
;
423 // Lookup-Table to decide if 4 raw bits are a modulation.
424 // We accept three or four "1" in any position
425 static const bool Mod_Manchester_LUT
[] = {
426 false, false, false, false, false, false, false, true,
427 false, false, false, true, false, true, true, true
430 #define IsManchesterModulationNibble1(b) (Mod_Manchester_LUT[(b & 0x00F0) >> 4])
431 #define IsManchesterModulationNibble2(b) (Mod_Manchester_LUT[(b & 0x000F)])
433 tDemod14a
*GetDemod14a(void) {
436 void Demod14aReset(void) {
437 Demod
.state
= DEMOD_14A_UNSYNCD
;
438 Demod
.len
= 0; // number of decoded data bytes
440 Demod
.shiftReg
= 0; // shiftreg to hold decoded data bits
441 Demod
.parityBits
= 0; //
442 Demod
.collisionPos
= 0; // Position of collision bit
443 Demod
.twoBits
= 0xFFFF; // buffer for 2 Bits
448 Demod
.syncBit
= 0xFFFF;
452 void Demod14aInit(uint8_t *data
, uint8_t *par
) {
458 // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
459 RAMFUNC
int ManchesterDecoding(uint8_t bit
, uint16_t offset
, uint32_t non_real_time
) {
460 Demod
.twoBits
= (Demod
.twoBits
<< 8) | bit
;
462 if (Demod
.state
== DEMOD_14A_UNSYNCD
) {
464 if (Demod
.highCnt
< 2) { // wait for a stable unmodulated signal
465 if (Demod
.twoBits
== 0x0000) {
471 Demod
.syncBit
= 0xFFFF; // not set
472 if ((Demod
.twoBits
& 0x7700) == 0x7000) Demod
.syncBit
= 7;
473 else if ((Demod
.twoBits
& 0x3B80) == 0x3800) Demod
.syncBit
= 6;
474 else if ((Demod
.twoBits
& 0x1DC0) == 0x1C00) Demod
.syncBit
= 5;
475 else if ((Demod
.twoBits
& 0x0EE0) == 0x0E00) Demod
.syncBit
= 4;
476 else if ((Demod
.twoBits
& 0x0770) == 0x0700) Demod
.syncBit
= 3;
477 else if ((Demod
.twoBits
& 0x03B8) == 0x0380) Demod
.syncBit
= 2;
478 else if ((Demod
.twoBits
& 0x01DC) == 0x01C0) Demod
.syncBit
= 1;
479 else if ((Demod
.twoBits
& 0x00EE) == 0x00E0) Demod
.syncBit
= 0;
480 if (Demod
.syncBit
!= 0xFFFF) {
481 Demod
.startTime
= non_real_time
? non_real_time
: (GetCountSspClk() & 0xfffffff8);
482 Demod
.startTime
-= Demod
.syncBit
;
483 Demod
.bitCount
= offset
; // number of decoded data bits
484 Demod
.state
= DEMOD_14A_MANCHESTER_DATA
;
489 if (IsManchesterModulationNibble1(Demod
.twoBits
>> Demod
.syncBit
)) { // modulation in first half
490 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // ... and in second half = collision
491 if (!Demod
.collisionPos
) {
492 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
494 } // modulation in first half only - Sequence D = 1
496 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) | 0x100; // in both cases, add a 1 to the shiftreg
497 if (Demod
.bitCount
== 9) { // if we decoded a full byte (including parity)
498 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
499 Demod
.parityBits
<<= 1; // make room for the parity bit
500 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
503 if ((Demod
.len
& 0x0007) == 0) { // every 8 data bytes
504 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // store 8 parity bits
505 Demod
.parityBits
= 0;
508 Demod
.endTime
= Demod
.startTime
+ 8 * (9 * Demod
.len
+ Demod
.bitCount
+ 1) - 4;
509 } else { // no modulation in first half
510 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // and modulation in second half = Sequence E = 0
512 Demod
.shiftReg
= (Demod
.shiftReg
>> 1); // add a 0 to the shiftreg
513 if (Demod
.bitCount
>= 9) { // if we decoded a full byte (including parity)
514 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
515 Demod
.parityBits
<<= 1; // make room for the new parity bit
516 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
519 if ((Demod
.len
& 0x0007) == 0) { // every 8 data bytes
520 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // store 8 parity bits1
521 Demod
.parityBits
= 0;
524 Demod
.endTime
= Demod
.startTime
+ 8 * (9 * Demod
.len
+ Demod
.bitCount
+ 1);
525 } else { // no modulation in both halves - End of communication
526 if (Demod
.bitCount
> 0) { // there are some remaining data bits
527 Demod
.shiftReg
>>= (9 - Demod
.bitCount
); // right align the decoded bits
528 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff; // and add them to the output
529 Demod
.parityBits
<<= 1; // add a (void) parity bit
530 Demod
.parityBits
<<= (8 - (Demod
.len
& 0x0007)); // left align remaining parity bits
531 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // and store them
533 } else if (Demod
.len
& 0x0007) { // there are some parity bits to store
534 Demod
.parityBits
<<= (8 - (Demod
.len
& 0x0007)); // left align remaining parity bits
535 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // and store them
538 return true; // we are finished with decoding the raw data sequence
539 } else { // nothing received. Start over
545 return false; // not finished yet, need more data
549 // Thinfilm, Kovio mangels ISO14443A in the way that they don't use start bit nor parity bits.
550 static RAMFUNC
int ManchesterDecoding_Thinfilm(uint8_t bit
) {
551 Demod
.twoBits
= (Demod
.twoBits
<< 8) | bit
;
553 if (Demod
.state
== DEMOD_14A_UNSYNCD
) {
555 if (Demod
.highCnt
< 2) { // wait for a stable unmodulated signal
556 if (Demod
.twoBits
== 0x0000) {
562 Demod
.syncBit
= 0xFFFF; // not set
563 if ((Demod
.twoBits
& 0x7700) == 0x7000) Demod
.syncBit
= 7;
564 else if ((Demod
.twoBits
& 0x3B80) == 0x3800) Demod
.syncBit
= 6;
565 else if ((Demod
.twoBits
& 0x1DC0) == 0x1C00) Demod
.syncBit
= 5;
566 else if ((Demod
.twoBits
& 0x0EE0) == 0x0E00) Demod
.syncBit
= 4;
567 else if ((Demod
.twoBits
& 0x0770) == 0x0700) Demod
.syncBit
= 3;
568 else if ((Demod
.twoBits
& 0x03B8) == 0x0380) Demod
.syncBit
= 2;
569 else if ((Demod
.twoBits
& 0x01DC) == 0x01C0) Demod
.syncBit
= 1;
570 else if ((Demod
.twoBits
& 0x00EE) == 0x00E0) Demod
.syncBit
= 0;
571 if (Demod
.syncBit
!= 0xFFFF) {
572 Demod
.startTime
= (GetCountSspClk() & 0xfffffff8);
573 Demod
.startTime
-= Demod
.syncBit
;
574 Demod
.bitCount
= 1; // number of decoded data bits
576 Demod
.state
= DEMOD_14A_MANCHESTER_DATA
;
581 if (IsManchesterModulationNibble1(Demod
.twoBits
>> Demod
.syncBit
)) { // modulation in first half
582 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // ... and in second half = collision
583 if (!Demod
.collisionPos
) {
584 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
586 } // modulation in first half only - Sequence D = 1
588 Demod
.shiftReg
= (Demod
.shiftReg
<< 1) | 0x1; // in both cases, add a 1 to the shiftreg
589 if (Demod
.bitCount
== 8) { // if we decoded a full byte
590 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
594 Demod
.endTime
= Demod
.startTime
+ 8 * (8 * Demod
.len
+ Demod
.bitCount
+ 1) - 4;
595 } else { // no modulation in first half
596 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // and modulation in second half = Sequence E = 0
598 Demod
.shiftReg
= (Demod
.shiftReg
<< 1); // add a 0 to the shiftreg
599 if (Demod
.bitCount
>= 8) { // if we decoded a full byte
600 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
604 Demod
.endTime
= Demod
.startTime
+ 8 * (8 * Demod
.len
+ Demod
.bitCount
+ 1);
605 } else { // no modulation in both halves - End of communication
606 if (Demod
.bitCount
> 0) { // there are some remaining data bits
607 Demod
.shiftReg
<<= (8 - Demod
.bitCount
); // left align the decoded bits
608 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff; // and add them to the output
612 return true; // we are finished with decoding the raw data sequence
613 } else { // nothing received. Start over
619 return false; // not finished yet, need more data
622 //=============================================================================
623 // Finally, a `sniffer' for ISO 14443 Type A
624 // Both sides of communication!
625 //=============================================================================
627 //-----------------------------------------------------------------------------
628 // Record the sequence of commands sent by the reader to the tag, with
629 // triggering so that we start recording at the point that the tag is moved
632 //-----------------------------------------------------------------------------
633 void RAMFUNC
SniffIso14443a(uint8_t param
) {
636 // bit 0 - trigger from first card answer
637 // bit 1 - trigger from first reader 7-bit request
638 iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER
);
640 // Allocate memory from BigBuf for some buffers
641 // free all previous allocations first
643 BigBuf_Clear_ext(false);
647 // The command (reader -> tag) that we're receiving.
648 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
649 uint8_t *receivedCmdPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
651 // The response (tag -> reader) that we're receiving.
652 uint8_t *receivedResp
= BigBuf_malloc(MAX_FRAME_SIZE
);
653 uint8_t *receivedRespPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
655 uint8_t previous_data
= 0;
656 int maxDataLen
= 0, dataLen
;
657 bool TagIsActive
= false;
658 bool ReaderIsActive
= false;
660 // Set up the demodulator for tag -> reader responses.
661 Demod14aInit(receivedResp
, receivedRespPar
);
663 // Set up the demodulator for the reader -> tag commands
664 Uart14aInit(receivedCmd
, receivedCmdPar
);
666 Dbprintf("Starting to sniff. Press PM3 Button to stop.");
668 // The DMA buffer, used to stream samples from the FPGA
669 dmabuf8_t
*dma
= get_dma8();
670 uint8_t *data
= dma
->buf
;
672 // Setup and start DMA.
673 if (!FpgaSetupSscDma((uint8_t *) dma
->buf
, DMA_BUFFER_SIZE
)) {
674 if (DBGLEVEL
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
678 // We won't start recording the frames that we acquire until we trigger;
679 // a good trigger condition to get started is probably when we see a
680 // response from the tag.
681 // triggered == false -- to wait first for card
682 bool triggered
= !(param
& 0x03);
684 uint32_t rx_samples
= 0;
687 while (BUTTON_PRESS() == false) {
691 register int readBufDataP
= data
- dma
->buf
;
692 register int dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
693 if (readBufDataP
<= dmaBufDataP
)
694 dataLen
= dmaBufDataP
- readBufDataP
;
696 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
;
698 // test for length of buffer
699 if (dataLen
> maxDataLen
) {
700 maxDataLen
= dataLen
;
701 if (dataLen
> (9 * DMA_BUFFER_SIZE
/ 10)) {
702 Dbprintf("[!] blew circular buffer! | datalen %u", dataLen
);
706 if (dataLen
< 1) continue;
708 // primary buffer was stopped( <-- we lost data!
709 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
710 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dma
->buf
;
711 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
712 Dbprintf("[-] RxEmpty ERROR | data length %d", dataLen
); // temporary
714 // secondary buffer sets as primary, secondary buffer was stopped
715 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
716 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dma
->buf
;
717 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
722 // Need two samples to feed Miller and Manchester-Decoder
723 if (rx_samples
& 0x01) {
725 if (!TagIsActive
) { // no need to try decoding reader data if the tag is sending
726 uint8_t readerdata
= (previous_data
& 0xF0) | (*data
>> 4);
727 if (MillerDecoding(readerdata
, (rx_samples
- 1) * 4)) {
730 // check - if there is a short 7bit request from reader
731 if ((!triggered
) && (param
& 0x02) && (Uart
.len
== 1) && (Uart
.bitCount
== 7)) triggered
= true;
734 if (!LogTrace(receivedCmd
,
736 Uart
.startTime
* 16 - DELAY_READER_AIR2ARM_AS_SNIFFER
,
737 Uart
.endTime
* 16 - DELAY_READER_AIR2ARM_AS_SNIFFER
,
741 /* ready to receive another command. */
743 /* reset the demod code, which might have been */
744 /* false-triggered by the commands from the reader. */
748 ReaderIsActive
= (Uart
.state
!= STATE_14A_UNSYNCD
);
751 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
752 if (!ReaderIsActive
) {
753 uint8_t tagdata
= (previous_data
<< 4) | (*data
& 0x0F);
754 if (ManchesterDecoding(tagdata
, 0, (rx_samples
- 1) * 4)) {
757 if (!LogTrace(receivedResp
,
759 Demod
.startTime
* 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER
,
760 Demod
.endTime
* 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER
,
764 if ((!triggered
) && (param
& 0x01)) triggered
= true;
766 // ready to receive another response.
768 // reset the Miller decoder including its (now outdated) input buffer
770 //Uart14aInit(receivedCmd, receivedCmdPar);
773 TagIsActive
= (Demod
.state
!= DEMOD_14A_UNSYNCD
);
777 previous_data
= *data
;
780 if (data
== dma
->buf
+ DMA_BUFFER_SIZE
) {
785 FpgaDisableTracing();
787 if (DBGLEVEL
>= DBG_ERROR
) {
788 Dbprintf("trace len = " _YELLOW_("%d"), BigBuf_get_traceLen());
793 //-----------------------------------------------------------------------------
794 // Prepare tag messages
795 //-----------------------------------------------------------------------------
796 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, uint16_t len
, uint8_t *par
, bool collision
) {
800 tosend_t
*ts
= get_tosend();
802 // Correction bit, might be removed when not needed
807 tosend_stuffbit(1); // <-----
813 ts
->buf
[++ts
->max
] = SEC_D
;
814 LastProxToAirDuration
= 8 * ts
->max
- 4;
816 for (uint16_t i
= 0; i
< len
; i
++) {
820 for (uint16_t j
= 0; j
< 8; j
++) {
822 ts
->buf
[++ts
->max
] = SEC_COLL
;
825 ts
->buf
[++ts
->max
] = SEC_D
;
827 ts
->buf
[++ts
->max
] = SEC_E
;
834 ts
->buf
[++ts
->max
] = SEC_COLL
;
835 LastProxToAirDuration
= 8 * ts
->max
;
837 // Get the parity bit
838 if (par
[i
>> 3] & (0x80 >> (i
& 0x0007))) {
839 ts
->buf
[++ts
->max
] = SEC_D
;
840 LastProxToAirDuration
= 8 * ts
->max
- 4;
842 ts
->buf
[++ts
->max
] = SEC_E
;
843 LastProxToAirDuration
= 8 * ts
->max
;
849 ts
->buf
[++ts
->max
] = SEC_F
;
851 // Convert from last byte pos to length
855 static void CodeIso14443aAsTagEx(const uint8_t *cmd
, uint16_t len
, bool collision
) {
856 uint8_t par
[MAX_PARITY_SIZE
] = {0};
857 GetParity(cmd
, len
, par
);
858 CodeIso14443aAsTagPar(cmd
, len
, par
, collision
);
860 static void CodeIso14443aAsTag(const uint8_t *cmd
, uint16_t len
) {
861 CodeIso14443aAsTagEx(cmd
, len
, false);
864 static void Code4bitAnswerAsTag(uint8_t cmd
) {
869 tosend_t
*ts
= get_tosend();
871 // Correction bit, might be removed when not needed
876 tosend_stuffbit(1); // 1
882 ts
->buf
[++ts
->max
] = SEC_D
;
884 for (uint8_t i
= 0; i
< 4; i
++) {
886 ts
->buf
[++ts
->max
] = SEC_D
;
887 LastProxToAirDuration
= 8 * ts
->max
- 4;
889 ts
->buf
[++ts
->max
] = SEC_E
;
890 LastProxToAirDuration
= 8 * ts
->max
;
896 ts
->buf
[++ts
->max
] = SEC_F
;
898 // Convert from last byte pos to length
902 //-----------------------------------------------------------------------------
903 // Wait for commands from reader
904 // stop when button is pressed or client usb connection resets
905 // or return TRUE when command is captured
906 //-----------------------------------------------------------------------------
907 bool GetIso14443aCommandFromReader(uint8_t *received
, uint8_t *par
, int *len
) {
908 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
909 // only, since we are receiving, not transmitting).
910 // Signal field is off with the appropriate LED
912 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
914 // Now run a `software UART` on the stream of incoming samples.
915 Uart14aInit(received
, par
);
918 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
922 uint16_t checker
= 0;
926 if (data_available())
932 if (checker
>= 3000) {
941 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
942 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
943 if (MillerDecoding(b
, 0)) {
952 bool prepare_tag_modulation(tag_response_info_t
*response_info
, size_t max_buffer_size
) {
953 // Example response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
954 // This will need the following byte array for a modulation sequence
955 // 144 data bits (18 * 8)
958 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
959 // 1 just for the case
961 // 166 bytes, since every bit that needs to be send costs us a byte
963 // Prepare the tag modulation bits from the message
964 CodeIso14443aAsTag(response_info
->response
, response_info
->response_n
);
966 tosend_t
*ts
= get_tosend();
968 // Make sure we do not exceed the free buffer space
969 if (ts
->max
> max_buffer_size
) {
970 Dbprintf("ToSend buffer, Out-of-bound, when modulating bits for tag answer:");
971 Dbhexdump(response_info
->response_n
, response_info
->response
, false);
975 // Copy the byte array, used for this modulation to the buffer position
976 memcpy(response_info
->modulation
, ts
->buf
, ts
->max
);
978 // Store the number of bytes that were used for encoding/modulation and the time needed to transfer them
979 response_info
->modulation_n
= ts
->max
;
980 response_info
->ProxToAirDuration
= LastProxToAirDuration
;
984 bool prepare_allocated_tag_modulation(tag_response_info_t
*response_info
, uint8_t **buffer
, size_t *max_buffer_size
) {
986 tosend_t
*ts
= get_tosend();
988 // Retrieve and store the current buffer index
989 response_info
->modulation
= *buffer
;
991 // Forward the prepare tag modulation function to the inner function
992 if (prepare_tag_modulation(response_info
, *max_buffer_size
)) {
993 // Update the free buffer offset and the remaining buffer size
995 *max_buffer_size
-= ts
->max
;
1002 bool SimulateIso14443aInit(int tagType
, int flags
, uint8_t *data
, tag_response_info_t
**responses
, uint32_t *cuid
, uint32_t counters
[3], uint8_t tearings
[3], uint8_t *pages
) {
1004 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
1005 static uint8_t rATQA
[2] = { 0x00 };
1006 // The second response contains the (mandatory) first 24 bits of the UID
1007 static uint8_t rUIDc1
[5] = { 0x00 };
1009 static uint8_t rUIDc2
[5] = { 0x00 };
1011 static uint8_t rUIDc3
[5] = { 0x00 };
1012 // Prepare the mandatory SAK (for 4, 7 and 10 byte UID)
1013 static uint8_t rSAKc1
[3] = { 0x00 };
1014 // Prepare the optional second SAK (for 7 and 10 byte UID), drop the cascade bit for 7b
1015 static uint8_t rSAKc2
[3] = { 0x00 };
1016 // Prepare the optional third SAK (for 10 byte UID), drop the cascade bit
1017 static uint8_t rSAKc3
[3] = { 0x00 };
1018 // dummy ATS (pseudo-ATR), answer to RATS
1019 // static uint8_t rRATS[] = { 0x04, 0x58, 0x80, 0x02, 0x00, 0x00 };
1020 static uint8_t rRATS
[] = { 0x05, 0x75, 0x80, 0x60, 0x02, 0x00, 0x00 };
1022 // GET_VERSION response for EV1/NTAG
1023 static uint8_t rVERSION
[10] = { 0x00 };
1024 // READ_SIG response for EV1/NTAG
1025 static uint8_t rSIGN
[34] = { 0x00 };
1027 static uint8_t rPPS
[3] = { 0xD0 };
1030 case 1: { // MIFARE Classic 1k
1035 case 2: { // MIFARE Ultralight
1038 // some first pages of UL/NTAG dump is special data
1039 mfu_dump_t
*mfu_header
= (mfu_dump_t
*) BigBuf_get_EM_addr();
1040 *pages
= MAX(mfu_header
->pages
, 15);
1043 case 3: { // MIFARE DESFire
1049 case 4: { // ISO/IEC 14443-4 - javacard (JCOP)
1054 case 5: { // MIFARE TNP3XXX
1060 case 6: { // MIFARE Mini 320b
1068 // some first pages of UL/NTAG dump is special data
1069 mfu_dump_t
*mfu_header
= (mfu_dump_t
*) BigBuf_get_EM_addr();
1070 *pages
= MAX(mfu_header
->pages
, 19);
1072 // counters and tearing flags
1073 // for old dumps with all zero headers, we need to set default values.
1074 for (uint8_t i
= 0; i
< 3; i
++) {
1076 counters
[i
] = le24toh(mfu_header
->counter_tearing
[i
]);
1078 if (mfu_header
->counter_tearing
[i
][3] != 0x00) {
1079 tearings
[i
] = mfu_header
->counter_tearing
[i
][3];
1084 if (memcmp(mfu_header
->version
, "\x00\x00\x00\x00\x00\x00\x00\x00", 8) == 0) {
1085 memcpy(rVERSION
, "\x00\x04\x04\x02\x01\x00\x11\x03", 8);
1087 memcpy(rVERSION
, mfu_header
->version
, 8);
1089 AddCrc14A(rVERSION
, sizeof(rVERSION
) - 2);
1092 memcpy(rSIGN
, mfu_header
->signature
, 32);
1093 AddCrc14A(rSIGN
, sizeof(rSIGN
) - 2);
1096 case 8: { // MIFARE Classic 4k
1101 case 9: { // FM11RF005SH (Shanghai Metro)
1107 case 10: { // ST25TA IKEA Rothult
1115 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Error: unknown tagtype (%d)", tagType
);
1121 // if uid not supplied then get from emulator memory
1122 if (data
[0] == 0 || (flags
& FLAG_UID_IN_EMUL
) == FLAG_UID_IN_EMUL
) {
1123 if (tagType
== 2 || tagType
== 7) {
1124 uint16_t start
= MFU_DUMP_PREFIX_LENGTH
;
1126 emlGetMemBt(emdata
, start
, sizeof(emdata
));
1127 memcpy(data
, emdata
, 3); // uid bytes 0-2
1128 memcpy(data
+ 3, emdata
+ 4, 4); // uid bytes 3-7
1129 flags
|= FLAG_7B_UID_IN_DATA
;
1131 emlGetMemBt(data
, 0, 4);
1132 flags
|= FLAG_4B_UID_IN_DATA
;
1136 if ((flags
& FLAG_4B_UID_IN_DATA
) == FLAG_4B_UID_IN_DATA
) {
1137 rUIDc1
[0] = data
[0];
1138 rUIDc1
[1] = data
[1];
1139 rUIDc1
[2] = data
[2];
1140 rUIDc1
[3] = data
[3];
1141 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1143 // Configure the ATQA and SAK accordingly
1145 rSAKc1
[0] = sak
& 0xFB;
1146 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1148 *cuid
= bytes_to_num(data
, 4);
1149 } else if ((flags
& FLAG_7B_UID_IN_DATA
) == FLAG_7B_UID_IN_DATA
) {
1150 rUIDc1
[0] = 0x88; // Cascade Tag marker
1151 rUIDc1
[1] = data
[0];
1152 rUIDc1
[2] = data
[1];
1153 rUIDc1
[3] = data
[2];
1154 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1156 rUIDc2
[0] = data
[3];
1157 rUIDc2
[1] = data
[4];
1158 rUIDc2
[2] = data
[5];
1159 rUIDc2
[3] = data
[6];
1160 rUIDc2
[4] = rUIDc2
[0] ^ rUIDc2
[1] ^ rUIDc2
[2] ^ rUIDc2
[3];
1162 // Configure the ATQA and SAK accordingly
1166 rSAKc2
[0] = sak
& 0xFB;
1167 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1168 AddCrc14A(rSAKc2
, sizeof(rSAKc2
) - 2);
1170 *cuid
= bytes_to_num(data
+ 3, 4);
1171 } else if ((flags
& FLAG_10B_UID_IN_DATA
) == FLAG_10B_UID_IN_DATA
) {
1172 rUIDc1
[0] = 0x88; // Cascade Tag marker
1173 rUIDc1
[1] = data
[0];
1174 rUIDc1
[2] = data
[1];
1175 rUIDc1
[3] = data
[2];
1176 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1178 rUIDc2
[0] = 0x88; // Cascade Tag marker
1179 rUIDc2
[1] = data
[3];
1180 rUIDc2
[2] = data
[4];
1181 rUIDc2
[3] = data
[5];
1182 rUIDc2
[4] = rUIDc2
[0] ^ rUIDc2
[1] ^ rUIDc2
[2] ^ rUIDc2
[3];
1184 rUIDc3
[0] = data
[6];
1185 rUIDc3
[1] = data
[7];
1186 rUIDc3
[2] = data
[8];
1187 rUIDc3
[3] = data
[9];
1188 rUIDc3
[4] = rUIDc3
[0] ^ rUIDc3
[1] ^ rUIDc3
[2] ^ rUIDc3
[3];
1190 // Configure the ATQA and SAK accordingly
1195 rSAKc3
[0] = sak
& 0xFB;
1196 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1197 AddCrc14A(rSAKc2
, sizeof(rSAKc2
) - 2);
1198 AddCrc14A(rSAKc3
, sizeof(rSAKc3
) - 2);
1200 *cuid
= bytes_to_num(data
+ 3 + 3, 4);
1202 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("[-] ERROR: UID size not defined");
1206 // Format byte = 0x58: FSCI=0x08 (FSC=256), TA(1) and TC(1) present,
1207 // TA(1) = 0x80: different divisors not supported, DR = 1, DS = 1
1208 // TB(1) = not present. Defaults: FWI = 4 (FWT = 256 * 16 * 2^4 * 1/fc = 4833us), SFGI = 0 (SFG = 256 * 16 * 2^0 * 1/fc = 302us)
1209 // TC(1) = 0x02: CID supported, NAD not supported
1210 AddCrc14A(rRATS
, sizeof(rRATS
) - 2);
1212 AddCrc14A(rPPS
, sizeof(rPPS
) - 2);
1214 static tag_response_info_t responses_init
[] = {
1215 { .response
= rATQA
, .response_n
= sizeof(rATQA
) }, // Answer to request - respond with card type
1216 { .response
= rUIDc1
, .response_n
= sizeof(rUIDc1
) }, // Anticollision cascade1 - respond with uid
1217 { .response
= rUIDc2
, .response_n
= sizeof(rUIDc2
) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1218 { .response
= rUIDc3
, .response_n
= sizeof(rUIDc3
) }, // Anticollision cascade3 - respond with 3rd half of uid if asked
1219 { .response
= rSAKc1
, .response_n
= sizeof(rSAKc1
) }, // Acknowledge select - cascade 1
1220 { .response
= rSAKc2
, .response_n
= sizeof(rSAKc2
) }, // Acknowledge select - cascade 2
1221 { .response
= rSAKc3
, .response_n
= sizeof(rSAKc3
) }, // Acknowledge select - cascade 3
1222 { .response
= rRATS
, .response_n
= sizeof(rRATS
) }, // dummy ATS (pseudo-ATR), answer to RATS
1223 { .response
= rVERSION
, .response_n
= sizeof(rVERSION
) }, // EV1/NTAG GET_VERSION response
1224 { .response
= rSIGN
, .response_n
= sizeof(rSIGN
) }, // EV1/NTAG READ_SIG response
1225 { .response
= rPPS
, .response_n
= sizeof(rPPS
) } // PPS response
1228 // "precompile" responses. There are 11 predefined responses with a total of 80 bytes data to transmit.
1229 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
1230 // 80 * 8 data bits, 80 * 1 parity bits, 11 start bits, 11 stop bits, 11 correction bits
1231 // 80 * 8 + 80 + 11 + 11 + 11 == 753
1232 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 753
1234 uint8_t *free_buffer
= BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE
);
1235 // modulation buffer pointer and current buffer free space size
1236 uint8_t *free_buffer_pointer
= free_buffer
;
1237 size_t free_buffer_size
= ALLOCATED_TAG_MODULATION_BUFFER_SIZE
;
1239 // Prepare the responses of the anticollision phase
1240 // there will be not enough time to do this at the moment the reader sends it REQA
1241 for (size_t i
= 0; i
< ARRAYLEN(responses_init
); i
++) {
1242 if (prepare_allocated_tag_modulation(&responses_init
[i
], &free_buffer_pointer
, &free_buffer_size
) == false) {
1243 BigBuf_free_keep_EM();
1244 if (DBGLEVEL
>= DBG_ERROR
) Dbprintf("Not enough modulation buffer size, exit after %d elements", i
);
1249 *responses
= responses_init
;
1254 //-----------------------------------------------------------------------------
1255 // Main loop of simulated tag: receive commands from reader, decide what
1256 // response to send, and send it.
1258 //-----------------------------------------------------------------------------
1259 void SimulateIso14443aTag(uint8_t tagType
, uint8_t flags
, uint8_t *data
, uint8_t exitAfterNReads
) {
1261 #define ATTACK_KEY_COUNT 8 // keep same as define in cmdhfmf.c -> readerAttack()
1263 tag_response_info_t
*responses
;
1266 uint32_t counters
[3] = { 0x00, 0x00, 0x00 };
1267 uint8_t tearings
[3] = { 0xbd, 0xbd, 0xbd };
1270 // Here, we collect CUID, block1, keytype1, NT1, NR1, AR1, CUID, block2, keytyp2, NT2, NR2, AR2
1271 // it should also collect block, keytype.
1272 uint8_t cardAUTHSC
= 0;
1273 uint8_t cardAUTHKEY
= 0xff; // no authentication
1274 // allow collecting up to 8 sets of nonces to allow recovery of up to 8 keys
1276 nonces_t ar_nr_nonces
[ATTACK_KEY_COUNT
]; // for attack types moebius
1277 memset(ar_nr_nonces
, 0x00, sizeof(ar_nr_nonces
));
1278 uint8_t moebius_count
= 0;
1281 uint8_t receivedCmd
[MAX_FRAME_SIZE
] = { 0x00 };
1282 uint8_t receivedCmdPar
[MAX_PARITY_SIZE
] = { 0x00 };
1284 // Allocate 512 bytes for the dynamic modulation, created when the reader queries for it
1285 // Such a response is less time critical, so we can prepare them on the fly
1286 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1287 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1288 uint8_t dynamic_response_buffer
[DYNAMIC_RESPONSE_BUFFER_SIZE
] = {0};
1289 uint8_t dynamic_modulation_buffer
[DYNAMIC_MODULATION_BUFFER_SIZE
] = {0};
1290 tag_response_info_t dynamic_response_info
= {
1291 .response
= dynamic_response_buffer
,
1293 .modulation
= dynamic_modulation_buffer
,
1297 // free eventually allocated BigBuf memory but keep Emulator Memory
1298 BigBuf_free_keep_EM();
1300 if (SimulateIso14443aInit(tagType
, flags
, data
, &responses
, &cuid
, counters
, tearings
, &pages
) == false) {
1301 BigBuf_free_keep_EM();
1302 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_EINIT
, NULL
, 0);
1306 // We need to listen to the high-frequency, peak-detected path.
1307 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1309 iso14a_set_timeout(201400); // 106 * 19ms default *100?
1313 // To control where we are in the protocol
1314 #define ORDER_NONE 0
1315 //#define ORDER_REQA 1
1316 //#define ORDER_SELECT_ALL_CL1 2
1317 //#define ORDER_SELECT_CL1 3
1318 #define ORDER_HALTED 5
1319 #define ORDER_WUPA 6
1320 #define ORDER_AUTH 7
1321 //#define ORDER_SELECT_ALL_CL2 20
1322 //#define ORDER_SELECT_CL2 25
1323 //#define ORDER_SELECT_ALL_CL3 30
1324 //#define ORDER_SELECT_CL3 35
1325 #define ORDER_EV1_COMP_WRITE 40
1326 //#define ORDER_RATS 70
1328 uint8_t order
= ORDER_NONE
;
1329 int retval
= PM3_SUCCESS
;
1331 // Just to allow some checks
1335 uint32_t numReads
= 0; //Counts numer of times reader reads a block
1337 // compatible write block number
1338 uint8_t wrblock
= 0;
1340 bool odd_reply
= true;
1347 bool finished
= false;
1348 bool button_pushed
= BUTTON_PRESS();
1349 while (!button_pushed
&& !finished
) {
1352 tag_response_info_t
*p_response
= NULL
;
1354 // Clean receive command buffer
1355 if (GetIso14443aCommandFromReader(receivedCmd
, receivedCmdPar
, &len
) == false) {
1356 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
1357 retval
= PM3_EOPABORTED
;
1361 // we need to check "ordered" states before, because received data may be same to any command - is wrong!!!
1362 if (order
== ORDER_EV1_COMP_WRITE
&& len
== 18) {
1363 // MIFARE_ULC_COMP_WRITE part 2
1364 // 16 bytes data + 2 bytes crc, only least significant 4 bytes are written
1365 bool isCrcCorrect
= CheckCrc14A(receivedCmd
, len
);
1367 // first blocks of emu are header
1368 emlSetMem_xt(receivedCmd
, wrblock
+ MFU_DUMP_PREFIX_LENGTH
/ 4, 1, 4);
1370 EmSend4bit(CARD_ACK
);
1372 // send NACK 0x1 == crc/parity error
1373 EmSend4bit(CARD_NACK_PA
);
1375 order
= ORDER_NONE
; // back to work state
1378 } else if (order
== ORDER_AUTH
&& len
== 8) {
1379 // Received {nr] and {ar} (part of authentication)
1380 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1381 uint32_t nr
= bytes_to_num(receivedCmd
, 4);
1382 uint32_t ar
= bytes_to_num(receivedCmd
+ 4, 4);
1384 // Collect AR/NR per keytype & sector
1385 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1389 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1390 // find which index to use
1391 if ((cardAUTHSC
== ar_nr_nonces
[i
].sector
) && (cardAUTHKEY
== ar_nr_nonces
[i
].keytype
))
1394 // keep track of empty slots.
1395 if (ar_nr_nonces
[i
].state
== EMPTY
)
1398 // if no empty slots. Choose first and overwrite.
1402 ar_nr_nonces
[index
].state
= EMPTY
;
1408 switch (ar_nr_nonces
[index
].state
) {
1410 // first nonce collect
1411 ar_nr_nonces
[index
].cuid
= cuid
;
1412 ar_nr_nonces
[index
].sector
= cardAUTHSC
;
1413 ar_nr_nonces
[index
].keytype
= cardAUTHKEY
;
1414 ar_nr_nonces
[index
].nonce
= nonce
;
1415 ar_nr_nonces
[index
].nr
= nr
;
1416 ar_nr_nonces
[index
].ar
= ar
;
1417 ar_nr_nonces
[index
].state
= FIRST
;
1421 // second nonce collect
1422 ar_nr_nonces
[index
].nonce2
= nonce
;
1423 ar_nr_nonces
[index
].nr2
= nr
;
1424 ar_nr_nonces
[index
].ar2
= ar
;
1425 ar_nr_nonces
[index
].state
= SECOND
;
1427 // send to client (one struct nonces_t)
1428 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_SUCCESS
, (uint8_t *)&ar_nr_nonces
[index
], sizeof(nonces_t
));
1430 ar_nr_nonces
[index
].state
= EMPTY
;
1431 ar_nr_nonces
[index
].sector
= 0;
1432 ar_nr_nonces
[index
].keytype
= 0;
1441 order
= ORDER_NONE
; // back to work state
1444 } else if (receivedCmd
[0] == ISO14443A_CMD_REQA
&& len
== 1) { // Received a REQUEST, but in HALTED, skip
1445 odd_reply
= !odd_reply
;
1447 p_response
= &responses
[RESP_INDEX_ATQA
];
1448 } else if (receivedCmd
[0] == ISO14443A_CMD_WUPA
&& len
== 1) { // Received a WAKEUP
1449 p_response
= &responses
[RESP_INDEX_ATQA
];
1450 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 2) { // Received request for UID (cascade 1)
1451 p_response
= &responses
[RESP_INDEX_UIDC1
];
1452 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 2) { // Received request for UID (cascade 2)
1453 p_response
= &responses
[RESP_INDEX_UIDC2
];
1454 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 2) { // Received request for UID (cascade 3)
1455 p_response
= &responses
[RESP_INDEX_UIDC3
];
1456 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 9) { // Received a SELECT (cascade 1)
1457 p_response
= &responses
[RESP_INDEX_SAKC1
];
1458 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 9) { // Received a SELECT (cascade 2)
1459 p_response
= &responses
[RESP_INDEX_SAKC2
];
1460 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 9) { // Received a SELECT (cascade 3)
1461 p_response
= &responses
[RESP_INDEX_SAKC3
];
1462 } else if (receivedCmd
[0] == ISO14443A_CMD_PPS
) {
1463 p_response
= &responses
[RESP_INDEX_PPS
];
1464 } else if (receivedCmd
[0] == ISO14443A_CMD_READBLOCK
&& len
== 4) { // Received a (plain) READ
1465 uint8_t block
= receivedCmd
[1];
1466 // if Ultralight or NTAG (4 byte blocks)
1467 if (tagType
== 7 || tagType
== 2) {
1468 if (block
> pages
) {
1469 // send NACK 0x0 == invalid argument
1470 EmSend4bit(CARD_NACK_IV
);
1472 // first blocks of emu are header
1473 uint16_t start
= block
* 4 + MFU_DUMP_PREFIX_LENGTH
;
1474 uint8_t emdata
[MAX_MIFARE_FRAME_SIZE
];
1475 emlGetMemBt(emdata
, start
, 16);
1476 AddCrc14A(emdata
, 16);
1477 EmSendCmd(emdata
, sizeof(emdata
));
1478 numReads
++; // Increment number of times reader requested a block
1480 if (exitAfterNReads
> 0 && numReads
== exitAfterNReads
) {
1481 Dbprintf("[MFUEMUL_WORK] %d reads done, exiting", numReads
);
1485 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1487 } else if (tagType
== 9 && block
== 1) {
1488 // FM11005SH. 16blocks, 4bytes / block.
1489 // block0 = 2byte Customer ID (CID), 2byte Manufacture ID (MID)
1490 // block1 = 4byte UID.
1491 p_response
= &responses
[RESP_INDEX_UIDC1
];
1492 } else { // all other tags (16 byte block tags)
1493 uint8_t emdata
[MAX_MIFARE_FRAME_SIZE
];
1494 emlGetMemBt(emdata
, block
, 16);
1495 AddCrc14A(emdata
, 16);
1496 EmSendCmd(emdata
, sizeof(emdata
));
1497 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1500 } else if (receivedCmd
[0] == MIFARE_ULEV1_FASTREAD
&& len
== 5) { // Received a FAST READ (ranged read)
1501 uint8_t block1
= receivedCmd
[1];
1502 uint8_t block2
= receivedCmd
[2];
1503 if (block1
> pages
) {
1504 // send NACK 0x0 == invalid argument
1505 EmSend4bit(CARD_NACK_IV
);
1507 uint8_t emdata
[MAX_FRAME_SIZE
];
1508 // first blocks of emu are header
1509 int start
= block1
* 4 + MFU_DUMP_PREFIX_LENGTH
;
1510 len
= (block2
- block1
+ 1) * 4;
1511 emlGetMemBt(emdata
, start
, len
);
1512 AddCrc14A(emdata
, len
);
1513 EmSendCmd(emdata
, len
+ 2);
1516 } else if (receivedCmd
[0] == MIFARE_ULC_WRITE
&& len
== 8 && (tagType
== 2 || tagType
== 7)) { // Received a WRITE
1517 // cmd + block + 4 bytes data + 2 bytes crc
1518 if (CheckCrc14A(receivedCmd
, len
)) {
1519 uint8_t block
= receivedCmd
[1];
1520 if (block
> pages
) {
1521 // send NACK 0x0 == invalid argument
1522 EmSend4bit(CARD_NACK_IV
);
1524 // first blocks of emu are header
1525 emlSetMem_xt(&receivedCmd
[2], block
+ MFU_DUMP_PREFIX_LENGTH
/ 4, 1, 4);
1527 EmSend4bit(CARD_ACK
);
1530 // send NACK 0x1 == crc/parity error
1531 EmSend4bit(CARD_NACK_PA
);
1534 } else if (receivedCmd
[0] == MIFARE_ULC_COMP_WRITE
&& len
== 4 && (tagType
== 2 || tagType
== 7)) {
1535 // cmd + block + 2 bytes crc
1536 if (CheckCrc14A(receivedCmd
, len
)) {
1537 wrblock
= receivedCmd
[1];
1538 if (wrblock
> pages
) {
1539 // send NACK 0x0 == invalid argument
1540 EmSend4bit(CARD_NACK_IV
);
1543 EmSend4bit(CARD_ACK
);
1545 order
= ORDER_EV1_COMP_WRITE
;
1548 // send NACK 0x1 == crc/parity error
1549 EmSend4bit(CARD_NACK_PA
);
1552 } else if (receivedCmd
[0] == MIFARE_ULEV1_READSIG
&& len
== 4 && tagType
== 7) { // Received a READ SIGNATURE --
1553 p_response
= &responses
[RESP_INDEX_SIGNATURE
];
1554 } else if (receivedCmd
[0] == MIFARE_ULEV1_READ_CNT
&& len
== 4 && tagType
== 7) { // Received a READ COUNTER --
1555 uint8_t index
= receivedCmd
[1];
1557 // send NACK 0x0 == invalid argument
1558 EmSend4bit(CARD_NACK_IV
);
1560 uint8_t cmd
[] = {0x00, 0x00, 0x00, 0x14, 0xa5};
1561 htole24(counters
[index
], cmd
);
1562 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1563 EmSendCmd(cmd
, sizeof(cmd
));
1566 } else if (receivedCmd
[0] == MIFARE_ULEV1_INCR_CNT
&& len
== 8 && tagType
== 7) { // Received a INC COUNTER --
1567 uint8_t index
= receivedCmd
[1];
1569 // send NACK 0x0 == invalid argument
1570 EmSend4bit(CARD_NACK_IV
);
1572 uint32_t val
= le24toh(receivedCmd
+ 2) + counters
[index
];
1573 // if new value + old value is bigger 24bits, fail
1574 if (val
> 0xFFFFFF) {
1575 // send NACK 0x4 == counter overflow
1576 EmSend4bit(CARD_NACK_NA
);
1578 counters
[index
] = val
;
1580 EmSend4bit(CARD_ACK
);
1584 } else if (receivedCmd
[0] == MIFARE_ULEV1_CHECKTEAR
&& len
== 4 && tagType
== 7) { // Received a CHECK_TEARING_EVENT --
1585 // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1586 uint8_t index
= receivedCmd
[1];
1588 // send NACK 0x0 == invalid argument
1589 EmSend4bit(CARD_NACK_IV
);
1592 cmd
[0] = tearings
[index
];
1593 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1594 EmSendCmd(cmd
, sizeof(cmd
));
1597 } else if (receivedCmd
[0] == ISO14443A_CMD_HALT
&& len
== 4) { // Received a HALT
1598 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1600 order
= ORDER_HALTED
;
1601 } else if (receivedCmd
[0] == MIFARE_ULEV1_VERSION
&& len
== 3 && (tagType
== 2 || tagType
== 7)) {
1602 p_response
= &responses
[RESP_INDEX_VERSION
];
1603 } else if ((receivedCmd
[0] == MIFARE_AUTH_KEYA
|| receivedCmd
[0] == MIFARE_AUTH_KEYB
) && len
== 4 && tagType
!= 2 && tagType
!= 7) { // Received an authentication request
1604 cardAUTHKEY
= receivedCmd
[0] - 0x60;
1605 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
1607 // incease nonce at AUTH requests. this is time consuming.
1608 nonce
= prng_successor(GetTickCount(), 32);
1609 num_to_bytes(nonce
, 4, dynamic_response_info
.response
);
1610 dynamic_response_info
.response_n
= 4;
1612 prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
);
1613 p_response
= &dynamic_response_info
;
1615 } else if (receivedCmd
[0] == ISO14443A_CMD_RATS
&& len
== 4) { // Received a RATS request
1616 if (tagType
== 1 || tagType
== 2) { // RATS not supported
1617 EmSend4bit(CARD_NACK_NA
);
1620 p_response
= &responses
[RESP_INDEX_RATS
];
1622 } else if (receivedCmd
[0] == MIFARE_ULC_AUTH_1
) { // ULC authentication, or Desfire Authentication
1623 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1625 } else if (receivedCmd
[0] == MIFARE_ULEV1_AUTH
&& len
== 7 && tagType
== 7) { // NTAG / EV-1 authentication
1626 // PWD stored in dump now
1628 emlGetMemBt(pwd
, (pages
- 1) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(pwd
));
1629 if (memcmp(receivedCmd
+ 1, pwd
, 4) == 0) {
1631 emlGetMemBt(pack
, pages
* 4 + MFU_DUMP_PREFIX_LENGTH
, 2);
1632 if (memcmp(pack
, "\x00\x00\x00\x00", 4) == 0) {
1633 memcpy(pack
, "\x80\x80\x00\x00", 4);
1635 AddCrc14A(pack
, sizeof(pack
) - 2);
1636 EmSendCmd(pack
, sizeof(pack
));
1638 EmSend4bit(CARD_NACK_NA
);
1639 if (DBGLEVEL
>= DBG_DEBUG
) Dbprintf("Auth attempt: %08x", bytes_to_num(receivedCmd
+ 1, 4));
1642 } else if (receivedCmd
[0] == MIFARE_ULEV1_VCSL
&& len
== 23 && tagType
== 7) {
1644 emlGetMemBt(cmd
, (pages
- 2) * 4 + 1 + MFU_DUMP_PREFIX_LENGTH
, 1);
1645 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1646 EmSendCmd(cmd
, sizeof(cmd
));
1651 // clear old dynamic responses
1652 dynamic_response_info
.response_n
= 0;
1653 dynamic_response_info
.modulation_n
= 0;
1655 // ST25TA512B IKEA Rothult
1656 if (tagType
== 10) {
1657 // we replay 90 00 for all commands but the read bin and we deny the verify cmd.
1659 if (memcmp("\x02\xa2\xb0\x00\x00\x1d\x51\x69", receivedCmd
, 8) == 0) {
1660 dynamic_response_info
.response
[0] = receivedCmd
[0];
1661 memcpy(dynamic_response_info
.response
+ 1, "\x00\x1b\xd1\x01\x17\x54\x02\x7a\x68\xa2\x34\xcb\xd0\xe2\x03\xc7\x3e\x62\x0b\xe8\xc6\x3c\x85\x2c\xc5\x31\x31\x31\x32\x90\x00", 31);
1662 dynamic_response_info
.response_n
= 32;
1663 } else if (memcmp("\x02\x00\x20\x00\x01\x00\x6e\xa9", receivedCmd
, 8) == 0) {
1664 dynamic_response_info
.response
[0] = receivedCmd
[0];
1665 dynamic_response_info
.response
[1] = 0x63;
1666 dynamic_response_info
.response
[2] = 0x00;
1667 dynamic_response_info
.response_n
= 3;
1668 } else if (memcmp("\x03\x00\x20\x00\x01\x10", receivedCmd
, 6) == 0) {
1669 Dbprintf("Reader sent password: ");
1670 Dbhexdump(16, receivedCmd
+ 6, 0);
1671 dynamic_response_info
.response
[0] = receivedCmd
[0];
1672 dynamic_response_info
.response
[1] = 0x90;
1673 dynamic_response_info
.response
[2] = 0x00;
1674 dynamic_response_info
.response_n
= 3;
1676 dynamic_response_info
.response
[0] = receivedCmd
[0];
1677 dynamic_response_info
.response
[1] = 0x90;
1678 dynamic_response_info
.response
[2] = 0x00;
1679 dynamic_response_info
.response_n
= 3;
1683 // Check for ISO 14443A-4 compliant commands, look at left nibble
1684 switch (receivedCmd
[0]) {
1686 case 0x03: { // IBlock (command no CID)
1687 dynamic_response_info
.response
[0] = receivedCmd
[0];
1688 dynamic_response_info
.response
[1] = 0x90;
1689 dynamic_response_info
.response
[2] = 0x00;
1690 dynamic_response_info
.response_n
= 3;
1694 case 0x0A: { // IBlock (command CID)
1695 dynamic_response_info
.response
[0] = receivedCmd
[0];
1696 dynamic_response_info
.response
[1] = 0x00;
1697 dynamic_response_info
.response
[2] = 0x90;
1698 dynamic_response_info
.response
[3] = 0x00;
1699 dynamic_response_info
.response_n
= 4;
1704 case 0x1B: { // Chaining command
1705 dynamic_response_info
.response
[0] = 0xaa | ((receivedCmd
[0]) & 1);
1706 dynamic_response_info
.response_n
= 2;
1712 dynamic_response_info
.response
[0] = receivedCmd
[0] ^ 0x11;
1713 dynamic_response_info
.response_n
= 2;
1717 case 0xBA: { // ping / pong
1718 dynamic_response_info
.response
[0] = 0xAB;
1719 dynamic_response_info
.response
[1] = 0x00;
1720 dynamic_response_info
.response_n
= 2;
1725 case 0xC2: { // Readers sends deselect command
1726 dynamic_response_info
.response
[0] = 0xCA;
1727 dynamic_response_info
.response
[1] = 0x00;
1728 dynamic_response_info
.response_n
= 2;
1733 // Never seen this command before
1734 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1735 if (DBGLEVEL
>= DBG_DEBUG
) {
1736 Dbprintf("Received unknown command (len=%d):", len
);
1737 Dbhexdump(len
, receivedCmd
, false);
1740 dynamic_response_info
.response_n
= 0;
1741 order
= ORDER_NONE
; // back to work state
1747 if (dynamic_response_info
.response_n
> 0) {
1749 // Copy the CID from the reader query
1751 dynamic_response_info
.response
[1] = receivedCmd
[1];
1753 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1754 AddCrc14A(dynamic_response_info
.response
, dynamic_response_info
.response_n
);
1755 dynamic_response_info
.response_n
+= 2;
1757 if (prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
1758 if (DBGLEVEL
>= DBG_DEBUG
) DbpString("Error preparing tag response");
1759 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1762 p_response
= &dynamic_response_info
;
1766 // Count number of wakeups received after a halt
1767 // if (order == ORDER_WUPA && lastorder == ORDER_HALTED) { happened++; }
1769 // Count number of other messages after a halt
1770 // if (order != ORDER_WUPA && lastorder == ORDER_HALTED) { happened2++; }
1775 EmSendPrecompiledCmd(p_response
);
1781 BigBuf_free_keep_EM();
1783 if (DBGLEVEL
>= DBG_EXTENDED
) {
1784 Dbprintf("-[ Wake ups after halt [%d]", happened
);
1785 Dbprintf("-[ Messages after halt [%d]", happened2
);
1786 Dbprintf("-[ Num of received cmd [%d]", cmdsRecvd
);
1787 Dbprintf("-[ Num of moebius tries [%d]", moebius_count
);
1790 reply_ng(CMD_HF_MIFARE_SIMULATE
, retval
, NULL
, 0);
1793 // prepare a delayed transfer. This simply shifts ToSend[] by a number
1794 // of bits specified in the delay parameter.
1795 static void PrepareDelayedTransfer(uint16_t delay
) {
1799 uint8_t bitmask
= 0;
1800 uint8_t bits_shifted
= 0;
1802 for (uint16_t i
= 0; i
< delay
; i
++)
1803 bitmask
|= (0x01 << i
);
1805 tosend_t
*ts
= get_tosend();
1807 ts
->buf
[ts
->max
++] = 0x00;
1809 for (uint16_t i
= 0; i
< ts
->max
; i
++) {
1810 uint8_t bits_to_shift
= ts
->buf
[i
] & bitmask
;
1811 ts
->buf
[i
] = ts
->buf
[i
] >> delay
;
1812 ts
->buf
[i
] = ts
->buf
[i
] | (bits_shifted
<< (8 - delay
));
1813 bits_shifted
= bits_to_shift
;
1818 //-------------------------------------------------------------------------------------
1819 // Transmit the command (to the tag) that was placed in ToSend[].
1820 // Parameter timing:
1821 // if NULL: transfer at next possible time, taking into account
1822 // request guard time and frame delay time
1823 // if == 0: transfer immediately and return time of transfer
1824 // if != 0: delay transfer until time specified
1825 //-------------------------------------------------------------------------------------
1826 static void TransmitFor14443a(const uint8_t *cmd
, uint16_t len
, uint32_t *timing
) {
1828 if (g_hf_field_active
== false) {
1829 Dbprintf("Warning: HF field is off, ignoring TransmitFor14443a command");
1832 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1835 if (*timing
== 0) // Measure time
1836 *timing
= (GetCountSspClk() + 8) & 0xfffffff8;
1838 PrepareDelayedTransfer(*timing
& 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
1840 if (DBGLEVEL
>= DBG_EXTENDED
&& GetCountSspClk() >= (*timing
& 0xfffffff8))
1841 Dbprintf("TransmitFor14443a: Missed timing");
1842 while (GetCountSspClk() < (*timing
& 0xfffffff8)) {}; // Delay transfer (multiple of 8 MF clock ticks)
1843 LastTimeProxToAirStart
= *timing
;
1846 uint32_t ThisTransferTime
= 0;
1847 ThisTransferTime
= ((MAX(NextTransferTime
, GetCountSspClk()) & 0xfffffff8) + 8);
1849 while (GetCountSspClk() < ThisTransferTime
) {};
1851 LastTimeProxToAirStart
= ThisTransferTime
;
1856 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1857 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
1862 NextTransferTime
= MAX(NextTransferTime
, LastTimeProxToAirStart
+ REQUEST_GUARD_TIME
);
1865 //-----------------------------------------------------------------------------
1866 // Prepare reader command (in bits, support short frames) to send to FPGA
1867 //-----------------------------------------------------------------------------
1868 static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd
, uint16_t bits
, const uint8_t *par
) {
1872 tosend_t
*ts
= get_tosend();
1874 // Start of Communication (Seq. Z)
1875 ts
->buf
[++ts
->max
] = SEC_Z
;
1876 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
1878 size_t bytecount
= nbytes(bits
);
1879 // Generate send structure for the data bits
1880 for (int i
= 0; i
< bytecount
; i
++) {
1881 // Get the current byte to send
1883 size_t bitsleft
= MIN((bits
- (i
* 8)), 8);
1885 for (j
= 0; j
< bitsleft
; j
++) {
1888 ts
->buf
[++ts
->max
] = SEC_X
;
1889 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 2;
1894 ts
->buf
[++ts
->max
] = SEC_Z
;
1895 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
1898 ts
->buf
[++ts
->max
] = SEC_Y
;
1905 // Only transmit parity bit if we transmitted a complete byte
1906 if (j
== 8 && par
!= NULL
) {
1907 // Get the parity bit
1908 if (par
[i
>> 3] & (0x80 >> (i
& 0x0007))) {
1910 ts
->buf
[++ts
->max
] = SEC_X
;
1911 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 2;
1916 ts
->buf
[++ts
->max
] = SEC_Z
;
1917 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
1920 ts
->buf
[++ts
->max
] = SEC_Y
;
1927 // End of Communication: Logic 0 followed by Sequence Y
1930 ts
->buf
[++ts
->max
] = SEC_Z
;
1931 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
1934 ts
->buf
[++ts
->max
] = SEC_Y
;
1936 ts
->buf
[++ts
->max
] = SEC_Y
;
1938 // Convert to length of command:
1942 //-----------------------------------------------------------------------------
1943 // Prepare reader command to send to FPGA
1944 //-----------------------------------------------------------------------------
1946 static void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *par) {
1947 CodeIso14443aBitsAsReaderPar(cmd, len * 8, par);
1950 //-----------------------------------------------------------------------------
1951 // Wait for commands from reader
1952 // Stop when button is pressed (return 1) or field was gone (return 2)
1953 // Or return 0 when command is captured
1954 //-----------------------------------------------------------------------------
1955 int EmGetCmd(uint8_t *received
, uint16_t *len
, uint8_t *par
) {
1962 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1963 // only, since we are receiving, not transmitting).
1964 // Signal field is off with the appropriate LED
1966 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1968 // Set ADC to read field strength
1969 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
1970 AT91C_BASE_ADC
->ADC_MR
=
1971 ADC_MODE_PRESCALE(63) |
1972 ADC_MODE_STARTUP_TIME(1) |
1973 ADC_MODE_SAMPLE_HOLD_TIME(15);
1976 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF_RDV40
);
1978 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
1982 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
1984 // Now run a 'software UART' on the stream of incoming samples.
1985 Uart14aInit(received
, par
);
1988 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1996 if (check
== 1000) {
1997 if (BUTTON_PRESS() || data_available()) {
1998 Dbprintf("----------- " _GREEN_("BREAKING") " ----------");
2005 // test if the field exists
2007 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF_RDV40
)) {
2011 analogAVG
+= (AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF_RDV40
] & 0x3FF);
2013 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
2015 if (analogCnt
>= 32) {
2017 if ((MAX_ADC_HF_VOLTAGE_RDV40
* (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
2020 timer
= GetTickCount();
2022 // 50ms no field --> card to idle state
2023 if (GetTickCountDelta(timer
) > 50) {
2035 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
2039 analogAVG
+= (AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
] & 0x3FF);
2041 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
2043 if (analogCnt
>= 32) {
2045 if ((MAX_ADC_HF_VOLTAGE
* (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
2048 timer
= GetTickCount();
2050 // 50ms no field --> card to idle state
2051 if (GetTickCountDelta(timer
) > 50) {
2064 // receive and test the miller decoding
2065 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2066 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2067 if (MillerDecoding(b
, 0)) {
2075 int EmSendCmd14443aRaw(uint8_t *resp
, uint16_t respLen
) {
2078 uint32_t ThisTransferTime
;
2079 bool correction_needed
;
2081 // Modulate Manchester
2082 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
2084 // Include correction bit if necessary
2085 if (Uart
.bitCount
== 7) {
2086 // Short tags (7 bits) don't have parity, determine the correct value from MSB
2087 correction_needed
= Uart
.output
[0] & 0x40;
2089 // The parity bits are left-aligned
2090 correction_needed
= Uart
.parity
[(Uart
.len
- 1) / 8] & (0x80 >> ((Uart
.len
- 1) & 7));
2092 // 1236, so correction bit needed
2093 i
= (correction_needed
) ? 0 : 1;
2095 // clear receiving shift register and holding register
2096 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
2097 b
= AT91C_BASE_SSC
->SSC_RHR
;
2100 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
2101 for (uint8_t j
= 0; j
< 5; j
++) { // allow timeout - better late than never
2102 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
2103 if (AT91C_BASE_SSC
->SSC_RHR
) break;
2106 while ((ThisTransferTime
= GetCountSspClk()) & 0x00000007);
2109 AT91C_BASE_SSC
->SSC_THR
= SEC_F
;
2112 for (; i
< respLen
;) {
2113 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2114 AT91C_BASE_SSC
->SSC_THR
= resp
[i
++];
2115 FpgaSendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2119 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
2120 uint8_t fpga_queued_bits
= FpgaSendQueueDelay
>> 3;
2121 for (i
= 0; i
<= (fpga_queued_bits
>> 3) + 1;) {
2122 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2123 AT91C_BASE_SSC
->SSC_THR
= SEC_F
;
2124 FpgaSendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2128 LastTimeProxToAirStart
= ThisTransferTime
+ (correction_needed
? 8 : 0);
2132 int EmSend4bit(uint8_t resp
) {
2133 Code4bitAnswerAsTag(resp
);
2134 tosend_t
*ts
= get_tosend();
2135 int res
= EmSendCmd14443aRaw(ts
->buf
, ts
->max
);
2136 // do the tracing for the previous reader request and this tag answer:
2137 uint8_t par
[1] = {0x00};
2138 GetParity(&resp
, 1, par
);
2139 EmLogTrace(Uart
.output
,
2141 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2142 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2146 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2147 (LastTimeProxToAirStart
+ LastProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2151 int EmSendCmdPar(uint8_t *resp
, uint16_t respLen
, uint8_t *par
) {
2152 return EmSendCmdParEx(resp
, respLen
, par
, false);
2154 int EmSendCmdParEx(uint8_t *resp
, uint16_t respLen
, uint8_t *par
, bool collision
) {
2155 CodeIso14443aAsTagPar(resp
, respLen
, par
, collision
);
2156 tosend_t
*ts
= get_tosend();
2157 int res
= EmSendCmd14443aRaw(ts
->buf
, ts
->max
);
2159 // do the tracing for the previous reader request and this tag answer:
2160 EmLogTrace(Uart
.output
,
2162 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2163 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2167 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2168 (LastTimeProxToAirStart
+ LastProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2172 int EmSendCmd(uint8_t *resp
, uint16_t respLen
) {
2173 return EmSendCmdEx(resp
, respLen
, false);
2175 int EmSendCmdEx(uint8_t *resp
, uint16_t respLen
, bool collision
) {
2176 uint8_t par
[MAX_PARITY_SIZE
] = {0x00};
2177 GetParity(resp
, respLen
, par
);
2178 return EmSendCmdParEx(resp
, respLen
, par
, collision
);
2181 int EmSendPrecompiledCmd(tag_response_info_t
*p_response
) {
2182 if (p_response
== NULL
) return 0;
2183 int ret
= EmSendCmd14443aRaw(p_response
->modulation
, p_response
->modulation_n
);
2184 // do the tracing for the previous reader request and this tag answer:
2185 uint8_t par
[MAX_PARITY_SIZE
] = {0x00};
2186 GetParity(p_response
->response
, p_response
->response_n
, par
);
2188 EmLogTrace(Uart
.output
,
2190 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2191 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2193 p_response
->response
,
2194 p_response
->response_n
,
2195 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2196 (LastTimeProxToAirStart
+ p_response
->ProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2201 bool EmLogTrace(uint8_t *reader_data
, uint16_t reader_len
, uint32_t reader_StartTime
,
2202 uint32_t reader_EndTime
, uint8_t *reader_Parity
, uint8_t *tag_data
,
2203 uint16_t tag_len
, uint32_t tag_StartTime
, uint32_t tag_EndTime
, uint8_t *tag_Parity
) {
2205 // we cannot exactly measure the end and start of a received command from reader. However we know that the delay from
2206 // end of the received command to start of the tag's (simulated by us) answer is n*128+20 or n*128+84 resp.
2207 // with n >= 9. The start of the tags answer can be measured and therefore the end of the received command be calculated:
2209 uint16_t reader_modlen
= reader_EndTime
- reader_StartTime
;
2210 uint16_t approx_fdt
= tag_StartTime
- reader_EndTime
;
2211 uint16_t exact_fdt
= (approx_fdt
- 20 + 32) / 64 * 64 + 20;
2212 reader_EndTime
= tag_StartTime
- exact_fdt
;
2213 reader_StartTime
= reader_EndTime
- reader_modlen
;
2215 if (!LogTrace(reader_data
, reader_len
, reader_StartTime
, reader_EndTime
, reader_Parity
, true))
2218 return (!LogTrace(tag_data
, tag_len
, tag_StartTime
, tag_EndTime
, tag_Parity
, false));
2222 //-----------------------------------------------------------------------------
2223 // Kovio - Thinfilm barcode. TAG-TALK-FIRST -
2224 // Wait a certain time for tag response
2225 // If a response is captured return TRUE
2226 // If it takes too long return FALSE
2227 //-----------------------------------------------------------------------------
2228 bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse
, uint8_t *received_len
) {
2230 if (!g_hf_field_active
) {
2231 Dbprintf("Warning: HF field is off, ignoring GetIso14443aAnswerFromTag_Thinfilm command");
2235 // Set FPGA mode to "reader listen mode", no modulation (listen
2236 // only, since we are receiving, not transmitting).
2237 // Signal field is on with the appropriate LED
2239 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
2241 // Now get the answer from the card
2242 Demod14aInit(receivedResponse
, NULL
);
2245 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2248 uint32_t receive_timer
= GetTickCount();
2252 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2253 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2254 if (ManchesterDecoding_Thinfilm(b
)) {
2255 *received_len
= Demod
.len
;
2257 LogTrace(receivedResponse
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, NULL
, false);
2262 if (GetTickCountDelta(receive_timer
) > 100)
2265 *received_len
= Demod
.len
;
2267 LogTrace(receivedResponse
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, NULL
, false);
2272 //-----------------------------------------------------------------------------
2273 // Wait a certain time for tag response
2274 // If a response is captured return TRUE
2275 // If it takes too long return FALSE
2276 //-----------------------------------------------------------------------------
2277 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, uint8_t *receivedResponsePar
, uint16_t offset
) {
2278 if (g_hf_field_active
== false)
2281 // Set FPGA mode to "reader listen mode", no modulation (listen
2282 // only, since we are receiving, not transmitting).
2283 // Signal field is on with the appropriate LED
2285 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
2287 // Now get the answer from the card
2288 Demod14aInit(receivedResponse
, receivedResponsePar
);
2291 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2294 volatile uint32_t c
= 0;
2295 uint32_t timeout
= iso14a_get_timeout();
2296 uint32_t receive_timer
= GetTickCount();
2300 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2301 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2302 if (ManchesterDecoding(b
, offset
, 0)) {
2303 NextTransferTime
= MAX(NextTransferTime
, Demod
.endTime
- (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 16 + FRAME_DELAY_TIME_PICC_TO_PCD
);
2305 } else if (c
++ > timeout
&& Demod
.state
== DEMOD_14A_UNSYNCD
) {
2310 // timeout already in ms + 100ms guard time
2311 if (GetTickCountDelta(receive_timer
) > timeout
+ 100)
2317 void ReaderTransmitBitsPar(uint8_t *frame
, uint16_t bits
, uint8_t *par
, uint32_t *timing
) {
2319 CodeIso14443aBitsAsReaderPar(frame
, bits
, par
);
2320 // Send command to tag
2321 tosend_t
*ts
= get_tosend();
2322 TransmitFor14443a(ts
->buf
, ts
->max
, timing
);
2323 if (g_trigger
) LED_A_ON();
2325 LogTrace(frame
, nbytes(bits
), (LastTimeProxToAirStart
<< 4) + DELAY_ARM2AIR_AS_READER
, ((LastTimeProxToAirStart
+ LastProxToAirDuration
) << 4) + DELAY_ARM2AIR_AS_READER
, par
, true);
2328 void ReaderTransmitPar(uint8_t *frame
, uint16_t len
, uint8_t *par
, uint32_t *timing
) {
2329 ReaderTransmitBitsPar(frame
, len
* 8, par
, timing
);
2332 static void ReaderTransmitBits(uint8_t *frame
, uint16_t len
, uint32_t *timing
) {
2333 // Generate parity and redirect
2334 uint8_t par
[MAX_PARITY_SIZE
] = {0x00};
2335 GetParity(frame
, len
/ 8, par
);
2336 ReaderTransmitBitsPar(frame
, len
, par
, timing
);
2339 void ReaderTransmit(uint8_t *frame
, uint16_t len
, uint32_t *timing
) {
2340 // Generate parity and redirect
2341 uint8_t par
[MAX_PARITY_SIZE
] = {0x00};
2342 GetParity(frame
, len
, par
);
2343 ReaderTransmitBitsPar(frame
, len
* 8, par
, timing
);
2346 static int ReaderReceiveOffset(uint8_t *receivedAnswer
, uint16_t offset
, uint8_t *par
) {
2347 if (!GetIso14443aAnswerFromTag(receivedAnswer
, par
, offset
))
2349 LogTrace(receivedAnswer
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, par
, false);
2353 int ReaderReceive(uint8_t *receivedAnswer
, uint8_t *par
) {
2354 if (!GetIso14443aAnswerFromTag(receivedAnswer
, par
, 0))
2356 LogTrace(receivedAnswer
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, par
, false);
2361 // This function misstreats the ISO 14443a anticollision procedure.
2362 // by fooling the reader there is a collision and forceing the reader to
2363 // increase the uid bytes. The might be an overflow, DoS will occure.
2364 void iso14443a_antifuzz(uint32_t flags
) {
2366 // We need to listen to the high-frequency, peak-detected path.
2367 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2369 BigBuf_free_keep_EM();
2375 // allocate buffers:
2376 uint8_t *received
= BigBuf_malloc(MAX_FRAME_SIZE
);
2377 uint8_t *receivedPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
2378 uint8_t *resp
= BigBuf_malloc(20);
2380 memset(received
, 0x00, MAX_FRAME_SIZE
);
2381 memset(received
, 0x00, MAX_PARITY_SIZE
);
2382 memset(resp
, 0xFF, 20);
2388 // Clean receive command buffer
2389 if (!GetIso14443aCommandFromReader(received
, receivedPar
, &len
)) {
2390 Dbprintf("Anti-fuzz stopped. Trace length: %d ", BigBuf_get_traceLen());
2393 if (received
[0] == ISO14443A_CMD_WUPA
|| received
[0] == ISO14443A_CMD_REQA
) {
2397 if ((flags
& FLAG_7B_UID_IN_DATA
) == FLAG_7B_UID_IN_DATA
) {
2405 // Received request for UID (cascade 1)
2406 //if (received[1] >= 0x20 && received[1] <= 0x57 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) {
2407 if (received
[1] >= 0x20 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
) {
2412 resp
[4] = resp
[0] ^ resp
[1] ^ resp
[2] ^ resp
[3];
2415 if ((flags
& FLAG_7B_UID_IN_DATA
) == FLAG_7B_UID_IN_DATA
) {
2420 // trigger a faulty/collision response
2421 EmSendCmdEx(resp
, 5, true);
2422 if (DBGLEVEL
>= DBG_EXTENDED
) Dbprintf("ANTICOLL or SELECT %x", received
[1]);
2426 } else if (received
[1] == 0x20 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
) { // Received request for UID (cascade 2)
2427 if (DBGLEVEL
>= DBG_EXTENDED
) Dbprintf("ANTICOLL or SELECT_2");
2428 } else if (received
[1] == 0x70 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
) { // Received a SELECT (cascade 1)
2429 } else if (received
[1] == 0x70 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
) { // Received a SELECT (cascade 2)
2431 Dbprintf("unknown command %x", received
[0]);
2435 reply_ng(CMD_HF_ISO14443A_ANTIFUZZ
, PM3_SUCCESS
, NULL
, 0);
2437 BigBuf_free_keep_EM();
2440 static void iso14a_set_ATS_times(uint8_t *ats
) {
2442 if (ats
[0] > 1) { // there is a format byte T0
2443 if ((ats
[1] & 0x20) == 0x20) { // there is an interface byte TB(1)
2445 if ((ats
[1] & 0x10) == 0x10) { // there is an interface byte TA(1) preceding TB(1)
2450 uint8_t fwi
= (tb1
& 0xf0) >> 4; // frame waiting time integer (FWI)
2452 uint32_t fwt
= 256 * 16 * (1 << fwi
); // frame waiting time (FWT) in 1/fc
2453 iso14a_set_timeout(fwt
/ (8 * 16));
2455 uint8_t sfgi
= tb1
& 0x0f; // startup frame guard time integer (SFGI)
2456 if (sfgi
!= 0 && sfgi
!= 15) {
2457 uint32_t sfgt
= 256 * 16 * (1 << sfgi
); // startup frame guard time (SFGT) in 1/fc
2458 NextTransferTime
= MAX(NextTransferTime
, Demod
.endTime
+ (sfgt
- DELAY_AIR2ARM_AS_READER
- DELAY_ARM2AIR_AS_READER
) / 16);
2464 static int GetATQA(uint8_t *resp
, uint8_t *resp_par
) {
2466 #define WUPA_RETRY_TIMEOUT 10 // 10ms
2467 uint8_t wupa
[] = { ISO14443A_CMD_WUPA
}; // 0x26 - REQA 0x52 - WAKE-UP
2469 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
2470 iso14a_set_timeout(1236 / 128 + 1); // response to WUPA is expected at exactly 1236/fc. No need to wait longer.
2472 uint32_t start_time
= GetTickCount();
2475 // we may need several tries if we did send an unknown command or a wrong authentication before...
2477 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
2478 ReaderTransmitBitsPar(wupa
, 7, NULL
, NULL
);
2480 len
= ReaderReceive(resp
, resp_par
);
2481 } while (len
== 0 && GetTickCountDelta(start_time
) <= WUPA_RETRY_TIMEOUT
);
2483 iso14a_set_timeout(save_iso14a_timeout
);
2487 // performs iso14443a anticollision (optional) and card select procedure
2488 // fills the uid and cuid pointer unless NULL
2489 // fills the card info record unless NULL
2490 // if anticollision is false, then the UID must be provided in uid_ptr[]
2491 // and num_cascades must be set (1: 4 Byte UID, 2: 7 Byte UID, 3: 10 Byte UID)
2492 // requests ATS unless no_rats is true
2493 int iso14443a_select_card(uint8_t *uid_ptr
, iso14a_card_select_t
*p_card
, uint32_t *cuid_ptr
, bool anticollision
, uint8_t num_cascades
, bool no_rats
) {
2495 uint8_t resp
[MAX_FRAME_SIZE
] = {0}; // theoretically. A usual RATS will be much smaller
2496 uint8_t resp_par
[MAX_PARITY_SIZE
] = {0};
2498 uint8_t sak
; // cascade uid
2499 bool do_cascade
= 1;
2500 int cascade_level
= 0;
2504 memset(p_card
->uid
, 0, 10);
2505 p_card
->ats_len
= 0;
2508 if (!GetATQA(resp
, resp_par
)) {
2513 p_card
->atqa
[0] = resp
[0];
2514 p_card
->atqa
[1] = resp
[1];
2517 if (anticollision
) {
2520 memset(uid_ptr
, 0, 10);
2523 if (hf14aconfig
.forceanticol
== 0) {
2524 // check for proprietary anticollision:
2525 if ((resp
[0] & 0x1F) == 0) return 3;
2526 } else if (hf14aconfig
.forceanticol
== 2) {
2527 return 3; // force skipping anticol
2528 } // else force executing
2530 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
2531 // which case we need to make a cascade 2 request and select - this is a long UID
2532 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
2533 for (; do_cascade
; cascade_level
++) {
2534 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
2535 uint8_t sel_all
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x20 };
2536 uint8_t sel_uid
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
2537 uint8_t uid_resp
[5] = {0}; // UID + original BCC
2538 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
2540 if (anticollision
) {
2543 ReaderTransmit(sel_all
, sizeof(sel_all
), NULL
);
2544 if (!ReaderReceive(resp
, resp_par
)) {
2545 Dbprintf("Card didn't answer to CL%i select all", cascade_level
+ 1);
2549 if (Demod
.collisionPos
) { // we had a collision and need to construct the UID bit by bit
2550 memset(uid_resp
, 0, 5);
2551 uint16_t uid_resp_bits
= 0;
2552 uint16_t collision_answer_offset
= 0;
2554 // anti-collision-loop:
2555 while (Demod
.collisionPos
) {
2556 Dbprintf("Multiple tags detected. Collision after Bit %d", Demod
.collisionPos
);
2557 for (uint16_t i
= collision_answer_offset
; i
< Demod
.collisionPos
; i
++, uid_resp_bits
++) { // add valid UID bits before collision point
2558 uint16_t UIDbit
= (resp
[i
/ 8] >> (i
% 8)) & 0x01;
2559 uid_resp
[uid_resp_bits
/ 8] |= UIDbit
<< (uid_resp_bits
% 8);
2561 uid_resp
[uid_resp_bits
/ 8] |= 1 << (uid_resp_bits
% 8); // next time select the card(s) with a 1 in the collision position
2563 // construct anticollision command:
2564 sel_uid
[1] = ((2 + uid_resp_bits
/ 8) << 4) | (uid_resp_bits
& 0x07); // length of data in bytes and bits
2565 for (uint16_t i
= 0; i
<= uid_resp_bits
/ 8; i
++) {
2566 sel_uid
[2 + i
] = uid_resp
[i
];
2568 collision_answer_offset
= uid_resp_bits
% 8;
2569 ReaderTransmitBits(sel_uid
, 16 + uid_resp_bits
, NULL
);
2570 if (!ReaderReceiveOffset(resp
, collision_answer_offset
, resp_par
)) return 0;
2573 // finally, add the last bits and BCC of the UID
2574 for (uint16_t i
= collision_answer_offset
; i
< (Demod
.len
- 1) * 8; i
++, uid_resp_bits
++) {
2575 uint16_t UIDbit
= (resp
[i
/ 8] >> (i
% 8)) & 0x01;
2576 uid_resp
[uid_resp_bits
/ 8] |= UIDbit
<< (uid_resp_bits
% 8);
2579 } else { // no collision, use the response to SELECT_ALL as current uid
2580 memcpy(uid_resp
, resp
, 5); // UID + original BCC
2584 if (cascade_level
< num_cascades
- 1) {
2586 memcpy(uid_resp
+ 1, uid_ptr
+ cascade_level
* 3, 3);
2588 memcpy(uid_resp
, uid_ptr
+ cascade_level
* 3, 4);
2591 size_t uid_resp_len
= 4;
2593 // calculate crypto UID. Always use last 4 Bytes.
2595 *cuid_ptr
= bytes_to_num(uid_resp
, 4);
2597 // Construct SELECT UID command
2598 sel_uid
[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
2600 if (anticollision
) {
2601 memcpy(sel_uid
+ 2, uid_resp
, 5); // the UID received during anticollision with original BCC
2602 uint8_t bcc
= sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate BCC
2603 if (sel_uid
[6] != bcc
) {
2604 Dbprintf("BCC%d incorrect, got 0x%02x, expected 0x%02x", cascade_level
, sel_uid
[6], bcc
);
2605 if (hf14aconfig
.forcebcc
== 0) {
2606 Dbprintf("Aborting");
2608 } else if (hf14aconfig
.forcebcc
== 1) {
2610 } // else use card BCC
2611 Dbprintf("Using BCC%d=" _YELLOW_("0x%02x") " to perform anticollision", cascade_level
, sel_uid
[6]);
2614 memcpy(sel_uid
+ 2, uid_resp
, 4); // the provided UID
2615 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
2618 AddCrc14A(sel_uid
, 7); // calculate and add CRC
2619 ReaderTransmit(sel_uid
, sizeof(sel_uid
), NULL
);
2622 if (!ReaderReceive(resp
, resp_par
)) {
2623 Dbprintf("Card didn't answer to select");
2628 // Test if more parts of the uid are coming
2629 do_cascade
= (((sak
& 0x04) /* && uid_resp[0] == 0x88 */) > 0);
2630 if (cascade_level
== 0) {
2631 if (hf14aconfig
.forcecl2
== 2) {
2633 } else if (hf14aconfig
.forcecl2
== 1) {
2636 } else if (cascade_level
== 1) {
2637 if (hf14aconfig
.forcecl3
== 2) {
2639 } else if (hf14aconfig
.forcecl3
== 1) {
2644 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
2645 // http://www.nxp.com/documents/application_note/AN10927.pdf
2646 uid_resp
[0] = uid_resp
[1];
2647 uid_resp
[1] = uid_resp
[2];
2648 uid_resp
[2] = uid_resp
[3];
2652 if (uid_ptr
&& anticollision
)
2653 memcpy(uid_ptr
+ (cascade_level
* 3), uid_resp
, uid_resp_len
);
2656 memcpy(p_card
->uid
+ (cascade_level
* 3), uid_resp
, uid_resp_len
);
2657 p_card
->uidlen
+= uid_resp_len
;
2665 if (hf14aconfig
.forcerats
== 0) {
2666 // PICC compliant with iso14443a-4 ---> (SAK & 0x20 != 0)
2667 if ((sak
& 0x20) == 0) return 2;
2668 } else if (hf14aconfig
.forcerats
== 2) {
2669 if ((sak
& 0x20) != 0) Dbprintf("Skipping RATS according to hf 14a config");
2671 } // else force RATS
2673 if ((sak
& 0x20) == 0) Dbprintf("Forcing RATS according to hf 14a config");
2675 // RATS, Request for answer to select
2676 if (no_rats
== false) {
2677 uint8_t rats
[] = { ISO14443A_CMD_RATS
, 0x80, 0x00, 0x00 }; // FSD=256, FSDI=8, CID=0
2679 ReaderTransmit(rats
, sizeof(rats
), NULL
);
2680 int len
= ReaderReceive(resp
, resp_par
);
2685 memcpy(p_card
->ats
, resp
, sizeof(p_card
->ats
));
2686 p_card
->ats_len
= len
;
2689 // reset the PCB block number
2690 iso14_pcb_blocknum
= 0;
2692 // set default timeout and delay next transfer based on ATS
2693 iso14a_set_ATS_times(resp
);
2698 int iso14443a_fast_select_card(uint8_t *uid_ptr
, uint8_t num_cascades
) {
2699 uint8_t resp
[5] = {0}; // theoretically. A usual RATS will be much smaller
2700 uint8_t resp_par
[1] = {0};
2701 uint8_t uid_resp
[4] = {0};
2703 uint8_t sak
= 0x04; // cascade uid
2704 int cascade_level
= 0;
2706 if (!GetATQA(resp
, resp_par
)) {
2710 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
2711 // which case we need to make a cascade 2 request and select - this is a long UID
2712 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
2713 for (; sak
& 0x04; cascade_level
++) {
2714 uint8_t sel_all
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x20 };
2715 uint8_t sel_uid
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
2716 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
2717 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
2719 if (cascade_level
< num_cascades
- 1) {
2721 memcpy(uid_resp
+ 1, uid_ptr
+ cascade_level
* 3, 3);
2723 memcpy(uid_resp
, uid_ptr
+ cascade_level
* 3, 4);
2726 // Construct SELECT UID command
2727 //sel_uid[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
2728 memcpy(sel_uid
+ 2, uid_resp
, 4); // the UID received during anticollision, or the provided UID
2729 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
2730 AddCrc14A(sel_uid
, 7); // calculate and add CRC
2731 ReaderTransmit(sel_uid
, sizeof(sel_uid
), NULL
);
2734 if (!ReaderReceive(resp
, resp_par
)) return 0;
2738 // Test if more parts of the uid are coming
2739 if ((sak
& 0x04) /* && uid_resp[0] == 0x88 */) {
2740 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
2741 // http://www.nxp.com/documents/application_note/AN10927.pdf
2742 uid_resp
[0] = uid_resp
[1];
2743 uid_resp
[1] = uid_resp
[2];
2744 uid_resp
[2] = uid_resp
[3];
2750 void iso14443a_setup(uint8_t fpga_minor_mode
) {
2752 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
2753 // Set up the synchronous serial port
2754 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A
);
2755 // connect Demodulated Signal to ADC:
2756 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2759 // Signal field is on with the appropriate LED
2760 if (fpga_minor_mode
== FPGA_HF_ISO14443A_READER_MOD
|| fpga_minor_mode
== FPGA_HF_ISO14443A_READER_LISTEN
)
2763 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| fpga_minor_mode
);
2769 // Prepare the demodulation functions
2772 NextTransferTime
= 2 * DELAY_ARM2AIR_AS_READER
;
2773 iso14a_set_timeout(1060); // 106 * 10ms default
2775 g_hf_field_active
= true;
2778 /* Peter Fillmore 2015
2779 Added card id field to the function
2780 info from ISO14443A standard
2783 b3 = depends on block
2784 b4 = Card ID following if set to 1
2785 b5 = depends on block type
2786 b6 = depends on block type
2789 b8 b7 b6 b5 b4 b3 b2 b1
2793 b8 b7 b6 b5 b4 b3 b2 b1
2797 b8 b7 b6 b5 b4 b3 b2 b1
2799 b5,b6 = 00 - DESELECT
2802 int iso14_apdu(uint8_t *cmd
, uint16_t cmd_len
, bool send_chaining
, void *data
, uint8_t *res
) {
2803 uint8_t parity
[MAX_PARITY_SIZE
] = {0x00};
2804 uint8_t real_cmd
[cmd_len
+ 4];
2807 // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02
2808 real_cmd
[0] = 0x02; // bnr,nad,cid,chn=0; i-block(0x00)
2809 if (send_chaining
) {
2810 real_cmd
[0] |= 0x10;
2812 // put block number into the PCB
2813 real_cmd
[0] |= iso14_pcb_blocknum
;
2814 memcpy(real_cmd
+ 1, cmd
, cmd_len
);
2817 real_cmd
[0] = 0xA2; // r-block + ACK
2818 real_cmd
[0] |= iso14_pcb_blocknum
;
2820 AddCrc14A(real_cmd
, cmd_len
+ 1);
2822 ReaderTransmit(real_cmd
, cmd_len
+ 3, NULL
);
2824 size_t len
= ReaderReceive(data
, parity
);
2825 uint8_t *data_bytes
= (uint8_t *) data
;
2828 return 0; //DATA LINK ERROR
2831 while (len
&& ((data_bytes
[0] & 0xF2) == 0xF2)) {
2832 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
2833 // temporarily increase timeout
2834 iso14a_set_timeout(MAX((data_bytes
[1] & 0x3f) * save_iso14a_timeout
, MAX_ISO14A_TIMEOUT
));
2835 // Transmit WTX back
2836 // byte1 - WTXM [1..59]. command FWT=FWT*WTXM
2837 data_bytes
[1] = data_bytes
[1] & 0x3f; // 2 high bits mandatory set to 0b
2838 // now need to fix CRC.
2839 AddCrc14A(data_bytes
, len
- 2);
2841 ReaderTransmit(data_bytes
, len
, NULL
);
2842 // retrieve the result again (with increased timeout)
2843 len
= ReaderReceive(data
, parity
);
2846 iso14a_set_timeout(save_iso14a_timeout
);
2849 // if we received an I- or R(ACK)-Block with a block number equal to the
2850 // current block number, toggle the current block number
2851 if (len
>= 3 // PCB+CRC = 3 bytes
2852 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
2853 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
2854 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) { // equal block numbers
2855 iso14_pcb_blocknum
^= 1;
2858 // if we received I-block with chaining we need to send ACK and receive another block of data
2860 *res
= data_bytes
[0];
2863 if (len
>= 3 && !CheckCrc14A(data_bytes
, len
)) {
2872 // memmove(data_bytes, data_bytes + 1, len);
2873 for (int i
= 0; i
< len
; i
++)
2874 data_bytes
[i
] = data_bytes
[i
+ 1];
2880 //-----------------------------------------------------------------------------
2881 // Read an ISO 14443a tag. Send out commands and store answers.
2882 //-----------------------------------------------------------------------------
2883 // arg0 iso_14a flags
2884 // arg1 high :: number of bits, if you want to send 7bits etc
2885 // low :: len of commandbytes
2887 // d.asBytes command bytes to send
2888 void ReaderIso14443a(PacketCommandNG
*c
) {
2889 iso14a_command_t param
= c
->oldarg
[0];
2890 size_t len
= c
->oldarg
[1] & 0xffff;
2891 size_t lenbits
= c
->oldarg
[1] >> 16;
2892 uint32_t timeout
= c
->oldarg
[2];
2893 uint8_t *cmd
= c
->data
.asBytes
;
2895 uint8_t buf
[PM3_CMD_DATA_SIZE
] = {0x00};
2896 uint8_t par
[MAX_PARITY_SIZE
] = {0x00};
2898 if ((param
& ISO14A_CONNECT
)) {
2899 iso14_pcb_blocknum
= 0;
2905 if ((param
& ISO14A_REQUEST_TRIGGER
))
2906 iso14a_set_trigger(true);
2908 if ((param
& ISO14A_CONNECT
)) {
2909 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
2911 // notify client selecting status.
2912 // if failed selecting, turn off antenna and quite.
2913 if (!(param
& ISO14A_NO_SELECT
)) {
2914 iso14a_card_select_t
*card
= (iso14a_card_select_t
*)buf
;
2915 arg0
= iso14443a_select_card(NULL
, card
, NULL
, true, 0, param
& ISO14A_NO_RATS
);
2916 FpgaDisableTracing();
2918 reply_mix(CMD_ACK
, arg0
, card
->uidlen
, 0, buf
, sizeof(iso14a_card_select_t
));
2923 uint32_t save_iso14a_timeout
= 0;
2924 if ((param
& ISO14A_SET_TIMEOUT
)) {
2925 save_iso14a_timeout
= iso14a_get_timeout();
2926 iso14a_set_timeout(timeout
);
2929 if ((param
& ISO14A_APDU
)) {
2931 arg0
= iso14_apdu(cmd
, len
, (param
& ISO14A_SEND_CHAINING
), buf
, &res
);
2932 FpgaDisableTracing();
2934 reply_old(CMD_ACK
, arg0
, res
, 0, buf
, sizeof(buf
));
2937 if ((param
& ISO14A_RAW
)) {
2939 if ((param
& ISO14A_APPEND_CRC
)) {
2940 // Don't append crc on empty bytearray...
2942 if ((param
& ISO14A_TOPAZMODE
))
2943 AddCrc14B(cmd
, len
);
2945 AddCrc14A(cmd
, len
);
2948 if (lenbits
) lenbits
+= 16;
2952 if (lenbits
> 0) { // want to send a specific number of bits (e.g. short commands)
2953 if ((param
& ISO14A_TOPAZMODE
)) {
2954 int bits_to_send
= lenbits
;
2956 ReaderTransmitBitsPar(&cmd
[i
++], MIN(bits_to_send
, 7), NULL
, NULL
); // first byte is always short (7bits) and no parity
2958 while (bits_to_send
> 0) {
2959 ReaderTransmitBitsPar(&cmd
[i
++], MIN(bits_to_send
, 8), NULL
, NULL
); // following bytes are 8 bit and no parity
2963 GetParity(cmd
, lenbits
/ 8, par
);
2964 ReaderTransmitBitsPar(cmd
, lenbits
, par
, NULL
); // bytes are 8 bit with odd parity
2966 } else { // want to send complete bytes only
2967 if ((param
& ISO14A_TOPAZMODE
)) {
2969 ReaderTransmitBitsPar(&cmd
[i
++], 7, NULL
, NULL
); // first byte: 7 bits, no paritiy
2971 ReaderTransmitBitsPar(&cmd
[i
++], 8, NULL
, NULL
); // following bytes: 8 bits, no paritiy
2974 ReaderTransmit(cmd
, len
, NULL
); // 8 bits, odd parity
2978 if (tearoff_hook() == PM3_ETEAROFF
) { // tearoff occurred
2979 FpgaDisableTracing();
2980 reply_mix(CMD_ACK
, 0, 0, 0, NULL
, 0);
2982 arg0
= ReaderReceive(buf
, par
);
2983 FpgaDisableTracing();
2984 reply_old(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
2988 if ((param
& ISO14A_REQUEST_TRIGGER
))
2989 iso14a_set_trigger(false);
2991 if ((param
& ISO14A_SET_TIMEOUT
)) {
2992 iso14a_set_timeout(save_iso14a_timeout
);
2995 if ((param
& ISO14A_NO_DISCONNECT
))
3003 // Determine the distance between two nonces.
3004 // Assume that the difference is small, but we don't know which is first.
3005 // Therefore try in alternating directions.
3006 static int32_t dist_nt(uint32_t nt1
, uint32_t nt2
) {
3008 if (nt1
== nt2
) return 0;
3010 uint32_t nttmp1
= nt1
;
3011 uint32_t nttmp2
= nt2
;
3013 for (uint16_t i
= 1; i
< 32768; i
++) {
3014 nttmp1
= prng_successor(nttmp1
, 1);
3015 if (nttmp1
== nt2
) return i
;
3017 nttmp2
= prng_successor(nttmp2
, 1);
3018 if (nttmp2
== nt1
) return -i
;
3021 return (-99999); // either nt1 or nt2 are invalid nonces
3025 #define PRNG_SEQUENCE_LENGTH (1 << 16)
3026 #define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up.
3027 #define MAX_SYNC_TRIES 32
3029 //-----------------------------------------------------------------------------
3030 // Recover several bits of the cypher stream. This implements (first stages of)
3031 // the algorithm described in "The Dark Side of Security by Obscurity and
3032 // Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
3033 // (article by Nicolas T. Courtois, 2009)
3034 //-----------------------------------------------------------------------------
3035 void ReaderMifare(bool first_try
, uint8_t block
, uint8_t keytype
) {
3037 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
);
3040 BigBuf_Clear_ext(false);
3044 uint8_t mf_auth
[] = { keytype
, block
, 0x00, 0x00 };
3045 uint8_t mf_nr_ar
[] = {0, 0, 0, 0, 0, 0, 0, 0};
3046 uint8_t uid
[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3047 uint8_t par_list
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3048 uint8_t ks_list
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3049 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
3050 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
3051 uint8_t par
[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
3052 uint8_t nt_diff
= 0;
3054 uint32_t nt
= 0, previous_nt
= 0, cuid
= 0;
3055 uint32_t sync_time
= GetCountSspClk() & 0xfffffff8;
3057 int32_t catch_up_cycles
= 0;
3058 int32_t last_catch_up
= 0;
3061 uint16_t elapsed_prng_sequences
= 1;
3062 uint16_t consecutive_resyncs
= 0;
3063 uint16_t unexpected_random
= 0;
3064 uint16_t sync_tries
= 0;
3066 bool have_uid
= false;
3067 uint8_t cascade_levels
= 0;
3069 // static variables here, is re-used in the next call
3070 static uint32_t nt_attacked
= 0;
3071 static int32_t sync_cycles
= 0;
3072 static uint8_t par_low
= 0;
3073 static uint8_t mf_nr_ar3
= 0;
3075 int return_status
= PM3_SUCCESS
;
3077 AddCrc14A(mf_auth
, 2);
3080 sync_cycles
= PRNG_SEQUENCE_LENGTH
; // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
3085 // we were unsuccessful on a previous call.
3086 // Try another READER nonce (first 3 parity bits remain the same)
3088 mf_nr_ar
[3] = mf_nr_ar3
;
3093 uint16_t checkbtn_cnt
= 0;
3095 for (i
= 0; true; ++i
) {
3097 bool received_nack
= false;
3101 // Test if the action was cancelled
3102 if (checkbtn_cnt
== 1000) {
3103 if (BUTTON_PRESS() || data_available()) {
3105 return_status
= PM3_EOPABORTED
;
3112 // this part is from Piwi's faster nonce collecting part in Hardnested.
3113 if (!have_uid
) { // need a full select cycle to get the uid first
3114 iso14a_card_select_t card_info
;
3115 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
3116 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (ALL)");
3119 switch (card_info
.uidlen
) {
3133 } else { // no need for anticollision. We can directly select the card
3134 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
3135 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (UID)");
3140 elapsed_prng_sequences
= 1;
3142 // Sending timeslot of ISO14443a frame
3143 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
3144 catch_up_cycles
= 0;
3146 #define SYNC_TIME_BUFFER 16 // if there is only SYNC_TIME_BUFFER left before next planned sync, wait for next PRNG cycle
3148 // if we missed the sync time already or are about to miss it, advance to the next nonce repeat
3149 while (sync_time
< GetCountSspClk() + SYNC_TIME_BUFFER
) {
3150 ++elapsed_prng_sequences
;
3151 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
3154 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
3155 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
3157 // Receive the (4 Byte) "random" TAG nonce
3158 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
))
3162 nt
= bytes_to_num(receivedAnswer
, 4);
3164 // Transmit reader nonce with fake par
3165 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
3167 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3168 int resp_res
= ReaderReceive(receivedAnswer
, receivedAnswerPar
);
3170 received_nack
= true;
3171 else if (resp_res
== 4) {
3172 // did we get lucky and got our dummykey to be valid?
3173 // however we dont feed key w uid it the prng..
3179 // we didn't calibrate our clock yet,
3180 // iceman: has to be calibrated every time.
3181 if (previous_nt
&& !nt_attacked
) {
3183 int nt_distance
= dist_nt(previous_nt
, nt
);
3185 // if no distance between, then we are in sync.
3186 if (nt_distance
== 0) {
3189 if (nt_distance
== -99999) { // invalid nonce received
3190 unexpected_random
++;
3191 if (unexpected_random
> MAX_UNEXPECTED_RANDOM
) {
3192 isOK
= -3; // Card has an unpredictable PRNG. Give up
3195 continue; // continue trying...
3199 if (++sync_tries
> MAX_SYNC_TRIES
) {
3200 isOK
= -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3204 sync_cycles
= (sync_cycles
- nt_distance
) / elapsed_prng_sequences
;
3206 // no negative sync_cycles
3207 if (sync_cycles
<= 0) sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3209 // reset sync_cycles
3210 if (sync_cycles
> PRNG_SEQUENCE_LENGTH
* 2) {
3211 sync_cycles
= PRNG_SEQUENCE_LENGTH
;
3212 sync_time
= GetCountSspClk() & 0xfffffff8;
3215 if (DBGLEVEL
>= DBG_EXTENDED
)
3216 Dbprintf("calibrating in cycle %d. nt_distance=%d, elapsed_prng_sequences=%d, new sync_cycles: %d\n", i
, nt_distance
, elapsed_prng_sequences
, sync_cycles
);
3224 if ((nt
!= nt_attacked
) && nt_attacked
) { // we somehow lost sync. Try to catch up again...
3226 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
3227 if (catch_up_cycles
== 99999) { // invalid nonce received. Don't resync on that one.
3228 catch_up_cycles
= 0;
3232 catch_up_cycles
/= elapsed_prng_sequences
;
3234 if (catch_up_cycles
== last_catch_up
) {
3235 consecutive_resyncs
++;
3237 last_catch_up
= catch_up_cycles
;
3238 consecutive_resyncs
= 0;
3241 if (consecutive_resyncs
< 3) {
3242 if (DBGLEVEL
>= DBG_EXTENDED
) {
3243 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, catch_up_cycles
, consecutive_resyncs
);
3246 sync_cycles
+= catch_up_cycles
;
3248 if (DBGLEVEL
>= DBG_EXTENDED
)
3249 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
);
3252 catch_up_cycles
= 0;
3253 consecutive_resyncs
= 0;
3258 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3259 if (received_nack
) {
3260 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
3263 par_low
= par
[0] & 0xE0; // there is no need to check all parities for other nt_diff. Parity Bits for mf_nr_ar[0..2] won't change
3265 par_list
[nt_diff
] = reflect8(par
[0]);
3266 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05; // xor with NACK value to get keystream
3268 // Test if the information is complete
3269 if (nt_diff
== 0x07) {
3274 nt_diff
= (nt_diff
+ 1) & 0x07;
3275 mf_nr_ar
[3] = (mf_nr_ar
[3] & 0x1F) | (nt_diff
<< 5);
3280 if (nt_diff
== 0 && first_try
) {
3282 if (par
[0] == 0) { // tried all 256 possible parities without success. Card doesn't send NACK.
3288 par
[0] = ((par
[0] & 0x1F) + 1) | par_low
;
3292 // reset the resyncs since we got a complete transaction on right time.
3293 consecutive_resyncs
= 0;
3296 mf_nr_ar
[3] &= 0x1F;
3298 if (DBGLEVEL
>= DBG_EXTENDED
) Dbprintf("Number of sent auth requests: %u", i
);
3300 FpgaDisableTracing();
3306 uint8_t par_list
[8];
3312 payload
.isOK
= isOK
;
3313 num_to_bytes(cuid
, 4, payload
.cuid
);
3314 num_to_bytes(nt
, 4, payload
.nt
);
3315 memcpy(payload
.par_list
, par_list
, sizeof(payload
.par_list
));
3316 memcpy(payload
.ks_list
, ks_list
, sizeof(payload
.ks_list
));
3317 memcpy(payload
.nr
, mf_nr_ar
, sizeof(payload
.nr
));
3318 memcpy(payload
.ar
, mf_nr_ar
+ 4, sizeof(payload
.ar
));
3320 reply_ng(CMD_HF_MIFARE_READER
, return_status
, (uint8_t *)&payload
, sizeof(payload
));
3327 * Mifare Classic NACK-bug detection
3328 * Thanks to @doegox for the feedback and new approaches.
3330 void DetectNACKbug(void) {
3331 uint8_t mf_auth
[] = {0x60, 0x00, 0xF5, 0x7B};
3332 uint8_t mf_nr_ar
[] = {0, 0, 0, 0, 0, 0, 0, 0};
3333 uint8_t uid
[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3334 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
3335 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
3336 uint8_t par
[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
3338 uint32_t nt
= 0, previous_nt
= 0, nt_attacked
= 0, cuid
= 0;
3339 int32_t catch_up_cycles
= 0, last_catch_up
= 0;
3340 uint8_t cascade_levels
= 0, num_nacks
= 0, isOK
= 0;
3341 uint16_t elapsed_prng_sequences
= 1;
3342 uint16_t consecutive_resyncs
= 0;
3343 uint16_t unexpected_random
= 0;
3344 uint16_t sync_tries
= 0;
3345 uint32_t sync_time
= 0;
3346 bool have_uid
= false;
3348 int32_t status
= PM3_SUCCESS
;
3350 // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
3351 int32_t sync_cycles
= PRNG_SEQUENCE_LENGTH
;
3354 BigBuf_Clear_ext(false);
3357 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
);
3359 sync_time
= GetCountSspClk() & 0xfffffff8;
3362 uint16_t checkbtn_cnt
= 0;
3365 for (i
= 1; true; ++i
) {
3367 bool received_nack
= false;
3369 // Cards always leaks a NACK, no matter the parity
3370 if ((i
== 10) && (num_nacks
== i
- 1)) {
3377 // Test if the action was cancelled
3378 if (checkbtn_cnt
== 1000) {
3379 if (BUTTON_PRESS() || data_available()) {
3380 status
= PM3_EOPABORTED
;
3387 // this part is from Piwi's faster nonce collecting part in Hardnested.
3388 if (!have_uid
) { // need a full select cycle to get the uid first
3389 iso14a_card_select_t card_info
;
3390 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
3391 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (ALL)");
3395 switch (card_info
.uidlen
) {
3411 } else { // no need for anticollision. We can directly select the card
3412 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
3413 if (DBGLEVEL
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (UID)");
3420 elapsed_prng_sequences
= 1;
3422 // Sending timeslot of ISO14443a frame
3423 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
3424 catch_up_cycles
= 0;
3426 // if we missed the sync time already, advance to the next nonce repeat
3427 while (GetCountSspClk() > sync_time
) {
3428 ++elapsed_prng_sequences
;
3429 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
3432 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
3433 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
3435 // Receive the (4 Byte) "random" TAG nonce
3436 if (!ReaderReceive(receivedAnswer
, receivedAnswerPar
))
3440 nt
= bytes_to_num(receivedAnswer
, 4);
3442 // Transmit reader nonce with fake par
3443 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
3445 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3446 if (ReaderReceive(receivedAnswer
, receivedAnswerPar
)) {
3447 received_nack
= true;
3449 // ALWAYS leak Detection. Well, we could be lucky and get a response nack on first try.
3450 if (i
== num_nacks
) {
3455 // we didn't calibrate our clock yet,
3456 // iceman: has to be calibrated every time.
3457 if (previous_nt
&& !nt_attacked
) {
3459 int nt_distance
= dist_nt(previous_nt
, nt
);
3461 // if no distance between, then we are in sync.
3462 if (nt_distance
== 0) {
3465 if (nt_distance
== -99999) { // invalid nonce received
3466 unexpected_random
++;
3467 if (unexpected_random
> MAX_UNEXPECTED_RANDOM
) {
3468 // Card has an unpredictable PRNG. Give up
3472 if (sync_cycles
<= 0) {
3473 sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3479 if (++sync_tries
> MAX_SYNC_TRIES
) {
3480 isOK
= 97; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3484 sync_cycles
= (sync_cycles
- nt_distance
) / elapsed_prng_sequences
;
3486 if (sync_cycles
<= 0)
3487 sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3489 if (sync_cycles
> PRNG_SEQUENCE_LENGTH
* 2) {
3490 isOK
= 96; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3494 if (DBGLEVEL
>= DBG_EXTENDED
)
3495 Dbprintf("calibrating in cycle %d. nt_distance=%d, elapsed_prng_sequences=%d, new sync_cycles: %d\n", i
, nt_distance
, elapsed_prng_sequences
, sync_cycles
);
3501 if ((nt
!= nt_attacked
) && nt_attacked
) {
3502 // we somehow lost sync. Try to catch up again...
3503 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
3505 if (catch_up_cycles
== 99999) {
3506 // invalid nonce received. Don't resync on that one.
3507 catch_up_cycles
= 0;
3511 catch_up_cycles
/= elapsed_prng_sequences
;
3513 if (catch_up_cycles
== last_catch_up
) {
3514 consecutive_resyncs
++;
3516 last_catch_up
= catch_up_cycles
;
3517 consecutive_resyncs
= 0;
3520 if (consecutive_resyncs
< 3) {
3521 if (DBGLEVEL
>= DBG_EXTENDED
) {
3522 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, catch_up_cycles
, consecutive_resyncs
);
3525 sync_cycles
+= catch_up_cycles
;
3527 if (DBGLEVEL
>= DBG_EXTENDED
) {
3528 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
);
3529 Dbprintf("nt [%08x] attacted [%08x]", nt
, nt_attacked
);
3532 catch_up_cycles
= 0;
3533 consecutive_resyncs
= 0;
3538 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3540 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
3542 // we are testing all 256 possibilities.
3545 // tried all 256 possible parities without success.
3547 // did we get one NACK?
3553 // reset the resyncs since we got a complete transaction on right time.
3554 consecutive_resyncs
= 0;
3557 // num_nacks = number of nacks recieved. should be only 1. if not its a clone card which always sends NACK (parity == 0) ?
3558 // i = number of authentications sent. Not always 256, since we are trying to sync but close to it.
3559 FpgaDisableTracing();
3561 uint8_t *data
= BigBuf_malloc(4);
3563 data
[1] = num_nacks
;
3564 num_to_bytes(i
, 2, data
+ 2);
3565 reply_ng(CMD_HF_MIFARE_NACK_DETECT
, status
, data
, 4);