1 //-----------------------------------------------------------------------------
2 // Copyright (C) Jonathan Westhues, Nov 2006
3 // Copyright (C) Gerhard de Koning Gans - May 2008
4 // Copyright (C) Proxmark3 contributors. See AUTHORS.md for details.
6 // This program is free software: you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation, either version 3 of the License, or
9 // (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // See LICENSE.txt for the text of the license.
17 //-----------------------------------------------------------------------------
18 // Routines to support ISO 14443 type A.
19 //-----------------------------------------------------------------------------
20 #include "iso14443a.h"
23 #include "proxmark3_arm.h"
27 #include "fpgaloader.h"
33 #include "mifareutil.h"
34 #include "commonutil.h"
36 #include "protocols.h"
37 #include "generator.h"
38 #include "desfire_crypto.h" // UL-C authentication helpers
40 #define MAX_ISO14A_TIMEOUT 524288
42 // this timeout is in MS
43 static uint32_t iso14a_timeout
;
45 static uint8_t colpos
= 0;
47 // the block number for the ISO14443-4 PCB
48 static uint8_t iso14_pcb_blocknum
= 0;
53 // minimum time between the start bits of consecutive transfers from reader to tag: 7000 carrier (13.56MHz) cycles
54 #define REQUEST_GUARD_TIME (7000/16 + 1)
55 // minimum time between last modulation of tag and next start bit from reader to tag: 1172 carrier cycles
56 #define FRAME_DELAY_TIME_PICC_TO_PCD (1172/16 + 1)
57 // bool LastCommandWasRequest = false;
60 // Total delays including SSC-Transfers between ARM and FPGA. These are in carrier clock cycles (1/13,56MHz)
62 // When the PM acts as reader and is receiving tag data, it takes
63 // 3 ticks delay in the AD converter
64 // 16 ticks until the modulation detector completes and sets curbit
65 // 8 ticks until bit_to_arm is assigned from curbit
66 // 8*16 ticks for the transfer from FPGA to ARM
67 // 4*16 ticks until we measure the time
68 // - 8*16 ticks because we measure the time of the previous transfer
69 #define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16)
71 // When the PM acts as a reader and is sending, it takes
72 // 4*16 ticks until we can write data to the sending hold register
73 // 8*16 ticks until the SHR is transferred to the Sending Shift Register
74 // 8 ticks until the first transfer starts
75 // 8 ticks later the FPGA samples the data
76 // 1 tick to assign mod_sig_coil
77 #define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1)
79 // The FPGA will report its internal sending delay in
80 static uint16_t FpgaSendQueueDelay
;
81 // the 5 first bits are the number of bits buffered in mod_sig_buf
82 // the last three bits are the remaining ticks/2 after the mod_sig_buf shift
83 #define DELAY_FPGA_QUEUE (FpgaSendQueueDelay<<1)
85 // When the PM acts as tag and is sending, it takes
86 // 4*16 + 8 ticks until we can write data to the sending hold register
87 // 8*16 ticks until the SHR is transferred to the Sending Shift Register
88 // 8 ticks later the FPGA samples the first data
89 // + 16 ticks until assigned to mod_sig
90 // + 1 tick to assign mod_sig_coil
91 // + a varying number of ticks in the FPGA Delay Queue (mod_sig_buf)
92 #define DELAY_ARM2AIR_AS_TAG (4*16 + 8 + 8*16 + 8 + 16 + 1 + DELAY_FPGA_QUEUE)
94 // When the PM acts as sniffer and is receiving tag data, it takes
95 // 3 ticks A/D conversion
96 // 14 ticks to complete the modulation detection
97 // 8 ticks (on average) until the result is stored in to_arm
98 // + the delays in transferring data - which is the same for
99 // sniffing reader and tag data and therefore not relevant
100 #define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8)
102 // When the PM acts as sniffer and is receiving reader data, it takes
103 // 2 ticks delay in analogue RF receiver (for the falling edge of the
104 // start bit, which marks the start of the communication)
105 // 3 ticks A/D conversion
106 // 8 ticks on average until the data is stored in to_arm.
107 // + the delays in transferring data - which is the same for
108 // sniffing reader and tag data and therefore not relevant
109 #define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8)
111 //variables used for timing purposes:
112 //these are in ssp_clk cycles:
113 static uint32_t NextTransferTime
;
114 static uint32_t LastTimeProxToAirStart
;
115 static uint32_t LastProxToAirDuration
;
117 // CARD TO READER - manchester
118 // Sequence D: 11110000 modulation with subcarrier during first half
119 // Sequence E: 00001111 modulation with subcarrier during second half
120 // Sequence F: 00000000 no modulation with subcarrier
121 // Sequence COLL: 11111111 load modulation over the full bitlength.
122 // Tricks the reader to think that multiple cards answer.
123 // (at least one card with 1 and at least one card with 0)
124 // READER TO CARD - miller
125 // Sequence X: 00001100 drop after half a period
126 // Sequence Y: 00000000 no drop
127 // Sequence Z: 11000000 drop at start
131 #define SEC_COLL 0xff
137 Default HF 14a config is set to:
138 forceanticol = 0 (auto)
139 forcebcc = 0 (expect valid BCC)
144 static hf14a_config hf14aconfig
= { 0, 0, 0, 0, 0 } ;
147 // Polling frames and configurations
148 iso14a_polling_parameters_t WUPA_POLLING_PARAMETERS
= {
149 .frames
= { {{ ISO14443A_CMD_WUPA
}, 1, 7, 0} },
153 iso14a_polling_parameters_t REQA_POLLING_PARAMETERS
= {
154 .frames
= { {{ ISO14443A_CMD_REQA
}, 1, 7, 0} },
159 // parity isn't used much
160 static uint8_t parity_array
[MAX_PARITY_SIZE
] = {0};
163 static uint8_t crypto1_auth_state
= AUTH_FIRST
;
164 static uint32_t crypto1_uid
;
165 struct Crypto1State crypto1_state
= {0, 0};
167 void printHf14aConfig(void) {
168 DbpString(_CYAN_("HF 14a config"));
169 Dbprintf(" [a] Anticol override.... %s%s%s",
170 (hf14aconfig
.forceanticol
== 0) ? _GREEN_("std") " ( follow standard )" : "",
171 (hf14aconfig
.forceanticol
== 1) ? _RED_("force") " ( always do anticol )" : "",
172 (hf14aconfig
.forceanticol
== 2) ? _RED_("skip") " ( always skip anticol )" : ""
174 Dbprintf(" [b] BCC override........ %s%s%s",
175 (hf14aconfig
.forcebcc
== 0) ? _GREEN_("std") " ( follow standard )" : "",
176 (hf14aconfig
.forcebcc
== 1) ? _RED_("fix") " ( fix bad BCC )" : "",
177 (hf14aconfig
.forcebcc
== 2) ? _RED_("ignore") " ( ignore bad BCC, always use card BCC )" : ""
179 Dbprintf(" [2] CL2 override........ %s%s%s",
180 (hf14aconfig
.forcecl2
== 0) ? _GREEN_("std") " ( follow standard )" : "",
181 (hf14aconfig
.forcecl2
== 1) ? _RED_("force") " ( always do CL2 )" : "",
182 (hf14aconfig
.forcecl2
== 2) ? _RED_("skip") " ( always skip CL2 )" : ""
184 Dbprintf(" [3] CL3 override........ %s%s%s",
185 (hf14aconfig
.forcecl3
== 0) ? _GREEN_("std") " ( follow standard )" : "",
186 (hf14aconfig
.forcecl3
== 1) ? _RED_("force") " ( always do CL3 )" : "",
187 (hf14aconfig
.forcecl3
== 2) ? _RED_("skip") " ( always skip CL3 )" : ""
189 Dbprintf(" [r] RATS override....... %s%s%s",
190 (hf14aconfig
.forcerats
== 0) ? _GREEN_("std") " ( follow standard )" : "",
191 (hf14aconfig
.forcerats
== 1) ? _RED_("force") " ( always do RATS )" : "",
192 (hf14aconfig
.forcerats
== 2) ? _RED_("skip") " ( always skip RATS )" : ""
197 * Called from the USB-handler to set the 14a configuration
198 * The 14a config is used for card selection sequence.
200 * Values set to '-1' implies no change
201 * @brief setSamplingConfig
204 void setHf14aConfig(const hf14a_config
*hc
) {
206 if ((hc
->forceanticol
>= 0) && (hc
->forceanticol
<= 2))
207 hf14aconfig
.forceanticol
= hc
->forceanticol
;
208 if ((hc
->forcebcc
>= 0) && (hc
->forcebcc
<= 2))
209 hf14aconfig
.forcebcc
= hc
->forcebcc
;
210 if ((hc
->forcecl2
>= 0) && (hc
->forcecl2
<= 2))
211 hf14aconfig
.forcecl2
= hc
->forcecl2
;
212 if ((hc
->forcecl3
>= 0) && (hc
->forcecl3
<= 2))
213 hf14aconfig
.forcecl3
= hc
->forcecl3
;
214 if ((hc
->forcerats
>= 0) && (hc
->forcerats
<= 2))
215 hf14aconfig
.forcerats
= hc
->forcerats
;
218 hf14a_config
*getHf14aConfig(void) {
222 void iso14a_set_trigger(bool enable
) {
226 void iso14a_set_timeout(uint32_t timeout
) {
227 iso14a_timeout
= timeout
+ (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 128 + 2;
230 uint32_t iso14a_get_timeout(void) {
231 return iso14a_timeout
- (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 128 - 2;
234 //-----------------------------------------------------------------------------
235 // Generate the parity value for a byte sequence
236 //-----------------------------------------------------------------------------
237 void GetParity(const uint8_t *pbtCmd
, uint16_t len
, uint8_t *par
) {
238 uint16_t paritybit_cnt
= 0;
239 uint16_t paritybyte_cnt
= 0;
240 uint8_t parityBits
= 0;
242 for (uint16_t i
= 0; i
< len
; i
++) {
243 // Generate the parity bits
244 parityBits
|= ((oddparity8(pbtCmd
[i
])) << (7 - paritybit_cnt
));
245 if (paritybit_cnt
== 7) {
246 par
[paritybyte_cnt
] = parityBits
; // save 8 Bits parity
247 parityBits
= 0; // and advance to next Parity Byte
255 // save remaining parity bits
256 par
[paritybyte_cnt
] = parityBits
;
260 //=============================================================================
261 // ISO 14443 Type A - Miller decoder
262 //=============================================================================
264 // This decoder is used when the PM3 acts as a tag.
265 // The reader will generate "pauses" by temporarily switching of the field.
266 // At the PM3 antenna we will therefore measure a modulated antenna voltage.
267 // The FPGA does a comparison with a threshold and would deliver e.g.:
268 // ........ 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 .......
269 // The Miller decoder needs to identify the following sequences:
270 // 2 (or 3) ticks pause followed by 6 (or 5) ticks unmodulated: pause at beginning - Sequence Z ("start of communication" or a "0")
271 // 8 ticks without a modulation: no pause - Sequence Y (a "0" or "end of communication" or "no information")
272 // 4 ticks unmodulated followed by 2 (or 3) ticks pause: pause in second half - Sequence X (a "1")
273 // Note 1: the bitstream may start at any time. We therefore need to sync.
274 // Note 2: the interpretation of Sequence Y and Z depends on the preceding sequence.
275 //-----------------------------------------------------------------------------
276 static tUart14a Uart
;
278 // Lookup-Table to decide if 4 raw bits are a modulation.
279 // We accept the following:
280 // 0001 - a 3 tick wide pause
281 // 0011 - a 2 tick wide pause, or a three tick wide pause shifted left
282 // 0111 - a 2 tick wide pause shifted left
283 // 1001 - a 2 tick wide pause shifted right
284 static const bool Mod_Miller_LUT
[] = {
285 false, true, false, true, false, false, false, true,
286 false, true, false, false, false, false, false, false
288 #define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4])
289 #define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)])
291 tUart14a
*GetUart14a(void) {
295 void Uart14aReset(void) {
296 Uart
.state
= STATE_14A_UNSYNCD
;
298 Uart
.len
= 0; // number of decoded data bytes
299 Uart
.parityLen
= 0; // number of decoded parity bytes
300 Uart
.shiftReg
= 0; // shiftreg to hold decoded data bits
301 Uart
.parityBits
= 0; // holds 8 parity bits
304 Uart
.fourBits
= 0x00000000; // clear the buffer for 4 Bits
309 void Uart14aInit(uint8_t *d
, uint16_t n
, uint8_t *par
) {
316 // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
317 RAMFUNC
bool MillerDecoding(uint8_t bit
, uint32_t non_real_time
) {
319 if (Uart
.len
== Uart
.output_len
) {
323 Uart
.fourBits
= (Uart
.fourBits
<< 8) | bit
;
325 if (Uart
.state
== STATE_14A_UNSYNCD
) { // not yet synced
326 Uart
.syncBit
= 9999; // not set
328 // 00x11111 2|3 ticks pause followed by 6|5 ticks unmodulated Sequence Z (a "0" or "start of communication")
329 // 11111111 8 ticks unmodulation Sequence Y (a "0" or "end of communication" or "no information")
330 // 111100x1 4 ticks unmodulated followed by 2|3 ticks pause Sequence X (a "1")
332 // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from
333 // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111)
334 // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern
335 // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's)
336 #define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00000111 11111111 11101111 10000000
337 #define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00000111 11111111 10001111 10000000
338 if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 0)) == ISO14443A_STARTBIT_PATTERN
>> 0) Uart
.syncBit
= 7;
339 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 1)) == ISO14443A_STARTBIT_PATTERN
>> 1) Uart
.syncBit
= 6;
340 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 2)) == ISO14443A_STARTBIT_PATTERN
>> 2) Uart
.syncBit
= 5;
341 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 3)) == ISO14443A_STARTBIT_PATTERN
>> 3) Uart
.syncBit
= 4;
342 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 4)) == ISO14443A_STARTBIT_PATTERN
>> 4) Uart
.syncBit
= 3;
343 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 5)) == ISO14443A_STARTBIT_PATTERN
>> 5) Uart
.syncBit
= 2;
344 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 6)) == ISO14443A_STARTBIT_PATTERN
>> 6) Uart
.syncBit
= 1;
345 else if ((Uart
.fourBits
& (ISO14443A_STARTBIT_MASK
>> 7)) == ISO14443A_STARTBIT_PATTERN
>> 7) Uart
.syncBit
= 0;
347 if (Uart
.syncBit
!= 9999) { // found a sync bit
348 Uart
.startTime
= (non_real_time
) ? non_real_time
: (GetCountSspClk() & 0xfffffff8);
349 Uart
.startTime
-= Uart
.syncBit
;
350 Uart
.endTime
= Uart
.startTime
;
351 Uart
.state
= STATE_14A_START_OF_COMMUNICATION
;
356 if (IsMillerModulationNibble1(Uart
.fourBits
>> Uart
.syncBit
)) {
358 if (IsMillerModulationNibble2(Uart
.fourBits
>> Uart
.syncBit
)) { // Modulation in both halves - error
360 } else { // Modulation in first half = Sequence Z = logic "0"
362 if (Uart
.state
== STATE_14A_MILLER_X
) { // error - must not follow after X
366 Uart
.shiftReg
= (Uart
.shiftReg
>> 1); // add a 0 to the shiftreg
367 Uart
.state
= STATE_14A_MILLER_Z
;
368 Uart
.endTime
= Uart
.startTime
+ 8 * (9 * Uart
.len
+ Uart
.bitCount
+ 1) - 6;
370 if (Uart
.bitCount
>= 9) { // if we decoded a full byte (including parity)
371 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff);
372 Uart
.parityBits
<<= 1; // make room for the parity bit
373 Uart
.parityBits
|= ((Uart
.shiftReg
>> 8) & 0x01); // store parity bit
376 if ((Uart
.len
& 0x0007) == 0) { // every 8 data bytes
377 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // store 8 parity bits
385 if (IsMillerModulationNibble2(Uart
.fourBits
>> Uart
.syncBit
)) { // Modulation second half = Sequence X = logic "1"
388 Uart
.shiftReg
= (Uart
.shiftReg
>> 1) | 0x100; // add a 1 to the shiftreg
389 Uart
.state
= STATE_14A_MILLER_X
;
390 Uart
.endTime
= Uart
.startTime
+ 8 * (9 * Uart
.len
+ Uart
.bitCount
+ 1) - 2;
392 if (Uart
.bitCount
>= 9) { // if we decoded a full byte (including parity)
394 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff);
395 Uart
.parityBits
<<= 1; // make room for the new parity bit
396 Uart
.parityBits
|= ((Uart
.shiftReg
>> 8) & 0x01); // store parity bit
400 if ((Uart
.len
& 0x0007) == 0) { // every 8 data bytes
401 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // store 8 parity bits
406 } else { // no modulation in both halves - Sequence Y
408 if (Uart
.state
== STATE_14A_MILLER_Z
|| Uart
.state
== STATE_14A_MILLER_Y
) { // Y after logic "0" - End of Communication
410 Uart
.state
= STATE_14A_UNSYNCD
;
411 Uart
.bitCount
--; // last "0" was part of EOC sequence
412 Uart
.shiftReg
<<= 1; // drop it
414 if (Uart
.bitCount
> 0) { // if we decoded some bits
415 Uart
.shiftReg
>>= (9 - Uart
.bitCount
); // right align them
416 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff); // add last byte to the output
417 Uart
.parityBits
<<= 1; // add a (void) parity bit
418 Uart
.parityBits
<<= (8 - (Uart
.len
& 0x0007)); // left align parity bits
419 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // and store it
423 if (Uart
.len
& 0x0007) { // there are some parity bits to store
424 Uart
.parityBits
<<= (8 - (Uart
.len
& 0x0007)); // left align remaining parity bits
425 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // and store them
429 return true; // we are finished with decoding the raw data sequence
431 Uart14aReset(); // Nothing received - start over
436 if (Uart
.state
== STATE_14A_START_OF_COMMUNICATION
) { // error - must not follow directly after SOC
438 } else { // a logic "0"
441 Uart
.shiftReg
>>= 1; // add a 0 to the shiftreg
442 Uart
.state
= STATE_14A_MILLER_Y
;
444 if (Uart
.bitCount
>= 9) { // if we decoded a full byte (including parity)
446 Uart
.output
[Uart
.len
++] = (Uart
.shiftReg
& 0xff);
447 Uart
.parityBits
<<= 1; // make room for the parity bit
448 Uart
.parityBits
|= ((Uart
.shiftReg
>> 8) & 0x01); // store parity bit
452 // Every 8 data bytes, store 8 parity bits into a parity byte
453 if ((Uart
.len
& 0x0007) == 0) { // every 8 data bytes
454 Uart
.parity
[Uart
.parityLen
++] = Uart
.parityBits
; // store 8 parity bits
462 return false; // not finished yet, need more data
465 //=============================================================================
466 // ISO 14443 Type A - Manchester decoder
467 //=============================================================================
469 // This decoder is used when the PM3 acts as a reader.
470 // The tag will modulate the reader field by asserting different loads to it. As a consequence, the voltage
471 // at the reader antenna will be modulated as well. The FPGA detects the modulation for us and would deliver e.g. the following:
472 // ........ 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 .......
473 // The Manchester decoder needs to identify the following sequences:
474 // 4 ticks modulated followed by 4 ticks unmodulated: Sequence D = 1 (also used as "start of communication")
475 // 4 ticks unmodulated followed by 4 ticks modulated: Sequence E = 0
476 // 8 ticks unmodulated: Sequence F = end of communication
477 // 8 ticks modulated: A collision. Save the collision position and treat as Sequence D
478 // Note 1: the bitstream may start at any time. We therefore need to sync.
479 // Note 2: parameter offset is used to determine the position of the parity bits (required for the anticollision command only)
480 static tDemod14a Demod
;
482 // Lookup-Table to decide if 4 raw bits are a modulation.
483 // We accept three or four "1" in any position
484 static const bool Mod_Manchester_LUT
[] = {
485 false, false, false, false, false, false, false, true,
486 false, false, false, true, false, true, true, true
489 #define IsManchesterModulationNibble1(b) (Mod_Manchester_LUT[(b & 0x00F0) >> 4])
490 #define IsManchesterModulationNibble2(b) (Mod_Manchester_LUT[(b & 0x000F)])
492 tDemod14a
*GetDemod14a(void) {
495 void Demod14aReset(void) {
496 Demod
.state
= DEMOD_14A_UNSYNCD
;
497 Demod
.twoBits
= 0xFFFF; // buffer for 2 Bits
500 Demod
.collisionPos
= 0; // Position of collision bit
501 Demod
.syncBit
= 0xFFFF;
502 Demod
.parityBits
= 0;
504 Demod
.shiftReg
= 0; // shiftreg to hold decoded data bits
506 Demod
.len
= 0; // number of decoded data bytes
512 void Demod14aInit(uint8_t *d
, uint16_t n
, uint8_t *par
) {
513 Demod
.output_len
= n
;
519 // use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
520 RAMFUNC
int ManchesterDecoding(uint8_t bit
, uint16_t offset
, uint32_t non_real_time
) {
522 if (Demod
.len
== Demod
.output_len
) {
526 Demod
.twoBits
= (Demod
.twoBits
<< 8) | bit
;
528 if (Demod
.state
== DEMOD_14A_UNSYNCD
) {
530 if (Demod
.highCnt
< 2) { // wait for a stable unmodulated signal
531 if (Demod
.twoBits
== 0x0000) {
537 Demod
.syncBit
= 0xFFFF; // not set
538 if ((Demod
.twoBits
& 0x7700) == 0x7000) Demod
.syncBit
= 7;
539 else if ((Demod
.twoBits
& 0x3B80) == 0x3800) Demod
.syncBit
= 6;
540 else if ((Demod
.twoBits
& 0x1DC0) == 0x1C00) Demod
.syncBit
= 5;
541 else if ((Demod
.twoBits
& 0x0EE0) == 0x0E00) Demod
.syncBit
= 4;
542 else if ((Demod
.twoBits
& 0x0770) == 0x0700) Demod
.syncBit
= 3;
543 else if ((Demod
.twoBits
& 0x03B8) == 0x0380) Demod
.syncBit
= 2;
544 else if ((Demod
.twoBits
& 0x01DC) == 0x01C0) Demod
.syncBit
= 1;
545 else if ((Demod
.twoBits
& 0x00EE) == 0x00E0) Demod
.syncBit
= 0;
546 if (Demod
.syncBit
!= 0xFFFF) {
547 Demod
.startTime
= non_real_time
? non_real_time
: (GetCountSspClk() & 0xfffffff8);
548 Demod
.startTime
-= Demod
.syncBit
;
549 Demod
.bitCount
= offset
; // number of decoded data bits
550 Demod
.state
= DEMOD_14A_MANCHESTER_DATA
;
555 if (IsManchesterModulationNibble1(Demod
.twoBits
>> Demod
.syncBit
)) { // modulation in first half
556 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // ... and in second half = collision
557 if (Demod
.collisionPos
== 0) {
558 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
560 } // modulation in first half only - Sequence D = 1
562 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) | 0x100; // in both cases, add a 1 to the shiftreg
563 if (Demod
.bitCount
== 9) { // if we decoded a full byte (including parity)
564 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
565 Demod
.parityBits
<<= 1; // make room for the parity bit
566 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
569 if ((Demod
.len
& 0x0007) == 0) { // every 8 data bytes
570 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // store 8 parity bits
571 Demod
.parityBits
= 0;
574 Demod
.endTime
= Demod
.startTime
+ 8 * (9 * Demod
.len
+ Demod
.bitCount
+ 1) - 4;
575 } else { // no modulation in first half
576 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // and modulation in second half = Sequence E = 0
578 Demod
.shiftReg
= (Demod
.shiftReg
>> 1); // add a 0 to the shiftreg
579 if (Demod
.bitCount
>= 9) { // if we decoded a full byte (including parity)
580 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
581 Demod
.parityBits
<<= 1; // make room for the new parity bit
582 Demod
.parityBits
|= ((Demod
.shiftReg
>> 8) & 0x01); // store parity bit
585 if ((Demod
.len
& 0x0007) == 0) { // every 8 data bytes
586 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // store 8 parity bits1
587 Demod
.parityBits
= 0;
590 Demod
.endTime
= Demod
.startTime
+ 8 * (9 * Demod
.len
+ Demod
.bitCount
+ 1);
591 } else { // no modulation in both halves - End of communication
593 if (Demod
.bitCount
> 0) { // there are some remaining data bits
594 Demod
.shiftReg
>>= (9 - Demod
.bitCount
); // right align the decoded bits
595 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff; // and add them to the output
596 Demod
.parityBits
<<= 1; // add a (void) parity bit
597 Demod
.parityBits
<<= (8 - (Demod
.len
& 0x0007)); // left align remaining parity bits
598 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // and store them
600 } else if (Demod
.len
& 0x0007) { // there are some parity bits to store
601 Demod
.parityBits
<<= (8 - (Demod
.len
& 0x0007)); // left align remaining parity bits
602 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // and store them
606 return true; // we are finished with decoding the raw data sequence
607 } else { // nothing received. Start over
613 return false; // not finished yet, need more data
617 // Thinfilm, Kovio mangles ISO14443A in the way that they don't use start bit nor parity bits.
618 static RAMFUNC
int ManchesterDecoding_Thinfilm(uint8_t bit
) {
620 if (Demod
.len
== Demod
.output_len
) {
624 Demod
.twoBits
= (Demod
.twoBits
<< 8) | bit
;
626 if (Demod
.state
== DEMOD_14A_UNSYNCD
) {
628 if (Demod
.highCnt
< 2) { // wait for a stable unmodulated signal
630 if (Demod
.twoBits
== 0x0000) {
637 Demod
.syncBit
= 0xFFFF; // not set
638 if ((Demod
.twoBits
& 0x7700) == 0x7000) Demod
.syncBit
= 7;
639 else if ((Demod
.twoBits
& 0x3B80) == 0x3800) Demod
.syncBit
= 6;
640 else if ((Demod
.twoBits
& 0x1DC0) == 0x1C00) Demod
.syncBit
= 5;
641 else if ((Demod
.twoBits
& 0x0EE0) == 0x0E00) Demod
.syncBit
= 4;
642 else if ((Demod
.twoBits
& 0x0770) == 0x0700) Demod
.syncBit
= 3;
643 else if ((Demod
.twoBits
& 0x03B8) == 0x0380) Demod
.syncBit
= 2;
644 else if ((Demod
.twoBits
& 0x01DC) == 0x01C0) Demod
.syncBit
= 1;
645 else if ((Demod
.twoBits
& 0x00EE) == 0x00E0) Demod
.syncBit
= 0;
647 if (Demod
.syncBit
!= 0xFFFF) {
648 Demod
.startTime
= (GetCountSspClk() & 0xfffffff8);
649 Demod
.startTime
-= Demod
.syncBit
;
650 Demod
.bitCount
= 1; // number of decoded data bits
652 Demod
.state
= DEMOD_14A_MANCHESTER_DATA
;
658 if (IsManchesterModulationNibble1(Demod
.twoBits
>> Demod
.syncBit
)) { // modulation in first half
660 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // ... and in second half = collision
661 if (Demod
.collisionPos
== 0) {
662 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
664 } // modulation in first half only - Sequence D = 1
666 Demod
.shiftReg
= (Demod
.shiftReg
<< 1) | 0x1; // in both cases, add a 1 to the shiftreg
668 if (Demod
.bitCount
== 8) { // if we decoded a full byte
669 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xFF);
674 Demod
.endTime
= Demod
.startTime
+ 8 * (8 * Demod
.len
+ Demod
.bitCount
+ 1) - 4;
676 } else { // no modulation in first half
678 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // and modulation in second half = Sequence E = 0
680 Demod
.shiftReg
= (Demod
.shiftReg
<< 1); // add a 0 to the shiftreg
681 if (Demod
.bitCount
>= 8) { // if we decoded a full byte
682 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xFF);
686 Demod
.endTime
= Demod
.startTime
+ 8 * (8 * Demod
.len
+ Demod
.bitCount
+ 1);
688 } else { // no modulation in both halves - End of communication
690 if (Demod
.bitCount
) { // there are some remaining data bits
691 Demod
.shiftReg
<<= (8 - Demod
.bitCount
); // left align the decoded bits
692 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xFF; // and add them to the output
694 // Dbprintf("A | len... %u - %u == 0x%02x", Demod.len, Demod.bitCount, Demod.output[0]);
699 return true; // we are finished with decoding the raw data sequence
700 } else { // nothing received. Start over
706 return false; // not finished yet, need more data
709 //=============================================================================
710 // Finally, a `sniffer' for ISO 14443 Type A
711 // Both sides of communication!
712 //=============================================================================
714 //-----------------------------------------------------------------------------
715 // Record the sequence of commands sent by the reader to the tag, with
716 // triggering so that we start recording at the point that the tag is moved
719 //-----------------------------------------------------------------------------
720 void RAMFUNC
SniffIso14443a(uint8_t param
) {
723 // bit 0 - trigger from first card answer
724 // bit 1 - trigger from first reader 7-bit request
725 iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER
);
727 // Allocate memory from BigBuf for some buffers
728 // free all previous allocations first
730 BigBuf_Clear_ext(false);
734 // The command (reader -> tag) that we're receiving.
735 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
736 uint8_t *receivedCmdPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
738 // The response (tag -> reader) that we're receiving.
739 uint8_t *receivedResp
= BigBuf_malloc(MAX_FRAME_SIZE
);
740 uint8_t *receivedRespPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
742 uint8_t previous_data
= 0;
743 int maxDataLen
= 0, dataLen
;
744 bool TagIsActive
= false;
745 bool ReaderIsActive
= false;
747 // Set up the demodulator for tag -> reader responses.
748 Demod14aInit(receivedResp
, MAX_FRAME_SIZE
, receivedRespPar
);
750 // Set up the demodulator for the reader -> tag commands
751 Uart14aInit(receivedCmd
, MAX_FRAME_SIZE
, receivedCmdPar
);
753 if (g_dbglevel
>= DBG_INFO
) {
754 DbpString("Press " _GREEN_("pm3 button") " to abort sniffing");
757 // The DMA buffer, used to stream samples from the FPGA
758 dmabuf8_t
*dma
= get_dma8();
759 uint8_t *data
= dma
->buf
;
761 // Setup and start DMA.
762 if (FpgaSetupSscDma((uint8_t *) dma
->buf
, DMA_BUFFER_SIZE
) == false) {
763 if (g_dbglevel
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
767 // We won't start recording the frames that we acquire until we trigger;
768 // a good trigger condition to get started is probably when we see a
769 // response from the tag.
770 // triggered == false -- to wait first for card
771 bool triggered
= !(param
& 0x03);
773 uint32_t rx_samples
= 0;
776 while (BUTTON_PRESS() == false) {
780 register int readBufDataP
= data
- dma
->buf
;
781 register int dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
782 if (readBufDataP
<= dmaBufDataP
) {
783 dataLen
= dmaBufDataP
- readBufDataP
;
785 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
;
788 // test for length of buffer
789 if (dataLen
> maxDataLen
) {
790 maxDataLen
= dataLen
;
791 if (dataLen
> (9 * DMA_BUFFER_SIZE
/ 10)) {
792 Dbprintf("[!] blew circular buffer! | datalen %u", dataLen
);
800 // primary buffer was stopped( <-- we lost data!
801 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
802 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dma
->buf
;
803 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
804 Dbprintf("[-] RxEmpty ERROR | data length %d", dataLen
); // temporary
806 // secondary buffer sets as primary, secondary buffer was stopped
807 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
808 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dma
->buf
;
809 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
814 // Need two samples to feed Miller and Manchester-Decoder
815 if (rx_samples
& 0x01) {
817 // no need to try decoding reader data if the tag is sending
818 if (TagIsActive
== false) {
820 uint8_t readerdata
= (previous_data
& 0xF0) | (*data
>> 4);
822 if (MillerDecoding(readerdata
, (rx_samples
- 1) * 4)) {
825 // check - if there is a short 7bit request from reader
826 if ((!triggered
) && (param
& 0x02) && (Uart
.len
== 1) && (Uart
.bitCount
== 7)) {
831 if (!LogTrace(receivedCmd
,
833 Uart
.startTime
* 16 - DELAY_READER_AIR2ARM_AS_SNIFFER
,
834 Uart
.endTime
* 16 - DELAY_READER_AIR2ARM_AS_SNIFFER
,
840 // ready to receive another command
842 // reset the demod code, which might have been
843 // false-triggered by the commands from the reader
847 ReaderIsActive
= (Uart
.state
!= STATE_14A_UNSYNCD
);
850 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
851 if (ReaderIsActive
== false) {
853 uint8_t tagdata
= (previous_data
<< 4) | (*data
& 0x0F);
855 if (ManchesterDecoding(tagdata
, 0, (rx_samples
- 1) * 4)) {
859 if (!LogTrace(receivedResp
,
861 Demod
.startTime
* 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER
,
862 Demod
.endTime
* 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER
,
866 if ((!triggered
) && (param
& 0x01)) {
870 // ready to receive another response.
872 // reset the Miller decoder including its (now outdated) input buffer
874 //Uart14aInit(receivedCmd, MAX_FRAME_SIZE, receivedCmdPar);
877 TagIsActive
= (Demod
.state
!= DEMOD_14A_UNSYNCD
);
881 previous_data
= *data
;
884 if (data
== dma
->buf
+ DMA_BUFFER_SIZE
) {
889 FpgaDisableTracing();
891 if (g_dbglevel
>= DBG_ERROR
) {
892 Dbprintf("trace len = " _YELLOW_("%d"), BigBuf_get_traceLen());
897 //-----------------------------------------------------------------------------
898 // Prepare tag messages
899 //-----------------------------------------------------------------------------
900 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, uint16_t len
, const uint8_t *par
, bool collision
) {
904 tosend_t
*ts
= get_tosend();
906 // Correction bit, might be removed when not needed
911 tosend_stuffbit(1); // <-----
917 ts
->buf
[++ts
->max
] = SEC_D
;
918 LastProxToAirDuration
= 8 * ts
->max
- 4;
920 for (uint16_t i
= 0; i
< len
; i
++) {
924 for (uint16_t j
= 0; j
< 8; j
++) {
926 ts
->buf
[++ts
->max
] = SEC_COLL
;
929 ts
->buf
[++ts
->max
] = SEC_D
;
931 ts
->buf
[++ts
->max
] = SEC_E
;
938 ts
->buf
[++ts
->max
] = SEC_COLL
;
939 LastProxToAirDuration
= 8 * ts
->max
;
941 // Get the parity bit
942 if (par
[i
>> 3] & (0x80 >> (i
& 0x0007))) {
943 ts
->buf
[++ts
->max
] = SEC_D
;
944 LastProxToAirDuration
= 8 * ts
->max
- 4;
946 ts
->buf
[++ts
->max
] = SEC_E
;
947 LastProxToAirDuration
= 8 * ts
->max
;
953 ts
->buf
[++ts
->max
] = SEC_F
;
955 // Convert from last byte pos to length
959 static void CodeIso14443aAsTagEx(const uint8_t *cmd
, uint16_t len
, bool collision
) {
960 GetParity(cmd
, len
, parity_array
);
961 CodeIso14443aAsTagPar(cmd
, len
, parity_array
, collision
);
963 static void CodeIso14443aAsTag(const uint8_t *cmd
, uint16_t len
) {
964 CodeIso14443aAsTagEx(cmd
, len
, false);
967 static void Code4bitAnswerAsTag(uint8_t cmd
) {
972 tosend_t
*ts
= get_tosend();
974 // Correction bit, might be removed when not needed
979 tosend_stuffbit(1); // 1
985 ts
->buf
[++ts
->max
] = SEC_D
;
987 for (uint8_t i
= 0; i
< 4; i
++) {
989 ts
->buf
[++ts
->max
] = SEC_D
;
990 LastProxToAirDuration
= 8 * ts
->max
- 4;
992 ts
->buf
[++ts
->max
] = SEC_E
;
993 LastProxToAirDuration
= 8 * ts
->max
;
999 ts
->buf
[++ts
->max
] = SEC_F
;
1001 // Convert from last byte pos to length
1005 //-----------------------------------------------------------------------------
1006 // Wait for commands from reader
1007 // stop when button is pressed or client usb connection resets
1008 // or return TRUE when command is captured
1009 //-----------------------------------------------------------------------------
1010 bool GetIso14443aCommandFromReader(uint8_t *received
, uint16_t received_maxlen
, uint8_t *par
, int *len
) {
1011 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1012 // only, since we are receiving, not transmitting).
1013 // Signal field is off with the appropriate LED
1015 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1017 // Now run a `software UART` on the stream of incoming samples.
1018 Uart14aInit(received
, received_maxlen
, par
);
1021 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1025 uint16_t checker
= 4000;
1030 // ever 3 * 4000, check if we got any data from client
1031 // takes long time, usually messes with simualtion
1033 if (data_available()) {
1040 // button press, takes a bit time, might mess with simualtion
1041 if (checker
-- == 0) {
1042 if (BUTTON_PRESS()) {
1050 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1051 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1052 if (MillerDecoding(b
, 0)) {
1061 bool prepare_tag_modulation(tag_response_info_t
*response_info
, size_t max_buffer_size
) {
1062 // Example response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
1063 // This will need the following byte array for a modulation sequence
1064 // 144 data bits (18 * 8)
1067 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
1068 // 1 just for the case
1070 // 166 bytes, since every bit that needs to be send costs us a byte
1072 // Prepare the tag modulation bits from the message
1073 CodeIso14443aAsTag(response_info
->response
, response_info
->response_n
);
1075 tosend_t
*ts
= get_tosend();
1077 // Make sure we do not exceed the free buffer space
1078 if (ts
->max
> max_buffer_size
) {
1079 Dbprintf("ToSend buffer, Out-of-bound, when modulating bits for tag answer:");
1080 Dbhexdump(response_info
->response_n
, response_info
->response
, false);
1084 // Copy the byte array, used for this modulation to the buffer position
1085 memcpy(response_info
->modulation
, ts
->buf
, ts
->max
);
1087 // Store the number of bytes that were used for encoding/modulation and the time needed to transfer them
1088 response_info
->modulation_n
= ts
->max
;
1089 response_info
->ProxToAirDuration
= LastProxToAirDuration
;
1093 bool prepare_allocated_tag_modulation(tag_response_info_t
*response_info
, uint8_t **buffer
, size_t *max_buffer_size
) {
1095 tosend_t
*ts
= get_tosend();
1097 // Retrieve and store the current buffer index
1098 response_info
->modulation
= *buffer
;
1100 // Forward the prepare tag modulation function to the inner function
1101 if (prepare_tag_modulation(response_info
, *max_buffer_size
)) {
1102 // Update the free buffer offset and the remaining buffer size
1104 *max_buffer_size
-= ts
->max
;
1111 bool SimulateIso14443aInit(uint8_t tagType
, uint16_t flags
, uint8_t *data
,
1112 uint8_t *iRATs
, size_t irats_len
, tag_response_info_t
**responses
,
1113 uint32_t *cuid
, uint32_t counters
[3], uint8_t tearings
[3], uint8_t *pages
) {
1115 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
1116 static uint8_t rATQA
[2] = { 0x00 };
1117 // The second response contains the (mandatory) first 24 bits of the UID
1118 static uint8_t rUIDc1
[5] = { 0x00 };
1120 static uint8_t rUIDc2
[5] = { 0x00 };
1122 static uint8_t rUIDc3
[5] = { 0x00 };
1123 // Prepare the mandatory SAK (for 4, 7 and 10 byte UID)
1124 static uint8_t rSAKc1
[3] = { 0x00 };
1125 // Prepare the optional second SAK (for 7 and 10 byte UID), drop the cascade bit for 7b
1126 static uint8_t rSAKc2
[3] = { 0x00 };
1127 // Prepare the optional third SAK (for 10 byte UID), drop the cascade bit
1128 static uint8_t rSAKc3
[3] = { 0x00 };
1129 // dummy ATS (pseudo-ATR), answer to RATS
1130 // Format byte = 0x58: FSCI=0x08 (FSC=256), TA(1) and TC(1) present,
1131 // TA(1) = 0x80: different divisors not supported, DR = 1, DS = 1
1132 // 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)
1133 // TC(1) = 0x02: CID supported, NAD not supported
1134 // static uint8_t rRATS[] = { 0x04, 0x58, 0x80, 0x02, 0x00, 0x00 };
1135 static uint8_t rRATS
[40] = { 0x05, 0x75, 0x80, 0x60, 0x02, 0x00, 0x00, 0x00 };
1136 uint8_t rRATS_len
= 8;
1138 // GET_VERSION response for EV1/NTAG
1139 static uint8_t rVERSION
[10] = { 0x00 };
1140 // READ_SIG response for EV1/NTAG
1141 static uint8_t rSIGN
[34] = { 0x00 };
1143 static uint8_t rPPS
[3] = { 0xD0 };
1145 static uint8_t rPACK
[4] = { 0x00, 0x00, 0x00, 0x00 };
1148 case 1: { // MIFARE Classic 1k
1153 case 2: { // MIFARE Ultralight
1156 // some first pages of UL/NTAG dump is special data
1157 mfu_dump_t
*mfu_header
= (mfu_dump_t
*) BigBuf_get_EM_addr();
1158 *pages
= MAX(mfu_header
->pages
, 15);
1160 // counters and tearing flags
1161 // for old dumps with all zero headers, we need to set default values.
1162 for (uint8_t i
= 0; i
< 3; i
++) {
1164 counters
[i
] = le24toh(mfu_header
->counter_tearing
[i
]);
1166 if (mfu_header
->counter_tearing
[i
][3] != 0x00) {
1167 tearings
[i
] = mfu_header
->counter_tearing
[i
][3];
1172 if (memcmp(mfu_header
->version
, "\x00\x00\x00\x00\x00\x00\x00\x00", 8) == 0) {
1173 memcpy(rVERSION
, "\x00\x04\x04\x02\x01\x00\x11\x03", 8);
1175 memcpy(rVERSION
, mfu_header
->version
, 8);
1177 AddCrc14A(rVERSION
, sizeof(rVERSION
) - 2);
1180 memcpy(rSIGN
, mfu_header
->signature
, 32);
1181 AddCrc14A(rSIGN
, sizeof(rSIGN
) - 2);
1184 case 3: { // MIFARE DESFire
1188 memcpy(rRATS
, "\x06\x75\x77\x81\x02\x80\x00\x00", 8);
1192 case 4: { // ISO/IEC 14443-4 - javacard (JCOP)
1197 case 5: { // MIFARE TNP3XXX
1203 case 6: { // MIFARE Mini 320b
1208 case 7: { // NTAG 215
1211 // some first pages of UL/NTAG dump is special data
1212 mfu_dump_t
*mfu_header
= (mfu_dump_t
*) BigBuf_get_EM_addr();
1213 *pages
= MAX(mfu_header
->pages
, 19);
1215 // counters and tearing flags
1216 // for old dumps with all zero headers, we need to set default values.
1217 for (uint8_t i
= 0; i
< 3; i
++) {
1219 counters
[i
] = le24toh(mfu_header
->counter_tearing
[i
]);
1221 if (mfu_header
->counter_tearing
[i
][3] != 0x00) {
1222 tearings
[i
] = mfu_header
->counter_tearing
[i
][3];
1227 if (memcmp(mfu_header
->version
, "\x00\x00\x00\x00\x00\x00\x00\x00", 8) == 0) {
1228 memcpy(rVERSION
, "\x00\x04\x04\x02\x01\x00\x11\x03", 8);
1230 memcpy(rVERSION
, mfu_header
->version
, 8);
1232 AddCrc14A(rVERSION
, sizeof(rVERSION
) - 2);
1235 memcpy(rSIGN
, mfu_header
->signature
, 32);
1236 AddCrc14A(rSIGN
, sizeof(rSIGN
) - 2);
1239 case 8: { // MIFARE Classic 4k
1244 case 9: { // FM11RF005SH (Shanghai Metro)
1250 case 10: { // ST25TA IKEA Rothult
1256 case 11: { // ISO/IEC 14443-4 - javacard (JCOP) / EMV
1258 memcpy(rRATS
, "\x13\x78\x80\x72\x02\x80\x31\x80\x66\xb1\x84\x0c\x01\x6e\x01\x83\x00\x90\x00", 19);
1264 case 12: { // HID Seos 4K card
1270 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Error: unknown tagtype (%d)", tagType
);
1275 // copy the iRATs if supplied.
1276 // iRATs is a pointer to 20 byte array
1277 // rRATS is a 40 byte array
1278 if ((flags
& FLAG_RATS_IN_DATA
) == FLAG_RATS_IN_DATA
) {
1279 memcpy(rRATS
, iRATs
, irats_len
);
1280 // rats len is dictated by the first char of the string, add 2 crc bytes
1281 rRATS_len
= (iRATs
[0] + 2);
1282 // Since its Varible length we can send value > 40 and overflow our array.
1283 // Even if RATS protocol defined as max 40 bytes doesn't mean people try stuff
1284 if (rRATS_len
> sizeof(rRATS
)) {
1285 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("[-] ERROR: iRATS overflow. Max %zu, got %zu", sizeof(rRATS
), rRATS_len
);
1290 // if uid not supplied then get from emulator memory
1291 if ((memcmp(data
, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 10) == 0) || IS_FLAG_UID_IN_EMUL(flags
)) {
1292 if (tagType
== 2 || tagType
== 7) {
1293 uint16_t start
= MFU_DUMP_PREFIX_LENGTH
;
1295 emlGet(emdata
, start
, sizeof(emdata
));
1296 memcpy(data
, emdata
, 3); // uid bytes 0-2
1297 memcpy(data
+ 3, emdata
+ 4, 4); // uid bytes 3-7
1298 FLAG_SET_UID_IN_DATA(flags
, 7);
1301 FLAG_SET_UID_IN_DATA(flags
, 4);
1305 if (IS_FLAG_UID_IN_DATA(flags
, 4)) {
1306 rUIDc1
[0] = data
[0];
1307 rUIDc1
[1] = data
[1];
1308 rUIDc1
[2] = data
[2];
1309 rUIDc1
[3] = data
[3];
1310 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1312 // Configure the ATQA and SAK accordingly
1315 if (tagType
== 11) {
1316 rSAKc1
[0] = sak
& 0xFC & 0X70;
1318 rSAKc1
[0] = sak
& 0xFB;
1321 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1323 *cuid
= bytes_to_num(data
, 4);
1324 } else if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
1325 rUIDc1
[0] = MIFARE_SELECT_CT
; // Cascade Tag marker
1326 rUIDc1
[1] = data
[0];
1327 rUIDc1
[2] = data
[1];
1328 rUIDc1
[3] = data
[2];
1329 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1331 rUIDc2
[0] = data
[3];
1332 rUIDc2
[1] = data
[4];
1333 rUIDc2
[2] = data
[5];
1334 rUIDc2
[3] = data
[6];
1335 rUIDc2
[4] = rUIDc2
[0] ^ rUIDc2
[1] ^ rUIDc2
[2] ^ rUIDc2
[3];
1337 // Configure the ATQA and SAK accordingly
1341 rSAKc2
[0] = sak
& 0xFB;
1342 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1343 AddCrc14A(rSAKc2
, sizeof(rSAKc2
) - 2);
1345 *cuid
= bytes_to_num(data
+ 3, 4);
1347 } else if (IS_FLAG_UID_IN_DATA(flags
, 10)) {
1349 rUIDc1
[0] = MIFARE_SELECT_CT
; // Cascade Tag marker
1350 rUIDc1
[1] = data
[0];
1351 rUIDc1
[2] = data
[1];
1352 rUIDc1
[3] = data
[2];
1353 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1355 rUIDc2
[0] = MIFARE_SELECT_CT
; // Cascade Tag marker
1356 rUIDc2
[1] = data
[3];
1357 rUIDc2
[2] = data
[4];
1358 rUIDc2
[3] = data
[5];
1359 rUIDc2
[4] = rUIDc2
[0] ^ rUIDc2
[1] ^ rUIDc2
[2] ^ rUIDc2
[3];
1361 rUIDc3
[0] = data
[6];
1362 rUIDc3
[1] = data
[7];
1363 rUIDc3
[2] = data
[8];
1364 rUIDc3
[3] = data
[9];
1365 rUIDc3
[4] = rUIDc3
[0] ^ rUIDc3
[1] ^ rUIDc3
[2] ^ rUIDc3
[3];
1367 // Configure the ATQA and SAK accordingly
1372 rSAKc3
[0] = sak
& 0xFB;
1373 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1374 AddCrc14A(rSAKc2
, sizeof(rSAKc2
) - 2);
1375 AddCrc14A(rSAKc3
, sizeof(rSAKc3
) - 2);
1377 *cuid
= bytes_to_num(data
+ 3 + 3, 4);
1379 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("[-] ERROR: UID size not defined");
1383 AddCrc14A(rRATS
, rRATS_len
- 2);
1385 AddCrc14A(rPPS
, sizeof(rPPS
) - 2);
1387 // EV1/NTAG, set PWD w AMIIBO algo if all zero.
1389 uint8_t pwd
[4] = {0, 0, 0, 0};
1390 uint8_t gen_pwd
[4] = {0, 0, 0, 0};
1391 emlGet(pwd
, (*pages
- 1) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(pwd
));
1392 emlGet(rPACK
, (*pages
) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(rPACK
));
1394 Uint4byteToMemBe(gen_pwd
, ul_ev1_pwdgenB(data
));
1395 if (memcmp(pwd
, gen_pwd
, sizeof(pwd
)) == 0) {
1401 AddCrc14A(rPACK
, sizeof(rPACK
) - 2);
1403 static tag_response_info_t responses_init
[] = {
1404 { .response
= rATQA
, .response_n
= sizeof(rATQA
) }, // Answer to request - respond with card type
1405 { .response
= rUIDc1
, .response_n
= sizeof(rUIDc1
) }, // Anticollision cascade1 - respond with uid
1406 { .response
= rUIDc2
, .response_n
= sizeof(rUIDc2
) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1407 { .response
= rUIDc3
, .response_n
= sizeof(rUIDc3
) }, // Anticollision cascade3 - respond with 3rd half of uid if asked
1408 { .response
= rSAKc1
, .response_n
= sizeof(rSAKc1
) }, // Acknowledge select - cascade 1
1409 { .response
= rSAKc2
, .response_n
= sizeof(rSAKc2
) }, // Acknowledge select - cascade 2
1410 { .response
= rSAKc3
, .response_n
= sizeof(rSAKc3
) }, // Acknowledge select - cascade 3
1411 { .response
= rRATS
, .response_n
= sizeof(rRATS
) }, // dummy ATS (pseudo-ATR), answer to RATS
1412 { .response
= rVERSION
, .response_n
= sizeof(rVERSION
) }, // EV1/NTAG GET_VERSION response
1413 { .response
= rSIGN
, .response_n
= sizeof(rSIGN
) }, // EV1/NTAG READ_SIG response
1414 { .response
= rPPS
, .response_n
= sizeof(rPPS
) }, // PPS response
1415 { .response
= rPACK
, .response_n
= sizeof(rPACK
) } // PACK response
1418 // since rats len is variable now.
1419 responses_init
[RESP_INDEX_RATS
].response_n
= rRATS_len
;
1421 // "precompiled" responses.
1422 // These exist for speed reasons. There are no time in the anti collision phase to calculate responses.
1423 // There are 12 predefined responses with a total of 84 bytes data to transmit.
1425 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
1426 // 85 * 8 data bits, 85 * 1 parity bits, 12 start bits, 12 stop bits, 12 correction bits
1427 // 85 * 8 + 85 + 12 + 12 + 12 == 801
1429 // 85 bytes normally (rats = 8 bytes)
1430 // 77 bytes + ratslen,
1432 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE ( ((77 + rRATS_len) * 8) + 77 + rRATS_len + 12 + 12 + 12)
1434 uint8_t *free_buffer
= BigBuf_calloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE
);
1435 // modulation buffer pointer and current buffer free space size
1436 uint8_t *free_buffer_pointer
= free_buffer
;
1437 size_t free_buffer_size
= ALLOCATED_TAG_MODULATION_BUFFER_SIZE
;
1439 // Prepare the responses of the anticollision phase
1440 // there will be not enough time to do this at the moment the reader sends it REQA
1441 for (size_t i
= 0; i
< ARRAYLEN(responses_init
); i
++) {
1442 if (prepare_allocated_tag_modulation(&responses_init
[i
], &free_buffer_pointer
, &free_buffer_size
) == false) {
1443 BigBuf_free_keep_EM();
1444 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Not enough modulation buffer size, exit after %d elements", i
);
1449 *responses
= responses_init
;
1453 //-----------------------------------------------------------------------------
1454 // Main loop of simulated tag: receive commands from reader, decide what
1455 // response to send, and send it.
1457 //-----------------------------------------------------------------------------
1458 void SimulateIso14443aTag(uint8_t tagType
, uint16_t flags
, uint8_t *data
, uint8_t exitAfterNReads
,
1459 uint8_t *iRATs
, size_t irats_len
) {
1461 #define ATTACK_KEY_COUNT 16
1463 tag_response_info_t
*responses
;
1466 uint32_t counters
[3] = { 0x00, 0x00, 0x00 };
1467 uint8_t tearings
[3] = { 0xbd, 0xbd, 0xbd };
1470 // Here, we collect CUID, block1, keytype1, NT1, NR1, AR1, CUID, block2, keytyp2, NT2, NR2, AR2
1471 // it should also collect block, keytype.
1472 uint8_t cardAUTHSC
= 0;
1473 uint8_t cardAUTHKEY
= 0xff; // no authentication
1474 // allow collecting up to 8 sets of nonces to allow recovery of up to 8 keys
1476 nonces_t ar_nr_nonces
[ATTACK_KEY_COUNT
]; // for attack types moebius
1477 memset(ar_nr_nonces
, 0x00, sizeof(ar_nr_nonces
));
1478 uint8_t moebius_count
= 0;
1481 uint8_t receivedCmd
[MAX_FRAME_SIZE
] = { 0x00 };
1482 uint8_t receivedCmdPar
[MAX_PARITY_SIZE
] = { 0x00 };
1484 // free eventually allocated BigBuf memory but keep Emulator Memory
1485 BigBuf_free_keep_EM();
1487 // Allocate 512 bytes for the dynamic modulation, created when the reader queries for it
1488 // Such a response is less time critical, so we can prepare them on the fly
1489 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1490 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1492 uint8_t *dynamic_response_buffer
= BigBuf_calloc(DYNAMIC_RESPONSE_BUFFER_SIZE
);
1493 uint8_t *dynamic_modulation_buffer
= BigBuf_calloc(DYNAMIC_MODULATION_BUFFER_SIZE
);
1494 tag_response_info_t dynamic_response_info
= {
1495 .response
= dynamic_response_buffer
,
1497 .modulation
= dynamic_modulation_buffer
,
1501 if (SimulateIso14443aInit(tagType
, flags
, data
, iRATs
, irats_len
, &responses
, &cuid
, counters
, tearings
, &pages
) == false) {
1502 BigBuf_free_keep_EM();
1503 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_EINIT
, NULL
, 0);
1507 // We need to listen to the high-frequency, peak-detected path.
1508 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1510 iso14a_set_timeout(201400); // 106 * 19ms default *100?
1514 // To control where we are in the protocol
1515 #define ORDER_NONE 0
1516 //#define ORDER_REQA 1
1517 //#define ORDER_SELECT_ALL_CL1 2
1518 //#define ORDER_SELECT_CL1 3
1519 #define ORDER_HALTED 5
1520 #define ORDER_WUPA 6
1521 #define ORDER_AUTH 7
1522 //#define ORDER_SELECT_ALL_CL2 20
1523 //#define ORDER_SELECT_CL2 25
1524 //#define ORDER_SELECT_ALL_CL3 30
1525 //#define ORDER_SELECT_CL3 35
1526 #define ORDER_EV1_COMP_WRITE 40
1527 //#define ORDER_RATS 70
1529 uint8_t order
= ORDER_NONE
;
1530 int retval
= PM3_SUCCESS
;
1532 // Just to allow some checks
1533 // int happened = 0;
1534 // int happened2 = 0;
1536 uint32_t numReads
= 0; //Counts numer of times reader reads a block
1538 // compatible write block number
1539 uint8_t wrblock
= 0;
1541 bool odd_reply
= true;
1548 bool finished
= false;
1549 while (finished
== false) {
1550 // BUTTON_PRESS check done in GetIso14443aCommandFromReader
1553 tag_response_info_t
*p_response
= NULL
;
1555 // Clean receive command buffer
1556 if (GetIso14443aCommandFromReader(receivedCmd
, sizeof(receivedCmd
), receivedCmdPar
, &len
) == false) {
1557 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
1558 retval
= PM3_EOPABORTED
;
1562 // we need to check "ordered" states before, because received data may be same to any command - is wrong!!!
1563 if (order
== ORDER_EV1_COMP_WRITE
&& len
== 18) {
1564 // MIFARE_ULC_COMP_WRITE part 2
1565 // 16 bytes data + 2 bytes crc, only least significant 4 bytes are written
1566 bool isCrcCorrect
= CheckCrc14A(receivedCmd
, len
);
1568 // first blocks of emu are header
1569 emlSetMem_xt(receivedCmd
, wrblock
+ MFU_DUMP_PREFIX_LENGTH
/ 4, 1, 4);
1571 EmSend4bit(CARD_ACK
);
1573 // send NACK 0x1 == crc/parity error
1574 EmSend4bit(CARD_NACK_PA
);
1576 order
= ORDER_NONE
; // back to work state
1579 } else if (order
== ORDER_AUTH
&& len
== 8) {
1580 // Received {nr] and {ar} (part of authentication)
1581 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1582 uint32_t nr
= bytes_to_num(receivedCmd
, 4);
1583 uint32_t ar
= bytes_to_num(receivedCmd
+ 4, 4);
1585 // Collect AR/NR per keytype & sector
1586 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1590 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1591 // find which index to use
1592 if ((cardAUTHSC
== ar_nr_nonces
[i
].sector
) && (cardAUTHKEY
== ar_nr_nonces
[i
].keytype
))
1595 // keep track of empty slots.
1596 if (ar_nr_nonces
[i
].state
== EMPTY
)
1599 // if no empty slots. Choose first and overwrite.
1603 ar_nr_nonces
[index
].state
= EMPTY
;
1609 switch ((nonce_state
)ar_nr_nonces
[index
].state
) {
1611 // first nonce collect
1612 ar_nr_nonces
[index
].cuid
= cuid
;
1613 ar_nr_nonces
[index
].sector
= cardAUTHSC
;
1614 ar_nr_nonces
[index
].keytype
= cardAUTHKEY
;
1615 ar_nr_nonces
[index
].nonce
= nonce
;
1616 ar_nr_nonces
[index
].nr
= nr
;
1617 ar_nr_nonces
[index
].ar
= ar
;
1618 ar_nr_nonces
[index
].state
= FIRST
;
1622 // second nonce collect
1623 ar_nr_nonces
[index
].nonce2
= nonce
;
1624 ar_nr_nonces
[index
].nr2
= nr
;
1625 ar_nr_nonces
[index
].ar2
= ar
;
1626 ar_nr_nonces
[index
].state
= SECOND
;
1628 // send to client (one struct nonces_t)
1629 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_SUCCESS
, (uint8_t *)&ar_nr_nonces
[index
], sizeof(nonces_t
));
1631 ar_nr_nonces
[index
].state
= EMPTY
;
1632 ar_nr_nonces
[index
].sector
= 0;
1633 ar_nr_nonces
[index
].keytype
= 0;
1642 order
= ORDER_NONE
; // back to work state
1645 } else if (receivedCmd
[0] == ISO14443A_CMD_REQA
&& len
== 1) { // Received a REQUEST, but in HALTED, skip
1646 odd_reply
= !odd_reply
;
1648 p_response
= &responses
[RESP_INDEX_ATQA
];
1650 } else if (receivedCmd
[0] == ISO14443A_CMD_WUPA
&& len
== 1) { // Received a WAKEUP
1651 p_response
= &responses
[RESP_INDEX_ATQA
];
1652 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 2) { // Received request for UID (cascade 1)
1653 p_response
= &responses
[RESP_INDEX_UIDC1
];
1654 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 2) { // Received request for UID (cascade 2)
1655 p_response
= &responses
[RESP_INDEX_UIDC2
];
1656 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 2) { // Received request for UID (cascade 3)
1657 p_response
= &responses
[RESP_INDEX_UIDC3
];
1658 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 9) { // Received a SELECT (cascade 1)
1659 p_response
= &responses
[RESP_INDEX_SAKC1
];
1660 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 9) { // Received a SELECT (cascade 2)
1661 p_response
= &responses
[RESP_INDEX_SAKC2
];
1662 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 9) { // Received a SELECT (cascade 3)
1663 p_response
= &responses
[RESP_INDEX_SAKC3
];
1664 } else if (receivedCmd
[0] == ISO14443A_CMD_PPS
) {
1665 p_response
= &responses
[RESP_INDEX_PPS
];
1666 } else if (receivedCmd
[0] == ISO14443A_CMD_READBLOCK
&& len
== 4) { // Received a (plain) READ
1667 uint8_t block
= receivedCmd
[1];
1668 // if Ultralight or NTAG (4 byte blocks)
1669 if (tagType
== 7 || tagType
== 2) {
1670 if (block
> pages
) {
1671 // send NACK 0x0 == invalid argument
1672 EmSend4bit(CARD_NACK_IV
);
1674 // first blocks of emu are header
1675 uint16_t start
= block
* 4 + MFU_DUMP_PREFIX_LENGTH
;
1676 uint8_t emdata
[MAX_MIFARE_FRAME_SIZE
];
1677 emlGet(emdata
, start
, 16);
1678 AddCrc14A(emdata
, 16);
1679 EmSendCmd(emdata
, sizeof(emdata
));
1680 numReads
++; // Increment number of times reader requested a block
1682 if (exitAfterNReads
> 0 && numReads
== exitAfterNReads
) {
1683 Dbprintf("[MFUEMUL_WORK] %d reads done, exiting", numReads
);
1687 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1689 } else if (tagType
== 9 && block
== 1) {
1690 // FM11005SH. 16blocks, 4bytes / block.
1691 // block0 = 2byte Customer ID (CID), 2byte Manufacture ID (MID)
1692 // block1 = 4byte UID.
1693 p_response
= &responses
[RESP_INDEX_UIDC1
];
1694 } else { // all other tags (16 byte block tags)
1695 uint8_t emdata
[MAX_MIFARE_FRAME_SIZE
] = {0};
1696 emlGet(emdata
, block
, 16);
1697 AddCrc14A(emdata
, 16);
1698 EmSendCmd(emdata
, sizeof(emdata
));
1699 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1702 } else if (receivedCmd
[0] == MIFARE_ULEV1_FASTREAD
&& len
== 5) { // Received a FAST READ (ranged read)
1703 uint8_t block1
= receivedCmd
[1];
1704 uint8_t block2
= receivedCmd
[2];
1705 if (block1
> pages
) {
1706 // send NACK 0x0 == invalid argument
1707 EmSend4bit(CARD_NACK_IV
);
1709 uint8_t emdata
[MAX_FRAME_SIZE
] = {0};
1710 // first blocks of emu are header
1711 int start
= block1
* 4 + MFU_DUMP_PREFIX_LENGTH
;
1712 len
= (block2
- block1
+ 1) * 4;
1713 emlGet(emdata
, start
, len
);
1714 AddCrc14A(emdata
, len
);
1715 EmSendCmd(emdata
, len
+ 2);
1718 } else if (receivedCmd
[0] == MIFARE_ULC_WRITE
&& len
== 8 && (tagType
== 2 || tagType
== 7)) { // Received a WRITE
1719 // cmd + block + 4 bytes data + 2 bytes crc
1720 if (CheckCrc14A(receivedCmd
, len
)) {
1721 uint8_t block
= receivedCmd
[1];
1722 if (block
> pages
) {
1723 // send NACK 0x0 == invalid argument
1724 EmSend4bit(CARD_NACK_IV
);
1726 // first blocks of emu are header
1727 emlSetMem_xt(&receivedCmd
[2], block
+ MFU_DUMP_PREFIX_LENGTH
/ 4, 1, 4);
1729 EmSend4bit(CARD_ACK
);
1732 // send NACK 0x1 == crc/parity error
1733 EmSend4bit(CARD_NACK_PA
);
1736 } else if (receivedCmd
[0] == MIFARE_ULC_COMP_WRITE
&& len
== 4 && (tagType
== 2 || tagType
== 7)) {
1737 // cmd + block + 2 bytes crc
1738 if (CheckCrc14A(receivedCmd
, len
)) {
1739 wrblock
= receivedCmd
[1];
1740 if (wrblock
> pages
) {
1741 // send NACK 0x0 == invalid argument
1742 EmSend4bit(CARD_NACK_IV
);
1745 EmSend4bit(CARD_ACK
);
1747 order
= ORDER_EV1_COMP_WRITE
;
1750 // send NACK 0x1 == crc/parity error
1751 EmSend4bit(CARD_NACK_PA
);
1754 } else if (receivedCmd
[0] == MIFARE_ULEV1_READSIG
&& len
== 4 && tagType
== 7) { // Received a READ SIGNATURE --
1755 p_response
= &responses
[RESP_INDEX_SIGNATURE
];
1756 } else if (receivedCmd
[0] == MIFARE_ULEV1_READ_CNT
&& len
== 4 && tagType
== 7) { // Received a READ COUNTER --
1757 uint8_t index
= receivedCmd
[1];
1759 // send NACK 0x0 == invalid argument
1760 EmSend4bit(CARD_NACK_IV
);
1762 uint8_t cmd
[] = {0x00, 0x00, 0x00, 0x14, 0xa5};
1763 htole24(counters
[index
], cmd
);
1764 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1765 EmSendCmd(cmd
, sizeof(cmd
));
1768 } else if (receivedCmd
[0] == MIFARE_ULEV1_INCR_CNT
&& len
== 8 && tagType
== 7) { // Received a INC COUNTER --
1769 uint8_t index
= receivedCmd
[1];
1771 // send NACK 0x0 == invalid argument
1772 EmSend4bit(CARD_NACK_IV
);
1774 uint32_t val
= le24toh(receivedCmd
+ 2) + counters
[index
];
1775 // if new value + old value is bigger 24bits, fail
1776 if (val
> 0xFFFFFF) {
1777 // send NACK 0x4 == counter overflow
1778 EmSend4bit(CARD_NACK_NA
);
1780 counters
[index
] = val
;
1782 EmSend4bit(CARD_ACK
);
1786 } else if (receivedCmd
[0] == MIFARE_ULEV1_CHECKTEAR
&& len
== 4 && tagType
== 7) { // Received a CHECK_TEARING_EVENT --
1787 // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1788 uint8_t index
= receivedCmd
[1];
1790 // send NACK 0x0 == invalid argument
1791 EmSend4bit(CARD_NACK_IV
);
1793 uint8_t cmd
[3] = {0, 0, 0};
1794 cmd
[0] = tearings
[index
];
1795 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1796 EmSendCmd(cmd
, sizeof(cmd
));
1799 } else if (receivedCmd
[0] == ISO14443A_CMD_HALT
&& len
== 4) { // Received a HALT
1800 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1802 order
= ORDER_HALTED
;
1803 } else if (receivedCmd
[0] == MIFARE_ULEV1_VERSION
&& len
== 3 && (tagType
== 2 || tagType
== 7)) {
1804 p_response
= &responses
[RESP_INDEX_VERSION
];
1805 } else if (receivedCmd
[0] == MFDES_GET_VERSION
&& len
== 4 && (tagType
== 3)) {
1806 p_response
= &responses
[RESP_INDEX_VERSION
];
1807 } else if ((receivedCmd
[0] == MIFARE_AUTH_KEYA
|| receivedCmd
[0] == MIFARE_AUTH_KEYB
) && len
== 4 && tagType
!= 2 && tagType
!= 7) { // Received an authentication request
1808 cardAUTHKEY
= receivedCmd
[0] - 0x60;
1809 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
1811 // incease nonce at AUTH requests. this is time consuming.
1812 nonce
= prng_successor(GetTickCount(), 32);
1813 num_to_bytes(nonce
, 4, dynamic_response_info
.response
);
1814 dynamic_response_info
.response_n
= 4;
1816 prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
);
1817 p_response
= &dynamic_response_info
;
1819 } else if (receivedCmd
[0] == ISO14443A_CMD_RATS
&& len
== 4) { // Received a RATS request
1820 if (tagType
== 1 || tagType
== 2) { // RATS not supported
1821 EmSend4bit(CARD_NACK_NA
);
1824 p_response
= &responses
[RESP_INDEX_RATS
];
1826 } else if (receivedCmd
[0] == MIFARE_ULC_AUTH_1
) { // ULC authentication, or Desfire Authentication
1827 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1829 } else if (receivedCmd
[0] == MIFARE_ULEV1_AUTH
&& len
== 7 && tagType
== 7) { // NTAG / EV-1
1830 uint8_t pwd
[4] = {0, 0, 0, 0};
1831 emlGet(pwd
, (pages
- 1) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(pwd
));
1832 if (g_dbglevel
>= DBG_DEBUG
) {
1833 Dbprintf("Reader sent password: ");
1834 Dbhexdump(4, receivedCmd
+ 1, 0);
1835 Dbprintf("Loaded password from memory: ");
1836 Dbhexdump(4, pwd
, 0);
1839 if (memcmp(pwd
, "\x00\x00\x00\x00", 4) == 0) {
1840 Uint4byteToMemLe(pwd
, ul_ev1_pwdgenB(data
));
1841 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Calc pwd... %02X %02X %02X %02X", pwd
[0], pwd
[1], pwd
[2], pwd
[3]);
1844 if (memcmp(receivedCmd
+ 1, pwd
, 4) == 0) {
1845 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Password match, responding with PACK.");
1846 p_response
= &responses
[RESP_INDEX_PACK
];
1848 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Password did not match, NACK_IV.");
1850 EmSend4bit(CARD_NACK_IV
);
1853 } else if (receivedCmd
[0] == MIFARE_ULEV1_VCSL
&& len
== 23 && tagType
== 7) {
1854 uint8_t cmd
[3] = {0, 0, 0};
1855 emlGet(cmd
, (pages
- 2) * 4 + 1 + MFU_DUMP_PREFIX_LENGTH
, 1);
1856 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1857 EmSendCmd(cmd
, sizeof(cmd
));
1862 // clear old dynamic responses
1863 dynamic_response_info
.response_n
= 0;
1864 dynamic_response_info
.modulation_n
= 0;
1866 // ST25TA512B IKEA Rothult
1867 if (tagType
== 10) {
1868 // we replay 90 00 for all commands but the read bin and we deny the verify cmd.
1870 if (memcmp("\x02\xa2\xb0\x00\x00\x1d\x51\x69", receivedCmd
, 8) == 0) {
1871 dynamic_response_info
.response
[0] = receivedCmd
[0];
1872 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);
1873 dynamic_response_info
.response_n
= 32;
1874 } else if (memcmp("\x02\x00\x20\x00\x01\x00\x6e\xa9", receivedCmd
, 8) == 0) {
1875 dynamic_response_info
.response
[0] = receivedCmd
[0];
1876 dynamic_response_info
.response
[1] = 0x63;
1877 dynamic_response_info
.response
[2] = 0x00;
1878 dynamic_response_info
.response_n
= 3;
1879 } else if (memcmp("\x03\x00\x20\x00\x01\x10", receivedCmd
, 6) == 0) {
1880 Dbprintf("Reader sent password: ");
1881 Dbhexdump(16, receivedCmd
+ 6, 0);
1882 dynamic_response_info
.response
[0] = receivedCmd
[0];
1883 dynamic_response_info
.response
[1] = 0x90;
1884 dynamic_response_info
.response
[2] = 0x00;
1885 dynamic_response_info
.response_n
= 3;
1887 dynamic_response_info
.response
[0] = receivedCmd
[0];
1888 dynamic_response_info
.response
[1] = 0x90;
1889 dynamic_response_info
.response
[2] = 0x00;
1890 dynamic_response_info
.response_n
= 3;
1894 // Check for ISO 14443A-4 compliant commands, look at left nibble
1895 switch (receivedCmd
[0]) {
1897 case 0x03: { // IBlock (command no CID)
1898 dynamic_response_info
.response
[0] = receivedCmd
[0];
1899 dynamic_response_info
.response
[1] = 0x90;
1900 dynamic_response_info
.response
[2] = 0x00;
1901 dynamic_response_info
.response_n
= 3;
1905 case 0x0A: { // IBlock (command CID)
1906 dynamic_response_info
.response
[0] = receivedCmd
[0];
1907 dynamic_response_info
.response
[1] = 0x00;
1908 dynamic_response_info
.response
[2] = 0x90;
1909 dynamic_response_info
.response
[3] = 0x00;
1910 dynamic_response_info
.response_n
= 4;
1915 case 0x1B: { // Chaining command
1916 dynamic_response_info
.response
[0] = 0xaa | ((receivedCmd
[0]) & 1);
1917 dynamic_response_info
.response_n
= 2;
1923 dynamic_response_info
.response
[0] = receivedCmd
[0] ^ 0x11;
1924 dynamic_response_info
.response_n
= 2;
1928 case 0xBA: { // ping / pong
1929 dynamic_response_info
.response
[0] = 0xAB;
1930 dynamic_response_info
.response
[1] = 0x00;
1931 dynamic_response_info
.response_n
= 2;
1936 case 0xC2: { // Readers sends deselect command
1937 dynamic_response_info
.response
[0] = 0xCA;
1938 dynamic_response_info
.response
[1] = 0x00;
1939 dynamic_response_info
.response_n
= 2;
1944 // Never seen this command before
1945 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1946 if (g_dbglevel
>= DBG_DEBUG
) {
1947 Dbprintf("Received unknown command (len=%d):", len
);
1948 Dbhexdump(len
, receivedCmd
, false);
1951 dynamic_response_info
.response_n
= 0;
1952 order
= ORDER_NONE
; // back to work state
1958 if (dynamic_response_info
.response_n
> 0) {
1960 // Copy the CID from the reader query
1962 dynamic_response_info
.response
[1] = receivedCmd
[1];
1964 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1965 AddCrc14A(dynamic_response_info
.response
, dynamic_response_info
.response_n
);
1966 dynamic_response_info
.response_n
+= 2;
1968 if (prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
1969 if (g_dbglevel
>= DBG_DEBUG
) DbpString("Error preparing tag response");
1970 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1973 p_response
= &dynamic_response_info
;
1977 // Count number of wakeups received after a halt
1978 // if (order == ORDER_WUPA && lastorder == ORDER_HALTED) { happened++; }
1980 // Count number of other messages after a halt
1981 // if (order != ORDER_WUPA && lastorder == ORDER_HALTED) { happened2++; }
1986 EmSendPrecompiledCmd(p_response
);
1992 BigBuf_free_keep_EM();
1994 if (g_dbglevel
>= DBG_EXTENDED
) {
1995 // Dbprintf("-[ Wake ups after halt [%d]", happened);
1996 // Dbprintf("-[ Messages after halt [%d]", happened2);
1997 Dbprintf("-[ Num of received cmd [%d]", cmdsRecvd
);
1998 Dbprintf("-[ Num of moebius tries [%d]", moebius_count
);
2001 reply_ng(CMD_HF_MIFARE_SIMULATE
, retval
, NULL
, 0);
2004 // prepare a delayed transfer. This simply shifts ToSend[] by a number
2005 // of bits specified in the delay parameter.
2006 static void PrepareDelayedTransfer(uint16_t delay
) {
2010 uint8_t bitmask
= 0;
2011 uint8_t bits_shifted
= 0;
2013 for (uint16_t i
= 0; i
< delay
; i
++)
2014 bitmask
|= (0x01 << i
);
2016 tosend_t
*ts
= get_tosend();
2018 ts
->buf
[ts
->max
++] = 0x00;
2020 for (uint32_t i
= 0; i
< ts
->max
; i
++) {
2021 uint8_t bits_to_shift
= ts
->buf
[i
] & bitmask
;
2022 ts
->buf
[i
] = ts
->buf
[i
] >> delay
;
2023 ts
->buf
[i
] = ts
->buf
[i
] | (bits_shifted
<< (8 - delay
));
2024 bits_shifted
= bits_to_shift
;
2029 //-------------------------------------------------------------------------------------
2030 // Transmit the command (to the tag) that was placed in ToSend[].
2031 // Parameter timing:
2032 // if NULL: transfer at next possible time, taking into account
2033 // request guard time and frame delay time
2034 // if == 0: transfer immediately and return time of transfer
2035 // if != 0: delay transfer until time specified
2036 //-------------------------------------------------------------------------------------
2037 static void TransmitFor14443a(const uint8_t *cmd
, uint16_t len
, uint32_t *timing
) {
2039 if (g_hf_field_active
== false) {
2040 Dbprintf("Warning: HF field is off");
2043 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2046 if (*timing
== 0) // Measure time
2047 *timing
= (GetCountSspClk() + 8) & 0xfffffff8;
2049 PrepareDelayedTransfer(*timing
& 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
2051 while (GetCountSspClk() < (*timing
& 0xfffffff8)) {}; // Delay transfer (multiple of 8 MF clock ticks)
2052 LastTimeProxToAirStart
= *timing
;
2055 uint32_t ThisTransferTime
= 0;
2056 ThisTransferTime
= ((MAX(NextTransferTime
, GetCountSspClk()) & 0xfffffff8) + 8);
2058 while (GetCountSspClk() < ThisTransferTime
) {};
2060 LastTimeProxToAirStart
= ThisTransferTime
;
2065 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2066 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
2071 NextTransferTime
= MAX(NextTransferTime
, LastTimeProxToAirStart
+ REQUEST_GUARD_TIME
);
2074 //-----------------------------------------------------------------------------
2075 // Prepare reader command (in bits, support short frames) to send to FPGA
2076 //-----------------------------------------------------------------------------
2077 static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd
, uint16_t bits
, const uint8_t *par
) {
2081 tosend_t
*ts
= get_tosend();
2083 // Start of Communication (Seq. Z)
2084 ts
->buf
[++ts
->max
] = SEC_Z
;
2085 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2087 size_t bytecount
= nbytes(bits
);
2088 // Generate send structure for the data bits
2089 for (int i
= 0; i
< bytecount
; i
++) {
2090 // Get the current byte to send
2092 size_t bitsleft
= MIN((bits
- (i
* 8)), 8);
2094 for (j
= 0; j
< bitsleft
; j
++) {
2097 ts
->buf
[++ts
->max
] = SEC_X
;
2098 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 2;
2103 ts
->buf
[++ts
->max
] = SEC_Z
;
2104 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2107 ts
->buf
[++ts
->max
] = SEC_Y
;
2114 // Only transmit parity bit if we transmitted a complete byte
2115 if (j
== 8 && par
!= NULL
) {
2116 // Get the parity bit
2117 if (par
[i
>> 3] & (0x80 >> (i
& 0x0007))) {
2119 ts
->buf
[++ts
->max
] = SEC_X
;
2120 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 2;
2125 ts
->buf
[++ts
->max
] = SEC_Z
;
2126 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2129 ts
->buf
[++ts
->max
] = SEC_Y
;
2136 // End of Communication: Logic 0 followed by Sequence Y
2139 ts
->buf
[++ts
->max
] = SEC_Z
;
2140 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2143 ts
->buf
[++ts
->max
] = SEC_Y
;
2145 ts
->buf
[++ts
->max
] = SEC_Y
;
2147 // Convert to length of command:
2151 //-----------------------------------------------------------------------------
2152 // Prepare reader command to send to FPGA
2153 //-----------------------------------------------------------------------------
2155 static void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *par) {
2156 CodeIso14443aBitsAsReaderPar(cmd, len * 8, par);
2159 //-----------------------------------------------------------------------------
2160 // Wait for commands from reader
2161 // Stop when button is pressed (return 1) or field was gone (return 2)
2162 // Or return 0 when command is captured
2163 //-----------------------------------------------------------------------------
2164 int EmGetCmd(uint8_t *received
, uint16_t received_max_len
, uint16_t *len
, uint8_t *par
) {
2171 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
2172 // only, since we are receiving, not transmitting).
2173 // Signal field is off with the appropriate LED
2175 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2177 // Set ADC to read field strength
2178 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
2179 AT91C_BASE_ADC
->ADC_MR
=
2180 ADC_MODE_PRESCALE(63) |
2181 ADC_MODE_STARTUP_TIME(1) |
2182 ADC_MODE_SAMPLE_HOLD_TIME(15);
2184 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
2187 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
2189 // Now run a 'software UART' on the stream of incoming samples.
2190 Uart14aInit(received
, received_max_len
, par
);
2193 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2197 uint16_t checker
= 4000;
2201 // ever 3 * 4000, check if we got any data from client
2202 // takes long time, usually messes with simualtion
2204 if (data_available()) {
2205 Dbprintf("----------- " _GREEN_("Breaking / Data") " ----------");
2211 // button press, takes a bit time, might mess with simualtion
2212 if (checker
-- == 0) {
2213 if (BUTTON_PRESS()) {
2214 Dbprintf("----------- " _GREEN_("Breaking / User aborted") " ----------");
2223 // test if the field exists
2224 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
2228 analogAVG
+= (AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
] & 0x3FF);
2230 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
2232 if (analogCnt
>= 32) {
2234 if ((MAX_ADC_HF_VOLTAGE
* (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
2237 timer
= GetTickCount();
2239 // 4ms no field --> card to idle state
2240 if (GetTickCountDelta(timer
) > 4) {
2252 // receive and test the miller decoding
2253 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2254 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2255 if (MillerDecoding(b
, 0)) {
2263 int EmSendCmd14443aRaw(const uint8_t *resp
, uint16_t respLen
) {
2266 uint32_t ThisTransferTime
= 0;
2267 bool correction_needed
;
2269 // Modulate Manchester
2270 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
2272 // Include correction bit if necessary
2273 if (Uart
.bitCount
== 7) {
2274 // Short tags (7 bits) don't have parity, determine the correct value from MSB
2275 correction_needed
= Uart
.output
[0] & 0x40;
2277 // The parity bits are left-aligned
2278 correction_needed
= Uart
.parity
[(Uart
.len
- 1) / 8] & (0x80 >> ((Uart
.len
- 1) & 7));
2280 // 1236, so correction bit needed
2281 i
= (correction_needed
) ? 0 : 1;
2283 // clear receiving shift register and holding register
2284 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
2285 b
= AT91C_BASE_SSC
->SSC_RHR
;
2288 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
2289 for (uint8_t j
= 0; j
< 5; j
++) { // allow timeout - better late than never
2290 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
2291 if (AT91C_BASE_SSC
->SSC_RHR
) {
2296 while ((ThisTransferTime
= GetCountSspClk()) & 0x00000007);
2299 AT91C_BASE_SSC
->SSC_THR
= SEC_F
;
2302 for (; i
< respLen
;) {
2303 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2304 AT91C_BASE_SSC
->SSC_THR
= resp
[i
++];
2305 FpgaSendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2309 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
2310 uint8_t fpga_queued_bits
= FpgaSendQueueDelay
>> 3;
2311 for (i
= 0; i
<= (fpga_queued_bits
>> 3) + 1;) {
2312 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2313 AT91C_BASE_SSC
->SSC_THR
= SEC_F
;
2314 FpgaSendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2318 LastTimeProxToAirStart
= ThisTransferTime
+ (correction_needed
? 8 : 0);
2322 int EmSend4bit(uint8_t resp
) {
2323 Code4bitAnswerAsTag(resp
);
2324 tosend_t
*ts
= get_tosend();
2325 int res
= EmSendCmd14443aRaw(ts
->buf
, ts
->max
);
2326 // do the tracing for the previous reader request and this tag answer:
2327 uint8_t par
[1] = {0x00};
2328 GetParity(&resp
, 1, par
);
2329 EmLogTrace(Uart
.output
,
2331 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2332 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2336 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2337 (LastTimeProxToAirStart
+ LastProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2341 int EmSendCmdPar(uint8_t *resp
, uint16_t respLen
, uint8_t *par
) {
2342 return EmSendCmdParEx(resp
, respLen
, par
, false);
2344 int EmSendCmdParEx(uint8_t *resp
, uint16_t respLen
, uint8_t *par
, bool collision
) {
2345 CodeIso14443aAsTagPar(resp
, respLen
, par
, collision
);
2346 tosend_t
*ts
= get_tosend();
2347 int res
= EmSendCmd14443aRaw(ts
->buf
, ts
->max
);
2349 // do the tracing for the previous reader request and this tag answer:
2350 EmLogTrace(Uart
.output
,
2352 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2353 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2357 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2358 (LastTimeProxToAirStart
+ LastProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2362 int EmSendCmd(uint8_t *resp
, uint16_t respLen
) {
2363 return EmSendCmdEx(resp
, respLen
, false);
2365 int EmSendCmdEx(uint8_t *resp
, uint16_t respLen
, bool collision
) {
2366 GetParity(resp
, respLen
, parity_array
);
2367 return EmSendCmdParEx(resp
, respLen
, parity_array
, collision
);
2370 int EmSendPrecompiledCmd(tag_response_info_t
*p_response
) {
2371 if (p_response
== NULL
) return 0;
2372 int ret
= EmSendCmd14443aRaw(p_response
->modulation
, p_response
->modulation_n
);
2373 // do the tracing for the previous reader request and this tag answer:
2374 GetParity(p_response
->response
, p_response
->response_n
, parity_array
);
2376 EmLogTrace(Uart
.output
,
2378 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2379 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2381 p_response
->response
,
2382 p_response
->response_n
,
2383 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2384 (LastTimeProxToAirStart
+ p_response
->ProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2389 bool EmLogTrace(uint8_t *reader_data
, uint16_t reader_len
, uint32_t reader_StartTime
,
2390 uint32_t reader_EndTime
, uint8_t *reader_Parity
, uint8_t *tag_data
,
2391 uint16_t tag_len
, uint32_t tag_StartTime
, uint32_t tag_EndTime
, uint8_t *tag_Parity
) {
2393 // we cannot exactly measure the end and start of a received command from reader. However we know that the delay from
2394 // end of the received command to start of the tag's (simulated by us) answer is n*128+20 or n*128+84 resp.
2395 // with n >= 9. The start of the tags answer can be measured and therefore the end of the received command be calculated:
2397 uint16_t reader_modlen
= reader_EndTime
- reader_StartTime
;
2398 uint16_t approx_fdt
= tag_StartTime
- reader_EndTime
;
2399 uint16_t exact_fdt
= (approx_fdt
- 20 + 32) / 64 * 64 + 20;
2400 reader_EndTime
= tag_StartTime
- exact_fdt
;
2401 reader_StartTime
= reader_EndTime
- reader_modlen
;
2403 if (!LogTrace(reader_data
, reader_len
, reader_StartTime
, reader_EndTime
, reader_Parity
, true))
2406 return (!LogTrace(tag_data
, tag_len
, tag_StartTime
, tag_EndTime
, tag_Parity
, false));
2410 //-----------------------------------------------------------------------------
2411 // Kovio - Thinfilm barcode. TAG-TALK-FIRST -
2412 // Wait a certain time for tag response
2413 // If a response is captured return TRUE
2414 // If it takes too long return FALSE
2415 //-----------------------------------------------------------------------------
2416 bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse
, uint16_t rec_maxlen
, uint8_t *received_len
) {
2418 if (g_hf_field_active
== false) {
2419 Dbprintf("Warning: HF field is off");
2423 // Set FPGA mode to "reader listen mode", no modulation (listen
2424 // only, since we are receiving, not transmitting).
2425 // Signal field is on with the appropriate LED
2427 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
2429 // Now get the answer from the card
2430 Demod14aInit(receivedResponse
, rec_maxlen
, NULL
);
2433 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2436 uint32_t timeout
= iso14a_get_timeout();
2437 uint32_t receive_timer
= GetTickCount();
2442 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2443 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2444 if (ManchesterDecoding_Thinfilm(b
)) {
2445 *received_len
= Demod
.len
;
2446 LogTrace(receivedResponse
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, NULL
, false);
2451 if (GetTickCountDelta(receive_timer
) > timeout
+ 100) {
2456 *received_len
= Demod
.len
;
2457 LogTrace(receivedResponse
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, NULL
, false);
2462 //-----------------------------------------------------------------------------
2463 // Wait a certain time for tag response
2464 // If a response is captured return TRUE
2465 // If it takes too long return FALSE
2466 //-----------------------------------------------------------------------------
2467 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, uint16_t rec_maxlen
, uint8_t *receivedResponsePar
, uint16_t offset
) {
2468 if (g_hf_field_active
== false) {
2469 Dbprintf("Warning: HF field is off");
2473 // Set FPGA mode to "reader listen mode", no modulation (listen
2474 // only, since we are receiving, not transmitting).
2475 // Signal field is on with the appropriate LED
2477 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
2479 // Now get the answer from the card
2480 Demod14aInit(receivedResponse
, rec_maxlen
, receivedResponsePar
);
2483 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2486 volatile uint32_t c
= 0;
2487 uint32_t timeout
= iso14a_get_timeout();
2488 uint32_t receive_timer
= GetTickCount();
2492 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2493 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2494 if (ManchesterDecoding(b
, offset
, 0)) {
2495 NextTransferTime
= MAX(NextTransferTime
, Demod
.endTime
- (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 16 + FRAME_DELAY_TIME_PICC_TO_PCD
);
2497 } else if (c
++ > timeout
&& Demod
.state
== DEMOD_14A_UNSYNCD
) {
2502 // timeout already in ms + 100ms guard time
2503 if (GetTickCountDelta(receive_timer
) > timeout
+ 100) {
2510 void ReaderTransmitBitsPar(uint8_t *frame
, uint16_t bits
, uint8_t *par
, uint32_t *timing
) {
2512 CodeIso14443aBitsAsReaderPar(frame
, bits
, par
);
2513 // Send command to tag
2514 tosend_t
*ts
= get_tosend();
2515 TransmitFor14443a(ts
->buf
, ts
->max
, timing
);
2516 if (g_trigger
) LED_A_ON();
2518 LogTrace(frame
, nbytes(bits
), (LastTimeProxToAirStart
<< 4) + DELAY_ARM2AIR_AS_READER
, ((LastTimeProxToAirStart
+ LastProxToAirDuration
) << 4) + DELAY_ARM2AIR_AS_READER
, par
, true);
2521 void ReaderTransmitPar(uint8_t *frame
, uint16_t len
, uint8_t *par
, uint32_t *timing
) {
2522 ReaderTransmitBitsPar(frame
, len
* 8, par
, timing
);
2525 static void ReaderTransmitBits(uint8_t *frame
, uint16_t len
, uint32_t *timing
) {
2526 // Generate parity and redirect
2527 GetParity(frame
, len
/ 8, parity_array
);
2528 ReaderTransmitBitsPar(frame
, len
, parity_array
, timing
);
2531 void ReaderTransmit(uint8_t *frame
, uint16_t len
, uint32_t *timing
) {
2532 // Generate parity and redirect
2533 GetParity(frame
, len
, parity_array
);
2534 ReaderTransmitBitsPar(frame
, len
* 8, parity_array
, timing
);
2537 static uint16_t ReaderReceiveOffset(uint8_t *receivedAnswer
, uint16_t answer_len
, uint16_t offset
, uint8_t *par
) {
2538 if (GetIso14443aAnswerFromTag(receivedAnswer
, answer_len
, par
, offset
) == false) {
2541 LogTrace(receivedAnswer
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, par
, false);
2545 uint16_t ReaderReceive(uint8_t *receivedAnswer
, uint16_t answer_maxlen
, uint8_t *par
) {
2546 if (GetIso14443aAnswerFromTag(receivedAnswer
, answer_maxlen
, par
, 0) == false) {
2549 LogTrace(receivedAnswer
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, par
, false);
2554 // This function misstreats the ISO 14443a anticollision procedure.
2555 // by fooling the reader there is a collision and forceing the reader to
2556 // increase the uid bytes. The might be an overflow, DoS will occur.
2557 void iso14443a_antifuzz(uint32_t flags
) {
2559 // We need to listen to the high-frequency, peak-detected path.
2560 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2562 BigBuf_free_keep_EM();
2568 // allocate buffers:
2569 uint8_t *received
= BigBuf_malloc(MAX_FRAME_SIZE
);
2570 uint8_t *receivedPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
2571 uint8_t *resp
= BigBuf_malloc(20);
2573 memset(received
, 0x00, MAX_FRAME_SIZE
);
2574 memset(received
, 0x00, MAX_PARITY_SIZE
);
2575 memset(resp
, 0xFF, 20);
2581 // Clean receive command buffer
2582 if (!GetIso14443aCommandFromReader(received
, MAX_FRAME_SIZE
, receivedPar
, &len
)) {
2583 Dbprintf("Anti-fuzz stopped. Trace length: %d ", BigBuf_get_traceLen());
2586 if (received
[0] == ISO14443A_CMD_WUPA
|| received
[0] == ISO14443A_CMD_REQA
) {
2590 if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
2598 // Received request for UID (cascade 1)
2599 //if (received[1] >= 0x20 && received[1] <= 0x57 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) {
2600 if (received
[1] >= 0x20 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
) {
2605 resp
[4] = resp
[0] ^ resp
[1] ^ resp
[2] ^ resp
[3];
2608 if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
2609 resp
[0] = MIFARE_SELECT_CT
;
2613 // trigger a faulty/collision response
2614 EmSendCmdEx(resp
, 5, true);
2615 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("ANTICOLL or SELECT %x", received
[1]);
2619 } else if (received
[1] == 0x20 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
) { // Received request for UID (cascade 2)
2620 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("ANTICOLL or SELECT_2");
2621 } else if (received
[1] == 0x70 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
) { // Received a SELECT (cascade 1)
2622 } else if (received
[1] == 0x70 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
) { // Received a SELECT (cascade 2)
2624 Dbprintf("unknown command %x", received
[0]);
2628 reply_ng(CMD_HF_ISO14443A_ANTIFUZZ
, PM3_SUCCESS
, NULL
, 0);
2630 BigBuf_free_keep_EM();
2633 static void iso14a_set_ATS_times(const uint8_t *ats
) {
2635 if (ats
[0] > 1) { // there is a format byte T0
2636 if ((ats
[1] & 0x20) == 0x20) { // there is an interface byte TB(1)
2638 if ((ats
[1] & 0x10) == 0x10) { // there is an interface byte TA(1) preceding TB(1)
2643 uint8_t fwi
= (tb1
& 0xf0) >> 4; // frame waiting time integer (FWI)
2645 uint32_t fwt
= 256 * 16 * (1 << fwi
); // frame waiting time (FWT) in 1/fc
2646 iso14a_set_timeout(fwt
/ (8 * 16));
2648 uint8_t sfgi
= tb1
& 0x0f; // startup frame guard time integer (SFGI)
2649 if (sfgi
!= 0 && sfgi
!= 15) {
2650 uint32_t sfgt
= 256 * 16 * (1 << sfgi
); // startup frame guard time (SFGT) in 1/fc
2651 NextTransferTime
= MAX(NextTransferTime
, Demod
.endTime
+ (sfgt
- DELAY_AIR2ARM_AS_READER
- DELAY_ARM2AIR_AS_READER
) / 16);
2658 static int GetATQA(uint8_t *resp
, uint16_t resp_len
, uint8_t *resp_par
, iso14a_polling_parameters_t
*polling_parameters
) {
2659 #define WUPA_RETRY_TIMEOUT 10
2661 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
2662 iso14a_set_timeout(1236 / 128 + 1); // response to WUPA is expected at exactly 1236/fc. No need to wait longer.
2664 bool first_try
= true;
2665 uint32_t retry_timeout
= WUPA_RETRY_TIMEOUT
* polling_parameters
->frame_count
+ polling_parameters
->extra_timeout
;
2666 uint32_t start_time
= 0;
2669 uint8_t current_frame
= 0;
2672 iso14a_polling_frame_t
*frame_parameters
= &polling_parameters
->frames
[current_frame
];
2674 if (frame_parameters
->last_byte_bits
== 8) {
2675 ReaderTransmit(frame_parameters
->frame
, frame_parameters
->frame_length
, NULL
);
2677 ReaderTransmitBitsPar(frame_parameters
->frame
, frame_parameters
->last_byte_bits
, NULL
, NULL
);
2680 if (frame_parameters
->extra_delay
) {
2681 SpinDelay(frame_parameters
->extra_delay
);
2685 len
= ReaderReceive(resp
, resp_len
, resp_par
);
2687 // We set the start_time here otherwise in some cases we miss the window and only ever try once
2689 start_time
= GetTickCount();
2694 // Go over frame configurations, loop back when we reach the end
2695 current_frame
= current_frame
< (polling_parameters
->frame_count
- 1) ? current_frame
+ 1 : 0;
2696 } while (len
== 0 && GetTickCountDelta(start_time
) <= retry_timeout
);
2698 iso14a_set_timeout(save_iso14a_timeout
);
2703 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
) {
2704 return iso14443a_select_cardEx(uid_ptr
, p_card
, cuid_ptr
, anticollision
, num_cascades
, no_rats
, &WUPA_POLLING_PARAMETERS
);
2708 // performs iso14443a anticollision (optional) and card select procedure
2709 // fills the uid and cuid pointer unless NULL
2710 // fills the card info record unless NULL
2711 // if anticollision is false, then the UID must be provided in uid_ptr[]
2712 // and num_cascades must be set (1: 4 Byte UID, 2: 7 Byte UID, 3: 10 Byte UID)
2713 // requests ATS unless no_rats is true
2714 int iso14443a_select_cardEx(uint8_t *uid_ptr
, iso14a_card_select_t
*p_card
, uint32_t *cuid_ptr
,
2715 bool anticollision
, uint8_t num_cascades
, bool no_rats
,
2716 iso14a_polling_parameters_t
*polling_parameters
) {
2718 uint8_t resp
[MAX_FRAME_SIZE
] = {0}; // theoretically. A usual RATS will be much smaller
2720 uint8_t sak
= 0; // cascade uid
2721 bool do_cascade
= 1;
2722 int cascade_level
= 0;
2726 memset(p_card
->uid
, 0, 10);
2727 p_card
->ats_len
= 0;
2730 if (GetATQA(resp
, sizeof(resp
), parity_array
, polling_parameters
) == 0) {
2735 p_card
->atqa
[0] = resp
[0];
2736 p_card
->atqa
[1] = resp
[1];
2739 // 11RF005SH or 11RF005M, Read UID again
2740 if (p_card
&& p_card
->atqa
[1] == 0x00) {
2742 if ((p_card
->atqa
[0] == 0x03) || (p_card
->atqa
[0] == 0x05)) {
2745 uint8_t fudan_read
[] = { 0x30, 0x01, 0x8B, 0xB9};
2746 ReaderTransmit(fudan_read
, sizeof(fudan_read
), NULL
);
2747 if (ReaderReceive(resp
, sizeof(resp
), parity_array
) == 0) {
2748 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Card didn't answer to select all");
2752 memcpy(p_card
->uid
, resp
, 4);
2755 if (GetATQA(resp
, sizeof(resp
), parity_array
, &WUPA_POLLING_PARAMETERS
) == 0) {
2759 if (GetATQA(resp
, sizeof(resp
), parity_array
, &WUPA_POLLING_PARAMETERS
) == 0) {
2769 if (anticollision
) {
2772 memset(uid_ptr
, 0, 10);
2775 if (hf14aconfig
.forceanticol
== 0) {
2776 // check for proprietary anticollision:
2777 if ((resp
[0] & 0x1F) == 0) {
2781 } else if (hf14aconfig
.forceanticol
== 2) {
2782 return 3; // force skipping anticol
2783 } // else force executing
2785 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
2786 // which case we need to make a cascade 2 request and select - this is a long UID
2787 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
2788 for (; do_cascade
; cascade_level
++) {
2789 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
2790 uint8_t sel_all
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x20 };
2791 uint8_t sel_uid
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
2792 uint8_t uid_resp
[5] = {0}; // UID + original BCC
2793 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
2795 if (anticollision
) {
2798 ReaderTransmit(sel_all
, sizeof(sel_all
), NULL
);
2799 if (ReaderReceive(resp
, sizeof(resp
), parity_array
) == 0) {
2800 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Card didn't answer to CL%i select all", cascade_level
+ 1);
2804 if (Demod
.collisionPos
) { // we had a collision and need to construct the UID bit by bit
2805 memset(uid_resp
, 0, 5);
2806 uint16_t uid_resp_bits
= 0;
2807 uint16_t collision_answer_offset
= 0;
2809 // anti-collision-loop:
2810 while (Demod
.collisionPos
) {
2811 Dbprintf("Multiple tags detected. Collision after Bit %d", Demod
.collisionPos
);
2813 for (uint16_t i
= collision_answer_offset
; i
< Demod
.collisionPos
; i
++, uid_resp_bits
++) { // add valid UID bits before collision point
2814 uint16_t UIDbit
= (resp
[i
/ 8] >> (i
% 8)) & 0x01;
2815 uid_resp
[uid_resp_bits
/ 8] |= UIDbit
<< (uid_resp_bits
% 8);
2818 uid_resp
[uid_resp_bits
/ 8] |= 1 << (uid_resp_bits
% 8); // next time select the card(s) with a 1 in the collision position
2820 // construct anticollision command:
2821 sel_uid
[1] = ((2 + uid_resp_bits
/ 8) << 4) | (uid_resp_bits
& 0x07); // length of data in bytes and bits
2822 for (uint16_t i
= 0; i
<= uid_resp_bits
/ 8; i
++) {
2823 sel_uid
[2 + i
] = uid_resp
[i
];
2826 collision_answer_offset
= uid_resp_bits
% 8;
2828 ReaderTransmitBits(sel_uid
, 16 + uid_resp_bits
, NULL
);
2829 if (ReaderReceiveOffset(resp
, sizeof(resp
), collision_answer_offset
, parity_array
) == 0) {
2834 // finally, add the last bits and BCC of the UID
2835 for (uint32_t i
= collision_answer_offset
; i
< Demod
.len
* 8; i
++, uid_resp_bits
++) {
2836 uint16_t UIDbit
= (resp
[i
/ 8] >> (i
% 8)) & 0x01;
2837 uid_resp
[uid_resp_bits
/ 8] |= UIDbit
<< (uid_resp_bits
% 8);
2840 } else { // no collision, use the response to SELECT_ALL as current uid
2841 memcpy(uid_resp
, resp
, 5); // UID + original BCC
2845 if (cascade_level
< num_cascades
- 1) {
2846 uid_resp
[0] = MIFARE_SELECT_CT
;
2847 memcpy(uid_resp
+ 1, uid_ptr
+ cascade_level
* 3, 3);
2849 memcpy(uid_resp
, uid_ptr
+ cascade_level
* 3, 4);
2852 size_t uid_resp_len
= 4;
2854 // calculate crypto UID. Always use last 4 Bytes.
2856 *cuid_ptr
= bytes_to_num(uid_resp
, 4);
2858 // Construct SELECT UID command
2859 sel_uid
[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
2861 if (anticollision
) {
2863 memcpy(sel_uid
+ 2, uid_resp
, 5); // the UID received during anticollision with original BCC
2864 uint8_t bcc
= sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate BCC
2865 if (sel_uid
[6] != bcc
) {
2867 Dbprintf("BCC%d incorrect, got 0x%02x, expected 0x%02x", cascade_level
, sel_uid
[6], bcc
);
2869 if (hf14aconfig
.forcebcc
== 0) {
2870 Dbprintf("Aborting");
2872 } else if (hf14aconfig
.forcebcc
== 1) {
2874 } // else use card BCC
2876 Dbprintf("Using BCC%d =" _YELLOW_("0x%02x"), cascade_level
, sel_uid
[6]);
2879 memcpy(sel_uid
+ 2, uid_resp
, 4); // the provided UID
2880 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
2883 AddCrc14A(sel_uid
, 7); // calculate and add CRC
2884 ReaderTransmit(sel_uid
, sizeof(sel_uid
), NULL
);
2887 if (ReaderReceive(resp
, sizeof(resp
), parity_array
) == 0) {
2888 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Card didn't answer to select");
2893 // Test if more parts of the uid are coming
2894 do_cascade
= (((sak
& 0x04) /* && uid_resp[0] == MIFARE_SELECT_CT */) > 0);
2896 if (cascade_level
== 0) {
2898 if (hf14aconfig
.forcecl2
== 2) {
2900 } else if (hf14aconfig
.forcecl2
== 1) {
2903 } else if (cascade_level
== 1) {
2905 if (hf14aconfig
.forcecl3
== 2) {
2907 } else if (hf14aconfig
.forcecl3
== 1) {
2912 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
2913 // http://www.nxp.com/documents/application_note/AN10927.pdf
2914 uid_resp
[0] = uid_resp
[1];
2915 uid_resp
[1] = uid_resp
[2];
2916 uid_resp
[2] = uid_resp
[3];
2920 if (uid_ptr
&& anticollision
)
2921 memcpy(uid_ptr
+ (cascade_level
* 3), uid_resp
, uid_resp_len
);
2924 memcpy(p_card
->uid
+ (cascade_level
* 3), uid_resp
, uid_resp_len
);
2925 p_card
->uidlen
+= uid_resp_len
;
2933 if (hf14aconfig
.forcerats
== 0) {
2934 // PICC compliant with iso14443a-4 ---> (SAK & 0x20 != 0)
2935 if ((sak
& 0x20) == 0) {
2939 } else if (hf14aconfig
.forcerats
== 2) {
2940 if ((sak
& 0x20) != 0) Dbprintf("Skipping RATS according to hf 14a config");
2942 } // else force RATS
2944 if ((sak
& 0x20) == 0) Dbprintf("Forcing RATS according to hf 14a config");
2946 // RATS, Request for answer to select
2947 if (no_rats
== false) {
2949 uint8_t rats
[] = { ISO14443A_CMD_RATS
, 0x80, 0x31, 0x73 }; // FSD=256, FSDI=8, CID=0
2950 ReaderTransmit(rats
, sizeof(rats
), NULL
);
2951 int len
= ReaderReceive(resp
, sizeof(resp
), parity_array
);
2957 memcpy(p_card
->ats
, resp
, sizeof(p_card
->ats
));
2958 p_card
->ats_len
= len
;
2961 // reset the PCB block number
2962 iso14_pcb_blocknum
= 0;
2964 // set default timeout and delay next transfer based on ATS
2965 iso14a_set_ATS_times(resp
);
2970 int iso14443a_fast_select_card(uint8_t *uid_ptr
, uint8_t num_cascades
) {
2971 uint8_t resp
[3] = { 0 }; // theoretically. max 1 Byte SAK, 2 Byte CRC, 3 bytes is enough
2972 uint8_t resp_par
[1] = {0};
2974 uint8_t sak
= 0x04; // cascade uid
2975 int cascade_level
= 1;
2977 if (GetATQA(resp
, sizeof(resp
), resp_par
, &WUPA_POLLING_PARAMETERS
) == 0) {
2981 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
2982 // which case we need to make a cascade 2 request and select - this is a long UID
2983 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
2984 for (; sak
& 0x04; cascade_level
++) {
2985 // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
2986 uint8_t sel_uid
[9] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x70 };
2988 // Construct SELECT UID command
2989 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
2990 sel_uid
[0] = ISO14443A_CMD_ANTICOLL_OR_SELECT
+ (cascade_level
- 1) * 2;
2993 if (cascade_level
< num_cascades
) {
2994 sel_uid
[2] = MIFARE_SELECT_CT
;
2995 memcpy(&sel_uid
[3], uid_ptr
+ (cascade_level
- 1) * 3, 3);
2997 memcpy(&sel_uid
[2], uid_ptr
+ (cascade_level
- 1) * 3, 4);
3000 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
3001 AddCrc14A(sel_uid
, 7); // calculate and add CRC
3002 ReaderTransmit(sel_uid
, sizeof(sel_uid
), NULL
);
3004 // Receive 1 Byte SAK, 2 Byte CRC
3005 if (ReaderReceive(resp
, sizeof(resp
), resp_par
) != 3) {
3014 void iso14443a_setup(uint8_t fpga_minor_mode
) {
3016 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
3017 // Set up the synchronous serial port
3018 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A
);
3019 // connect Demodulated Signal to ADC:
3020 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
3023 // Signal field is on with the appropriate LED
3024 if (fpga_minor_mode
== FPGA_HF_ISO14443A_READER_MOD
|| fpga_minor_mode
== FPGA_HF_ISO14443A_READER_LISTEN
)
3027 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| fpga_minor_mode
);
3033 // Prepare the demodulation functions
3036 NextTransferTime
= 2 * DELAY_ARM2AIR_AS_READER
;
3037 iso14a_set_timeout(1060); // 106 * 10ms default
3039 g_hf_field_active
= true;
3042 /* Peter Fillmore 2015
3043 Added card id field to the function info from ISO14443A standard
3047 b3 = depends on block
3048 b4 = Card ID following if set to 1
3049 b5 = depends on block type
3050 b6 = depends on block type
3054 b8 b7 b6 b5 b4 b3 b2 b1
3059 b8 b7 b6 b5 b4 b3 b2 b1
3064 b8 b7 b6 b5 b4 b3 b2 b1
3066 b5,b6 = 00 - DESELECT
3069 int iso14_apdu(uint8_t *cmd
, uint16_t cmd_len
, bool send_chaining
, void *data
, uint16_t data_len
, uint8_t *res
) {
3070 uint8_t *real_cmd
= BigBuf_calloc(cmd_len
+ 4);
3073 // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02
3074 real_cmd
[0] = 0x02; // bnr,nad,cid,chn=0; i-block(0x00)
3075 if (send_chaining
) {
3076 real_cmd
[0] |= 0x10;
3078 // put block number into the PCB
3079 real_cmd
[0] |= iso14_pcb_blocknum
;
3080 memcpy(real_cmd
+ 1, cmd
, cmd_len
);
3083 real_cmd
[0] = 0xA2; // r-block + ACK
3084 real_cmd
[0] |= iso14_pcb_blocknum
;
3086 AddCrc14A(real_cmd
, cmd_len
+ 1);
3088 ReaderTransmit(real_cmd
, cmd_len
+ 3, NULL
);
3090 size_t len
= ReaderReceive(data
, data_len
, parity_array
);
3091 uint8_t *data_bytes
= (uint8_t *) data
;
3095 return 0; // DATA LINK ERROR
3098 while (len
&& ((data_bytes
[0] & 0xF2) == 0xF2)) {
3099 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
3100 // temporarily increase timeout
3101 iso14a_set_timeout(MAX((data_bytes
[1] & 0x3f) * save_iso14a_timeout
, MAX_ISO14A_TIMEOUT
));
3102 // Transmit WTX back
3103 // byte1 - WTXM [1..59]. command FWT=FWT*WTXM
3104 data_bytes
[1] = data_bytes
[1] & 0x3f; // 2 high bits mandatory set to 0b
3105 // now need to fix CRC.
3106 AddCrc14A(data_bytes
, len
- 2);
3108 ReaderTransmit(data_bytes
, len
, NULL
);
3109 // retrieve the result again (with increased timeout)
3110 len
= ReaderReceive(data
, data_len
, parity_array
);
3113 iso14a_set_timeout(save_iso14a_timeout
);
3116 // if we received an I- or R(ACK)-Block with a block number equal to the
3117 // current block number, toggle the current block number
3118 if (len
>= 3 // PCB+CRC = 3 bytes
3119 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
3120 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
3121 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) { // equal block numbers
3122 iso14_pcb_blocknum
^= 1;
3125 // if we received I-block with chaining we need to send ACK and receive another block of data
3127 *res
= data_bytes
[0];
3131 if (len
>= 3 && !CheckCrc14A(data_bytes
, len
)) {
3141 // memmove(data_bytes, data_bytes + 1, len);
3142 for (int i
= 0; i
< len
; i
++) {
3143 data_bytes
[i
] = data_bytes
[i
+ 1];
3151 //-----------------------------------------------------------------------------
3152 // Read an ISO 14443a tag. Send out commands and store answers.
3153 //-----------------------------------------------------------------------------
3154 // arg0 iso_14a flags
3155 // arg1 high :: number of bits, if you want to send 7bits etc
3156 // low :: len of commandbytes
3158 // d.asBytes command bytes to send
3159 void ReaderIso14443a(PacketCommandNG
*c
) {
3160 iso14a_command_t param
= c
->oldarg
[0];
3161 size_t len
= c
->oldarg
[1] & 0xffff;
3162 size_t lenbits
= c
->oldarg
[1] >> 16;
3163 uint32_t timeout
= c
->oldarg
[2];
3164 uint8_t *cmd
= c
->data
.asBytes
;
3167 uint8_t buf
[PM3_CMD_DATA_SIZE_MIX
] = {0x00};
3169 if ((param
& ISO14A_CONNECT
) == ISO14A_CONNECT
) {
3170 iso14_pcb_blocknum
= 0;
3176 if ((param
& ISO14A_REQUEST_TRIGGER
) == ISO14A_REQUEST_TRIGGER
) {
3177 iso14a_set_trigger(true);
3180 if ((param
& ISO14A_CONNECT
) == ISO14A_CONNECT
) {
3181 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3183 // notify client selecting status.
3184 // if failed selecting, turn off antenna and quit.
3185 if ((param
& ISO14A_NO_SELECT
) != ISO14A_NO_SELECT
) {
3186 iso14a_card_select_t
*card
= (iso14a_card_select_t
*)buf
;
3188 arg0
= iso14443a_select_cardEx(
3194 ((param
& ISO14A_NO_RATS
) == ISO14A_NO_RATS
),
3195 ((param
& ISO14A_USE_CUSTOM_POLLING
) == ISO14A_USE_CUSTOM_POLLING
) ? (iso14a_polling_parameters_t
*)cmd
: &WUPA_POLLING_PARAMETERS
3197 // TODO: Improve by adding a cmd parser pointer and moving it by struct length to allow combining data with polling params
3198 FpgaDisableTracing();
3200 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3201 crypto1_auth_state
= AUTH_FIRST
;
3202 crypto1_deinit(&crypto1_state
);
3205 reply_mix(CMD_ACK
, arg0
, card
->uidlen
, 0, buf
, sizeof(iso14a_card_select_t
));
3211 uint32_t save_iso14a_timeout
= 0;
3212 if ((param
& ISO14A_SET_TIMEOUT
) == ISO14A_SET_TIMEOUT
) {
3213 save_iso14a_timeout
= iso14a_get_timeout();
3214 iso14a_set_timeout(timeout
);
3217 if ((param
& ISO14A_APDU
) == ISO14A_APDU
) {
3222 ((param
& ISO14A_SEND_CHAINING
) == ISO14A_SEND_CHAINING
),
3227 FpgaDisableTracing();
3229 reply_mix(CMD_ACK
, arg0
, res
, 0, buf
, sizeof(buf
));
3232 if ((param
& ISO14A_RAW
) == ISO14A_RAW
) {
3233 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3234 // Intercept special Auth command 6xxx<key>CRCA
3235 if ((len
== 10) && ((cmd
[0] & 0xF0) == 0x60)) {
3236 uint64_t ui64key
= bytes_to_num((uint8_t *)&cmd
[2], 6);
3238 if (mifare_classic_authex_cmd(&crypto1_state
, crypto1_uid
, cmd
[1], cmd
[0], ui64key
, crypto1_auth_state
, NULL
, NULL
, NULL
, NULL
, false, false)) {
3239 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Auth error");
3242 crypto1_auth_state
= AUTH_NESTED
;
3243 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Auth succeeded");
3246 reply_mix(CMD_ACK
, 1, 0, 0, &res
, 1);
3250 if ((param
& ISO14A_APPEND_CRC
) == ISO14A_APPEND_CRC
) {
3251 // Don't append crc on empty bytearray...
3254 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3255 AddCrc14B(cmd
, len
);
3257 AddCrc14A(cmd
, len
);
3267 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3268 // Force explicit parity
3271 // want to send a specific number of bits (e.g. short commands)
3274 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3276 int bits_to_send
= lenbits
;
3279 ReaderTransmitBitsPar(&cmd
[i
++], MIN(bits_to_send
, 7), NULL
, NULL
); // first byte is always short (7bits) and no parity
3282 while (bits_to_send
> 0) {
3283 ReaderTransmitBitsPar(&cmd
[i
++], MIN(bits_to_send
, 8), NULL
, NULL
); // following bytes are 8 bit and no parity
3288 GetParity(cmd
, lenbits
/ 8, parity_array
);
3289 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3290 mf_crypto1_encrypt(&crypto1_state
, cmd
, len
, parity_array
);
3292 ReaderTransmitBitsPar(cmd
, lenbits
, parity_array
, NULL
); // bytes are 8 bit with odd parity
3295 } else { // want to send complete bytes only
3296 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3299 ReaderTransmitBitsPar(&cmd
[i
++], 7, NULL
, NULL
); // first byte: 7 bits, no paritiy
3302 ReaderTransmitBitsPar(&cmd
[i
++], 8, NULL
, NULL
); // following bytes: 8 bits, no paritiy
3306 ReaderTransmit(cmd
, len
, NULL
); // 8 bits, odd parity
3310 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3312 if (cmd
[0] == TOPAZ_WRITE_E8
|| cmd
[0] == TOPAZ_WRITE_NE8
) {
3315 if (tearoff_hook() == PM3_ETEAROFF
) {
3316 FpgaDisableTracing();
3317 reply_mix(CMD_ACK
, 0, 0, 0, NULL
, 0);
3319 arg0
= ReaderReceive(buf
, sizeof(buf
), parity_array
);
3320 FpgaDisableTracing();
3321 reply_mix(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
3325 arg0
= ReaderReceive(buf
, sizeof(buf
), parity_array
);
3326 FpgaDisableTracing();
3327 reply_mix(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
3333 if (tearoff_hook() == PM3_ETEAROFF
) {
3334 FpgaDisableTracing();
3335 reply_mix(CMD_ACK
, 0, 0, 0, NULL
, 0);
3337 arg0
= ReaderReceive(buf
, sizeof(buf
), parity_array
);
3339 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3340 mf_crypto1_decrypt(&crypto1_state
, buf
, arg0
);
3342 FpgaDisableTracing();
3343 reply_mix(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
3348 if ((param
& ISO14A_REQUEST_TRIGGER
) == ISO14A_REQUEST_TRIGGER
)
3349 iso14a_set_trigger(false);
3351 if ((param
& ISO14A_SET_TIMEOUT
) == ISO14A_SET_TIMEOUT
) {
3352 iso14a_set_timeout(save_iso14a_timeout
);
3355 if ((param
& ISO14A_NO_DISCONNECT
) == ISO14A_NO_DISCONNECT
) {
3360 crypto1_auth_state
= AUTH_FIRST
;
3365 // Determine the distance between two nonces.
3366 // Assume that the difference is small, but we don't know which is first.
3367 // Therefore try in alternating directions.
3368 static int32_t dist_nt(uint32_t nt1
, uint32_t nt2
) {
3370 if (nt1
== nt2
) return 0;
3372 uint32_t nttmp1
= nt1
;
3373 uint32_t nttmp2
= nt2
;
3375 for (uint16_t i
= 1; i
< 32768; i
++) {
3376 nttmp1
= prng_successor(nttmp1
, 1);
3377 if (nttmp1
== nt2
) return i
;
3379 nttmp2
= prng_successor(nttmp2
, 1);
3380 if (nttmp2
== nt1
) return -i
;
3383 return (-99999); // either nt1 or nt2 are invalid nonces
3387 #define PRNG_SEQUENCE_LENGTH (1 << 16)
3388 #define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up.
3389 #define MAX_SYNC_TRIES 32
3391 //-----------------------------------------------------------------------------
3392 // Recover several bits of the cypher stream. This implements (first stages of)
3393 // the algorithm described in "The Dark Side of Security by Obscurity and
3394 // Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
3395 // (article by Nicolas T. Courtois, 2009)
3396 //-----------------------------------------------------------------------------
3397 void ReaderMifare(bool first_try
, uint8_t block
, uint8_t keytype
) {
3399 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
);
3402 BigBuf_Clear_ext(false);
3406 uint8_t mf_auth
[4] = { keytype
, block
, 0x00, 0x00 };
3407 uint8_t mf_nr_ar
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3408 uint8_t uid
[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3409 uint8_t par_list
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3410 uint8_t ks_list
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3411 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
3412 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
3413 uint8_t par
[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
3414 uint8_t nt_diff
= 0;
3416 uint32_t nt
= 0, previous_nt
= 0, cuid
= 0;
3417 uint32_t sync_time
= GetCountSspClk() & 0xfffffff8;
3419 int32_t catch_up_cycles
= 0;
3420 int32_t last_catch_up
= 0;
3423 uint16_t elapsed_prng_sequences
= 1;
3424 uint16_t consecutive_resyncs
= 0;
3425 uint16_t unexpected_random
= 0;
3426 uint16_t sync_tries
= 0;
3428 bool have_uid
= false;
3429 uint8_t cascade_levels
= 0;
3431 // static variables here, is re-used in the next call
3432 static int32_t sync_cycles
= 0;
3433 static uint32_t nt_attacked
= 0;
3434 static uint8_t mf_nr_ar3
= 0;
3435 static uint8_t par_low
= 0;
3437 int return_status
= PM3_SUCCESS
;
3439 AddCrc14A(mf_auth
, 2);
3442 sync_cycles
= PRNG_SEQUENCE_LENGTH
; // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
3447 // we were unsuccessful on a previous call.
3448 // Try another READER nonce (first 3 parity bits remain the same)
3450 mf_nr_ar
[3] = mf_nr_ar3
;
3455 uint16_t checkbtn_cnt
= 0;
3457 for (i
= 0; true; ++i
) {
3459 bool received_nack
= false;
3463 // Test if the action was cancelled
3464 if (checkbtn_cnt
== 1000) {
3465 if (BUTTON_PRESS() || data_available()) {
3467 return_status
= PM3_EOPABORTED
;
3474 // this part is from Piwi's faster nonce collecting part in Hardnested.
3475 if (!have_uid
) { // need a full select cycle to get the uid first
3476 iso14a_card_select_t card_info
;
3477 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
3478 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (ALL)");
3481 switch (card_info
.uidlen
) {
3495 } else { // no need for anticollision. We can directly select the card
3496 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
3497 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (UID)");
3502 elapsed_prng_sequences
= 1;
3504 // Sending timeslot of ISO14443a frame
3505 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
3506 catch_up_cycles
= 0;
3508 #define SYNC_TIME_BUFFER 16 // if there is only SYNC_TIME_BUFFER left before next planned sync, wait for next PRNG cycle
3510 // if we missed the sync time already or are about to miss it, advance to the next nonce repeat
3511 while (sync_time
< GetCountSspClk() + SYNC_TIME_BUFFER
) {
3512 ++elapsed_prng_sequences
;
3513 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
3516 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
3517 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
3519 // Receive the (4 Byte) "random" TAG nonce
3520 if (ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) != 4)
3524 nt
= bytes_to_num(receivedAnswer
, 4);
3526 // Transmit reader nonce with fake par
3527 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
3529 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3530 int resp_res
= ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
);
3532 received_nack
= true;
3533 else if (resp_res
== 4) {
3534 // did we get lucky and got our dummykey to be valid?
3535 // however we don't feed key w uid it the prng..
3537 return_status
= PM3_ESOFT
;
3542 // we didn't calibrate our clock yet,
3543 // iceman: has to be calibrated every time.
3544 if (previous_nt
&& !nt_attacked
) {
3546 int nt_distance
= dist_nt(previous_nt
, nt
);
3548 // if no distance between, then we are in sync.
3549 if (nt_distance
== 0) {
3552 if (nt_distance
== -99999) { // invalid nonce received
3553 unexpected_random
++;
3554 if (unexpected_random
> MAX_UNEXPECTED_RANDOM
) {
3555 isOK
= 3; // Card has an unpredictable PRNG. Give up
3556 return_status
= PM3_ESOFT
;
3559 continue; // continue trying...
3563 if (++sync_tries
> MAX_SYNC_TRIES
) {
3564 isOK
= 4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3565 return_status
= PM3_ESOFT
;
3569 sync_cycles
= (sync_cycles
- nt_distance
) / elapsed_prng_sequences
;
3571 // no negative sync_cycles, and too small sync_cycles will result in continuous misses
3572 if (sync_cycles
<= 10) sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3574 // reset sync_cycles
3575 if (sync_cycles
> PRNG_SEQUENCE_LENGTH
* 2) {
3576 sync_cycles
= PRNG_SEQUENCE_LENGTH
;
3577 sync_time
= GetCountSspClk() & 0xfffffff8;
3580 if (g_dbglevel
>= DBG_EXTENDED
)
3581 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
);
3587 if ((nt
!= nt_attacked
) && nt_attacked
) { // we somehow lost sync. Try to catch up again...
3589 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
3590 if (catch_up_cycles
== 99999) { // invalid nonce received. Don't resync on that one.
3591 catch_up_cycles
= 0;
3595 catch_up_cycles
/= elapsed_prng_sequences
;
3597 if (catch_up_cycles
== last_catch_up
) {
3598 consecutive_resyncs
++;
3600 last_catch_up
= catch_up_cycles
;
3601 consecutive_resyncs
= 0;
3604 if (consecutive_resyncs
< 3) {
3605 if (g_dbglevel
>= DBG_EXTENDED
) {
3606 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, catch_up_cycles
, consecutive_resyncs
);
3609 sync_cycles
+= catch_up_cycles
;
3611 if (g_dbglevel
>= DBG_EXTENDED
)
3612 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
);
3615 catch_up_cycles
= 0;
3616 consecutive_resyncs
= 0;
3621 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3622 if (received_nack
) {
3623 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
3626 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
3628 par_list
[nt_diff
] = reflect8(par
[0]);
3629 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05; // xor with NACK value to get keystream
3631 // Test if the information is complete
3632 if (nt_diff
== 0x07) {
3634 return_status
= PM3_SUCCESS
;
3638 nt_diff
= (nt_diff
+ 1) & 0x07;
3639 mf_nr_ar
[3] = (mf_nr_ar
[3] & 0x1F) | (nt_diff
<< 5);
3644 if (nt_diff
== 0 && first_try
) {
3646 if (par
[0] == 0) { // tried all 256 possible parities without success. Card doesn't send NACK.
3648 return_status
= PM3_ESOFT
;
3653 par
[0] = ((par
[0] & 0x1F) + 1) | par_low
;
3657 // reset the resyncs since we got a complete transaction on right time.
3658 consecutive_resyncs
= 0;
3661 mf_nr_ar
[3] &= 0x1F;
3663 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("Number of sent auth requests: %u", i
);
3665 FpgaDisableTracing();
3671 uint8_t par_list
[8];
3677 payload
.isOK
= isOK
;
3678 num_to_bytes(cuid
, 4, payload
.cuid
);
3679 num_to_bytes(nt
, 4, payload
.nt
);
3680 memcpy(payload
.par_list
, par_list
, sizeof(payload
.par_list
));
3681 memcpy(payload
.ks_list
, ks_list
, sizeof(payload
.ks_list
));
3682 memcpy(payload
.nr
, mf_nr_ar
, sizeof(payload
.nr
));
3683 memcpy(payload
.ar
, mf_nr_ar
+ 4, sizeof(payload
.ar
));
3685 reply_ng(CMD_HF_MIFARE_READER
, return_status
, (uint8_t *)&payload
, sizeof(payload
));
3692 * Mifare Classic NACK-bug detection
3693 * Thanks to @doegox for the feedback and new approaches.
3695 void DetectNACKbug(void) {
3696 uint8_t mf_auth
[4] = { MIFARE_AUTH_KEYA
, 0x00, 0xF5, 0x7B };
3697 uint8_t mf_nr_ar
[8] = { 0x00 };
3698 uint8_t uid
[10] = { 0x00 };
3699 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = { 0x00 };
3700 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = { 0x00 };
3701 uint8_t par
[1] = {0x00 }; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
3703 uint32_t nt
= 0, previous_nt
= 0, nt_attacked
= 0, cuid
= 0;
3704 int32_t catch_up_cycles
= 0, last_catch_up
= 0;
3705 uint8_t cascade_levels
= 0, num_nacks
= 0, isOK
= 0;
3706 uint16_t elapsed_prng_sequences
= 1;
3707 uint16_t consecutive_resyncs
= 0;
3708 uint16_t unexpected_random
= 0;
3709 uint16_t sync_tries
= 0;
3710 uint32_t sync_time
= 0;
3711 bool have_uid
= false;
3713 int32_t status
= PM3_SUCCESS
;
3715 // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
3716 int32_t sync_cycles
= PRNG_SEQUENCE_LENGTH
;
3719 BigBuf_Clear_ext(false);
3722 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
);
3724 sync_time
= GetCountSspClk() & 0xfffffff8;
3727 uint16_t checkbtn_cnt
= 0;
3730 for (i
= 1; true; ++i
) {
3732 bool received_nack
= false;
3734 // Cards always leaks a NACK, no matter the parity
3735 if ((i
== 10) && (num_nacks
== i
- 1)) {
3742 // Test if the action was cancelled
3743 if (checkbtn_cnt
== 1000) {
3744 if (BUTTON_PRESS() || data_available()) {
3745 status
= PM3_EOPABORTED
;
3752 // this part is from Piwi's faster nonce collecting part in Hardnested.
3753 if (!have_uid
) { // need a full select cycle to get the uid first
3754 iso14a_card_select_t card_info
;
3755 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
3756 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (ALL)");
3760 switch (card_info
.uidlen
) {
3776 } else { // no need for anticollision. We can directly select the card
3777 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
3778 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (UID)");
3785 elapsed_prng_sequences
= 1;
3787 // Sending timeslot of ISO14443a frame
3788 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
3789 catch_up_cycles
= 0;
3791 // if we missed the sync time already, advance to the next nonce repeat
3792 while (GetCountSspClk() > sync_time
) {
3793 ++elapsed_prng_sequences
;
3794 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
3797 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
3798 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
3800 // Receive the (4 Byte) "random" TAG nonce
3801 if (ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) {
3806 nt
= bytes_to_num(receivedAnswer
, 4);
3808 // Transmit reader nonce with fake par
3809 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
3811 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3812 if (ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
)) {
3813 received_nack
= true;
3815 // ALWAYS leak Detection. Well, we could be lucky and get a response nack on first try.
3816 if (i
== num_nacks
) {
3821 // we didn't calibrate our clock yet,
3822 // iceman: has to be calibrated every time.
3823 if (previous_nt
&& !nt_attacked
) {
3825 int nt_distance
= dist_nt(previous_nt
, nt
);
3827 // if no distance between, then we are in sync.
3828 if (nt_distance
== 0) {
3831 if (nt_distance
== -99999) { // invalid nonce received
3832 unexpected_random
++;
3833 if (unexpected_random
> MAX_UNEXPECTED_RANDOM
) {
3834 // Card has an unpredictable PRNG. Give up
3838 if (sync_cycles
<= 0) {
3839 sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3845 if (++sync_tries
> MAX_SYNC_TRIES
) {
3846 isOK
= 97; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3850 sync_cycles
= (sync_cycles
- nt_distance
) / elapsed_prng_sequences
;
3852 if (sync_cycles
<= 0) {
3853 sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3856 if (sync_cycles
> PRNG_SEQUENCE_LENGTH
* 2) {
3857 isOK
= 96; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3861 if (g_dbglevel
>= DBG_EXTENDED
) {
3862 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
);
3868 if ((nt
!= nt_attacked
) && nt_attacked
) {
3869 // we somehow lost sync. Try to catch up again...
3870 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
3872 if (catch_up_cycles
== 99999) {
3873 // invalid nonce received. Don't resync on that one.
3874 catch_up_cycles
= 0;
3878 catch_up_cycles
/= elapsed_prng_sequences
;
3880 if (catch_up_cycles
== last_catch_up
) {
3881 consecutive_resyncs
++;
3883 last_catch_up
= catch_up_cycles
;
3884 consecutive_resyncs
= 0;
3887 if (consecutive_resyncs
< 3) {
3888 if (g_dbglevel
>= DBG_EXTENDED
) {
3889 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, catch_up_cycles
, consecutive_resyncs
);
3892 sync_cycles
+= catch_up_cycles
;
3894 if (g_dbglevel
>= DBG_EXTENDED
) {
3895 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
);
3896 Dbprintf("nt [%08x] attacted [%08x]", nt
, nt_attacked
);
3899 catch_up_cycles
= 0;
3900 consecutive_resyncs
= 0;
3905 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3906 if (received_nack
) {
3907 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
3910 // we are testing all 256 possibilities.
3913 // tried all 256 possible parities without success.
3915 // did we get one NACK?
3916 if (num_nacks
== 1) {
3922 // reset the resyncs since we got a complete transaction on right time.
3923 consecutive_resyncs
= 0;
3926 // num_nacks = number of nacks received. should be only 1. if not its a clone card which always sends NACK (parity == 0) ?
3927 // i = number of authentications sent. Not always 256, since we are trying to sync but close to it.
3928 FpgaDisableTracing();
3930 uint8_t *data
= BigBuf_malloc(4);
3932 data
[1] = num_nacks
;
3933 num_to_bytes(i
, 2, data
+ 2);
3934 reply_ng(CMD_HF_MIFARE_NACK_DETECT
, status
, data
, 4);
3942 Based upon the SimulateIso14443aTag, this aims to instead take an AID Value you've supplied, and return your selected response.
3943 It can also continue after the AID has been selected, and respond to other request types.
3944 This was forked from the original function to allow for more flexibility in the future, and to increase the processing speed of the original function.
3947 void SimulateIso14443aTagAID(uint8_t tagType
, uint16_t flags
, uint8_t *data
,
3948 uint8_t *iRATs
, size_t irats_len
, uint8_t *aid
, uint8_t *resp
,
3949 uint8_t *apdu
, int aidLen
, int respondLen
, int apduLen
, bool enumerate
) {
3950 tag_response_info_t
*responses
;
3952 uint32_t counters
[3] = { 0x00, 0x00, 0x00 };
3953 uint8_t tearings
[3] = { 0xbd, 0xbd, 0xbd };
3957 uint8_t receivedCmd
[MAX_FRAME_SIZE
] = { 0x00 };
3958 uint8_t receivedCmdPar
[MAX_PARITY_SIZE
] = { 0x00 };
3960 // free eventually allocated BigBuf memory but keep Emulator Memory
3961 BigBuf_free_keep_EM();
3963 // Increased the buffer size to allow for more complex responses
3964 #define DYNAMIC_RESPONSE_BUFFER2_SIZE 512
3965 #define DYNAMIC_MODULATION_BUFFER2_SIZE 1536
3967 uint8_t *dynamic_response_buffer2
= BigBuf_calloc(DYNAMIC_RESPONSE_BUFFER2_SIZE
);
3968 uint8_t *dynamic_modulation_buffer2
= BigBuf_calloc(DYNAMIC_MODULATION_BUFFER2_SIZE
);
3969 tag_response_info_t dynamic_response_info
= {
3970 .response
= dynamic_response_buffer2
,
3972 .modulation
= dynamic_modulation_buffer2
,
3976 if (SimulateIso14443aInit(tagType
, flags
, data
, iRATs
, irats_len
, &responses
, &cuid
, counters
, tearings
, &pages
) == false) {
3977 BigBuf_free_keep_EM();
3978 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_EINIT
, NULL
, 0);
3982 // We need to listen to the high-frequency, peak-detected path.
3983 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
3985 iso14a_set_timeout(201400); // 106 * 19ms default *100?
3988 int retval
= PM3_SUCCESS
;
3990 bool odd_reply
= true;
3996 // Filters for when this comes through
3997 static uint8_t aidFilter
[30] = { 0x00 }; // Default AID Value
3998 static uint8_t aidResponse
[100] = { 0x00 }; // Default AID Response
3999 static uint8_t apduCommand
[100] = { 0x00 }; // Default APDU GetData Response
4001 // Copy the AID, AID Response, and the GetData APDU response into our variables
4003 memcpy(aidFilter
, aid
, aidLen
);
4006 memcpy(aidResponse
, resp
, respondLen
);
4009 memcpy(apduCommand
, apdu
, apduLen
);
4014 bool finished
= false;
4015 while (finished
== false) {
4016 // BUTTON_PRESS check done in GetIso14443aCommandFromReader
4019 tag_response_info_t
*p_response
= NULL
;
4021 // Clean receive command buffer
4022 if (GetIso14443aCommandFromReader(receivedCmd
, sizeof(receivedCmd
), receivedCmdPar
, &len
) == false) {
4023 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
4024 retval
= PM3_EOPABORTED
;
4028 if (receivedCmd
[0] == ISO14443A_CMD_REQA
&& len
== 1) { // Received a REQUEST, but in HALTED, skip
4029 odd_reply
= !odd_reply
;
4031 p_response
= &responses
[RESP_INDEX_ATQA
];
4033 } else if (receivedCmd
[0] == ISO14443A_CMD_WUPA
&& len
== 1) { // Received a WAKEUP
4034 p_response
= &responses
[RESP_INDEX_ATQA
];
4035 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 2) { // Received request for UID (cascade 1)
4036 p_response
= &responses
[RESP_INDEX_UIDC1
];
4037 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 2) { // Received request for UID (cascade 2)
4038 p_response
= &responses
[RESP_INDEX_UIDC2
];
4039 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 2) { // Received request for UID (cascade 3)
4040 p_response
= &responses
[RESP_INDEX_UIDC3
];
4041 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 9) { // Received a SELECT (cascade 1)
4042 p_response
= &responses
[RESP_INDEX_SAKC1
];
4043 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 9) { // Received a SELECT (cascade 2)
4044 p_response
= &responses
[RESP_INDEX_SAKC2
];
4045 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 9) { // Received a SELECT (cascade 3)
4046 p_response
= &responses
[RESP_INDEX_SAKC3
];
4047 } else if (receivedCmd
[0] == ISO14443A_CMD_PPS
) {
4048 p_response
= &responses
[RESP_INDEX_PPS
];
4049 } else if (receivedCmd
[0] == ISO14443A_CMD_HALT
&& len
== 4) { // Received a HALT
4050 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
4053 } else if (receivedCmd
[0] == ISO14443A_CMD_RATS
&& len
== 4) { // Received a RATS request
4054 p_response
= &responses
[RESP_INDEX_RATS
];
4056 // clear old dynamic responses
4057 dynamic_response_info
.response_n
= 0;
4058 dynamic_response_info
.modulation_n
= 0;
4060 // Check for ISO 14443A-4 compliant commands, look at left nibble
4061 switch (receivedCmd
[0]) {
4063 case 0x0A: { // IBlock (command CID)
4064 dynamic_response_info
.response
[0] = receivedCmd
[0];
4065 dynamic_response_info
.response
[1] = 0x00;
4067 switch (receivedCmd
[3]) { // APDU Class Byte
4068 // receivedCmd in this case is expecting to structured with a CID, then the APDU command for SelectFile
4069 // | IBlock (CID) | CID | APDU Command | CRC |
4071 case 0xA4: { // SELECT FILE
4072 // Select File AID uses the following format for GlobalPlatform
4074 // | 00 | A4 | 04 | 00 | xx | AID | 00 |
4075 // xx in this case is len of the AID value in hex
4077 // aid len is found as a hex value in receivedCmd[6] (Index Starts at 0)
4078 int aid_len
= receivedCmd
[6];
4079 uint8_t *received_aid
= &receivedCmd
[7];
4081 // aid enumeration flag
4082 if (enumerate
== true) {
4083 Dbprintf("Received AID (%d):", aid_len
);
4084 Dbhexdump(aid_len
, received_aid
, false);
4087 if (memcmp(aidFilter
, received_aid
, aid_len
) == 0) { // Evaluate the AID sent by the Reader to the AID supplied
4088 // AID Response will be parsed here
4089 memcpy(dynamic_response_info
.response
+ 2, aidResponse
, respondLen
+ 2);
4090 dynamic_response_info
.response_n
= respondLen
+ 2;
4091 } else { // Any other SELECT FILE command will return with a Not Found
4092 dynamic_response_info
.response
[2] = 0x6A;
4093 dynamic_response_info
.response
[3] = 0x82;
4094 dynamic_response_info
.response_n
= 4;
4099 case 0xDA: { // PUT DATA
4100 // Just send them a 90 00 response
4101 dynamic_response_info
.response
[2] = 0x90;
4102 dynamic_response_info
.response
[3] = 0x00;
4103 dynamic_response_info
.response_n
= 4;
4107 case 0xCA: { // GET DATA
4108 if (sentCount
== 0) {
4109 // APDU Command will just be parsed here
4110 memcpy(dynamic_response_info
.response
+ 2, apduCommand
, apduLen
+ 2);
4111 dynamic_response_info
.response_n
= respondLen
+ 2;
4120 // Any other non-listed command
4121 // Respond Not Found
4122 dynamic_response_info
.response
[2] = 0x6A;
4123 dynamic_response_info
.response
[3] = 0x82;
4124 dynamic_response_info
.response_n
= 4;
4132 case 0xC2: { // Readers sends deselect command
4133 dynamic_response_info
.response
[0] = 0xCA;
4134 dynamic_response_info
.response
[1] = 0x00;
4135 dynamic_response_info
.response_n
= 2;
4141 // Never seen this command before
4142 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
4143 if (g_dbglevel
>= DBG_DEBUG
) {
4144 Dbprintf("Received unknown command (len=%d):", len
);
4145 Dbhexdump(len
, receivedCmd
, false);
4148 dynamic_response_info
.response_n
= 0;
4152 if (dynamic_response_info
.response_n
> 0) {
4154 // Copy the CID from the reader query
4155 dynamic_response_info
.response
[1] = receivedCmd
[1];
4157 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
4158 AddCrc14A(dynamic_response_info
.response
, dynamic_response_info
.response_n
);
4159 dynamic_response_info
.response_n
+= 2;
4161 if (prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
4162 if (g_dbglevel
>= DBG_DEBUG
) DbpString("Error preparing tag response");
4163 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
4166 p_response
= &dynamic_response_info
;
4171 EmSendPrecompiledCmd(p_response
);
4177 BigBuf_free_keep_EM();
4179 reply_ng(CMD_HF_MIFARE_SIMULATE
, retval
, NULL
, 0);