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
) {
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
592 if (Demod
.bitCount
> 0) { // there are some remaining data bits
593 Demod
.shiftReg
>>= (9 - Demod
.bitCount
); // right align the decoded bits
594 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff; // and add them to the output
595 Demod
.parityBits
<<= 1; // add a (void) parity bit
596 Demod
.parityBits
<<= (8 - (Demod
.len
& 0x0007)); // left align remaining parity bits
597 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // and store them
599 } else if (Demod
.len
& 0x0007) { // there are some parity bits to store
600 Demod
.parityBits
<<= (8 - (Demod
.len
& 0x0007)); // left align remaining parity bits
601 Demod
.parity
[Demod
.parityLen
++] = Demod
.parityBits
; // and store them
604 return true; // we are finished with decoding the raw data sequence
605 } else { // nothing received. Start over
611 return false; // not finished yet, need more data
615 // Thinfilm, Kovio mangles ISO14443A in the way that they don't use start bit nor parity bits.
616 static RAMFUNC
int ManchesterDecoding_Thinfilm(uint8_t bit
) {
618 if (Demod
.len
== Demod
.output_len
) {
622 Demod
.twoBits
= (Demod
.twoBits
<< 8) | bit
;
624 if (Demod
.state
== DEMOD_14A_UNSYNCD
) {
626 if (Demod
.highCnt
< 2) { // wait for a stable unmodulated signal
627 if (Demod
.twoBits
== 0x0000) {
633 Demod
.syncBit
= 0xFFFF; // not set
634 if ((Demod
.twoBits
& 0x7700) == 0x7000) Demod
.syncBit
= 7;
635 else if ((Demod
.twoBits
& 0x3B80) == 0x3800) Demod
.syncBit
= 6;
636 else if ((Demod
.twoBits
& 0x1DC0) == 0x1C00) Demod
.syncBit
= 5;
637 else if ((Demod
.twoBits
& 0x0EE0) == 0x0E00) Demod
.syncBit
= 4;
638 else if ((Demod
.twoBits
& 0x0770) == 0x0700) Demod
.syncBit
= 3;
639 else if ((Demod
.twoBits
& 0x03B8) == 0x0380) Demod
.syncBit
= 2;
640 else if ((Demod
.twoBits
& 0x01DC) == 0x01C0) Demod
.syncBit
= 1;
641 else if ((Demod
.twoBits
& 0x00EE) == 0x00E0) Demod
.syncBit
= 0;
642 if (Demod
.syncBit
!= 0xFFFF) {
643 Demod
.startTime
= (GetCountSspClk() & 0xfffffff8);
644 Demod
.startTime
-= Demod
.syncBit
;
645 Demod
.bitCount
= 1; // number of decoded data bits
647 Demod
.state
= DEMOD_14A_MANCHESTER_DATA
;
652 if (IsManchesterModulationNibble1(Demod
.twoBits
>> Demod
.syncBit
)) { // modulation in first half
653 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // ... and in second half = collision
654 if (!Demod
.collisionPos
) {
655 Demod
.collisionPos
= (Demod
.len
<< 3) + Demod
.bitCount
;
657 } // modulation in first half only - Sequence D = 1
659 Demod
.shiftReg
= (Demod
.shiftReg
<< 1) | 0x1; // in both cases, add a 1 to the shiftreg
660 if (Demod
.bitCount
== 8) { // if we decoded a full byte
661 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
665 Demod
.endTime
= Demod
.startTime
+ 8 * (8 * Demod
.len
+ Demod
.bitCount
+ 1) - 4;
666 } else { // no modulation in first half
667 if (IsManchesterModulationNibble2(Demod
.twoBits
>> Demod
.syncBit
)) { // and modulation in second half = Sequence E = 0
669 Demod
.shiftReg
= (Demod
.shiftReg
<< 1); // add a 0 to the shiftreg
670 if (Demod
.bitCount
>= 8) { // if we decoded a full byte
671 Demod
.output
[Demod
.len
++] = (Demod
.shiftReg
& 0xff);
675 Demod
.endTime
= Demod
.startTime
+ 8 * (8 * Demod
.len
+ Demod
.bitCount
+ 1);
676 } else { // no modulation in both halves - End of communication
677 if (Demod
.bitCount
> 0) { // there are some remaining data bits
678 Demod
.shiftReg
<<= (8 - Demod
.bitCount
); // left align the decoded bits
679 Demod
.output
[Demod
.len
++] = Demod
.shiftReg
& 0xff; // and add them to the output
683 return true; // we are finished with decoding the raw data sequence
684 } else { // nothing received. Start over
690 return false; // not finished yet, need more data
693 //=============================================================================
694 // Finally, a `sniffer' for ISO 14443 Type A
695 // Both sides of communication!
696 //=============================================================================
698 //-----------------------------------------------------------------------------
699 // Record the sequence of commands sent by the reader to the tag, with
700 // triggering so that we start recording at the point that the tag is moved
703 //-----------------------------------------------------------------------------
704 void RAMFUNC
SniffIso14443a(uint8_t param
) {
707 // bit 0 - trigger from first card answer
708 // bit 1 - trigger from first reader 7-bit request
709 iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER
);
711 // Allocate memory from BigBuf for some buffers
712 // free all previous allocations first
714 BigBuf_Clear_ext(false);
718 // The command (reader -> tag) that we're receiving.
719 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
720 uint8_t *receivedCmdPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
722 // The response (tag -> reader) that we're receiving.
723 uint8_t *receivedResp
= BigBuf_malloc(MAX_FRAME_SIZE
);
724 uint8_t *receivedRespPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
726 uint8_t previous_data
= 0;
727 int maxDataLen
= 0, dataLen
;
728 bool TagIsActive
= false;
729 bool ReaderIsActive
= false;
731 // Set up the demodulator for tag -> reader responses.
732 Demod14aInit(receivedResp
, MAX_FRAME_SIZE
, receivedRespPar
);
734 // Set up the demodulator for the reader -> tag commands
735 Uart14aInit(receivedCmd
, MAX_FRAME_SIZE
, receivedCmdPar
);
737 if (g_dbglevel
>= DBG_INFO
) {
738 DbpString("Press " _GREEN_("pm3 button") " to abort sniffing");
741 // The DMA buffer, used to stream samples from the FPGA
742 dmabuf8_t
*dma
= get_dma8();
743 uint8_t *data
= dma
->buf
;
745 // Setup and start DMA.
746 if (FpgaSetupSscDma((uint8_t *) dma
->buf
, DMA_BUFFER_SIZE
) == false) {
747 if (g_dbglevel
> 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
751 // We won't start recording the frames that we acquire until we trigger;
752 // a good trigger condition to get started is probably when we see a
753 // response from the tag.
754 // triggered == false -- to wait first for card
755 bool triggered
= !(param
& 0x03);
757 uint32_t rx_samples
= 0;
760 while (BUTTON_PRESS() == false) {
764 register int readBufDataP
= data
- dma
->buf
;
765 register int dmaBufDataP
= DMA_BUFFER_SIZE
- AT91C_BASE_PDC_SSC
->PDC_RCR
;
766 if (readBufDataP
<= dmaBufDataP
) {
767 dataLen
= dmaBufDataP
- readBufDataP
;
769 dataLen
= DMA_BUFFER_SIZE
- readBufDataP
+ dmaBufDataP
;
772 // test for length of buffer
773 if (dataLen
> maxDataLen
) {
774 maxDataLen
= dataLen
;
775 if (dataLen
> (9 * DMA_BUFFER_SIZE
/ 10)) {
776 Dbprintf("[!] blew circular buffer! | datalen %u", dataLen
);
784 // primary buffer was stopped( <-- we lost data!
785 if (!AT91C_BASE_PDC_SSC
->PDC_RCR
) {
786 AT91C_BASE_PDC_SSC
->PDC_RPR
= (uint32_t) dma
->buf
;
787 AT91C_BASE_PDC_SSC
->PDC_RCR
= DMA_BUFFER_SIZE
;
788 Dbprintf("[-] RxEmpty ERROR | data length %d", dataLen
); // temporary
790 // secondary buffer sets as primary, secondary buffer was stopped
791 if (!AT91C_BASE_PDC_SSC
->PDC_RNCR
) {
792 AT91C_BASE_PDC_SSC
->PDC_RNPR
= (uint32_t) dma
->buf
;
793 AT91C_BASE_PDC_SSC
->PDC_RNCR
= DMA_BUFFER_SIZE
;
798 // Need two samples to feed Miller and Manchester-Decoder
799 if (rx_samples
& 0x01) {
801 // no need to try decoding reader data if the tag is sending
802 if (TagIsActive
== false) {
804 uint8_t readerdata
= (previous_data
& 0xF0) | (*data
>> 4);
806 if (MillerDecoding(readerdata
, (rx_samples
- 1) * 4)) {
809 // check - if there is a short 7bit request from reader
810 if ((!triggered
) && (param
& 0x02) && (Uart
.len
== 1) && (Uart
.bitCount
== 7)) {
815 if (!LogTrace(receivedCmd
,
817 Uart
.startTime
* 16 - DELAY_READER_AIR2ARM_AS_SNIFFER
,
818 Uart
.endTime
* 16 - DELAY_READER_AIR2ARM_AS_SNIFFER
,
824 // ready to receive another command
826 // reset the demod code, which might have been
827 // false-triggered by the commands from the reader
831 ReaderIsActive
= (Uart
.state
!= STATE_14A_UNSYNCD
);
834 // no need to try decoding tag data if the reader is sending - and we cannot afford the time
835 if (ReaderIsActive
== false) {
837 uint8_t tagdata
= (previous_data
<< 4) | (*data
& 0x0F);
839 if (ManchesterDecoding(tagdata
, 0, (rx_samples
- 1) * 4)) {
843 if (!LogTrace(receivedResp
,
845 Demod
.startTime
* 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER
,
846 Demod
.endTime
* 16 - DELAY_TAG_AIR2ARM_AS_SNIFFER
,
850 if ((!triggered
) && (param
& 0x01)) {
854 // ready to receive another response.
856 // reset the Miller decoder including its (now outdated) input buffer
858 //Uart14aInit(receivedCmd, MAX_FRAME_SIZE, receivedCmdPar);
861 TagIsActive
= (Demod
.state
!= DEMOD_14A_UNSYNCD
);
865 previous_data
= *data
;
868 if (data
== dma
->buf
+ DMA_BUFFER_SIZE
) {
873 FpgaDisableTracing();
875 if (g_dbglevel
>= DBG_ERROR
) {
876 Dbprintf("trace len = " _YELLOW_("%d"), BigBuf_get_traceLen());
881 //-----------------------------------------------------------------------------
882 // Prepare tag messages
883 //-----------------------------------------------------------------------------
884 static void CodeIso14443aAsTagPar(const uint8_t *cmd
, uint16_t len
, const uint8_t *par
, bool collision
) {
888 tosend_t
*ts
= get_tosend();
890 // Correction bit, might be removed when not needed
895 tosend_stuffbit(1); // <-----
901 ts
->buf
[++ts
->max
] = SEC_D
;
902 LastProxToAirDuration
= 8 * ts
->max
- 4;
904 for (uint16_t i
= 0; i
< len
; i
++) {
908 for (uint16_t j
= 0; j
< 8; j
++) {
910 ts
->buf
[++ts
->max
] = SEC_COLL
;
913 ts
->buf
[++ts
->max
] = SEC_D
;
915 ts
->buf
[++ts
->max
] = SEC_E
;
922 ts
->buf
[++ts
->max
] = SEC_COLL
;
923 LastProxToAirDuration
= 8 * ts
->max
;
925 // Get the parity bit
926 if (par
[i
>> 3] & (0x80 >> (i
& 0x0007))) {
927 ts
->buf
[++ts
->max
] = SEC_D
;
928 LastProxToAirDuration
= 8 * ts
->max
- 4;
930 ts
->buf
[++ts
->max
] = SEC_E
;
931 LastProxToAirDuration
= 8 * ts
->max
;
937 ts
->buf
[++ts
->max
] = SEC_F
;
939 // Convert from last byte pos to length
943 static void CodeIso14443aAsTagEx(const uint8_t *cmd
, uint16_t len
, bool collision
) {
944 GetParity(cmd
, len
, parity_array
);
945 CodeIso14443aAsTagPar(cmd
, len
, parity_array
, collision
);
947 static void CodeIso14443aAsTag(const uint8_t *cmd
, uint16_t len
) {
948 CodeIso14443aAsTagEx(cmd
, len
, false);
951 static void Code4bitAnswerAsTag(uint8_t cmd
) {
956 tosend_t
*ts
= get_tosend();
958 // Correction bit, might be removed when not needed
963 tosend_stuffbit(1); // 1
969 ts
->buf
[++ts
->max
] = SEC_D
;
971 for (uint8_t i
= 0; i
< 4; i
++) {
973 ts
->buf
[++ts
->max
] = SEC_D
;
974 LastProxToAirDuration
= 8 * ts
->max
- 4;
976 ts
->buf
[++ts
->max
] = SEC_E
;
977 LastProxToAirDuration
= 8 * ts
->max
;
983 ts
->buf
[++ts
->max
] = SEC_F
;
985 // Convert from last byte pos to length
989 //-----------------------------------------------------------------------------
990 // Wait for commands from reader
991 // stop when button is pressed or client usb connection resets
992 // or return TRUE when command is captured
993 //-----------------------------------------------------------------------------
994 bool GetIso14443aCommandFromReader(uint8_t *received
, uint16_t received_maxlen
, uint8_t *par
, int *len
) {
995 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
996 // only, since we are receiving, not transmitting).
997 // Signal field is off with the appropriate LED
999 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1001 // Now run a `software UART` on the stream of incoming samples.
1002 Uart14aInit(received
, received_maxlen
, par
);
1005 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1009 uint16_t checker
= 4000;
1014 // ever 3 * 4000, check if we got any data from client
1015 // takes long time, usually messes with simualtion
1017 if (data_available()) {
1024 // button press, takes a bit time, might mess with simualtion
1025 if (checker
-- == 0) {
1026 if (BUTTON_PRESS()) {
1034 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1035 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1036 if (MillerDecoding(b
, 0)) {
1045 bool prepare_tag_modulation(tag_response_info_t
*response_info
, size_t max_buffer_size
) {
1046 // Example response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
1047 // This will need the following byte array for a modulation sequence
1048 // 144 data bits (18 * 8)
1051 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
1052 // 1 just for the case
1054 // 166 bytes, since every bit that needs to be send costs us a byte
1056 // Prepare the tag modulation bits from the message
1057 CodeIso14443aAsTag(response_info
->response
, response_info
->response_n
);
1059 tosend_t
*ts
= get_tosend();
1061 // Make sure we do not exceed the free buffer space
1062 if (ts
->max
> max_buffer_size
) {
1063 Dbprintf("ToSend buffer, Out-of-bound, when modulating bits for tag answer:");
1064 Dbhexdump(response_info
->response_n
, response_info
->response
, false);
1068 // Copy the byte array, used for this modulation to the buffer position
1069 memcpy(response_info
->modulation
, ts
->buf
, ts
->max
);
1071 // Store the number of bytes that were used for encoding/modulation and the time needed to transfer them
1072 response_info
->modulation_n
= ts
->max
;
1073 response_info
->ProxToAirDuration
= LastProxToAirDuration
;
1077 bool prepare_allocated_tag_modulation(tag_response_info_t
*response_info
, uint8_t **buffer
, size_t *max_buffer_size
) {
1079 tosend_t
*ts
= get_tosend();
1081 // Retrieve and store the current buffer index
1082 response_info
->modulation
= *buffer
;
1084 // Forward the prepare tag modulation function to the inner function
1085 if (prepare_tag_modulation(response_info
, *max_buffer_size
)) {
1086 // Update the free buffer offset and the remaining buffer size
1088 *max_buffer_size
-= ts
->max
;
1095 bool SimulateIso14443aInit(uint8_t tagType
, uint16_t flags
, uint8_t *data
, uint8_t *iRATs
, tag_response_info_t
**responses
,
1096 uint32_t *cuid
, uint32_t counters
[3], uint8_t tearings
[3], uint8_t *pages
) {
1098 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
1099 static uint8_t rATQA
[2] = { 0x00 };
1100 // The second response contains the (mandatory) first 24 bits of the UID
1101 static uint8_t rUIDc1
[5] = { 0x00 };
1103 static uint8_t rUIDc2
[5] = { 0x00 };
1105 static uint8_t rUIDc3
[5] = { 0x00 };
1106 // Prepare the mandatory SAK (for 4, 7 and 10 byte UID)
1107 static uint8_t rSAKc1
[3] = { 0x00 };
1108 // Prepare the optional second SAK (for 7 and 10 byte UID), drop the cascade bit for 7b
1109 static uint8_t rSAKc2
[3] = { 0x00 };
1110 // Prepare the optional third SAK (for 10 byte UID), drop the cascade bit
1111 static uint8_t rSAKc3
[3] = { 0x00 };
1112 // dummy ATS (pseudo-ATR), answer to RATS
1113 // Format byte = 0x58: FSCI=0x08 (FSC=256), TA(1) and TC(1) present,
1114 // TA(1) = 0x80: different divisors not supported, DR = 1, DS = 1
1115 // 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)
1116 // TC(1) = 0x02: CID supported, NAD not supported
1117 // static uint8_t rRATS[] = { 0x04, 0x58, 0x80, 0x02, 0x00, 0x00 };
1118 static uint8_t rRATS
[40] = { 0x05, 0x75, 0x80, 0x60, 0x02, 0x00, 0x00, 0x00 };
1119 uint8_t rRATS_len
= 8;
1121 // GET_VERSION response for EV1/NTAG
1122 static uint8_t rVERSION
[10] = { 0x00 };
1123 // READ_SIG response for EV1/NTAG
1124 static uint8_t rSIGN
[34] = { 0x00 };
1126 static uint8_t rPPS
[3] = { 0xD0 };
1128 static uint8_t rPACK
[4] = { 0x00, 0x00, 0x00, 0x00 };
1131 case 1: { // MIFARE Classic 1k
1136 case 2: { // MIFARE Ultralight
1139 // some first pages of UL/NTAG dump is special data
1140 mfu_dump_t
*mfu_header
= (mfu_dump_t
*) BigBuf_get_EM_addr();
1141 *pages
= MAX(mfu_header
->pages
, 15);
1143 // counters and tearing flags
1144 // for old dumps with all zero headers, we need to set default values.
1145 for (uint8_t i
= 0; i
< 3; i
++) {
1147 counters
[i
] = le24toh(mfu_header
->counter_tearing
[i
]);
1149 if (mfu_header
->counter_tearing
[i
][3] != 0x00) {
1150 tearings
[i
] = mfu_header
->counter_tearing
[i
][3];
1155 if (memcmp(mfu_header
->version
, "\x00\x00\x00\x00\x00\x00\x00\x00", 8) == 0) {
1156 memcpy(rVERSION
, "\x00\x04\x04\x02\x01\x00\x11\x03", 8);
1158 memcpy(rVERSION
, mfu_header
->version
, 8);
1160 AddCrc14A(rVERSION
, sizeof(rVERSION
) - 2);
1163 memcpy(rSIGN
, mfu_header
->signature
, 32);
1164 AddCrc14A(rSIGN
, sizeof(rSIGN
) - 2);
1167 case 3: { // MIFARE DESFire
1171 memcpy(rRATS
, "\x06\x75\x77\x81\x02\x80\x00\x00", 8);
1175 case 4: { // ISO/IEC 14443-4 - javacard (JCOP)
1180 case 5: { // MIFARE TNP3XXX
1186 case 6: { // MIFARE Mini 320b
1191 case 7: { // NTAG 215
1194 // some first pages of UL/NTAG dump is special data
1195 mfu_dump_t
*mfu_header
= (mfu_dump_t
*) BigBuf_get_EM_addr();
1196 *pages
= MAX(mfu_header
->pages
, 19);
1198 // counters and tearing flags
1199 // for old dumps with all zero headers, we need to set default values.
1200 for (uint8_t i
= 0; i
< 3; i
++) {
1202 counters
[i
] = le24toh(mfu_header
->counter_tearing
[i
]);
1204 if (mfu_header
->counter_tearing
[i
][3] != 0x00) {
1205 tearings
[i
] = mfu_header
->counter_tearing
[i
][3];
1210 if (memcmp(mfu_header
->version
, "\x00\x00\x00\x00\x00\x00\x00\x00", 8) == 0) {
1211 memcpy(rVERSION
, "\x00\x04\x04\x02\x01\x00\x11\x03", 8);
1213 memcpy(rVERSION
, mfu_header
->version
, 8);
1215 AddCrc14A(rVERSION
, sizeof(rVERSION
) - 2);
1218 memcpy(rSIGN
, mfu_header
->signature
, 32);
1219 AddCrc14A(rSIGN
, sizeof(rSIGN
) - 2);
1222 case 8: { // MIFARE Classic 4k
1227 case 9: { // FM11RF005SH (Shanghai Metro)
1233 case 10: { // ST25TA IKEA Rothult
1239 case 11: { // ISO/IEC 14443-4 - javacard (JCOP) / EMV
1241 memcpy(rRATS
, "\x13\x78\x80\x72\x02\x80\x31\x80\x66\xb1\x84\x0c\x01\x6e\x01\x83\x00\x90\x00", 19);
1247 case 12: { // HID Seos 4K card
1253 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Error: unknown tagtype (%d)", tagType
);
1258 // copy the iRATs if supplied
1259 if ((flags
& FLAG_RATS_IN_DATA
) == FLAG_RATS_IN_DATA
) {
1260 memcpy(rRATS
, iRATs
, sizeof(iRATs
));
1261 // rats len is dictated by the first char of the string, add 2 crc bytes
1262 rRATS_len
= (iRATs
[0] + 2);
1265 // if uid not supplied then get from emulator memory
1266 if ((memcmp(data
, "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 10) == 0) || IS_FLAG_UID_IN_EMUL(flags
)) {
1267 if (tagType
== 2 || tagType
== 7) {
1268 uint16_t start
= MFU_DUMP_PREFIX_LENGTH
;
1270 emlGet(emdata
, start
, sizeof(emdata
));
1271 memcpy(data
, emdata
, 3); // uid bytes 0-2
1272 memcpy(data
+ 3, emdata
+ 4, 4); // uid bytes 3-7
1273 FLAG_SET_UID_IN_DATA(flags
, 7);
1276 FLAG_SET_UID_IN_DATA(flags
, 4);
1280 if (IS_FLAG_UID_IN_DATA(flags
, 4)) {
1281 rUIDc1
[0] = data
[0];
1282 rUIDc1
[1] = data
[1];
1283 rUIDc1
[2] = data
[2];
1284 rUIDc1
[3] = data
[3];
1285 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1287 // Configure the ATQA and SAK accordingly
1290 if (tagType
== 11) {
1291 rSAKc1
[0] = sak
& 0xFC & 0X70;
1293 rSAKc1
[0] = sak
& 0xFB;
1296 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1298 *cuid
= bytes_to_num(data
, 4);
1299 } else if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
1300 rUIDc1
[0] = MIFARE_SELECT_CT
; // Cascade Tag marker
1301 rUIDc1
[1] = data
[0];
1302 rUIDc1
[2] = data
[1];
1303 rUIDc1
[3] = data
[2];
1304 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1306 rUIDc2
[0] = data
[3];
1307 rUIDc2
[1] = data
[4];
1308 rUIDc2
[2] = data
[5];
1309 rUIDc2
[3] = data
[6];
1310 rUIDc2
[4] = rUIDc2
[0] ^ rUIDc2
[1] ^ rUIDc2
[2] ^ rUIDc2
[3];
1312 // Configure the ATQA and SAK accordingly
1316 rSAKc2
[0] = sak
& 0xFB;
1317 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1318 AddCrc14A(rSAKc2
, sizeof(rSAKc2
) - 2);
1320 *cuid
= bytes_to_num(data
+ 3, 4);
1322 } else if (IS_FLAG_UID_IN_DATA(flags
, 10)) {
1324 rUIDc1
[0] = MIFARE_SELECT_CT
; // Cascade Tag marker
1325 rUIDc1
[1] = data
[0];
1326 rUIDc1
[2] = data
[1];
1327 rUIDc1
[3] = data
[2];
1328 rUIDc1
[4] = rUIDc1
[0] ^ rUIDc1
[1] ^ rUIDc1
[2] ^ rUIDc1
[3];
1330 rUIDc2
[0] = MIFARE_SELECT_CT
; // Cascade Tag marker
1331 rUIDc2
[1] = data
[3];
1332 rUIDc2
[2] = data
[4];
1333 rUIDc2
[3] = data
[5];
1334 rUIDc2
[4] = rUIDc2
[0] ^ rUIDc2
[1] ^ rUIDc2
[2] ^ rUIDc2
[3];
1336 rUIDc3
[0] = data
[6];
1337 rUIDc3
[1] = data
[7];
1338 rUIDc3
[2] = data
[8];
1339 rUIDc3
[3] = data
[9];
1340 rUIDc3
[4] = rUIDc3
[0] ^ rUIDc3
[1] ^ rUIDc3
[2] ^ rUIDc3
[3];
1342 // Configure the ATQA and SAK accordingly
1347 rSAKc3
[0] = sak
& 0xFB;
1348 AddCrc14A(rSAKc1
, sizeof(rSAKc1
) - 2);
1349 AddCrc14A(rSAKc2
, sizeof(rSAKc2
) - 2);
1350 AddCrc14A(rSAKc3
, sizeof(rSAKc3
) - 2);
1352 *cuid
= bytes_to_num(data
+ 3 + 3, 4);
1354 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("[-] ERROR: UID size not defined");
1358 AddCrc14A(rRATS
, rRATS_len
- 2);
1360 AddCrc14A(rPPS
, sizeof(rPPS
) - 2);
1362 // EV1/NTAG, set PWD w AMIIBO algo if all zero.
1364 uint8_t pwd
[4] = {0, 0, 0, 0};
1365 uint8_t gen_pwd
[4] = {0, 0, 0, 0};
1366 emlGet(pwd
, (*pages
- 1) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(pwd
));
1367 emlGet(rPACK
, (*pages
) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(rPACK
));
1369 Uint4byteToMemBe(gen_pwd
, ul_ev1_pwdgenB(data
));
1370 if (memcmp(pwd
, gen_pwd
, sizeof(pwd
)) == 0) {
1376 AddCrc14A(rPACK
, sizeof(rPACK
) - 2);
1378 static tag_response_info_t responses_init
[] = {
1379 { .response
= rATQA
, .response_n
= sizeof(rATQA
) }, // Answer to request - respond with card type
1380 { .response
= rUIDc1
, .response_n
= sizeof(rUIDc1
) }, // Anticollision cascade1 - respond with uid
1381 { .response
= rUIDc2
, .response_n
= sizeof(rUIDc2
) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1382 { .response
= rUIDc3
, .response_n
= sizeof(rUIDc3
) }, // Anticollision cascade3 - respond with 3rd half of uid if asked
1383 { .response
= rSAKc1
, .response_n
= sizeof(rSAKc1
) }, // Acknowledge select - cascade 1
1384 { .response
= rSAKc2
, .response_n
= sizeof(rSAKc2
) }, // Acknowledge select - cascade 2
1385 { .response
= rSAKc3
, .response_n
= sizeof(rSAKc3
) }, // Acknowledge select - cascade 3
1386 { .response
= rRATS
, .response_n
= sizeof(rRATS
) }, // dummy ATS (pseudo-ATR), answer to RATS
1387 { .response
= rVERSION
, .response_n
= sizeof(rVERSION
) }, // EV1/NTAG GET_VERSION response
1388 { .response
= rSIGN
, .response_n
= sizeof(rSIGN
) }, // EV1/NTAG READ_SIG response
1389 { .response
= rPPS
, .response_n
= sizeof(rPPS
) }, // PPS response
1390 { .response
= rPACK
, .response_n
= sizeof(rPACK
) } // PACK response
1393 // since rats len is variable now.
1394 responses_init
[RESP_INDEX_RATS
].response_n
= rRATS_len
;
1396 // "precompiled" responses.
1397 // These exist for speed reasons. There are no time in the anti collision phase to calculate responses.
1398 // There are 12 predefined responses with a total of 84 bytes data to transmit.
1400 // Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
1401 // 85 * 8 data bits, 85 * 1 parity bits, 12 start bits, 12 stop bits, 12 correction bits
1402 // 85 * 8 + 85 + 12 + 12 + 12 == 801
1404 // 85 bytes normally (rats = 8 bytes)
1405 // 77 bytes + ratslen,
1407 #define ALLOCATED_TAG_MODULATION_BUFFER_SIZE ( ((77 + rRATS_len) * 8) + 77 + rRATS_len + 12 + 12 + 12)
1409 uint8_t *free_buffer
= BigBuf_calloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE
);
1410 // modulation buffer pointer and current buffer free space size
1411 uint8_t *free_buffer_pointer
= free_buffer
;
1412 size_t free_buffer_size
= ALLOCATED_TAG_MODULATION_BUFFER_SIZE
;
1414 // Prepare the responses of the anticollision phase
1415 // there will be not enough time to do this at the moment the reader sends it REQA
1416 for (size_t i
= 0; i
< ARRAYLEN(responses_init
); i
++) {
1417 if (prepare_allocated_tag_modulation(&responses_init
[i
], &free_buffer_pointer
, &free_buffer_size
) == false) {
1418 BigBuf_free_keep_EM();
1419 if (g_dbglevel
>= DBG_ERROR
) Dbprintf("Not enough modulation buffer size, exit after %d elements", i
);
1424 *responses
= responses_init
;
1428 //-----------------------------------------------------------------------------
1429 // Main loop of simulated tag: receive commands from reader, decide what
1430 // response to send, and send it.
1432 //-----------------------------------------------------------------------------
1433 void SimulateIso14443aTag(uint8_t tagType
, uint16_t flags
, uint8_t *data
, uint8_t exitAfterNReads
, uint8_t *iRATs
) {
1435 #define ATTACK_KEY_COUNT 16
1437 tag_response_info_t
*responses
;
1440 uint32_t counters
[3] = { 0x00, 0x00, 0x00 };
1441 uint8_t tearings
[3] = { 0xbd, 0xbd, 0xbd };
1444 // Here, we collect CUID, block1, keytype1, NT1, NR1, AR1, CUID, block2, keytyp2, NT2, NR2, AR2
1445 // it should also collect block, keytype.
1446 uint8_t cardAUTHSC
= 0;
1447 uint8_t cardAUTHKEY
= 0xff; // no authentication
1448 // allow collecting up to 8 sets of nonces to allow recovery of up to 8 keys
1450 nonces_t ar_nr_nonces
[ATTACK_KEY_COUNT
]; // for attack types moebius
1451 memset(ar_nr_nonces
, 0x00, sizeof(ar_nr_nonces
));
1452 uint8_t moebius_count
= 0;
1455 uint8_t receivedCmd
[MAX_FRAME_SIZE
] = { 0x00 };
1456 uint8_t receivedCmdPar
[MAX_PARITY_SIZE
] = { 0x00 };
1458 // free eventually allocated BigBuf memory but keep Emulator Memory
1459 BigBuf_free_keep_EM();
1461 // Allocate 512 bytes for the dynamic modulation, created when the reader queries for it
1462 // Such a response is less time critical, so we can prepare them on the fly
1463 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1464 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1466 uint8_t *dynamic_response_buffer
= BigBuf_calloc(DYNAMIC_RESPONSE_BUFFER_SIZE
);
1467 uint8_t *dynamic_modulation_buffer
= BigBuf_calloc(DYNAMIC_MODULATION_BUFFER_SIZE
);
1468 tag_response_info_t dynamic_response_info
= {
1469 .response
= dynamic_response_buffer
,
1471 .modulation
= dynamic_modulation_buffer
,
1475 if (SimulateIso14443aInit(tagType
, flags
, data
, iRATs
, &responses
, &cuid
, counters
, tearings
, &pages
) == false) {
1476 BigBuf_free_keep_EM();
1477 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_EINIT
, NULL
, 0);
1481 // We need to listen to the high-frequency, peak-detected path.
1482 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
1484 iso14a_set_timeout(201400); // 106 * 19ms default *100?
1488 // To control where we are in the protocol
1489 #define ORDER_NONE 0
1490 //#define ORDER_REQA 1
1491 //#define ORDER_SELECT_ALL_CL1 2
1492 //#define ORDER_SELECT_CL1 3
1493 #define ORDER_HALTED 5
1494 #define ORDER_WUPA 6
1495 #define ORDER_AUTH 7
1496 //#define ORDER_SELECT_ALL_CL2 20
1497 //#define ORDER_SELECT_CL2 25
1498 //#define ORDER_SELECT_ALL_CL3 30
1499 //#define ORDER_SELECT_CL3 35
1500 #define ORDER_EV1_COMP_WRITE 40
1501 //#define ORDER_RATS 70
1503 uint8_t order
= ORDER_NONE
;
1504 int retval
= PM3_SUCCESS
;
1506 // Just to allow some checks
1507 // int happened = 0;
1508 // int happened2 = 0;
1510 uint32_t numReads
= 0; //Counts numer of times reader reads a block
1512 // compatible write block number
1513 uint8_t wrblock
= 0;
1515 bool odd_reply
= true;
1522 bool finished
= false;
1523 while (finished
== false) {
1524 // BUTTON_PRESS check done in GetIso14443aCommandFromReader
1527 tag_response_info_t
*p_response
= NULL
;
1529 // Clean receive command buffer
1530 if (GetIso14443aCommandFromReader(receivedCmd
, sizeof(receivedCmd
), receivedCmdPar
, &len
) == false) {
1531 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
1532 retval
= PM3_EOPABORTED
;
1536 // we need to check "ordered" states before, because received data may be same to any command - is wrong!!!
1537 if (order
== ORDER_EV1_COMP_WRITE
&& len
== 18) {
1538 // MIFARE_ULC_COMP_WRITE part 2
1539 // 16 bytes data + 2 bytes crc, only least significant 4 bytes are written
1540 bool isCrcCorrect
= CheckCrc14A(receivedCmd
, len
);
1542 // first blocks of emu are header
1543 emlSetMem_xt(receivedCmd
, wrblock
+ MFU_DUMP_PREFIX_LENGTH
/ 4, 1, 4);
1545 EmSend4bit(CARD_ACK
);
1547 // send NACK 0x1 == crc/parity error
1548 EmSend4bit(CARD_NACK_PA
);
1550 order
= ORDER_NONE
; // back to work state
1553 } else if (order
== ORDER_AUTH
&& len
== 8) {
1554 // Received {nr] and {ar} (part of authentication)
1555 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1556 uint32_t nr
= bytes_to_num(receivedCmd
, 4);
1557 uint32_t ar
= bytes_to_num(receivedCmd
+ 4, 4);
1559 // Collect AR/NR per keytype & sector
1560 if ((flags
& FLAG_NR_AR_ATTACK
) == FLAG_NR_AR_ATTACK
) {
1564 for (uint8_t i
= 0; i
< ATTACK_KEY_COUNT
; i
++) {
1565 // find which index to use
1566 if ((cardAUTHSC
== ar_nr_nonces
[i
].sector
) && (cardAUTHKEY
== ar_nr_nonces
[i
].keytype
))
1569 // keep track of empty slots.
1570 if (ar_nr_nonces
[i
].state
== EMPTY
)
1573 // if no empty slots. Choose first and overwrite.
1577 ar_nr_nonces
[index
].state
= EMPTY
;
1583 switch ((nonce_state
)ar_nr_nonces
[index
].state
) {
1585 // first nonce collect
1586 ar_nr_nonces
[index
].cuid
= cuid
;
1587 ar_nr_nonces
[index
].sector
= cardAUTHSC
;
1588 ar_nr_nonces
[index
].keytype
= cardAUTHKEY
;
1589 ar_nr_nonces
[index
].nonce
= nonce
;
1590 ar_nr_nonces
[index
].nr
= nr
;
1591 ar_nr_nonces
[index
].ar
= ar
;
1592 ar_nr_nonces
[index
].state
= FIRST
;
1596 // second nonce collect
1597 ar_nr_nonces
[index
].nonce2
= nonce
;
1598 ar_nr_nonces
[index
].nr2
= nr
;
1599 ar_nr_nonces
[index
].ar2
= ar
;
1600 ar_nr_nonces
[index
].state
= SECOND
;
1602 // send to client (one struct nonces_t)
1603 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_SUCCESS
, (uint8_t *)&ar_nr_nonces
[index
], sizeof(nonces_t
));
1605 ar_nr_nonces
[index
].state
= EMPTY
;
1606 ar_nr_nonces
[index
].sector
= 0;
1607 ar_nr_nonces
[index
].keytype
= 0;
1616 order
= ORDER_NONE
; // back to work state
1619 } else if (receivedCmd
[0] == ISO14443A_CMD_REQA
&& len
== 1) { // Received a REQUEST, but in HALTED, skip
1620 odd_reply
= !odd_reply
;
1622 p_response
= &responses
[RESP_INDEX_ATQA
];
1624 } else if (receivedCmd
[0] == ISO14443A_CMD_WUPA
&& len
== 1) { // Received a WAKEUP
1625 p_response
= &responses
[RESP_INDEX_ATQA
];
1626 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 2) { // Received request for UID (cascade 1)
1627 p_response
= &responses
[RESP_INDEX_UIDC1
];
1628 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 2) { // Received request for UID (cascade 2)
1629 p_response
= &responses
[RESP_INDEX_UIDC2
];
1630 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 2) { // Received request for UID (cascade 3)
1631 p_response
= &responses
[RESP_INDEX_UIDC3
];
1632 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 9) { // Received a SELECT (cascade 1)
1633 p_response
= &responses
[RESP_INDEX_SAKC1
];
1634 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 9) { // Received a SELECT (cascade 2)
1635 p_response
= &responses
[RESP_INDEX_SAKC2
];
1636 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 9) { // Received a SELECT (cascade 3)
1637 p_response
= &responses
[RESP_INDEX_SAKC3
];
1638 } else if (receivedCmd
[0] == ISO14443A_CMD_PPS
) {
1639 p_response
= &responses
[RESP_INDEX_PPS
];
1640 } else if (receivedCmd
[0] == ISO14443A_CMD_READBLOCK
&& len
== 4) { // Received a (plain) READ
1641 uint8_t block
= receivedCmd
[1];
1642 // if Ultralight or NTAG (4 byte blocks)
1643 if (tagType
== 7 || tagType
== 2) {
1644 if (block
> pages
) {
1645 // send NACK 0x0 == invalid argument
1646 EmSend4bit(CARD_NACK_IV
);
1648 // first blocks of emu are header
1649 uint16_t start
= block
* 4 + MFU_DUMP_PREFIX_LENGTH
;
1650 uint8_t emdata
[MAX_MIFARE_FRAME_SIZE
];
1651 emlGet(emdata
, start
, 16);
1652 AddCrc14A(emdata
, 16);
1653 EmSendCmd(emdata
, sizeof(emdata
));
1654 numReads
++; // Increment number of times reader requested a block
1656 if (exitAfterNReads
> 0 && numReads
== exitAfterNReads
) {
1657 Dbprintf("[MFUEMUL_WORK] %d reads done, exiting", numReads
);
1661 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1663 } else if (tagType
== 9 && block
== 1) {
1664 // FM11005SH. 16blocks, 4bytes / block.
1665 // block0 = 2byte Customer ID (CID), 2byte Manufacture ID (MID)
1666 // block1 = 4byte UID.
1667 p_response
= &responses
[RESP_INDEX_UIDC1
];
1668 } else { // all other tags (16 byte block tags)
1669 uint8_t emdata
[MAX_MIFARE_FRAME_SIZE
] = {0};
1670 emlGet(emdata
, block
, 16);
1671 AddCrc14A(emdata
, 16);
1672 EmSendCmd(emdata
, sizeof(emdata
));
1673 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1676 } else if (receivedCmd
[0] == MIFARE_ULEV1_FASTREAD
&& len
== 5) { // Received a FAST READ (ranged read)
1677 uint8_t block1
= receivedCmd
[1];
1678 uint8_t block2
= receivedCmd
[2];
1679 if (block1
> pages
) {
1680 // send NACK 0x0 == invalid argument
1681 EmSend4bit(CARD_NACK_IV
);
1683 uint8_t emdata
[MAX_FRAME_SIZE
] = {0};
1684 // first blocks of emu are header
1685 int start
= block1
* 4 + MFU_DUMP_PREFIX_LENGTH
;
1686 len
= (block2
- block1
+ 1) * 4;
1687 emlGet(emdata
, start
, len
);
1688 AddCrc14A(emdata
, len
);
1689 EmSendCmd(emdata
, len
+ 2);
1692 } else if (receivedCmd
[0] == MIFARE_ULC_WRITE
&& len
== 8 && (tagType
== 2 || tagType
== 7)) { // Received a WRITE
1693 // cmd + block + 4 bytes data + 2 bytes crc
1694 if (CheckCrc14A(receivedCmd
, len
)) {
1695 uint8_t block
= receivedCmd
[1];
1696 if (block
> pages
) {
1697 // send NACK 0x0 == invalid argument
1698 EmSend4bit(CARD_NACK_IV
);
1700 // first blocks of emu are header
1701 emlSetMem_xt(&receivedCmd
[2], block
+ MFU_DUMP_PREFIX_LENGTH
/ 4, 1, 4);
1703 EmSend4bit(CARD_ACK
);
1706 // send NACK 0x1 == crc/parity error
1707 EmSend4bit(CARD_NACK_PA
);
1710 } else if (receivedCmd
[0] == MIFARE_ULC_COMP_WRITE
&& len
== 4 && (tagType
== 2 || tagType
== 7)) {
1711 // cmd + block + 2 bytes crc
1712 if (CheckCrc14A(receivedCmd
, len
)) {
1713 wrblock
= receivedCmd
[1];
1714 if (wrblock
> pages
) {
1715 // send NACK 0x0 == invalid argument
1716 EmSend4bit(CARD_NACK_IV
);
1719 EmSend4bit(CARD_ACK
);
1721 order
= ORDER_EV1_COMP_WRITE
;
1724 // send NACK 0x1 == crc/parity error
1725 EmSend4bit(CARD_NACK_PA
);
1728 } else if (receivedCmd
[0] == MIFARE_ULEV1_READSIG
&& len
== 4 && tagType
== 7) { // Received a READ SIGNATURE --
1729 p_response
= &responses
[RESP_INDEX_SIGNATURE
];
1730 } else if (receivedCmd
[0] == MIFARE_ULEV1_READ_CNT
&& len
== 4 && tagType
== 7) { // Received a READ COUNTER --
1731 uint8_t index
= receivedCmd
[1];
1733 // send NACK 0x0 == invalid argument
1734 EmSend4bit(CARD_NACK_IV
);
1736 uint8_t cmd
[] = {0x00, 0x00, 0x00, 0x14, 0xa5};
1737 htole24(counters
[index
], cmd
);
1738 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1739 EmSendCmd(cmd
, sizeof(cmd
));
1742 } else if (receivedCmd
[0] == MIFARE_ULEV1_INCR_CNT
&& len
== 8 && tagType
== 7) { // Received a INC COUNTER --
1743 uint8_t index
= receivedCmd
[1];
1745 // send NACK 0x0 == invalid argument
1746 EmSend4bit(CARD_NACK_IV
);
1748 uint32_t val
= le24toh(receivedCmd
+ 2) + counters
[index
];
1749 // if new value + old value is bigger 24bits, fail
1750 if (val
> 0xFFFFFF) {
1751 // send NACK 0x4 == counter overflow
1752 EmSend4bit(CARD_NACK_NA
);
1754 counters
[index
] = val
;
1756 EmSend4bit(CARD_ACK
);
1760 } else if (receivedCmd
[0] == MIFARE_ULEV1_CHECKTEAR
&& len
== 4 && tagType
== 7) { // Received a CHECK_TEARING_EVENT --
1761 // first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1762 uint8_t index
= receivedCmd
[1];
1764 // send NACK 0x0 == invalid argument
1765 EmSend4bit(CARD_NACK_IV
);
1767 uint8_t cmd
[3] = {0, 0, 0};
1768 cmd
[0] = tearings
[index
];
1769 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1770 EmSendCmd(cmd
, sizeof(cmd
));
1773 } else if (receivedCmd
[0] == ISO14443A_CMD_HALT
&& len
== 4) { // Received a HALT
1774 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1776 order
= ORDER_HALTED
;
1777 } else if (receivedCmd
[0] == MIFARE_ULEV1_VERSION
&& len
== 3 && (tagType
== 2 || tagType
== 7)) {
1778 p_response
= &responses
[RESP_INDEX_VERSION
];
1779 } else if (receivedCmd
[0] == MFDES_GET_VERSION
&& len
== 4 && (tagType
== 3)) {
1780 p_response
= &responses
[RESP_INDEX_VERSION
];
1781 } else if ((receivedCmd
[0] == MIFARE_AUTH_KEYA
|| receivedCmd
[0] == MIFARE_AUTH_KEYB
) && len
== 4 && tagType
!= 2 && tagType
!= 7) { // Received an authentication request
1782 cardAUTHKEY
= receivedCmd
[0] - 0x60;
1783 cardAUTHSC
= receivedCmd
[1] / 4; // received block num
1785 // incease nonce at AUTH requests. this is time consuming.
1786 nonce
= prng_successor(GetTickCount(), 32);
1787 num_to_bytes(nonce
, 4, dynamic_response_info
.response
);
1788 dynamic_response_info
.response_n
= 4;
1790 prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
);
1791 p_response
= &dynamic_response_info
;
1793 } else if (receivedCmd
[0] == ISO14443A_CMD_RATS
&& len
== 4) { // Received a RATS request
1794 if (tagType
== 1 || tagType
== 2) { // RATS not supported
1795 EmSend4bit(CARD_NACK_NA
);
1798 p_response
= &responses
[RESP_INDEX_RATS
];
1800 } else if (receivedCmd
[0] == MIFARE_ULC_AUTH_1
) { // ULC authentication, or Desfire Authentication
1801 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1803 } else if (receivedCmd
[0] == MIFARE_ULEV1_AUTH
&& len
== 7 && tagType
== 7) { // NTAG / EV-1
1804 uint8_t pwd
[4] = {0, 0, 0, 0};
1805 emlGet(pwd
, (pages
- 1) * 4 + MFU_DUMP_PREFIX_LENGTH
, sizeof(pwd
));
1806 if (g_dbglevel
>= DBG_DEBUG
) {
1807 Dbprintf("Reader sent password: ");
1808 Dbhexdump(4, receivedCmd
+ 1, 0);
1809 Dbprintf("Loaded password from memory: ");
1810 Dbhexdump(4, pwd
, 0);
1813 if (memcmp(pwd
, "\x00\x00\x00\x00", 4) == 0) {
1814 Uint4byteToMemLe(pwd
, ul_ev1_pwdgenB(data
));
1815 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Calc pwd... %02X %02X %02X %02X", pwd
[0], pwd
[1], pwd
[2], pwd
[3]);
1818 if (memcmp(receivedCmd
+ 1, pwd
, 4) == 0) {
1819 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Password match, responding with PACK.");
1820 p_response
= &responses
[RESP_INDEX_PACK
];
1822 if (g_dbglevel
>= DBG_DEBUG
) Dbprintf("Password did not match, NACK_IV.");
1824 EmSend4bit(CARD_NACK_IV
);
1827 } else if (receivedCmd
[0] == MIFARE_ULEV1_VCSL
&& len
== 23 && tagType
== 7) {
1828 uint8_t cmd
[3] = {0, 0, 0};
1829 emlGet(cmd
, (pages
- 2) * 4 + 1 + MFU_DUMP_PREFIX_LENGTH
, 1);
1830 AddCrc14A(cmd
, sizeof(cmd
) - 2);
1831 EmSendCmd(cmd
, sizeof(cmd
));
1836 // clear old dynamic responses
1837 dynamic_response_info
.response_n
= 0;
1838 dynamic_response_info
.modulation_n
= 0;
1840 // ST25TA512B IKEA Rothult
1841 if (tagType
== 10) {
1842 // we replay 90 00 for all commands but the read bin and we deny the verify cmd.
1844 if (memcmp("\x02\xa2\xb0\x00\x00\x1d\x51\x69", receivedCmd
, 8) == 0) {
1845 dynamic_response_info
.response
[0] = receivedCmd
[0];
1846 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);
1847 dynamic_response_info
.response_n
= 32;
1848 } else if (memcmp("\x02\x00\x20\x00\x01\x00\x6e\xa9", receivedCmd
, 8) == 0) {
1849 dynamic_response_info
.response
[0] = receivedCmd
[0];
1850 dynamic_response_info
.response
[1] = 0x63;
1851 dynamic_response_info
.response
[2] = 0x00;
1852 dynamic_response_info
.response_n
= 3;
1853 } else if (memcmp("\x03\x00\x20\x00\x01\x10", receivedCmd
, 6) == 0) {
1854 Dbprintf("Reader sent password: ");
1855 Dbhexdump(16, receivedCmd
+ 6, 0);
1856 dynamic_response_info
.response
[0] = receivedCmd
[0];
1857 dynamic_response_info
.response
[1] = 0x90;
1858 dynamic_response_info
.response
[2] = 0x00;
1859 dynamic_response_info
.response_n
= 3;
1861 dynamic_response_info
.response
[0] = receivedCmd
[0];
1862 dynamic_response_info
.response
[1] = 0x90;
1863 dynamic_response_info
.response
[2] = 0x00;
1864 dynamic_response_info
.response_n
= 3;
1868 // Check for ISO 14443A-4 compliant commands, look at left nibble
1869 switch (receivedCmd
[0]) {
1871 case 0x03: { // IBlock (command no CID)
1872 dynamic_response_info
.response
[0] = receivedCmd
[0];
1873 dynamic_response_info
.response
[1] = 0x90;
1874 dynamic_response_info
.response
[2] = 0x00;
1875 dynamic_response_info
.response_n
= 3;
1879 case 0x0A: { // IBlock (command CID)
1880 dynamic_response_info
.response
[0] = receivedCmd
[0];
1881 dynamic_response_info
.response
[1] = 0x00;
1882 dynamic_response_info
.response
[2] = 0x90;
1883 dynamic_response_info
.response
[3] = 0x00;
1884 dynamic_response_info
.response_n
= 4;
1889 case 0x1B: { // Chaining command
1890 dynamic_response_info
.response
[0] = 0xaa | ((receivedCmd
[0]) & 1);
1891 dynamic_response_info
.response_n
= 2;
1897 dynamic_response_info
.response
[0] = receivedCmd
[0] ^ 0x11;
1898 dynamic_response_info
.response_n
= 2;
1902 case 0xBA: { // ping / pong
1903 dynamic_response_info
.response
[0] = 0xAB;
1904 dynamic_response_info
.response
[1] = 0x00;
1905 dynamic_response_info
.response_n
= 2;
1910 case 0xC2: { // Readers sends deselect command
1911 dynamic_response_info
.response
[0] = 0xCA;
1912 dynamic_response_info
.response
[1] = 0x00;
1913 dynamic_response_info
.response_n
= 2;
1918 // Never seen this command before
1919 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1920 if (g_dbglevel
>= DBG_DEBUG
) {
1921 Dbprintf("Received unknown command (len=%d):", len
);
1922 Dbhexdump(len
, receivedCmd
, false);
1925 dynamic_response_info
.response_n
= 0;
1926 order
= ORDER_NONE
; // back to work state
1932 if (dynamic_response_info
.response_n
> 0) {
1934 // Copy the CID from the reader query
1936 dynamic_response_info
.response
[1] = receivedCmd
[1];
1938 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1939 AddCrc14A(dynamic_response_info
.response
, dynamic_response_info
.response_n
);
1940 dynamic_response_info
.response_n
+= 2;
1942 if (prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
1943 if (g_dbglevel
>= DBG_DEBUG
) DbpString("Error preparing tag response");
1944 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
1947 p_response
= &dynamic_response_info
;
1951 // Count number of wakeups received after a halt
1952 // if (order == ORDER_WUPA && lastorder == ORDER_HALTED) { happened++; }
1954 // Count number of other messages after a halt
1955 // if (order != ORDER_WUPA && lastorder == ORDER_HALTED) { happened2++; }
1960 EmSendPrecompiledCmd(p_response
);
1966 BigBuf_free_keep_EM();
1968 if (g_dbglevel
>= DBG_EXTENDED
) {
1969 // Dbprintf("-[ Wake ups after halt [%d]", happened);
1970 // Dbprintf("-[ Messages after halt [%d]", happened2);
1971 Dbprintf("-[ Num of received cmd [%d]", cmdsRecvd
);
1972 Dbprintf("-[ Num of moebius tries [%d]", moebius_count
);
1975 reply_ng(CMD_HF_MIFARE_SIMULATE
, retval
, NULL
, 0);
1978 // prepare a delayed transfer. This simply shifts ToSend[] by a number
1979 // of bits specified in the delay parameter.
1980 static void PrepareDelayedTransfer(uint16_t delay
) {
1984 uint8_t bitmask
= 0;
1985 uint8_t bits_shifted
= 0;
1987 for (uint16_t i
= 0; i
< delay
; i
++)
1988 bitmask
|= (0x01 << i
);
1990 tosend_t
*ts
= get_tosend();
1992 ts
->buf
[ts
->max
++] = 0x00;
1994 for (uint32_t i
= 0; i
< ts
->max
; i
++) {
1995 uint8_t bits_to_shift
= ts
->buf
[i
] & bitmask
;
1996 ts
->buf
[i
] = ts
->buf
[i
] >> delay
;
1997 ts
->buf
[i
] = ts
->buf
[i
] | (bits_shifted
<< (8 - delay
));
1998 bits_shifted
= bits_to_shift
;
2003 //-------------------------------------------------------------------------------------
2004 // Transmit the command (to the tag) that was placed in ToSend[].
2005 // Parameter timing:
2006 // if NULL: transfer at next possible time, taking into account
2007 // request guard time and frame delay time
2008 // if == 0: transfer immediately and return time of transfer
2009 // if != 0: delay transfer until time specified
2010 //-------------------------------------------------------------------------------------
2011 static void TransmitFor14443a(const uint8_t *cmd
, uint16_t len
, uint32_t *timing
) {
2013 if (g_hf_field_active
== false) {
2014 Dbprintf("Warning: HF field is off");
2017 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
2020 if (*timing
== 0) // Measure time
2021 *timing
= (GetCountSspClk() + 8) & 0xfffffff8;
2023 PrepareDelayedTransfer(*timing
& 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
2025 while (GetCountSspClk() < (*timing
& 0xfffffff8)) {}; // Delay transfer (multiple of 8 MF clock ticks)
2026 LastTimeProxToAirStart
= *timing
;
2029 uint32_t ThisTransferTime
= 0;
2030 ThisTransferTime
= ((MAX(NextTransferTime
, GetCountSspClk()) & 0xfffffff8) + 8);
2032 while (GetCountSspClk() < ThisTransferTime
) {};
2034 LastTimeProxToAirStart
= ThisTransferTime
;
2039 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2040 AT91C_BASE_SSC
->SSC_THR
= cmd
[c
];
2045 NextTransferTime
= MAX(NextTransferTime
, LastTimeProxToAirStart
+ REQUEST_GUARD_TIME
);
2048 //-----------------------------------------------------------------------------
2049 // Prepare reader command (in bits, support short frames) to send to FPGA
2050 //-----------------------------------------------------------------------------
2051 static void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd
, uint16_t bits
, const uint8_t *par
) {
2055 tosend_t
*ts
= get_tosend();
2057 // Start of Communication (Seq. Z)
2058 ts
->buf
[++ts
->max
] = SEC_Z
;
2059 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2061 size_t bytecount
= nbytes(bits
);
2062 // Generate send structure for the data bits
2063 for (int i
= 0; i
< bytecount
; i
++) {
2064 // Get the current byte to send
2066 size_t bitsleft
= MIN((bits
- (i
* 8)), 8);
2068 for (j
= 0; j
< bitsleft
; j
++) {
2071 ts
->buf
[++ts
->max
] = SEC_X
;
2072 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 2;
2077 ts
->buf
[++ts
->max
] = SEC_Z
;
2078 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2081 ts
->buf
[++ts
->max
] = SEC_Y
;
2088 // Only transmit parity bit if we transmitted a complete byte
2089 if (j
== 8 && par
!= NULL
) {
2090 // Get the parity bit
2091 if (par
[i
>> 3] & (0x80 >> (i
& 0x0007))) {
2093 ts
->buf
[++ts
->max
] = SEC_X
;
2094 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 2;
2099 ts
->buf
[++ts
->max
] = SEC_Z
;
2100 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2103 ts
->buf
[++ts
->max
] = SEC_Y
;
2110 // End of Communication: Logic 0 followed by Sequence Y
2113 ts
->buf
[++ts
->max
] = SEC_Z
;
2114 LastProxToAirDuration
= 8 * (ts
->max
+ 1) - 6;
2117 ts
->buf
[++ts
->max
] = SEC_Y
;
2119 ts
->buf
[++ts
->max
] = SEC_Y
;
2121 // Convert to length of command:
2125 //-----------------------------------------------------------------------------
2126 // Prepare reader command to send to FPGA
2127 //-----------------------------------------------------------------------------
2129 static void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *par) {
2130 CodeIso14443aBitsAsReaderPar(cmd, len * 8, par);
2133 //-----------------------------------------------------------------------------
2134 // Wait for commands from reader
2135 // Stop when button is pressed (return 1) or field was gone (return 2)
2136 // Or return 0 when command is captured
2137 //-----------------------------------------------------------------------------
2138 int EmGetCmd(uint8_t *received
, uint16_t received_max_len
, uint16_t *len
, uint8_t *par
) {
2145 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
2146 // only, since we are receiving, not transmitting).
2147 // Signal field is off with the appropriate LED
2149 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2151 // Set ADC to read field strength
2152 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_SWRST
;
2153 AT91C_BASE_ADC
->ADC_MR
=
2154 ADC_MODE_PRESCALE(63) |
2155 ADC_MODE_STARTUP_TIME(1) |
2156 ADC_MODE_SAMPLE_HOLD_TIME(15);
2158 AT91C_BASE_ADC
->ADC_CHER
= ADC_CHANNEL(ADC_CHAN_HF
);
2161 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
2163 // Now run a 'software UART' on the stream of incoming samples.
2164 Uart14aInit(received
, received_max_len
, par
);
2167 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2171 uint16_t checker
= 4000;
2175 // ever 3 * 4000, check if we got any data from client
2176 // takes long time, usually messes with simualtion
2178 if (data_available()) {
2179 Dbprintf("----------- " _GREEN_("Breaking / Data") " ----------");
2185 // button press, takes a bit time, might mess with simualtion
2186 if (checker
-- == 0) {
2187 if (BUTTON_PRESS()) {
2188 Dbprintf("----------- " _GREEN_("Breaking / User aborted") " ----------");
2197 // test if the field exists
2198 if (AT91C_BASE_ADC
->ADC_SR
& ADC_END_OF_CONVERSION(ADC_CHAN_HF
)) {
2202 analogAVG
+= (AT91C_BASE_ADC
->ADC_CDR
[ADC_CHAN_HF
] & 0x3FF);
2204 AT91C_BASE_ADC
->ADC_CR
= AT91C_ADC_START
;
2206 if (analogCnt
>= 32) {
2208 if ((MAX_ADC_HF_VOLTAGE
* (analogAVG
/ analogCnt
) >> 10) < MF_MINFIELDV
) {
2211 timer
= GetTickCount();
2213 // 4ms no field --> card to idle state
2214 if (GetTickCountDelta(timer
) > 4) {
2226 // receive and test the miller decoding
2227 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2228 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2229 if (MillerDecoding(b
, 0)) {
2237 int EmSendCmd14443aRaw(const uint8_t *resp
, uint16_t respLen
) {
2240 uint32_t ThisTransferTime
;
2241 bool correction_needed
;
2243 // Modulate Manchester
2244 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_TAGSIM_MOD
);
2246 // Include correction bit if necessary
2247 if (Uart
.bitCount
== 7) {
2248 // Short tags (7 bits) don't have parity, determine the correct value from MSB
2249 correction_needed
= Uart
.output
[0] & 0x40;
2251 // The parity bits are left-aligned
2252 correction_needed
= Uart
.parity
[(Uart
.len
- 1) / 8] & (0x80 >> ((Uart
.len
- 1) & 7));
2254 // 1236, so correction bit needed
2255 i
= (correction_needed
) ? 0 : 1;
2257 // clear receiving shift register and holding register
2258 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
2259 b
= AT91C_BASE_SSC
->SSC_RHR
;
2262 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
2263 for (uint8_t j
= 0; j
< 5; j
++) { // allow timeout - better late than never
2264 while (!(AT91C_BASE_SSC
->SSC_SR
& AT91C_SSC_RXRDY
));
2265 if (AT91C_BASE_SSC
->SSC_RHR
) break;
2268 while ((ThisTransferTime
= GetCountSspClk()) & 0x00000007);
2271 AT91C_BASE_SSC
->SSC_THR
= SEC_F
;
2274 for (; i
< respLen
;) {
2275 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2276 AT91C_BASE_SSC
->SSC_THR
= resp
[i
++];
2277 FpgaSendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2281 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
2282 uint8_t fpga_queued_bits
= FpgaSendQueueDelay
>> 3;
2283 for (i
= 0; i
<= (fpga_queued_bits
>> 3) + 1;) {
2284 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
2285 AT91C_BASE_SSC
->SSC_THR
= SEC_F
;
2286 FpgaSendQueueDelay
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2290 LastTimeProxToAirStart
= ThisTransferTime
+ (correction_needed
? 8 : 0);
2294 int EmSend4bit(uint8_t resp
) {
2295 Code4bitAnswerAsTag(resp
);
2296 tosend_t
*ts
= get_tosend();
2297 int res
= EmSendCmd14443aRaw(ts
->buf
, ts
->max
);
2298 // do the tracing for the previous reader request and this tag answer:
2299 uint8_t par
[1] = {0x00};
2300 GetParity(&resp
, 1, par
);
2301 EmLogTrace(Uart
.output
,
2303 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2304 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2308 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2309 (LastTimeProxToAirStart
+ LastProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2313 int EmSendCmdPar(uint8_t *resp
, uint16_t respLen
, uint8_t *par
) {
2314 return EmSendCmdParEx(resp
, respLen
, par
, false);
2316 int EmSendCmdParEx(uint8_t *resp
, uint16_t respLen
, uint8_t *par
, bool collision
) {
2317 CodeIso14443aAsTagPar(resp
, respLen
, par
, collision
);
2318 tosend_t
*ts
= get_tosend();
2319 int res
= EmSendCmd14443aRaw(ts
->buf
, ts
->max
);
2321 // do the tracing for the previous reader request and this tag answer:
2322 EmLogTrace(Uart
.output
,
2324 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2325 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2329 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2330 (LastTimeProxToAirStart
+ LastProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2334 int EmSendCmd(uint8_t *resp
, uint16_t respLen
) {
2335 return EmSendCmdEx(resp
, respLen
, false);
2337 int EmSendCmdEx(uint8_t *resp
, uint16_t respLen
, bool collision
) {
2338 GetParity(resp
, respLen
, parity_array
);
2339 return EmSendCmdParEx(resp
, respLen
, parity_array
, collision
);
2342 int EmSendPrecompiledCmd(tag_response_info_t
*p_response
) {
2343 if (p_response
== NULL
) return 0;
2344 int ret
= EmSendCmd14443aRaw(p_response
->modulation
, p_response
->modulation_n
);
2345 // do the tracing for the previous reader request and this tag answer:
2346 GetParity(p_response
->response
, p_response
->response_n
, parity_array
);
2348 EmLogTrace(Uart
.output
,
2350 Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2351 Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
,
2353 p_response
->response
,
2354 p_response
->response_n
,
2355 LastTimeProxToAirStart
* 16 + DELAY_ARM2AIR_AS_TAG
,
2356 (LastTimeProxToAirStart
+ p_response
->ProxToAirDuration
) * 16 + DELAY_ARM2AIR_AS_TAG
,
2361 bool EmLogTrace(uint8_t *reader_data
, uint16_t reader_len
, uint32_t reader_StartTime
,
2362 uint32_t reader_EndTime
, uint8_t *reader_Parity
, uint8_t *tag_data
,
2363 uint16_t tag_len
, uint32_t tag_StartTime
, uint32_t tag_EndTime
, uint8_t *tag_Parity
) {
2365 // we cannot exactly measure the end and start of a received command from reader. However we know that the delay from
2366 // end of the received command to start of the tag's (simulated by us) answer is n*128+20 or n*128+84 resp.
2367 // with n >= 9. The start of the tags answer can be measured and therefore the end of the received command be calculated:
2369 uint16_t reader_modlen
= reader_EndTime
- reader_StartTime
;
2370 uint16_t approx_fdt
= tag_StartTime
- reader_EndTime
;
2371 uint16_t exact_fdt
= (approx_fdt
- 20 + 32) / 64 * 64 + 20;
2372 reader_EndTime
= tag_StartTime
- exact_fdt
;
2373 reader_StartTime
= reader_EndTime
- reader_modlen
;
2375 if (!LogTrace(reader_data
, reader_len
, reader_StartTime
, reader_EndTime
, reader_Parity
, true))
2378 return (!LogTrace(tag_data
, tag_len
, tag_StartTime
, tag_EndTime
, tag_Parity
, false));
2382 //-----------------------------------------------------------------------------
2383 // Kovio - Thinfilm barcode. TAG-TALK-FIRST -
2384 // Wait a certain time for tag response
2385 // If a response is captured return TRUE
2386 // If it takes too long return FALSE
2387 //-----------------------------------------------------------------------------
2388 bool GetIso14443aAnswerFromTag_Thinfilm(uint8_t *receivedResponse
, uint16_t resp_len
, uint8_t *received_len
) {
2390 if (g_hf_field_active
== false) {
2391 Dbprintf("Warning: HF field is off, ignoring GetIso14443aAnswerFromTag_Thinfilm command");
2395 // Set FPGA mode to "reader listen mode", no modulation (listen
2396 // only, since we are receiving, not transmitting).
2397 // Signal field is on with the appropriate LED
2399 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
2401 // Now get the answer from the card
2402 Demod14aInit(receivedResponse
, resp_len
, NULL
);
2405 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2408 uint32_t timeout
= iso14a_get_timeout();
2409 uint32_t receive_timer
= GetTickCount();
2414 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2415 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2416 if (ManchesterDecoding_Thinfilm(b
)) {
2417 *received_len
= Demod
.len
;
2419 LogTrace(receivedResponse
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, NULL
, false);
2424 if (GetTickCountDelta(receive_timer
) > timeout
+ 100)
2428 *received_len
= Demod
.len
;
2430 LogTrace(receivedResponse
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, NULL
, false);
2435 //-----------------------------------------------------------------------------
2436 // Wait a certain time for tag response
2437 // If a response is captured return TRUE
2438 // If it takes too long return FALSE
2439 //-----------------------------------------------------------------------------
2440 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse
, uint16_t rec_maxlen
, uint8_t *receivedResponsePar
, uint16_t offset
) {
2441 if (g_hf_field_active
== false) {
2442 Dbprintf("Warning: HF field is off");
2446 // Set FPGA mode to "reader listen mode", no modulation (listen
2447 // only, since we are receiving, not transmitting).
2448 // Signal field is on with the appropriate LED
2450 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
2452 // Now get the answer from the card
2453 Demod14aInit(receivedResponse
, rec_maxlen
, receivedResponsePar
);
2456 uint8_t b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2459 volatile uint32_t c
= 0;
2460 uint32_t timeout
= iso14a_get_timeout();
2461 uint32_t receive_timer
= GetTickCount();
2465 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
2466 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
2467 if (ManchesterDecoding(b
, offset
, 0)) {
2468 NextTransferTime
= MAX(NextTransferTime
, Demod
.endTime
- (DELAY_AIR2ARM_AS_READER
+ DELAY_ARM2AIR_AS_READER
) / 16 + FRAME_DELAY_TIME_PICC_TO_PCD
);
2470 } else if (c
++ > timeout
&& Demod
.state
== DEMOD_14A_UNSYNCD
) {
2475 // timeout already in ms + 100ms guard time
2476 if (GetTickCountDelta(receive_timer
) > timeout
+ 100) {
2483 void ReaderTransmitBitsPar(uint8_t *frame
, uint16_t bits
, uint8_t *par
, uint32_t *timing
) {
2485 CodeIso14443aBitsAsReaderPar(frame
, bits
, par
);
2486 // Send command to tag
2487 tosend_t
*ts
= get_tosend();
2488 TransmitFor14443a(ts
->buf
, ts
->max
, timing
);
2489 if (g_trigger
) LED_A_ON();
2491 LogTrace(frame
, nbytes(bits
), (LastTimeProxToAirStart
<< 4) + DELAY_ARM2AIR_AS_READER
, ((LastTimeProxToAirStart
+ LastProxToAirDuration
) << 4) + DELAY_ARM2AIR_AS_READER
, par
, true);
2494 void ReaderTransmitPar(uint8_t *frame
, uint16_t len
, uint8_t *par
, uint32_t *timing
) {
2495 ReaderTransmitBitsPar(frame
, len
* 8, par
, timing
);
2498 static void ReaderTransmitBits(uint8_t *frame
, uint16_t len
, uint32_t *timing
) {
2499 // Generate parity and redirect
2500 GetParity(frame
, len
/ 8, parity_array
);
2501 ReaderTransmitBitsPar(frame
, len
, parity_array
, timing
);
2504 void ReaderTransmit(uint8_t *frame
, uint16_t len
, uint32_t *timing
) {
2505 // Generate parity and redirect
2506 GetParity(frame
, len
, parity_array
);
2507 ReaderTransmitBitsPar(frame
, len
* 8, parity_array
, timing
);
2510 static uint16_t ReaderReceiveOffset(uint8_t *receivedAnswer
, uint16_t answer_len
, uint16_t offset
, uint8_t *par
) {
2511 if (GetIso14443aAnswerFromTag(receivedAnswer
, answer_len
, par
, offset
) == false) {
2514 LogTrace(receivedAnswer
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, par
, false);
2518 uint16_t ReaderReceive(uint8_t *receivedAnswer
, uint16_t answer_maxlen
, uint8_t *par
) {
2519 if (GetIso14443aAnswerFromTag(receivedAnswer
, answer_maxlen
, par
, 0) == false) {
2522 LogTrace(receivedAnswer
, Demod
.len
, Demod
.startTime
* 16 - DELAY_AIR2ARM_AS_READER
, Demod
.endTime
* 16 - DELAY_AIR2ARM_AS_READER
, par
, false);
2527 // This function misstreats the ISO 14443a anticollision procedure.
2528 // by fooling the reader there is a collision and forceing the reader to
2529 // increase the uid bytes. The might be an overflow, DoS will occur.
2530 void iso14443a_antifuzz(uint32_t flags
) {
2532 // We need to listen to the high-frequency, peak-detected path.
2533 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
2535 BigBuf_free_keep_EM();
2541 // allocate buffers:
2542 uint8_t *received
= BigBuf_malloc(MAX_FRAME_SIZE
);
2543 uint8_t *receivedPar
= BigBuf_malloc(MAX_PARITY_SIZE
);
2544 uint8_t *resp
= BigBuf_malloc(20);
2546 memset(received
, 0x00, MAX_FRAME_SIZE
);
2547 memset(received
, 0x00, MAX_PARITY_SIZE
);
2548 memset(resp
, 0xFF, 20);
2554 // Clean receive command buffer
2555 if (!GetIso14443aCommandFromReader(received
, MAX_FRAME_SIZE
, receivedPar
, &len
)) {
2556 Dbprintf("Anti-fuzz stopped. Trace length: %d ", BigBuf_get_traceLen());
2559 if (received
[0] == ISO14443A_CMD_WUPA
|| received
[0] == ISO14443A_CMD_REQA
) {
2563 if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
2571 // Received request for UID (cascade 1)
2572 //if (received[1] >= 0x20 && received[1] <= 0x57 && received[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT) {
2573 if (received
[1] >= 0x20 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
) {
2578 resp
[4] = resp
[0] ^ resp
[1] ^ resp
[2] ^ resp
[3];
2581 if (IS_FLAG_UID_IN_DATA(flags
, 7)) {
2582 resp
[0] = MIFARE_SELECT_CT
;
2586 // trigger a faulty/collision response
2587 EmSendCmdEx(resp
, 5, true);
2588 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("ANTICOLL or SELECT %x", received
[1]);
2592 } else if (received
[1] == 0x20 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
) { // Received request for UID (cascade 2)
2593 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("ANTICOLL or SELECT_2");
2594 } else if (received
[1] == 0x70 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
) { // Received a SELECT (cascade 1)
2595 } else if (received
[1] == 0x70 && received
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
) { // Received a SELECT (cascade 2)
2597 Dbprintf("unknown command %x", received
[0]);
2601 reply_ng(CMD_HF_ISO14443A_ANTIFUZZ
, PM3_SUCCESS
, NULL
, 0);
2603 BigBuf_free_keep_EM();
2606 static void iso14a_set_ATS_times(const uint8_t *ats
) {
2608 if (ats
[0] > 1) { // there is a format byte T0
2609 if ((ats
[1] & 0x20) == 0x20) { // there is an interface byte TB(1)
2611 if ((ats
[1] & 0x10) == 0x10) { // there is an interface byte TA(1) preceding TB(1)
2616 uint8_t fwi
= (tb1
& 0xf0) >> 4; // frame waiting time integer (FWI)
2618 uint32_t fwt
= 256 * 16 * (1 << fwi
); // frame waiting time (FWT) in 1/fc
2619 iso14a_set_timeout(fwt
/ (8 * 16));
2621 uint8_t sfgi
= tb1
& 0x0f; // startup frame guard time integer (SFGI)
2622 if (sfgi
!= 0 && sfgi
!= 15) {
2623 uint32_t sfgt
= 256 * 16 * (1 << sfgi
); // startup frame guard time (SFGT) in 1/fc
2624 NextTransferTime
= MAX(NextTransferTime
, Demod
.endTime
+ (sfgt
- DELAY_AIR2ARM_AS_READER
- DELAY_ARM2AIR_AS_READER
) / 16);
2631 static int GetATQA(uint8_t *resp
, uint16_t resp_len
, uint8_t *resp_par
, iso14a_polling_parameters_t
*polling_parameters
) {
2632 #define WUPA_RETRY_TIMEOUT 10
2634 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
2635 iso14a_set_timeout(1236 / 128 + 1); // response to WUPA is expected at exactly 1236/fc. No need to wait longer.
2637 bool first_try
= true;
2638 uint32_t retry_timeout
= WUPA_RETRY_TIMEOUT
* polling_parameters
->frame_count
+ polling_parameters
->extra_timeout
;
2639 uint32_t start_time
= 0;
2642 uint8_t current_frame
= 0;
2645 iso14a_polling_frame_t
*frame_parameters
= &polling_parameters
->frames
[current_frame
];
2647 if (frame_parameters
->last_byte_bits
== 8) {
2648 ReaderTransmit(frame_parameters
->frame
, frame_parameters
->frame_length
, NULL
);
2650 ReaderTransmitBitsPar(frame_parameters
->frame
, frame_parameters
->last_byte_bits
, NULL
, NULL
);
2653 if (frame_parameters
->extra_delay
) {
2654 SpinDelay(frame_parameters
->extra_delay
);
2658 len
= ReaderReceive(resp
, resp_len
, resp_par
);
2660 // We set the start_time here otherwise in some cases we miss the window and only ever try once
2662 start_time
= GetTickCount();
2667 // Go over frame configurations, loop back when we reach the end
2668 current_frame
= current_frame
< (polling_parameters
->frame_count
- 1) ? current_frame
+ 1 : 0;
2669 } while (len
== 0 && GetTickCountDelta(start_time
) <= retry_timeout
);
2671 iso14a_set_timeout(save_iso14a_timeout
);
2676 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
) {
2677 return iso14443a_select_cardEx(uid_ptr
, p_card
, cuid_ptr
, anticollision
, num_cascades
, no_rats
, &WUPA_POLLING_PARAMETERS
);
2681 // performs iso14443a anticollision (optional) and card select procedure
2682 // fills the uid and cuid pointer unless NULL
2683 // fills the card info record unless NULL
2684 // if anticollision is false, then the UID must be provided in uid_ptr[]
2685 // and num_cascades must be set (1: 4 Byte UID, 2: 7 Byte UID, 3: 10 Byte UID)
2686 // requests ATS unless no_rats is true
2687 int iso14443a_select_cardEx(uint8_t *uid_ptr
, iso14a_card_select_t
*p_card
, uint32_t *cuid_ptr
,
2688 bool anticollision
, uint8_t num_cascades
, bool no_rats
,
2689 iso14a_polling_parameters_t
*polling_parameters
) {
2691 uint8_t resp
[MAX_FRAME_SIZE
] = {0}; // theoretically. A usual RATS will be much smaller
2693 uint8_t sak
= 0; // cascade uid
2694 bool do_cascade
= 1;
2695 int cascade_level
= 0;
2699 memset(p_card
->uid
, 0, 10);
2700 p_card
->ats_len
= 0;
2703 if (GetATQA(resp
, sizeof(resp
), parity_array
, polling_parameters
) == 0) {
2708 p_card
->atqa
[0] = resp
[0];
2709 p_card
->atqa
[1] = resp
[1];
2712 // 11RF005SH or 11RF005M, Read UID again
2713 if (p_card
&& p_card
->atqa
[1] == 0x00) {
2715 if ((p_card
->atqa
[0] == 0x03) || (p_card
->atqa
[0] == 0x05)) {
2718 uint8_t fudan_read
[] = { 0x30, 0x01, 0x8B, 0xB9};
2719 ReaderTransmit(fudan_read
, sizeof(fudan_read
), NULL
);
2720 if (ReaderReceive(resp
, sizeof(resp
), parity_array
) == 0) {
2721 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Card didn't answer to select all");
2725 memcpy(p_card
->uid
, resp
, 4);
2728 if (GetATQA(resp
, sizeof(resp
), parity_array
, &WUPA_POLLING_PARAMETERS
) == 0) {
2732 if (GetATQA(resp
, sizeof(resp
), parity_array
, &WUPA_POLLING_PARAMETERS
) == 0) {
2742 if (anticollision
) {
2745 memset(uid_ptr
, 0, 10);
2748 if (hf14aconfig
.forceanticol
== 0) {
2749 // check for proprietary anticollision:
2750 if ((resp
[0] & 0x1F) == 0) {
2754 } else if (hf14aconfig
.forceanticol
== 2) {
2755 return 3; // force skipping anticol
2756 } // else force executing
2758 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
2759 // which case we need to make a cascade 2 request and select - this is a long UID
2760 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
2761 for (; do_cascade
; cascade_level
++) {
2762 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
2763 uint8_t sel_all
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x20 };
2764 uint8_t sel_uid
[] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x70, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
2765 uint8_t uid_resp
[5] = {0}; // UID + original BCC
2766 sel_uid
[0] = sel_all
[0] = 0x93 + cascade_level
* 2;
2768 if (anticollision
) {
2771 ReaderTransmit(sel_all
, sizeof(sel_all
), NULL
);
2772 if (ReaderReceive(resp
, sizeof(resp
), parity_array
) == 0) {
2773 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Card didn't answer to CL%i select all", cascade_level
+ 1);
2777 if (Demod
.collisionPos
) { // we had a collision and need to construct the UID bit by bit
2778 memset(uid_resp
, 0, 5);
2779 uint16_t uid_resp_bits
= 0;
2780 uint16_t collision_answer_offset
= 0;
2782 // anti-collision-loop:
2783 while (Demod
.collisionPos
) {
2784 Dbprintf("Multiple tags detected. Collision after Bit %d", Demod
.collisionPos
);
2786 for (uint16_t i
= collision_answer_offset
; i
< Demod
.collisionPos
; i
++, uid_resp_bits
++) { // add valid UID bits before collision point
2787 uint16_t UIDbit
= (resp
[i
/ 8] >> (i
% 8)) & 0x01;
2788 uid_resp
[uid_resp_bits
/ 8] |= UIDbit
<< (uid_resp_bits
% 8);
2791 uid_resp
[uid_resp_bits
/ 8] |= 1 << (uid_resp_bits
% 8); // next time select the card(s) with a 1 in the collision position
2793 // construct anticollision command:
2794 sel_uid
[1] = ((2 + uid_resp_bits
/ 8) << 4) | (uid_resp_bits
& 0x07); // length of data in bytes and bits
2795 for (uint16_t i
= 0; i
<= uid_resp_bits
/ 8; i
++) {
2796 sel_uid
[2 + i
] = uid_resp
[i
];
2799 collision_answer_offset
= uid_resp_bits
% 8;
2801 ReaderTransmitBits(sel_uid
, 16 + uid_resp_bits
, NULL
);
2802 if (ReaderReceiveOffset(resp
, sizeof(resp
), collision_answer_offset
, parity_array
) == 0) {
2807 // finally, add the last bits and BCC of the UID
2808 for (uint32_t i
= collision_answer_offset
; i
< Demod
.len
* 8; i
++, uid_resp_bits
++) {
2809 uint16_t UIDbit
= (resp
[i
/ 8] >> (i
% 8)) & 0x01;
2810 uid_resp
[uid_resp_bits
/ 8] |= UIDbit
<< (uid_resp_bits
% 8);
2813 } else { // no collision, use the response to SELECT_ALL as current uid
2814 memcpy(uid_resp
, resp
, 5); // UID + original BCC
2818 if (cascade_level
< num_cascades
- 1) {
2819 uid_resp
[0] = MIFARE_SELECT_CT
;
2820 memcpy(uid_resp
+ 1, uid_ptr
+ cascade_level
* 3, 3);
2822 memcpy(uid_resp
, uid_ptr
+ cascade_level
* 3, 4);
2825 size_t uid_resp_len
= 4;
2827 // calculate crypto UID. Always use last 4 Bytes.
2829 *cuid_ptr
= bytes_to_num(uid_resp
, 4);
2831 // Construct SELECT UID command
2832 sel_uid
[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
2834 if (anticollision
) {
2836 memcpy(sel_uid
+ 2, uid_resp
, 5); // the UID received during anticollision with original BCC
2837 uint8_t bcc
= sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate BCC
2838 if (sel_uid
[6] != bcc
) {
2840 Dbprintf("BCC%d incorrect, got 0x%02x, expected 0x%02x", cascade_level
, sel_uid
[6], bcc
);
2842 if (hf14aconfig
.forcebcc
== 0) {
2843 Dbprintf("Aborting");
2845 } else if (hf14aconfig
.forcebcc
== 1) {
2847 } // else use card BCC
2849 Dbprintf("Using BCC%d =" _YELLOW_("0x%02x"), cascade_level
, sel_uid
[6]);
2852 memcpy(sel_uid
+ 2, uid_resp
, 4); // the provided UID
2853 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
2856 AddCrc14A(sel_uid
, 7); // calculate and add CRC
2857 ReaderTransmit(sel_uid
, sizeof(sel_uid
), NULL
);
2860 if (ReaderReceive(resp
, sizeof(resp
), parity_array
) == 0) {
2861 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Card didn't answer to select");
2866 // Test if more parts of the uid are coming
2867 do_cascade
= (((sak
& 0x04) /* && uid_resp[0] == MIFARE_SELECT_CT */) > 0);
2869 if (cascade_level
== 0) {
2871 if (hf14aconfig
.forcecl2
== 2) {
2873 } else if (hf14aconfig
.forcecl2
== 1) {
2876 } else if (cascade_level
== 1) {
2878 if (hf14aconfig
.forcecl3
== 2) {
2880 } else if (hf14aconfig
.forcecl3
== 1) {
2885 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
2886 // http://www.nxp.com/documents/application_note/AN10927.pdf
2887 uid_resp
[0] = uid_resp
[1];
2888 uid_resp
[1] = uid_resp
[2];
2889 uid_resp
[2] = uid_resp
[3];
2893 if (uid_ptr
&& anticollision
)
2894 memcpy(uid_ptr
+ (cascade_level
* 3), uid_resp
, uid_resp_len
);
2897 memcpy(p_card
->uid
+ (cascade_level
* 3), uid_resp
, uid_resp_len
);
2898 p_card
->uidlen
+= uid_resp_len
;
2906 if (hf14aconfig
.forcerats
== 0) {
2907 // PICC compliant with iso14443a-4 ---> (SAK & 0x20 != 0)
2908 if ((sak
& 0x20) == 0) {
2912 } else if (hf14aconfig
.forcerats
== 2) {
2913 if ((sak
& 0x20) != 0) Dbprintf("Skipping RATS according to hf 14a config");
2915 } // else force RATS
2917 if ((sak
& 0x20) == 0) Dbprintf("Forcing RATS according to hf 14a config");
2919 // RATS, Request for answer to select
2920 if (no_rats
== false) {
2922 uint8_t rats
[] = { ISO14443A_CMD_RATS
, 0x80, 0x31, 0x73 }; // FSD=256, FSDI=8, CID=0
2923 ReaderTransmit(rats
, sizeof(rats
), NULL
);
2924 int len
= ReaderReceive(resp
, sizeof(resp
), parity_array
);
2930 memcpy(p_card
->ats
, resp
, sizeof(p_card
->ats
));
2931 p_card
->ats_len
= len
;
2934 // reset the PCB block number
2935 iso14_pcb_blocknum
= 0;
2937 // set default timeout and delay next transfer based on ATS
2938 iso14a_set_ATS_times(resp
);
2943 int iso14443a_fast_select_card(uint8_t *uid_ptr
, uint8_t num_cascades
) {
2944 uint8_t resp
[3] = { 0 }; // theoretically. max 1 Byte SAK, 2 Byte CRC, 3 bytes is enough
2945 uint8_t resp_par
[1] = {0};
2947 uint8_t sak
= 0x04; // cascade uid
2948 int cascade_level
= 1;
2950 if (GetATQA(resp
, sizeof(resp
), resp_par
, &WUPA_POLLING_PARAMETERS
) == 0) {
2954 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
2955 // which case we need to make a cascade 2 request and select - this is a long UID
2956 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
2957 for (; sak
& 0x04; cascade_level
++) {
2958 // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
2959 uint8_t sel_uid
[9] = { ISO14443A_CMD_ANTICOLL_OR_SELECT
, 0x70 };
2961 // Construct SELECT UID command
2962 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
2963 sel_uid
[0] = ISO14443A_CMD_ANTICOLL_OR_SELECT
+ (cascade_level
- 1) * 2;
2966 if (cascade_level
< num_cascades
) {
2967 sel_uid
[2] = MIFARE_SELECT_CT
;
2968 memcpy(&sel_uid
[3], uid_ptr
+ (cascade_level
- 1) * 3, 3);
2970 memcpy(&sel_uid
[2], uid_ptr
+ (cascade_level
- 1) * 3, 4);
2973 sel_uid
[6] = sel_uid
[2] ^ sel_uid
[3] ^ sel_uid
[4] ^ sel_uid
[5]; // calculate and add BCC
2974 AddCrc14A(sel_uid
, 7); // calculate and add CRC
2975 ReaderTransmit(sel_uid
, sizeof(sel_uid
), NULL
);
2977 // Receive 1 Byte SAK, 2 Byte CRC
2978 if (ReaderReceive(resp
, sizeof(resp
), resp_par
) != 3) {
2987 void iso14443a_setup(uint8_t fpga_minor_mode
) {
2989 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
2990 // Set up the synchronous serial port
2991 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A
);
2992 // connect Demodulated Signal to ADC:
2993 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
2996 // Signal field is on with the appropriate LED
2997 if (fpga_minor_mode
== FPGA_HF_ISO14443A_READER_MOD
|| fpga_minor_mode
== FPGA_HF_ISO14443A_READER_LISTEN
)
3000 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| fpga_minor_mode
);
3006 // Prepare the demodulation functions
3009 NextTransferTime
= 2 * DELAY_ARM2AIR_AS_READER
;
3010 iso14a_set_timeout(1060); // 106 * 10ms default
3012 g_hf_field_active
= true;
3015 /* Peter Fillmore 2015
3016 Added card id field to the function info from ISO14443A standard
3020 b3 = depends on block
3021 b4 = Card ID following if set to 1
3022 b5 = depends on block type
3023 b6 = depends on block type
3027 b8 b7 b6 b5 b4 b3 b2 b1
3032 b8 b7 b6 b5 b4 b3 b2 b1
3037 b8 b7 b6 b5 b4 b3 b2 b1
3039 b5,b6 = 00 - DESELECT
3042 int iso14_apdu(uint8_t *cmd
, uint16_t cmd_len
, bool send_chaining
, void *data
, uint16_t data_len
, uint8_t *res
) {
3043 uint8_t *real_cmd
= BigBuf_calloc(cmd_len
+ 4);
3046 // ISO 14443 APDU frame: PCB [CID] [NAD] APDU CRC PCB=0x02
3047 real_cmd
[0] = 0x02; // bnr,nad,cid,chn=0; i-block(0x00)
3048 if (send_chaining
) {
3049 real_cmd
[0] |= 0x10;
3051 // put block number into the PCB
3052 real_cmd
[0] |= iso14_pcb_blocknum
;
3053 memcpy(real_cmd
+ 1, cmd
, cmd_len
);
3056 real_cmd
[0] = 0xA2; // r-block + ACK
3057 real_cmd
[0] |= iso14_pcb_blocknum
;
3059 AddCrc14A(real_cmd
, cmd_len
+ 1);
3061 ReaderTransmit(real_cmd
, cmd_len
+ 3, NULL
);
3063 size_t len
= ReaderReceive(data
, data_len
, parity_array
);
3064 uint8_t *data_bytes
= (uint8_t *) data
;
3068 return 0; // DATA LINK ERROR
3071 while (len
&& ((data_bytes
[0] & 0xF2) == 0xF2)) {
3072 uint32_t save_iso14a_timeout
= iso14a_get_timeout();
3073 // temporarily increase timeout
3074 iso14a_set_timeout(MAX((data_bytes
[1] & 0x3f) * save_iso14a_timeout
, MAX_ISO14A_TIMEOUT
));
3075 // Transmit WTX back
3076 // byte1 - WTXM [1..59]. command FWT=FWT*WTXM
3077 data_bytes
[1] = data_bytes
[1] & 0x3f; // 2 high bits mandatory set to 0b
3078 // now need to fix CRC.
3079 AddCrc14A(data_bytes
, len
- 2);
3081 ReaderTransmit(data_bytes
, len
, NULL
);
3082 // retrieve the result again (with increased timeout)
3083 len
= ReaderReceive(data
, data_len
, parity_array
);
3086 iso14a_set_timeout(save_iso14a_timeout
);
3089 // if we received an I- or R(ACK)-Block with a block number equal to the
3090 // current block number, toggle the current block number
3091 if (len
>= 3 // PCB+CRC = 3 bytes
3092 && ((data_bytes
[0] & 0xC0) == 0 // I-Block
3093 || (data_bytes
[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
3094 && (data_bytes
[0] & 0x01) == iso14_pcb_blocknum
) { // equal block numbers
3095 iso14_pcb_blocknum
^= 1;
3098 // if we received I-block with chaining we need to send ACK and receive another block of data
3100 *res
= data_bytes
[0];
3104 if (len
>= 3 && !CheckCrc14A(data_bytes
, len
)) {
3114 // memmove(data_bytes, data_bytes + 1, len);
3115 for (int i
= 0; i
< len
; i
++) {
3116 data_bytes
[i
] = data_bytes
[i
+ 1];
3124 //-----------------------------------------------------------------------------
3125 // Read an ISO 14443a tag. Send out commands and store answers.
3126 //-----------------------------------------------------------------------------
3127 // arg0 iso_14a flags
3128 // arg1 high :: number of bits, if you want to send 7bits etc
3129 // low :: len of commandbytes
3131 // d.asBytes command bytes to send
3132 void ReaderIso14443a(PacketCommandNG
*c
) {
3133 iso14a_command_t param
= c
->oldarg
[0];
3134 size_t len
= c
->oldarg
[1] & 0xffff;
3135 size_t lenbits
= c
->oldarg
[1] >> 16;
3136 uint32_t timeout
= c
->oldarg
[2];
3137 uint8_t *cmd
= c
->data
.asBytes
;
3140 uint8_t buf
[PM3_CMD_DATA_SIZE_MIX
] = {0x00};
3142 if ((param
& ISO14A_CONNECT
) == ISO14A_CONNECT
) {
3143 iso14_pcb_blocknum
= 0;
3149 if ((param
& ISO14A_REQUEST_TRIGGER
) == ISO14A_REQUEST_TRIGGER
) {
3150 iso14a_set_trigger(true);
3153 if ((param
& ISO14A_CONNECT
) == ISO14A_CONNECT
) {
3154 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN
);
3156 // notify client selecting status.
3157 // if failed selecting, turn off antenna and quit.
3158 if ((param
& ISO14A_NO_SELECT
) != ISO14A_NO_SELECT
) {
3159 iso14a_card_select_t
*card
= (iso14a_card_select_t
*)buf
;
3161 arg0
= iso14443a_select_cardEx(
3167 ((param
& ISO14A_NO_RATS
) == ISO14A_NO_RATS
),
3168 ((param
& ISO14A_USE_CUSTOM_POLLING
) == ISO14A_USE_CUSTOM_POLLING
) ? (iso14a_polling_parameters_t
*)cmd
: &WUPA_POLLING_PARAMETERS
3170 // TODO: Improve by adding a cmd parser pointer and moving it by struct length to allow combining data with polling params
3171 FpgaDisableTracing();
3173 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3174 crypto1_auth_state
= AUTH_FIRST
;
3175 crypto1_deinit(&crypto1_state
);
3178 reply_mix(CMD_ACK
, arg0
, card
->uidlen
, 0, buf
, sizeof(iso14a_card_select_t
));
3184 uint32_t save_iso14a_timeout
= 0;
3185 if ((param
& ISO14A_SET_TIMEOUT
) == ISO14A_SET_TIMEOUT
) {
3186 save_iso14a_timeout
= iso14a_get_timeout();
3187 iso14a_set_timeout(timeout
);
3190 if ((param
& ISO14A_APDU
) == ISO14A_APDU
) {
3195 ((param
& ISO14A_SEND_CHAINING
) == ISO14A_SEND_CHAINING
),
3200 FpgaDisableTracing();
3202 reply_mix(CMD_ACK
, arg0
, res
, 0, buf
, sizeof(buf
));
3205 if ((param
& ISO14A_RAW
) == ISO14A_RAW
) {
3206 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3207 // Intercept special Auth command 6xxx<key>CRCA
3208 if ((len
== 10) && ((cmd
[0] & 0xF0) == 0x60)) {
3209 uint64_t ui64key
= bytes_to_num((uint8_t *)&cmd
[2], 6);
3211 if (mifare_classic_authex_cmd(&crypto1_state
, crypto1_uid
, cmd
[1], cmd
[0], ui64key
, crypto1_auth_state
, NULL
, NULL
, NULL
, NULL
, false, false)) {
3212 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Auth error");
3215 crypto1_auth_state
= AUTH_NESTED
;
3216 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Auth succeeded");
3219 reply_mix(CMD_ACK
, 1, 0, 0, &res
, 1);
3223 if ((param
& ISO14A_APPEND_CRC
) == ISO14A_APPEND_CRC
) {
3224 // Don't append crc on empty bytearray...
3227 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3228 AddCrc14B(cmd
, len
);
3230 AddCrc14A(cmd
, len
);
3240 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3241 // Force explicit parity
3244 // want to send a specific number of bits (e.g. short commands)
3247 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3249 int bits_to_send
= lenbits
;
3252 ReaderTransmitBitsPar(&cmd
[i
++], MIN(bits_to_send
, 7), NULL
, NULL
); // first byte is always short (7bits) and no parity
3255 while (bits_to_send
> 0) {
3256 ReaderTransmitBitsPar(&cmd
[i
++], MIN(bits_to_send
, 8), NULL
, NULL
); // following bytes are 8 bit and no parity
3261 GetParity(cmd
, lenbits
/ 8, parity_array
);
3262 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3263 mf_crypto1_encrypt(&crypto1_state
, cmd
, len
, parity_array
);
3265 ReaderTransmitBitsPar(cmd
, lenbits
, parity_array
, NULL
); // bytes are 8 bit with odd parity
3268 } else { // want to send complete bytes only
3269 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3272 ReaderTransmitBitsPar(&cmd
[i
++], 7, NULL
, NULL
); // first byte: 7 bits, no paritiy
3275 ReaderTransmitBitsPar(&cmd
[i
++], 8, NULL
, NULL
); // following bytes: 8 bits, no paritiy
3279 ReaderTransmit(cmd
, len
, NULL
); // 8 bits, odd parity
3283 if ((param
& ISO14A_TOPAZMODE
) == ISO14A_TOPAZMODE
) {
3285 if (cmd
[0] == TOPAZ_WRITE_E8
|| cmd
[0] == TOPAZ_WRITE_NE8
) {
3288 if (tearoff_hook() == PM3_ETEAROFF
) {
3289 FpgaDisableTracing();
3290 reply_mix(CMD_ACK
, 0, 0, 0, NULL
, 0);
3292 arg0
= ReaderReceive(buf
, sizeof(buf
), parity_array
);
3293 FpgaDisableTracing();
3294 reply_mix(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
3298 arg0
= ReaderReceive(buf
, sizeof(buf
), parity_array
);
3299 FpgaDisableTracing();
3300 reply_mix(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
3306 if (tearoff_hook() == PM3_ETEAROFF
) {
3307 FpgaDisableTracing();
3308 reply_mix(CMD_ACK
, 0, 0, 0, NULL
, 0);
3310 arg0
= ReaderReceive(buf
, sizeof(buf
), parity_array
);
3312 if ((param
& ISO14A_CRYPTO1MODE
) == ISO14A_CRYPTO1MODE
) {
3313 mf_crypto1_decrypt(&crypto1_state
, buf
, arg0
);
3315 FpgaDisableTracing();
3316 reply_mix(CMD_ACK
, arg0
, 0, 0, buf
, sizeof(buf
));
3321 if ((param
& ISO14A_REQUEST_TRIGGER
) == ISO14A_REQUEST_TRIGGER
)
3322 iso14a_set_trigger(false);
3324 if ((param
& ISO14A_SET_TIMEOUT
) == ISO14A_SET_TIMEOUT
) {
3325 iso14a_set_timeout(save_iso14a_timeout
);
3328 if ((param
& ISO14A_NO_DISCONNECT
) == ISO14A_NO_DISCONNECT
) {
3333 crypto1_auth_state
= AUTH_FIRST
;
3338 // Determine the distance between two nonces.
3339 // Assume that the difference is small, but we don't know which is first.
3340 // Therefore try in alternating directions.
3341 static int32_t dist_nt(uint32_t nt1
, uint32_t nt2
) {
3343 if (nt1
== nt2
) return 0;
3345 uint32_t nttmp1
= nt1
;
3346 uint32_t nttmp2
= nt2
;
3348 for (uint16_t i
= 1; i
< 32768; i
++) {
3349 nttmp1
= prng_successor(nttmp1
, 1);
3350 if (nttmp1
== nt2
) return i
;
3352 nttmp2
= prng_successor(nttmp2
, 1);
3353 if (nttmp2
== nt1
) return -i
;
3356 return (-99999); // either nt1 or nt2 are invalid nonces
3360 #define PRNG_SEQUENCE_LENGTH (1 << 16)
3361 #define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up.
3362 #define MAX_SYNC_TRIES 32
3364 //-----------------------------------------------------------------------------
3365 // Recover several bits of the cypher stream. This implements (first stages of)
3366 // the algorithm described in "The Dark Side of Security by Obscurity and
3367 // Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
3368 // (article by Nicolas T. Courtois, 2009)
3369 //-----------------------------------------------------------------------------
3370 void ReaderMifare(bool first_try
, uint8_t block
, uint8_t keytype
) {
3372 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
);
3375 BigBuf_Clear_ext(false);
3379 uint8_t mf_auth
[4] = { keytype
, block
, 0x00, 0x00 };
3380 uint8_t mf_nr_ar
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3381 uint8_t uid
[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
3382 uint8_t par_list
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3383 uint8_t ks_list
[8] = {0, 0, 0, 0, 0, 0, 0, 0};
3384 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = {0x00};
3385 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = {0x00};
3386 uint8_t par
[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
3387 uint8_t nt_diff
= 0;
3389 uint32_t nt
= 0, previous_nt
= 0, cuid
= 0;
3390 uint32_t sync_time
= GetCountSspClk() & 0xfffffff8;
3392 int32_t catch_up_cycles
= 0;
3393 int32_t last_catch_up
= 0;
3396 uint16_t elapsed_prng_sequences
= 1;
3397 uint16_t consecutive_resyncs
= 0;
3398 uint16_t unexpected_random
= 0;
3399 uint16_t sync_tries
= 0;
3401 bool have_uid
= false;
3402 uint8_t cascade_levels
= 0;
3404 // static variables here, is re-used in the next call
3405 static int32_t sync_cycles
= 0;
3406 static uint32_t nt_attacked
= 0;
3407 static uint8_t mf_nr_ar3
= 0;
3408 static uint8_t par_low
= 0;
3410 int return_status
= PM3_SUCCESS
;
3412 AddCrc14A(mf_auth
, 2);
3415 sync_cycles
= PRNG_SEQUENCE_LENGTH
; // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
3420 // we were unsuccessful on a previous call.
3421 // Try another READER nonce (first 3 parity bits remain the same)
3423 mf_nr_ar
[3] = mf_nr_ar3
;
3428 uint16_t checkbtn_cnt
= 0;
3430 for (i
= 0; true; ++i
) {
3432 bool received_nack
= false;
3436 // Test if the action was cancelled
3437 if (checkbtn_cnt
== 1000) {
3438 if (BUTTON_PRESS() || data_available()) {
3440 return_status
= PM3_EOPABORTED
;
3447 // this part is from Piwi's faster nonce collecting part in Hardnested.
3448 if (!have_uid
) { // need a full select cycle to get the uid first
3449 iso14a_card_select_t card_info
;
3450 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
3451 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (ALL)");
3454 switch (card_info
.uidlen
) {
3468 } else { // no need for anticollision. We can directly select the card
3469 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
3470 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (UID)");
3475 elapsed_prng_sequences
= 1;
3477 // Sending timeslot of ISO14443a frame
3478 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
3479 catch_up_cycles
= 0;
3481 #define SYNC_TIME_BUFFER 16 // if there is only SYNC_TIME_BUFFER left before next planned sync, wait for next PRNG cycle
3483 // if we missed the sync time already or are about to miss it, advance to the next nonce repeat
3484 while (sync_time
< GetCountSspClk() + SYNC_TIME_BUFFER
) {
3485 ++elapsed_prng_sequences
;
3486 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
3489 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
3490 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
3492 // Receive the (4 Byte) "random" TAG nonce
3493 if (ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) != 4)
3497 nt
= bytes_to_num(receivedAnswer
, 4);
3499 // Transmit reader nonce with fake par
3500 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
3502 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3503 int resp_res
= ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
);
3505 received_nack
= true;
3506 else if (resp_res
== 4) {
3507 // did we get lucky and got our dummykey to be valid?
3508 // however we don't feed key w uid it the prng..
3510 return_status
= PM3_ESOFT
;
3515 // we didn't calibrate our clock yet,
3516 // iceman: has to be calibrated every time.
3517 if (previous_nt
&& !nt_attacked
) {
3519 int nt_distance
= dist_nt(previous_nt
, nt
);
3521 // if no distance between, then we are in sync.
3522 if (nt_distance
== 0) {
3525 if (nt_distance
== -99999) { // invalid nonce received
3526 unexpected_random
++;
3527 if (unexpected_random
> MAX_UNEXPECTED_RANDOM
) {
3528 isOK
= 3; // Card has an unpredictable PRNG. Give up
3529 return_status
= PM3_ESOFT
;
3532 continue; // continue trying...
3536 if (++sync_tries
> MAX_SYNC_TRIES
) {
3537 isOK
= 4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3538 return_status
= PM3_ESOFT
;
3542 sync_cycles
= (sync_cycles
- nt_distance
) / elapsed_prng_sequences
;
3544 // no negative sync_cycles, and too small sync_cycles will result in continuous misses
3545 if (sync_cycles
<= 10) sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3547 // reset sync_cycles
3548 if (sync_cycles
> PRNG_SEQUENCE_LENGTH
* 2) {
3549 sync_cycles
= PRNG_SEQUENCE_LENGTH
;
3550 sync_time
= GetCountSspClk() & 0xfffffff8;
3553 if (g_dbglevel
>= DBG_EXTENDED
)
3554 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
);
3560 if ((nt
!= nt_attacked
) && nt_attacked
) { // we somehow lost sync. Try to catch up again...
3562 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
3563 if (catch_up_cycles
== 99999) { // invalid nonce received. Don't resync on that one.
3564 catch_up_cycles
= 0;
3568 catch_up_cycles
/= elapsed_prng_sequences
;
3570 if (catch_up_cycles
== last_catch_up
) {
3571 consecutive_resyncs
++;
3573 last_catch_up
= catch_up_cycles
;
3574 consecutive_resyncs
= 0;
3577 if (consecutive_resyncs
< 3) {
3578 if (g_dbglevel
>= DBG_EXTENDED
) {
3579 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, catch_up_cycles
, consecutive_resyncs
);
3582 sync_cycles
+= catch_up_cycles
;
3584 if (g_dbglevel
>= DBG_EXTENDED
)
3585 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
);
3588 catch_up_cycles
= 0;
3589 consecutive_resyncs
= 0;
3594 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3595 if (received_nack
) {
3596 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
3599 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
3601 par_list
[nt_diff
] = reflect8(par
[0]);
3602 ks_list
[nt_diff
] = receivedAnswer
[0] ^ 0x05; // xor with NACK value to get keystream
3604 // Test if the information is complete
3605 if (nt_diff
== 0x07) {
3607 return_status
= PM3_SUCCESS
;
3611 nt_diff
= (nt_diff
+ 1) & 0x07;
3612 mf_nr_ar
[3] = (mf_nr_ar
[3] & 0x1F) | (nt_diff
<< 5);
3617 if (nt_diff
== 0 && first_try
) {
3619 if (par
[0] == 0) { // tried all 256 possible parities without success. Card doesn't send NACK.
3621 return_status
= PM3_ESOFT
;
3626 par
[0] = ((par
[0] & 0x1F) + 1) | par_low
;
3630 // reset the resyncs since we got a complete transaction on right time.
3631 consecutive_resyncs
= 0;
3634 mf_nr_ar
[3] &= 0x1F;
3636 if (g_dbglevel
>= DBG_EXTENDED
) Dbprintf("Number of sent auth requests: %u", i
);
3638 FpgaDisableTracing();
3644 uint8_t par_list
[8];
3650 payload
.isOK
= isOK
;
3651 num_to_bytes(cuid
, 4, payload
.cuid
);
3652 num_to_bytes(nt
, 4, payload
.nt
);
3653 memcpy(payload
.par_list
, par_list
, sizeof(payload
.par_list
));
3654 memcpy(payload
.ks_list
, ks_list
, sizeof(payload
.ks_list
));
3655 memcpy(payload
.nr
, mf_nr_ar
, sizeof(payload
.nr
));
3656 memcpy(payload
.ar
, mf_nr_ar
+ 4, sizeof(payload
.ar
));
3658 reply_ng(CMD_HF_MIFARE_READER
, return_status
, (uint8_t *)&payload
, sizeof(payload
));
3665 * Mifare Classic NACK-bug detection
3666 * Thanks to @doegox for the feedback and new approaches.
3668 void DetectNACKbug(void) {
3669 uint8_t mf_auth
[4] = { MIFARE_AUTH_KEYA
, 0x00, 0xF5, 0x7B };
3670 uint8_t mf_nr_ar
[8] = { 0x00 };
3671 uint8_t uid
[10] = { 0x00 };
3672 uint8_t receivedAnswer
[MAX_MIFARE_FRAME_SIZE
] = { 0x00 };
3673 uint8_t receivedAnswerPar
[MAX_MIFARE_PARITY_SIZE
] = { 0x00 };
3674 uint8_t par
[1] = {0x00 }; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
3676 uint32_t nt
= 0, previous_nt
= 0, nt_attacked
= 0, cuid
= 0;
3677 int32_t catch_up_cycles
= 0, last_catch_up
= 0;
3678 uint8_t cascade_levels
= 0, num_nacks
= 0, isOK
= 0;
3679 uint16_t elapsed_prng_sequences
= 1;
3680 uint16_t consecutive_resyncs
= 0;
3681 uint16_t unexpected_random
= 0;
3682 uint16_t sync_tries
= 0;
3683 uint32_t sync_time
= 0;
3684 bool have_uid
= false;
3686 int32_t status
= PM3_SUCCESS
;
3688 // Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
3689 int32_t sync_cycles
= PRNG_SEQUENCE_LENGTH
;
3692 BigBuf_Clear_ext(false);
3695 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD
);
3697 sync_time
= GetCountSspClk() & 0xfffffff8;
3700 uint16_t checkbtn_cnt
= 0;
3703 for (i
= 1; true; ++i
) {
3705 bool received_nack
= false;
3707 // Cards always leaks a NACK, no matter the parity
3708 if ((i
== 10) && (num_nacks
== i
- 1)) {
3715 // Test if the action was cancelled
3716 if (checkbtn_cnt
== 1000) {
3717 if (BUTTON_PRESS() || data_available()) {
3718 status
= PM3_EOPABORTED
;
3725 // this part is from Piwi's faster nonce collecting part in Hardnested.
3726 if (!have_uid
) { // need a full select cycle to get the uid first
3727 iso14a_card_select_t card_info
;
3728 if (!iso14443a_select_card(uid
, &card_info
, &cuid
, true, 0, true)) {
3729 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (ALL)");
3733 switch (card_info
.uidlen
) {
3749 } else { // no need for anticollision. We can directly select the card
3750 if (!iso14443a_fast_select_card(uid
, cascade_levels
)) {
3751 if (g_dbglevel
>= DBG_INFO
) Dbprintf("Mifare: Can't select card (UID)");
3758 elapsed_prng_sequences
= 1;
3760 // Sending timeslot of ISO14443a frame
3761 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
+ catch_up_cycles
;
3762 catch_up_cycles
= 0;
3764 // if we missed the sync time already, advance to the next nonce repeat
3765 while (GetCountSspClk() > sync_time
) {
3766 ++elapsed_prng_sequences
;
3767 sync_time
= (sync_time
& 0xfffffff8) + sync_cycles
;
3770 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
3771 ReaderTransmit(mf_auth
, sizeof(mf_auth
), &sync_time
);
3773 // Receive the (4 Byte) "random" TAG nonce
3774 if (ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
) == 0) {
3779 nt
= bytes_to_num(receivedAnswer
, 4);
3781 // Transmit reader nonce with fake par
3782 ReaderTransmitPar(mf_nr_ar
, sizeof(mf_nr_ar
), par
, NULL
);
3784 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3785 if (ReaderReceive(receivedAnswer
, sizeof(receivedAnswer
), receivedAnswerPar
)) {
3786 received_nack
= true;
3788 // ALWAYS leak Detection. Well, we could be lucky and get a response nack on first try.
3789 if (i
== num_nacks
) {
3794 // we didn't calibrate our clock yet,
3795 // iceman: has to be calibrated every time.
3796 if (previous_nt
&& !nt_attacked
) {
3798 int nt_distance
= dist_nt(previous_nt
, nt
);
3800 // if no distance between, then we are in sync.
3801 if (nt_distance
== 0) {
3804 if (nt_distance
== -99999) { // invalid nonce received
3805 unexpected_random
++;
3806 if (unexpected_random
> MAX_UNEXPECTED_RANDOM
) {
3807 // Card has an unpredictable PRNG. Give up
3811 if (sync_cycles
<= 0) {
3812 sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3818 if (++sync_tries
> MAX_SYNC_TRIES
) {
3819 isOK
= 97; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3823 sync_cycles
= (sync_cycles
- nt_distance
) / elapsed_prng_sequences
;
3825 if (sync_cycles
<= 0) {
3826 sync_cycles
+= PRNG_SEQUENCE_LENGTH
;
3829 if (sync_cycles
> PRNG_SEQUENCE_LENGTH
* 2) {
3830 isOK
= 96; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
3834 if (g_dbglevel
>= DBG_EXTENDED
) {
3835 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
);
3841 if ((nt
!= nt_attacked
) && nt_attacked
) {
3842 // we somehow lost sync. Try to catch up again...
3843 catch_up_cycles
= -dist_nt(nt_attacked
, nt
);
3845 if (catch_up_cycles
== 99999) {
3846 // invalid nonce received. Don't resync on that one.
3847 catch_up_cycles
= 0;
3851 catch_up_cycles
/= elapsed_prng_sequences
;
3853 if (catch_up_cycles
== last_catch_up
) {
3854 consecutive_resyncs
++;
3856 last_catch_up
= catch_up_cycles
;
3857 consecutive_resyncs
= 0;
3860 if (consecutive_resyncs
< 3) {
3861 if (g_dbglevel
>= DBG_EXTENDED
) {
3862 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i
, catch_up_cycles
, consecutive_resyncs
);
3865 sync_cycles
+= catch_up_cycles
;
3867 if (g_dbglevel
>= DBG_EXTENDED
) {
3868 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
);
3869 Dbprintf("nt [%08x] attacted [%08x]", nt
, nt_attacked
);
3872 catch_up_cycles
= 0;
3873 consecutive_resyncs
= 0;
3878 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
3879 if (received_nack
) {
3880 catch_up_cycles
= 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
3883 // we are testing all 256 possibilities.
3886 // tried all 256 possible parities without success.
3888 // did we get one NACK?
3889 if (num_nacks
== 1) {
3895 // reset the resyncs since we got a complete transaction on right time.
3896 consecutive_resyncs
= 0;
3899 // num_nacks = number of nacks received. should be only 1. if not its a clone card which always sends NACK (parity == 0) ?
3900 // i = number of authentications sent. Not always 256, since we are trying to sync but close to it.
3901 FpgaDisableTracing();
3903 uint8_t *data
= BigBuf_malloc(4);
3905 data
[1] = num_nacks
;
3906 num_to_bytes(i
, 2, data
+ 2);
3907 reply_ng(CMD_HF_MIFARE_NACK_DETECT
, status
, data
, 4);
3915 Based upon the SimulateIso14443aTag, this aims to instead take an AID Value you've supplied, and return your selected response.
3916 It can also continue after the AID has been selected, and respond to other request types.
3917 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.
3920 void SimulateIso14443aTagAID(uint8_t tagType
, uint16_t flags
, uint8_t *data
, uint8_t *iRATs
, uint8_t *aid
, uint8_t *resp
, uint8_t *apdu
, int aidLen
, int respondLen
, int apduLen
, bool enumerate
) {
3921 tag_response_info_t
*responses
;
3923 uint32_t counters
[3] = { 0x00, 0x00, 0x00 };
3924 uint8_t tearings
[3] = { 0xbd, 0xbd, 0xbd };
3928 uint8_t receivedCmd
[MAX_FRAME_SIZE
] = { 0x00 };
3929 uint8_t receivedCmdPar
[MAX_PARITY_SIZE
] = { 0x00 };
3931 // free eventually allocated BigBuf memory but keep Emulator Memory
3932 BigBuf_free_keep_EM();
3934 // Increased the buffer size to allow for more complex responses
3935 #define DYNAMIC_RESPONSE_BUFFER2_SIZE 512
3936 #define DYNAMIC_MODULATION_BUFFER2_SIZE 1536
3938 uint8_t *dynamic_response_buffer2
= BigBuf_calloc(DYNAMIC_RESPONSE_BUFFER2_SIZE
);
3939 uint8_t *dynamic_modulation_buffer2
= BigBuf_calloc(DYNAMIC_MODULATION_BUFFER2_SIZE
);
3940 tag_response_info_t dynamic_response_info
= {
3941 .response
= dynamic_response_buffer2
,
3943 .modulation
= dynamic_modulation_buffer2
,
3947 if (SimulateIso14443aInit(tagType
, flags
, data
, iRATs
, &responses
, &cuid
, counters
, tearings
, &pages
) == false) {
3948 BigBuf_free_keep_EM();
3949 reply_ng(CMD_HF_MIFARE_SIMULATE
, PM3_EINIT
, NULL
, 0);
3953 // We need to listen to the high-frequency, peak-detected path.
3954 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN
);
3956 iso14a_set_timeout(201400); // 106 * 19ms default *100?
3959 int retval
= PM3_SUCCESS
;
3961 bool odd_reply
= true;
3967 // Filters for when this comes through
3968 static uint8_t aidFilter
[30] = { 0x00 }; // Default AID Value
3969 static uint8_t aidResponse
[100] = { 0x00 }; // Default AID Response
3970 static uint8_t apduCommand
[100] = { 0x00 }; // Default APDU GetData Response
3972 // Copy the AID, AID Response, and the GetData APDU response into our variables
3974 memcpy(aidFilter
, aid
, aidLen
);
3977 memcpy(aidResponse
, resp
, respondLen
);
3980 memcpy(apduCommand
, apdu
, apduLen
);
3985 bool finished
= false;
3986 while (finished
== false) {
3987 // BUTTON_PRESS check done in GetIso14443aCommandFromReader
3990 tag_response_info_t
*p_response
= NULL
;
3992 // Clean receive command buffer
3993 if (GetIso14443aCommandFromReader(receivedCmd
, sizeof(receivedCmd
), receivedCmdPar
, &len
) == false) {
3994 Dbprintf("Emulator stopped. Trace length: %d ", BigBuf_get_traceLen());
3995 retval
= PM3_EOPABORTED
;
3999 if (receivedCmd
[0] == ISO14443A_CMD_REQA
&& len
== 1) { // Received a REQUEST, but in HALTED, skip
4000 odd_reply
= !odd_reply
;
4002 p_response
= &responses
[RESP_INDEX_ATQA
];
4004 } else if (receivedCmd
[0] == ISO14443A_CMD_WUPA
&& len
== 1) { // Received a WAKEUP
4005 p_response
= &responses
[RESP_INDEX_ATQA
];
4006 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 2) { // Received request for UID (cascade 1)
4007 p_response
= &responses
[RESP_INDEX_UIDC1
];
4008 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 2) { // Received request for UID (cascade 2)
4009 p_response
= &responses
[RESP_INDEX_UIDC2
];
4010 } else if (receivedCmd
[1] == 0x20 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 2) { // Received request for UID (cascade 3)
4011 p_response
= &responses
[RESP_INDEX_UIDC3
];
4012 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT
&& len
== 9) { // Received a SELECT (cascade 1)
4013 p_response
= &responses
[RESP_INDEX_SAKC1
];
4014 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_2
&& len
== 9) { // Received a SELECT (cascade 2)
4015 p_response
= &responses
[RESP_INDEX_SAKC2
];
4016 } else if (receivedCmd
[1] == 0x70 && receivedCmd
[0] == ISO14443A_CMD_ANTICOLL_OR_SELECT_3
&& len
== 9) { // Received a SELECT (cascade 3)
4017 p_response
= &responses
[RESP_INDEX_SAKC3
];
4018 } else if (receivedCmd
[0] == ISO14443A_CMD_PPS
) {
4019 p_response
= &responses
[RESP_INDEX_PPS
];
4020 } else if (receivedCmd
[0] == ISO14443A_CMD_HALT
&& len
== 4) { // Received a HALT
4021 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
4024 } else if (receivedCmd
[0] == ISO14443A_CMD_RATS
&& len
== 4) { // Received a RATS request
4025 p_response
= &responses
[RESP_INDEX_RATS
];
4027 // clear old dynamic responses
4028 dynamic_response_info
.response_n
= 0;
4029 dynamic_response_info
.modulation_n
= 0;
4031 // Check for ISO 14443A-4 compliant commands, look at left nibble
4032 switch (receivedCmd
[0]) {
4034 case 0x0A: { // IBlock (command CID)
4035 dynamic_response_info
.response
[0] = receivedCmd
[0];
4036 dynamic_response_info
.response
[1] = 0x00;
4038 switch (receivedCmd
[3]) { // APDU Class Byte
4039 // receivedCmd in this case is expecting to structured with a CID, then the APDU command for SelectFile
4040 // | IBlock (CID) | CID | APDU Command | CRC |
4042 case 0xA4: { // SELECT FILE
4043 // Select File AID uses the following format for GlobalPlatform
4045 // | 00 | A4 | 04 | 00 | xx | AID | 00 |
4046 // xx in this case is len of the AID value in hex
4048 // aid len is found as a hex value in receivedCmd[6] (Index Starts at 0)
4049 int aid_len
= receivedCmd
[6];
4050 uint8_t *recieved_aid
= &receivedCmd
[7];
4052 // aid enumeration flag
4053 if (enumerate
== true) {
4054 Dbprintf("Received AID (%d):", aid_len
);
4055 Dbhexdump(aid_len
, recieved_aid
, false);
4058 if (memcmp(aidFilter
, recieved_aid
, aid_len
) == 0) { // Evaluate the AID sent by the Reader to the AID supplied
4059 // AID Response will be parsed here
4060 memcpy(dynamic_response_info
.response
+ 2, aidResponse
, respondLen
+ 2);
4061 dynamic_response_info
.response_n
= respondLen
+ 2;
4062 } else { // Any other SELECT FILE command will return with a Not Found
4063 dynamic_response_info
.response
[2] = 0x6A;
4064 dynamic_response_info
.response
[3] = 0x82;
4065 dynamic_response_info
.response_n
= 4;
4070 case 0xDA: { // PUT DATA
4071 // Just send them a 90 00 response
4072 dynamic_response_info
.response
[2] = 0x90;
4073 dynamic_response_info
.response
[3] = 0x00;
4074 dynamic_response_info
.response_n
= 4;
4078 case 0xCA: { // GET DATA
4079 if (sentCount
== 0) {
4080 // APDU Command will just be parsed here
4081 memcpy(dynamic_response_info
.response
+ 2, apduCommand
, apduLen
+ 2);
4082 dynamic_response_info
.response_n
= respondLen
+ 2;
4091 // Any other non-listed command
4092 // Respond Not Found
4093 dynamic_response_info
.response
[2] = 0x6A;
4094 dynamic_response_info
.response
[3] = 0x82;
4095 dynamic_response_info
.response_n
= 4;
4103 case 0xC2: { // Readers sends deselect command
4104 dynamic_response_info
.response
[0] = 0xCA;
4105 dynamic_response_info
.response
[1] = 0x00;
4106 dynamic_response_info
.response_n
= 2;
4112 // Never seen this command before
4113 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
4114 if (g_dbglevel
>= DBG_DEBUG
) {
4115 Dbprintf("Received unknown command (len=%d):", len
);
4116 Dbhexdump(len
, receivedCmd
, false);
4119 dynamic_response_info
.response_n
= 0;
4123 if (dynamic_response_info
.response_n
> 0) {
4125 // Copy the CID from the reader query
4126 dynamic_response_info
.response
[1] = receivedCmd
[1];
4128 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
4129 AddCrc14A(dynamic_response_info
.response
, dynamic_response_info
.response_n
);
4130 dynamic_response_info
.response_n
+= 2;
4132 if (prepare_tag_modulation(&dynamic_response_info
, DYNAMIC_MODULATION_BUFFER_SIZE
) == false) {
4133 if (g_dbglevel
>= DBG_DEBUG
) DbpString("Error preparing tag response");
4134 LogTrace(receivedCmd
, Uart
.len
, Uart
.startTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.endTime
* 16 - DELAY_AIR2ARM_AS_TAG
, Uart
.parity
, true);
4137 p_response
= &dynamic_response_info
;
4142 EmSendPrecompiledCmd(p_response
);
4148 BigBuf_free_keep_EM();
4150 reply_ng(CMD_HF_MIFARE_SIMULATE
, retval
, NULL
, 0);