]> cvs.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443a.c
REM: removed some unused code, GetDeltaCountUS() and a global counter variable....
[proxmark3-svn] / armsrc / iso14443a.c
CommitLineData
a126332a 1 //-----------------------------------------------------------------------------
b62a5a84 2// Merlok - June 2011, 2012
15c4dc5a 3// Gerhard de Koning Gans - May 2008
534983d7 4// Hagen Fritsch - June 2010
bd20f8f4 5//
6// This code is licensed to you under the terms of the GNU GPL, version 2 or,
7// at your option, any later version. See the LICENSE.txt file for the text of
8// the license.
15c4dc5a 9//-----------------------------------------------------------------------------
bd20f8f4 10// Routines to support ISO 14443 type A.
11//-----------------------------------------------------------------------------
12
e30c654b 13#include "proxmark3.h"
15c4dc5a 14#include "apps.h"
f7e3ed82 15#include "util.h"
9ab7a6c7 16#include "string.h"
902cb3c0 17#include "cmd.h"
15c4dc5a 18#include "iso14443crc.h"
534983d7 19#include "iso14443a.h"
6fc68747 20#include "iso14443b.h"
20f9a2a1
M
21#include "crapto1.h"
22#include "mifareutil.h"
3000dc4e 23#include "BigBuf.h"
f8ada309 24#include "parity.h"
25
534983d7 26static uint32_t iso14a_timeout;
1e262141 27int rsamples = 0;
1e262141 28uint8_t trigger = 0;
b0127e65 29// the block number for the ISO14443-4 PCB
30static uint8_t iso14_pcb_blocknum = 0;
15c4dc5a 31
7bc95e2e 32//
33// ISO14443 timing:
34//
35// minimum time between the start bits of consecutive transfers from reader to tag: 7000 carrier (13.56Mhz) cycles
36#define REQUEST_GUARD_TIME (7000/16 + 1)
37// minimum time between last modulation of tag and next start bit from reader to tag: 1172 carrier cycles
38#define FRAME_DELAY_TIME_PICC_TO_PCD (1172/16 + 1)
39// bool LastCommandWasRequest = FALSE;
40
41//
42// Total delays including SSC-Transfers between ARM and FPGA. These are in carrier clock cycles (1/13,56MHz)
43//
d714d3ef 44// When the PM acts as reader and is receiving tag data, it takes
45// 3 ticks delay in the AD converter
46// 16 ticks until the modulation detector completes and sets curbit
47// 8 ticks until bit_to_arm is assigned from curbit
48// 8*16 ticks for the transfer from FPGA to ARM
7bc95e2e 49// 4*16 ticks until we measure the time
50// - 8*16 ticks because we measure the time of the previous transfer
d714d3ef 51#define DELAY_AIR2ARM_AS_READER (3 + 16 + 8 + 8*16 + 4*16 - 8*16)
7bc95e2e 52
53// When the PM acts as a reader and is sending, it takes
54// 4*16 ticks until we can write data to the sending hold register
55// 8*16 ticks until the SHR is transferred to the Sending Shift Register
56// 8 ticks until the first transfer starts
57// 8 ticks later the FPGA samples the data
58// 1 tick to assign mod_sig_coil
59#define DELAY_ARM2AIR_AS_READER (4*16 + 8*16 + 8 + 8 + 1)
60
61// When the PM acts as tag and is receiving it takes
d714d3ef 62// 2 ticks delay in the RF part (for the first falling edge),
7bc95e2e 63// 3 ticks for the A/D conversion,
64// 8 ticks on average until the start of the SSC transfer,
65// 8 ticks until the SSC samples the first data
66// 7*16 ticks to complete the transfer from FPGA to ARM
67// 8 ticks until the next ssp_clk rising edge
d714d3ef 68// 4*16 ticks until we measure the time
7bc95e2e 69// - 8*16 ticks because we measure the time of the previous transfer
d714d3ef 70#define DELAY_AIR2ARM_AS_TAG (2 + 3 + 8 + 8 + 7*16 + 8 + 4*16 - 8*16)
7bc95e2e 71
72// The FPGA will report its internal sending delay in
73uint16_t FpgaSendQueueDelay;
74// the 5 first bits are the number of bits buffered in mod_sig_buf
75// the last three bits are the remaining ticks/2 after the mod_sig_buf shift
76#define DELAY_FPGA_QUEUE (FpgaSendQueueDelay<<1)
77
78// When the PM acts as tag and is sending, it takes
d714d3ef 79// 4*16 ticks until we can write data to the sending hold register
7bc95e2e 80// 8*16 ticks until the SHR is transferred to the Sending Shift Register
81// 8 ticks until the first transfer starts
82// 8 ticks later the FPGA samples the data
83// + a varying number of ticks in the FPGA Delay Queue (mod_sig_buf)
84// + 1 tick to assign mod_sig_coil
d714d3ef 85#define DELAY_ARM2AIR_AS_TAG (4*16 + 8*16 + 8 + 8 + DELAY_FPGA_QUEUE + 1)
7bc95e2e 86
87// When the PM acts as sniffer and is receiving tag data, it takes
88// 3 ticks A/D conversion
d714d3ef 89// 14 ticks to complete the modulation detection
90// 8 ticks (on average) until the result is stored in to_arm
7bc95e2e 91// + the delays in transferring data - which is the same for
92// sniffing reader and tag data and therefore not relevant
d714d3ef 93#define DELAY_TAG_AIR2ARM_AS_SNIFFER (3 + 14 + 8)
7bc95e2e 94
d714d3ef 95// When the PM acts as sniffer and is receiving reader data, it takes
96// 2 ticks delay in analogue RF receiver (for the falling edge of the
97// start bit, which marks the start of the communication)
7bc95e2e 98// 3 ticks A/D conversion
d714d3ef 99// 8 ticks on average until the data is stored in to_arm.
7bc95e2e 100// + the delays in transferring data - which is the same for
101// sniffing reader and tag data and therefore not relevant
d714d3ef 102#define DELAY_READER_AIR2ARM_AS_SNIFFER (2 + 3 + 8)
7bc95e2e 103
104//variables used for timing purposes:
105//these are in ssp_clk cycles:
6a1f2d82 106static uint32_t NextTransferTime;
107static uint32_t LastTimeProxToAirStart;
108static uint32_t LastProxToAirDuration;
7bc95e2e 109
8f51ddb0 110// CARD TO READER - manchester
72934aa3 111// Sequence D: 11110000 modulation with subcarrier during first half
112// Sequence E: 00001111 modulation with subcarrier during second half
113// Sequence F: 00000000 no modulation with subcarrier
8f51ddb0 114// READER TO CARD - miller
72934aa3 115// Sequence X: 00001100 drop after half a period
116// Sequence Y: 00000000 no drop
117// Sequence Z: 11000000 drop at start
118#define SEC_D 0xf0
119#define SEC_E 0x0f
120#define SEC_F 0x00
121#define SEC_X 0x0c
122#define SEC_Y 0x00
123#define SEC_Z 0xc0
15c4dc5a 124
902cb3c0 125void iso14a_set_trigger(bool enable) {
534983d7 126 trigger = enable;
127}
128
b0127e65 129void iso14a_set_timeout(uint32_t timeout) {
130 iso14a_timeout = timeout;
19a700a8 131 if(MF_DBGLEVEL >= 3) Dbprintf("ISO14443A Timeout set to %ld (%dms)", iso14a_timeout, iso14a_timeout / 106);
b0127e65 132}
8556b852 133
19a700a8 134void iso14a_set_ATS_timeout(uint8_t *ats) {
135
136 uint8_t tb1;
137 uint8_t fwi;
138 uint32_t fwt;
139
140 if (ats[0] > 1) { // there is a format byte T0
141 if ((ats[1] & 0x20) == 0x20) { // there is an interface byte TB(1)
4c0cf2d2 142
143 if ((ats[1] & 0x10) == 0x10) // there is an interface byte TA(1) preceding TB(1)
19a700a8 144 tb1 = ats[3];
4c0cf2d2 145 else
19a700a8 146 tb1 = ats[2];
4c0cf2d2 147
19a700a8 148 fwi = (tb1 & 0xf0) >> 4; // frame waiting indicator (FWI)
ca5bad3d 149 fwt = 256 * 16 * (1 << fwi); // frame waiting time (FWT) in 1/fc
150 //fwt = 4096 * (1 << fwi);
19a700a8 151
ca5bad3d 152 iso14a_set_timeout(fwt/(8*16));
153 //iso14a_set_timeout(fwt/128);
19a700a8 154 }
155 }
156}
157
15c4dc5a 158//-----------------------------------------------------------------------------
159// Generate the parity value for a byte sequence
e30c654b 160//
15c4dc5a 161//-----------------------------------------------------------------------------
6a1f2d82 162void GetParity(const uint8_t *pbtCmd, uint16_t iLen, uint8_t *par)
15c4dc5a 163{
6a1f2d82 164 uint16_t paritybit_cnt = 0;
165 uint16_t paritybyte_cnt = 0;
166 uint8_t parityBits = 0;
167
168 for (uint16_t i = 0; i < iLen; i++) {
169 // Generate the parity bits
f8ada309 170 parityBits |= ((oddparity8(pbtCmd[i])) << (7-paritybit_cnt));
6a1f2d82 171 if (paritybit_cnt == 7) {
172 par[paritybyte_cnt] = parityBits; // save 8 Bits parity
173 parityBits = 0; // and advance to next Parity Byte
174 paritybyte_cnt++;
175 paritybit_cnt = 0;
176 } else {
177 paritybit_cnt++;
178 }
5f6d6c90 179 }
6a1f2d82 180
181 // save remaining parity bits
182 par[paritybyte_cnt] = parityBits;
183
15c4dc5a 184}
185
534983d7 186void AppendCrc14443a(uint8_t* data, int len)
15c4dc5a 187{
5f6d6c90 188 ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
15c4dc5a 189}
190
7bc95e2e 191//=============================================================================
192// ISO 14443 Type A - Miller decoder
193//=============================================================================
194// Basics:
195// This decoder is used when the PM3 acts as a tag.
196// The reader will generate "pauses" by temporarily switching of the field.
197// At the PM3 antenna we will therefore measure a modulated antenna voltage.
198// The FPGA does a comparison with a threshold and would deliver e.g.:
199// ........ 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 .......
200// The Miller decoder needs to identify the following sequences:
201// 2 (or 3) ticks pause followed by 6 (or 5) ticks unmodulated: pause at beginning - Sequence Z ("start of communication" or a "0")
202// 8 ticks without a modulation: no pause - Sequence Y (a "0" or "end of communication" or "no information")
203// 4 ticks unmodulated followed by 2 (or 3) ticks pause: pause in second half - Sequence X (a "1")
204// Note 1: the bitstream may start at any time. We therefore need to sync.
205// Note 2: the interpretation of Sequence Y and Z depends on the preceding sequence.
15c4dc5a 206//-----------------------------------------------------------------------------
b62a5a84 207static tUart Uart;
15c4dc5a 208
d7aa3739 209// Lookup-Table to decide if 4 raw bits are a modulation.
0ec548dc 210// We accept the following:
211// 0001 - a 3 tick wide pause
212// 0011 - a 2 tick wide pause, or a three tick wide pause shifted left
213// 0111 - a 2 tick wide pause shifted left
214// 1001 - a 2 tick wide pause shifted right
d7aa3739 215const bool Mod_Miller_LUT[] = {
0ec548dc 216 FALSE, TRUE, FALSE, TRUE, FALSE, FALSE, FALSE, TRUE,
217 FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE
d7aa3739 218};
0ec548dc 219#define IsMillerModulationNibble1(b) (Mod_Miller_LUT[(b & 0x000000F0) >> 4])
220#define IsMillerModulationNibble2(b) (Mod_Miller_LUT[(b & 0x0000000F)])
d7aa3739 221
7bc95e2e 222void UartReset()
15c4dc5a 223{
7bc95e2e 224 Uart.state = STATE_UNSYNCD;
225 Uart.bitCount = 0;
226 Uart.len = 0; // number of decoded data bytes
6a1f2d82 227 Uart.parityLen = 0; // number of decoded parity bytes
7bc95e2e 228 Uart.shiftReg = 0; // shiftreg to hold decoded data bits
6a1f2d82 229 Uart.parityBits = 0; // holds 8 parity bits
7bc95e2e 230 Uart.startTime = 0;
231 Uart.endTime = 0;
46c65fed 232
233 Uart.byteCntMax = 0;
234 Uart.posCnt = 0;
235 Uart.syncBit = 9999;
7bc95e2e 236}
15c4dc5a 237
6a1f2d82 238void UartInit(uint8_t *data, uint8_t *parity)
239{
240 Uart.output = data;
241 Uart.parity = parity;
0ec548dc 242 Uart.fourBits = 0x00000000; // clear the buffer for 4 Bits
6a1f2d82 243 UartReset();
244}
d714d3ef 245
7bc95e2e 246// use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
247static RAMFUNC bool MillerDecoding(uint8_t bit, uint32_t non_real_time)
248{
15c4dc5a 249
0ec548dc 250 Uart.fourBits = (Uart.fourBits << 8) | bit;
7bc95e2e 251
0c8d25eb 252 if (Uart.state == STATE_UNSYNCD) { // not yet synced
3fe4ff4f 253
0ec548dc 254 Uart.syncBit = 9999; // not set
46c65fed 255
256 // 00x11111 2|3 ticks pause followed by 6|5 ticks unmodulated Sequence Z (a "0" or "start of communication")
257 // 11111111 8 ticks unmodulation Sequence Y (a "0" or "end of communication" or "no information")
258 // 111100x1 4 ticks unmodulated followed by 2|3 ticks pause Sequence X (a "1")
259
0ec548dc 260 // The start bit is one ore more Sequence Y followed by a Sequence Z (... 11111111 00x11111). We need to distinguish from
46c65fed 261 // Sequence X followed by Sequence Y followed by Sequence Z (111100x1 11111111 00x11111)
262 // we therefore look for a ...xx1111 11111111 00x11111xxxxxx... pattern
0ec548dc 263 // (12 '1's followed by 2 '0's, eventually followed by another '0', followed by 5 '1's)
46c65fed 264 //
265#define ISO14443A_STARTBIT_MASK 0x07FFEF80 // mask is 00001111 11111111 1110 1111 10000000
266#define ISO14443A_STARTBIT_PATTERN 0x07FF8F80 // pattern is 00001111 11111111 1000 1111 10000000
267
0ec548dc 268 if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 0)) == ISO14443A_STARTBIT_PATTERN >> 0) Uart.syncBit = 7;
269 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 1)) == ISO14443A_STARTBIT_PATTERN >> 1) Uart.syncBit = 6;
270 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 2)) == ISO14443A_STARTBIT_PATTERN >> 2) Uart.syncBit = 5;
271 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 3)) == ISO14443A_STARTBIT_PATTERN >> 3) Uart.syncBit = 4;
272 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 4)) == ISO14443A_STARTBIT_PATTERN >> 4) Uart.syncBit = 3;
273 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 5)) == ISO14443A_STARTBIT_PATTERN >> 5) Uart.syncBit = 2;
274 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 6)) == ISO14443A_STARTBIT_PATTERN >> 6) Uart.syncBit = 1;
275 else if ((Uart.fourBits & (ISO14443A_STARTBIT_MASK >> 7)) == ISO14443A_STARTBIT_PATTERN >> 7) Uart.syncBit = 0;
276
277 if (Uart.syncBit != 9999) { // found a sync bit
7bc95e2e 278 Uart.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8);
279 Uart.startTime -= Uart.syncBit;
d7aa3739 280 Uart.endTime = Uart.startTime;
7bc95e2e 281 Uart.state = STATE_START_OF_COMMUNICATION;
15c4dc5a 282 }
283
7bc95e2e 284 } else {
15c4dc5a 285
0ec548dc 286 if (IsMillerModulationNibble1(Uart.fourBits >> Uart.syncBit)) {
287 if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation in both halves - error
d7aa3739 288 UartReset();
d7aa3739 289 } else { // Modulation in first half = Sequence Z = logic "0"
7bc95e2e 290 if (Uart.state == STATE_MILLER_X) { // error - must not follow after X
291 UartReset();
7bc95e2e 292 } else {
293 Uart.bitCount++;
294 Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg
295 Uart.state = STATE_MILLER_Z;
296 Uart.endTime = Uart.startTime + 8*(9*Uart.len + Uart.bitCount + 1) - 6;
297 if(Uart.bitCount >= 9) { // if we decoded a full byte (including parity)
298 Uart.output[Uart.len++] = (Uart.shiftReg & 0xff);
299 Uart.parityBits <<= 1; // make room for the parity bit
300 Uart.parityBits |= ((Uart.shiftReg >> 8) & 0x01); // store parity bit
301 Uart.bitCount = 0;
302 Uart.shiftReg = 0;
6a1f2d82 303 if((Uart.len&0x0007) == 0) { // every 8 data bytes
304 Uart.parity[Uart.parityLen++] = Uart.parityBits; // store 8 parity bits
305 Uart.parityBits = 0;
306 }
15c4dc5a 307 }
7bc95e2e 308 }
d7aa3739 309 }
310 } else {
0ec548dc 311 if (IsMillerModulationNibble2(Uart.fourBits >> Uart.syncBit)) { // Modulation second half = Sequence X = logic "1"
7bc95e2e 312 Uart.bitCount++;
313 Uart.shiftReg = (Uart.shiftReg >> 1) | 0x100; // add a 1 to the shiftreg
314 Uart.state = STATE_MILLER_X;
315 Uart.endTime = Uart.startTime + 8*(9*Uart.len + Uart.bitCount + 1) - 2;
316 if(Uart.bitCount >= 9) { // if we decoded a full byte (including parity)
317 Uart.output[Uart.len++] = (Uart.shiftReg & 0xff);
318 Uart.parityBits <<= 1; // make room for the new parity bit
319 Uart.parityBits |= ((Uart.shiftReg >> 8) & 0x01); // store parity bit
320 Uart.bitCount = 0;
321 Uart.shiftReg = 0;
6a1f2d82 322 if ((Uart.len&0x0007) == 0) { // every 8 data bytes
323 Uart.parity[Uart.parityLen++] = Uart.parityBits; // store 8 parity bits
324 Uart.parityBits = 0;
325 }
7bc95e2e 326 }
d7aa3739 327 } else { // no modulation in both halves - Sequence Y
7bc95e2e 328 if (Uart.state == STATE_MILLER_Z || Uart.state == STATE_MILLER_Y) { // Y after logic "0" - End of Communication
15c4dc5a 329 Uart.state = STATE_UNSYNCD;
6a1f2d82 330 Uart.bitCount--; // last "0" was part of EOC sequence
331 Uart.shiftReg <<= 1; // drop it
332 if(Uart.bitCount > 0) { // if we decoded some bits
333 Uart.shiftReg >>= (9 - Uart.bitCount); // right align them
334 Uart.output[Uart.len++] = (Uart.shiftReg & 0xff); // add last byte to the output
335 Uart.parityBits <<= 1; // add a (void) parity bit
336 Uart.parityBits <<= (8 - (Uart.len&0x0007)); // left align parity bits
337 Uart.parity[Uart.parityLen++] = Uart.parityBits; // and store it
338 return TRUE;
339 } else if (Uart.len & 0x0007) { // there are some parity bits to store
340 Uart.parityBits <<= (8 - (Uart.len&0x0007)); // left align remaining parity bits
341 Uart.parity[Uart.parityLen++] = Uart.parityBits; // and store them
52bfb955 342 }
343 if (Uart.len) {
6a1f2d82 344 return TRUE; // we are finished with decoding the raw data sequence
52bfb955 345 } else {
0c8d25eb 346 UartReset(); // Nothing received - start over
7bc95e2e 347 }
15c4dc5a 348 }
7bc95e2e 349 if (Uart.state == STATE_START_OF_COMMUNICATION) { // error - must not follow directly after SOC
350 UartReset();
7bc95e2e 351 } else { // a logic "0"
352 Uart.bitCount++;
353 Uart.shiftReg = (Uart.shiftReg >> 1); // add a 0 to the shiftreg
354 Uart.state = STATE_MILLER_Y;
355 if(Uart.bitCount >= 9) { // if we decoded a full byte (including parity)
356 Uart.output[Uart.len++] = (Uart.shiftReg & 0xff);
357 Uart.parityBits <<= 1; // make room for the parity bit
358 Uart.parityBits |= ((Uart.shiftReg >> 8) & 0x01); // store parity bit
359 Uart.bitCount = 0;
360 Uart.shiftReg = 0;
6a1f2d82 361 if ((Uart.len&0x0007) == 0) { // every 8 data bytes
362 Uart.parity[Uart.parityLen++] = Uart.parityBits; // store 8 parity bits
363 Uart.parityBits = 0;
364 }
15c4dc5a 365 }
366 }
d7aa3739 367 }
15c4dc5a 368 }
7bc95e2e 369
370 }
15c4dc5a 371
7bc95e2e 372 return FALSE; // not finished yet, need more data
15c4dc5a 373}
374
7bc95e2e 375
376
15c4dc5a 377//=============================================================================
e691fc45 378// ISO 14443 Type A - Manchester decoder
15c4dc5a 379//=============================================================================
e691fc45 380// Basics:
7bc95e2e 381// This decoder is used when the PM3 acts as a reader.
e691fc45 382// The tag will modulate the reader field by asserting different loads to it. As a consequence, the voltage
383// at the reader antenna will be modulated as well. The FPGA detects the modulation for us and would deliver e.g. the following:
384// ........ 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 .......
385// The Manchester decoder needs to identify the following sequences:
386// 4 ticks modulated followed by 4 ticks unmodulated: Sequence D = 1 (also used as "start of communication")
387// 4 ticks unmodulated followed by 4 ticks modulated: Sequence E = 0
388// 8 ticks unmodulated: Sequence F = end of communication
389// 8 ticks modulated: A collision. Save the collision position and treat as Sequence D
7bc95e2e 390// Note 1: the bitstream may start at any time. We therefore need to sync.
e691fc45 391// Note 2: parameter offset is used to determine the position of the parity bits (required for the anticollision command only)
b62a5a84 392static tDemod Demod;
15c4dc5a 393
d7aa3739 394// Lookup-Table to decide if 4 raw bits are a modulation.
d714d3ef 395// We accept three or four "1" in any position
7bc95e2e 396const bool Mod_Manchester_LUT[] = {
d7aa3739 397 FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE,
d714d3ef 398 FALSE, FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE
7bc95e2e 399};
400
401#define IsManchesterModulationNibble1(b) (Mod_Manchester_LUT[(b & 0x00F0) >> 4])
402#define IsManchesterModulationNibble2(b) (Mod_Manchester_LUT[(b & 0x000F)])
15c4dc5a 403
2f2d9fc5 404
7bc95e2e 405void DemodReset()
e691fc45 406{
7bc95e2e 407 Demod.state = DEMOD_UNSYNCD;
408 Demod.len = 0; // number of decoded data bytes
6a1f2d82 409 Demod.parityLen = 0;
7bc95e2e 410 Demod.shiftReg = 0; // shiftreg to hold decoded data bits
411 Demod.parityBits = 0; //
412 Demod.collisionPos = 0; // Position of collision bit
413 Demod.twoBits = 0xffff; // buffer for 2 Bits
414 Demod.highCnt = 0;
415 Demod.startTime = 0;
416 Demod.endTime = 0;
46c65fed 417
418 //
419 Demod.bitCount = 0;
420 Demod.syncBit = 0xFFFF;
421 Demod.samples = 0;
e691fc45 422}
15c4dc5a 423
6a1f2d82 424void DemodInit(uint8_t *data, uint8_t *parity)
425{
426 Demod.output = data;
427 Demod.parity = parity;
428 DemodReset();
429}
430
7bc95e2e 431// use parameter non_real_time to provide a timestamp. Set to 0 if the decoder should measure real time
432static RAMFUNC int ManchesterDecoding(uint8_t bit, uint16_t offset, uint32_t non_real_time)
e691fc45 433{
7bc95e2e 434 Demod.twoBits = (Demod.twoBits << 8) | bit;
e691fc45 435
7bc95e2e 436 if (Demod.state == DEMOD_UNSYNCD) {
437
438 if (Demod.highCnt < 2) { // wait for a stable unmodulated signal
439 if (Demod.twoBits == 0x0000) {
440 Demod.highCnt++;
441 } else {
442 Demod.highCnt = 0;
443 }
444 } else {
445 Demod.syncBit = 0xFFFF; // not set
446 if ((Demod.twoBits & 0x7700) == 0x7000) Demod.syncBit = 7;
447 else if ((Demod.twoBits & 0x3B80) == 0x3800) Demod.syncBit = 6;
448 else if ((Demod.twoBits & 0x1DC0) == 0x1C00) Demod.syncBit = 5;
449 else if ((Demod.twoBits & 0x0EE0) == 0x0E00) Demod.syncBit = 4;
450 else if ((Demod.twoBits & 0x0770) == 0x0700) Demod.syncBit = 3;
451 else if ((Demod.twoBits & 0x03B8) == 0x0380) Demod.syncBit = 2;
452 else if ((Demod.twoBits & 0x01DC) == 0x01C0) Demod.syncBit = 1;
453 else if ((Demod.twoBits & 0x00EE) == 0x00E0) Demod.syncBit = 0;
d7aa3739 454 if (Demod.syncBit != 0xFFFF) {
7bc95e2e 455 Demod.startTime = non_real_time?non_real_time:(GetCountSspClk() & 0xfffffff8);
456 Demod.startTime -= Demod.syncBit;
457 Demod.bitCount = offset; // number of decoded data bits
e691fc45 458 Demod.state = DEMOD_MANCHESTER_DATA;
2f2d9fc5 459 }
7bc95e2e 460 }
15c4dc5a 461
7bc95e2e 462 } else {
15c4dc5a 463
7bc95e2e 464 if (IsManchesterModulationNibble1(Demod.twoBits >> Demod.syncBit)) { // modulation in first half
465 if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // ... and in second half = collision
e691fc45 466 if (!Demod.collisionPos) {
467 Demod.collisionPos = (Demod.len << 3) + Demod.bitCount;
468 }
469 } // modulation in first half only - Sequence D = 1
7bc95e2e 470 Demod.bitCount++;
471 Demod.shiftReg = (Demod.shiftReg >> 1) | 0x100; // in both cases, add a 1 to the shiftreg
472 if(Demod.bitCount == 9) { // if we decoded a full byte (including parity)
e691fc45 473 Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
7bc95e2e 474 Demod.parityBits <<= 1; // make room for the parity bit
e691fc45 475 Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
476 Demod.bitCount = 0;
477 Demod.shiftReg = 0;
6a1f2d82 478 if((Demod.len&0x0007) == 0) { // every 8 data bytes
479 Demod.parity[Demod.parityLen++] = Demod.parityBits; // store 8 parity bits
480 Demod.parityBits = 0;
481 }
15c4dc5a 482 }
7bc95e2e 483 Demod.endTime = Demod.startTime + 8*(9*Demod.len + Demod.bitCount + 1) - 4;
484 } else { // no modulation in first half
485 if (IsManchesterModulationNibble2(Demod.twoBits >> Demod.syncBit)) { // and modulation in second half = Sequence E = 0
e691fc45 486 Demod.bitCount++;
7bc95e2e 487 Demod.shiftReg = (Demod.shiftReg >> 1); // add a 0 to the shiftreg
e691fc45 488 if(Demod.bitCount >= 9) { // if we decoded a full byte (including parity)
e691fc45 489 Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
7bc95e2e 490 Demod.parityBits <<= 1; // make room for the new parity bit
e691fc45 491 Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
492 Demod.bitCount = 0;
493 Demod.shiftReg = 0;
6a1f2d82 494 if ((Demod.len&0x0007) == 0) { // every 8 data bytes
495 Demod.parity[Demod.parityLen++] = Demod.parityBits; // store 8 parity bits1
496 Demod.parityBits = 0;
497 }
15c4dc5a 498 }
7bc95e2e 499 Demod.endTime = Demod.startTime + 8*(9*Demod.len + Demod.bitCount + 1);
e691fc45 500 } else { // no modulation in both halves - End of communication
6a1f2d82 501 if(Demod.bitCount > 0) { // there are some remaining data bits
502 Demod.shiftReg >>= (9 - Demod.bitCount); // right align the decoded bits
503 Demod.output[Demod.len++] = Demod.shiftReg & 0xff; // and add them to the output
504 Demod.parityBits <<= 1; // add a (void) parity bit
505 Demod.parityBits <<= (8 - (Demod.len&0x0007)); // left align remaining parity bits
506 Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them
507 return TRUE;
508 } else if (Demod.len & 0x0007) { // there are some parity bits to store
509 Demod.parityBits <<= (8 - (Demod.len&0x0007)); // left align remaining parity bits
510 Demod.parity[Demod.parityLen++] = Demod.parityBits; // and store them
52bfb955 511 }
512 if (Demod.len) {
d7aa3739 513 return TRUE; // we are finished with decoding the raw data sequence
514 } else { // nothing received. Start over
515 DemodReset();
e691fc45 516 }
15c4dc5a 517 }
7bc95e2e 518 }
e691fc45 519 }
e691fc45 520 return FALSE; // not finished yet, need more data
15c4dc5a 521}
522
523//=============================================================================
524// Finally, a `sniffer' for ISO 14443 Type A
525// Both sides of communication!
526//=============================================================================
527
528//-----------------------------------------------------------------------------
529// Record the sequence of commands sent by the reader to the tag, with
530// triggering so that we start recording at the point that the tag is moved
531// near the reader.
532//-----------------------------------------------------------------------------
d26849d4 533void RAMFUNC SniffIso14443a(uint8_t param) {
5cd9ec01
M
534 // param:
535 // bit 0 - trigger from first card answer
536 // bit 1 - trigger from first reader 7-bit request
5cd9ec01 537 LEDsoff();
5cd9ec01 538
99cf19d9 539 iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER);
7bc95e2e 540
f71f4deb 541 // Allocate memory from BigBuf for some buffers
542 // free all previous allocations first
aaa1a9a2 543 BigBuf_free(); BigBuf_Clear_ext(false);
7838f4be 544
545 // init trace buffer
546 clear_trace();
547 set_tracing(TRUE);
548
5cd9ec01 549 // The command (reader -> tag) that we're receiving.
f71f4deb 550 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
551 uint8_t *receivedCmdPar = BigBuf_malloc(MAX_PARITY_SIZE);
6a1f2d82 552
5cd9ec01 553 // The response (tag -> reader) that we're receiving.
f71f4deb 554 uint8_t *receivedResponse = BigBuf_malloc(MAX_FRAME_SIZE);
555 uint8_t *receivedResponsePar = BigBuf_malloc(MAX_PARITY_SIZE);
5cd9ec01
M
556
557 // The DMA buffer, used to stream samples from the FPGA
f71f4deb 558 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
559
7bc95e2e 560 uint8_t *data = dmaBuf;
561 uint8_t previous_data = 0;
5cd9ec01
M
562 int maxDataLen = 0;
563 int dataLen = 0;
7bc95e2e 564 bool TagIsActive = FALSE;
565 bool ReaderIsActive = FALSE;
566
5cd9ec01 567 // Set up the demodulator for tag -> reader responses.
6a1f2d82 568 DemodInit(receivedResponse, receivedResponsePar);
569
5cd9ec01 570 // Set up the demodulator for the reader -> tag commands
6a1f2d82 571 UartInit(receivedCmd, receivedCmdPar);
572
7bc95e2e 573 // Setup and start DMA.
5cd9ec01 574 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
7bc95e2e 575
99cf19d9 576 // We won't start recording the frames that we acquire until we trigger;
577 // a good trigger condition to get started is probably when we see a
578 // response from the tag.
579 // triggered == FALSE -- to wait first for card
580 bool triggered = !(param & 0x03);
581
5cd9ec01 582 // And now we loop, receiving samples.
7bc95e2e 583 for(uint32_t rsamples = 0; TRUE; ) {
584
5cd9ec01
M
585 if(BUTTON_PRESS()) {
586 DbpString("cancelled by button");
7bc95e2e 587 break;
5cd9ec01 588 }
15c4dc5a 589
5cd9ec01
M
590 LED_A_ON();
591 WDT_HIT();
15c4dc5a 592
5cd9ec01
M
593 int register readBufDataP = data - dmaBuf;
594 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
595 if (readBufDataP <= dmaBufDataP){
596 dataLen = dmaBufDataP - readBufDataP;
597 } else {
7bc95e2e 598 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP;
5cd9ec01
M
599 }
600 // test for length of buffer
601 if(dataLen > maxDataLen) {
602 maxDataLen = dataLen;
f71f4deb 603 if(dataLen > (9 * DMA_BUFFER_SIZE / 10)) {
7bc95e2e 604 Dbprintf("blew circular buffer! dataLen=%d", dataLen);
605 break;
5cd9ec01
M
606 }
607 }
608 if(dataLen < 1) continue;
609
610 // primary buffer was stopped( <-- we lost data!
611 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
612 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
613 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
7bc95e2e 614 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen); // temporary
5cd9ec01
M
615 }
616 // secondary buffer sets as primary, secondary buffer was stopped
617 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
618 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
619 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
620 }
621
622 LED_A_OFF();
7bc95e2e 623
624 if (rsamples & 0x01) { // Need two samples to feed Miller and Manchester-Decoder
3be2a5ae 625
7bc95e2e 626 if(!TagIsActive) { // no need to try decoding reader data if the tag is sending
627 uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
628 if (MillerDecoding(readerdata, (rsamples-1)*4)) {
629 LED_C_ON();
5cd9ec01 630
7bc95e2e 631 // check - if there is a short 7bit request from reader
632 if ((!triggered) && (param & 0x02) && (Uart.len == 1) && (Uart.bitCount == 7)) triggered = TRUE;
5cd9ec01 633
7bc95e2e 634 if(triggered) {
6a1f2d82 635 if (!LogTrace(receivedCmd,
636 Uart.len,
637 Uart.startTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER,
638 Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER,
639 Uart.parity,
640 TRUE)) break;
7bc95e2e 641 }
642 /* And ready to receive another command. */
643 UartReset();
644 /* And also reset the demod code, which might have been */
645 /* false-triggered by the commands from the reader. */
646 DemodReset();
647 LED_B_OFF();
648 }
649 ReaderIsActive = (Uart.state != STATE_UNSYNCD);
5cd9ec01 650 }
3be2a5ae 651
7bc95e2e 652 if(!ReaderIsActive) { // no need to try decoding tag data if the reader is sending - and we cannot afford the time
653 uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
654 if(ManchesterDecoding(tagdata, 0, (rsamples-1)*4)) {
655 LED_B_ON();
5cd9ec01 656
6a1f2d82 657 if (!LogTrace(receivedResponse,
658 Demod.len,
659 Demod.startTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER,
660 Demod.endTime*16 - DELAY_TAG_AIR2ARM_AS_SNIFFER,
661 Demod.parity,
662 FALSE)) break;
5cd9ec01 663
7bc95e2e 664 if ((!triggered) && (param & 0x01)) triggered = TRUE;
5cd9ec01 665
7bc95e2e 666 // And ready to receive another response.
667 DemodReset();
0ec548dc 668 // And reset the Miller decoder including itS (now outdated) input buffer
669 UartInit(receivedCmd, receivedCmdPar);
670
7bc95e2e 671 LED_C_OFF();
672 }
673 TagIsActive = (Demod.state != DEMOD_UNSYNCD);
674 }
5cd9ec01
M
675 }
676
7bc95e2e 677 previous_data = *data;
678 rsamples++;
5cd9ec01 679 data++;
d714d3ef 680 if(data == dmaBuf + DMA_BUFFER_SIZE) {
5cd9ec01
M
681 data = dmaBuf;
682 }
683 } // main cycle
684
7bc95e2e 685 FpgaDisableSscDma();
7838f4be 686 LEDsoff();
687
7bc95e2e 688 Dbprintf("maxDataLen=%d, Uart.state=%x, Uart.len=%d", maxDataLen, Uart.state, Uart.len);
3000dc4e 689 Dbprintf("traceLen=%d, Uart.output[0]=%08x", BigBuf_get_traceLen(), (uint32_t)Uart.output[0]);
5ee53a0e 690
691 set_tracing(FALSE);
15c4dc5a 692}
693
15c4dc5a 694//-----------------------------------------------------------------------------
695// Prepare tag messages
696//-----------------------------------------------------------------------------
6a1f2d82 697static void CodeIso14443aAsTagPar(const uint8_t *cmd, uint16_t len, uint8_t *parity)
15c4dc5a 698{
8f51ddb0 699 ToSendReset();
15c4dc5a 700
701 // Correction bit, might be removed when not needed
702 ToSendStuffBit(0);
703 ToSendStuffBit(0);
704 ToSendStuffBit(0);
705 ToSendStuffBit(0);
706 ToSendStuffBit(1); // 1
707 ToSendStuffBit(0);
708 ToSendStuffBit(0);
709 ToSendStuffBit(0);
8f51ddb0 710
15c4dc5a 711 // Send startbit
72934aa3 712 ToSend[++ToSendMax] = SEC_D;
7bc95e2e 713 LastProxToAirDuration = 8 * ToSendMax - 4;
15c4dc5a 714
6a1f2d82 715 for(uint16_t i = 0; i < len; i++) {
8f51ddb0 716 uint8_t b = cmd[i];
15c4dc5a 717
718 // Data bits
6a1f2d82 719 for(uint16_t j = 0; j < 8; j++) {
15c4dc5a 720 if(b & 1) {
72934aa3 721 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 722 } else {
72934aa3 723 ToSend[++ToSendMax] = SEC_E;
8f51ddb0
M
724 }
725 b >>= 1;
726 }
15c4dc5a 727
0014cb46 728 // Get the parity bit
6a1f2d82 729 if (parity[i>>3] & (0x80>>(i&0x0007))) {
8f51ddb0 730 ToSend[++ToSendMax] = SEC_D;
7bc95e2e 731 LastProxToAirDuration = 8 * ToSendMax - 4;
15c4dc5a 732 } else {
72934aa3 733 ToSend[++ToSendMax] = SEC_E;
7bc95e2e 734 LastProxToAirDuration = 8 * ToSendMax;
15c4dc5a 735 }
8f51ddb0 736 }
15c4dc5a 737
8f51ddb0
M
738 // Send stopbit
739 ToSend[++ToSendMax] = SEC_F;
15c4dc5a 740
8f51ddb0 741 // Convert from last byte pos to length
6fc68747 742 ++ToSendMax;
8f51ddb0
M
743}
744
6a1f2d82 745static void CodeIso14443aAsTag(const uint8_t *cmd, uint16_t len)
746{
7504dc50 747 uint8_t par[MAX_PARITY_SIZE] = {0};
6a1f2d82 748 GetParity(cmd, len, par);
749 CodeIso14443aAsTagPar(cmd, len, par);
15c4dc5a 750}
751
15c4dc5a 752
8f51ddb0
M
753static void Code4bitAnswerAsTag(uint8_t cmd)
754{
755 int i;
756
5f6d6c90 757 ToSendReset();
8f51ddb0
M
758
759 // Correction bit, might be removed when not needed
760 ToSendStuffBit(0);
761 ToSendStuffBit(0);
762 ToSendStuffBit(0);
763 ToSendStuffBit(0);
764 ToSendStuffBit(1); // 1
765 ToSendStuffBit(0);
766 ToSendStuffBit(0);
767 ToSendStuffBit(0);
768
769 // Send startbit
770 ToSend[++ToSendMax] = SEC_D;
771
772 uint8_t b = cmd;
773 for(i = 0; i < 4; i++) {
774 if(b & 1) {
775 ToSend[++ToSendMax] = SEC_D;
7bc95e2e 776 LastProxToAirDuration = 8 * ToSendMax - 4;
8f51ddb0
M
777 } else {
778 ToSend[++ToSendMax] = SEC_E;
7bc95e2e 779 LastProxToAirDuration = 8 * ToSendMax;
8f51ddb0
M
780 }
781 b >>= 1;
782 }
783
784 // Send stopbit
785 ToSend[++ToSendMax] = SEC_F;
786
5f6d6c90 787 // Convert from last byte pos to length
788 ToSendMax++;
15c4dc5a 789}
790
791//-----------------------------------------------------------------------------
792// Wait for commands from reader
793// Stop when button is pressed
794// Or return TRUE when command is captured
795//-----------------------------------------------------------------------------
6a1f2d82 796static int GetIso14443aCommandFromReader(uint8_t *received, uint8_t *parity, int *len)
15c4dc5a 797{
798 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
799 // only, since we are receiving, not transmitting).
800 // Signal field is off with the appropriate LED
801 LED_D_OFF();
802 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
803
ca5bad3d 804 // Now run a `software UART` on the stream of incoming samples.
6a1f2d82 805 UartInit(received, parity);
7bc95e2e 806
807 // clear RXRDY:
808 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 809
810 for(;;) {
811 WDT_HIT();
812
813 if(BUTTON_PRESS()) return FALSE;
7bc95e2e 814
15c4dc5a 815 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
7bc95e2e 816 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
817 if(MillerDecoding(b, 0)) {
818 *len = Uart.len;
15c4dc5a 819 return TRUE;
820 }
7bc95e2e 821 }
15c4dc5a 822 }
823}
28afbd2b 824
6a1f2d82 825static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen, bool correctionNeeded);
7bc95e2e 826int EmSend4bitEx(uint8_t resp, bool correctionNeeded);
28afbd2b 827int EmSend4bit(uint8_t resp);
6a1f2d82 828int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, bool correctionNeeded, uint8_t *par);
829int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool correctionNeeded);
830int EmSendCmd(uint8_t *resp, uint16_t respLen);
831int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par);
832bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_StartTime, uint32_t reader_EndTime, uint8_t *reader_Parity,
833 uint8_t *tag_data, uint16_t tag_len, uint32_t tag_StartTime, uint32_t tag_EndTime, uint8_t *tag_Parity);
15c4dc5a 834
117d9ec2 835static uint8_t* free_buffer_pointer;
ce02f6f9 836
837typedef struct {
ca5bad3d 838 uint8_t* response;
839 size_t response_n;
840 uint8_t* modulation;
841 size_t modulation_n;
842 uint32_t ProxToAirDuration;
ce02f6f9 843} tag_response_info_t;
844
ce02f6f9 845bool prepare_tag_modulation(tag_response_info_t* response_info, size_t max_buffer_size) {
7bc95e2e 846 // Example response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
ce02f6f9 847 // This will need the following byte array for a modulation sequence
848 // 144 data bits (18 * 8)
849 // 18 parity bits
850 // 2 Start and stop
851 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
852 // 1 just for the case
853 // ----------- +
854 // 166 bytes, since every bit that needs to be send costs us a byte
855 //
f71f4deb 856
857
ce02f6f9 858 // Prepare the tag modulation bits from the message
859 CodeIso14443aAsTag(response_info->response,response_info->response_n);
860
861 // Make sure we do not exceed the free buffer space
862 if (ToSendMax > max_buffer_size) {
863 Dbprintf("Out of memory, when modulating bits for tag answer:");
864 Dbhexdump(response_info->response_n,response_info->response,false);
865 return false;
866 }
867
868 // Copy the byte array, used for this modulation to the buffer position
869 memcpy(response_info->modulation,ToSend,ToSendMax);
870
7bc95e2e 871 // Store the number of bytes that were used for encoding/modulation and the time needed to transfer them
ce02f6f9 872 response_info->modulation_n = ToSendMax;
7bc95e2e 873 response_info->ProxToAirDuration = LastProxToAirDuration;
ce02f6f9 874
875 return true;
876}
877
f71f4deb 878
879// "precompile" responses. There are 7 predefined responses with a total of 28 bytes data to transmit.
880// Coded responses need one byte per bit to transfer (data, parity, start, stop, correction)
881// 28 * 8 data bits, 28 * 1 parity bits, 7 start bits, 7 stop bits, 7 correction bits
882// -> need 273 bytes buffer
c9216a92 883// 44 * 8 data bits, 44 * 1 parity bits, 9 start bits, 9 stop bits, 9 correction bits --370
884// 47 * 8 data bits, 47 * 1 parity bits, 10 start bits, 10 stop bits, 10 correction bits
885#define ALLOCATED_TAG_MODULATION_BUFFER_SIZE 453
f71f4deb 886
ce02f6f9 887bool prepare_allocated_tag_modulation(tag_response_info_t* response_info) {
ca5bad3d 888 // Retrieve and store the current buffer index
889 response_info->modulation = free_buffer_pointer;
890
891 // Determine the maximum size we can use from our buffer
892 size_t max_buffer_size = ALLOCATED_TAG_MODULATION_BUFFER_SIZE;
893
894 // Forward the prepare tag modulation function to the inner function
895 if (prepare_tag_modulation(response_info, max_buffer_size)) {
896 // Update the free buffer offset
897 free_buffer_pointer += ToSendMax;
898 return true;
899 } else {
900 return false;
901 }
ce02f6f9 902}
903
15c4dc5a 904//-----------------------------------------------------------------------------
905// Main loop of simulated tag: receive commands from reader, decide what
906// response to send, and send it.
907//-----------------------------------------------------------------------------
0db6ed9a 908void SimulateIso14443aTag(int tagType, int flags, byte_t* data)
15c4dc5a 909{
a126332a 910 uint32_t counters[] = {0,0,0};
d26849d4 911 //Here, we collect UID,NT,AR,NR,UID2,NT2,AR2,NR2
912 // This can be used in a reader-only attack.
913 // (it can also be retrieved via 'hf 14a list', but hey...
914 uint32_t ar_nr_responses[] = {0,0,0,0,0,0,0,0,0,0};
915 uint8_t ar_nr_collected = 0;
916
81cd0474 917 uint8_t sak;
32719adf 918
919 // PACK response to PWD AUTH for EV1/NTAG
e98572a1 920 uint8_t response8[4] = {0,0,0,0};
32719adf 921
81cd0474 922 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
e98572a1 923 uint8_t response1[2] = {0,0};
81cd0474 924
925 switch (tagType) {
926 case 1: { // MIFARE Classic
927 // Says: I am Mifare 1k - original line
928 response1[0] = 0x04;
929 response1[1] = 0x00;
930 sak = 0x08;
931 } break;
932 case 2: { // MIFARE Ultralight
933 // Says: I am a stupid memory tag, no crypto
32719adf 934 response1[0] = 0x44;
81cd0474 935 response1[1] = 0x00;
936 sak = 0x00;
937 } break;
938 case 3: { // MIFARE DESFire
939 // Says: I am a DESFire tag, ph33r me
940 response1[0] = 0x04;
941 response1[1] = 0x03;
942 sak = 0x20;
943 } break;
944 case 4: { // ISO/IEC 14443-4
945 // Says: I am a javacard (JCOP)
946 response1[0] = 0x04;
947 response1[1] = 0x00;
948 sak = 0x28;
949 } break;
3fe4ff4f 950 case 5: { // MIFARE TNP3XXX
951 // Says: I am a toy
952 response1[0] = 0x01;
953 response1[1] = 0x0f;
954 sak = 0x01;
d26849d4 955 } break;
956 case 6: { // MIFARE Mini
957 // Says: I am a Mifare Mini, 320b
958 response1[0] = 0x44;
959 response1[1] = 0x00;
960 sak = 0x09;
961 } break;
32719adf 962 case 7: { // NTAG?
963 // Says: I am a NTAG,
964 response1[0] = 0x44;
965 response1[1] = 0x00;
966 sak = 0x00;
967 // PACK
968 response8[0] = 0x80;
969 response8[1] = 0x80;
970 ComputeCrc14443(CRC_14443_A, response8, 2, &response8[2], &response8[3]);
2b1f4228 971 // uid not supplied then get from emulator memory
972 if (data[0]==0) {
973 uint16_t start = 4 * (0+12);
974 uint8_t emdata[8];
975 emlGetMemBt( emdata, start, sizeof(emdata));
976 memcpy(data, emdata, 3); //uid bytes 0-2
977 memcpy(data+3, emdata+4, 4); //uid bytes 3-7
978 flags |= FLAG_7B_UID_IN_DATA;
979 }
32719adf 980 } break;
81cd0474 981 default: {
982 Dbprintf("Error: unkown tagtype (%d)",tagType);
983 return;
984 } break;
985 }
986
987 // The second response contains the (mandatory) first 24 bits of the UID
c8b6da22 988 uint8_t response2[5] = {0x00};
81cd0474 989
990 // Check if the uid uses the (optional) part
c8b6da22 991 uint8_t response2a[5] = {0x00};
992
d26849d4 993 if (flags & FLAG_7B_UID_IN_DATA) {
81cd0474 994 response2[0] = 0x88;
d26849d4 995 response2[1] = data[0];
996 response2[2] = data[1];
997 response2[3] = data[2];
998
999 response2a[0] = data[3];
1000 response2a[1] = data[4];
1001 response2a[2] = data[5];
c3c241f3 1002 response2a[3] = data[6]; //??
81cd0474 1003 response2a[4] = response2a[0] ^ response2a[1] ^ response2a[2] ^ response2a[3];
1004
1005 // Configure the ATQA and SAK accordingly
1006 response1[0] |= 0x40;
1007 sak |= 0x04;
1008 } else {
d26849d4 1009 memcpy(response2, data, 4);
1010 //num_to_bytes(uid_1st,4,response2);
81cd0474 1011 // Configure the ATQA and SAK accordingly
1012 response1[0] &= 0xBF;
1013 sak &= 0xFB;
1014 }
1015
1016 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
1017 response2[4] = response2[0] ^ response2[1] ^ response2[2] ^ response2[3];
1018
1019 // Prepare the mandatory SAK (for 4 and 7 byte UID)
c8b6da22 1020 uint8_t response3[3] = {0x00};
81cd0474 1021 response3[0] = sak;
1022 ComputeCrc14443(CRC_14443_A, response3, 1, &response3[1], &response3[2]);
1023
1024 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
c8b6da22 1025 uint8_t response3a[3] = {0x00};
81cd0474 1026 response3a[0] = sak & 0xFB;
1027 ComputeCrc14443(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]);
1028
0de8e387 1029 uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
6a1f2d82 1030 uint8_t response6[] = { 0x04, 0x58, 0x80, 0x02, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS:
1031 // Format byte = 0x58: FSCI=0x08 (FSC=256), TA(1) and TC(1) present,
1032 // TA(1) = 0x80: different divisors not supported, DR = 1, DS = 1
1033 // 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)
1034 // TC(1) = 0x02: CID supported, NAD not supported
ce02f6f9 1035 ComputeCrc14443(CRC_14443_A, response6, 4, &response6[4], &response6[5]);
1036
2b1f4228 1037 // Prepare GET_VERSION (different for UL EV-1 / NTAG)
32719adf 1038 //uint8_t response7_EV1[] = {0x00, 0x04, 0x03, 0x01, 0x01, 0x00, 0x0b, 0x03, 0xfd, 0xf7}; //EV1 48bytes VERSION.
2b1f4228 1039 //uint8_t response7_NTAG[] = {0x00, 0x04, 0x04, 0x02, 0x01, 0x00, 0x11, 0x03, 0x01, 0x9e}; //NTAG 215
32719adf 1040
c9216a92 1041 // Prepare CHK_TEARING
2b1f4228 1042 //uint8_t response9[] = {0xBD,0x90,0x3f};
c9216a92 1043
1044 #define TAG_RESPONSE_COUNT 10
7bc95e2e 1045 tag_response_info_t responses[TAG_RESPONSE_COUNT] = {
1046 { .response = response1, .response_n = sizeof(response1) }, // Answer to request - respond with card type
1047 { .response = response2, .response_n = sizeof(response2) }, // Anticollision cascade1 - respond with uid
1048 { .response = response2a, .response_n = sizeof(response2a) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1049 { .response = response3, .response_n = sizeof(response3) }, // Acknowledge select - cascade 1
1050 { .response = response3a, .response_n = sizeof(response3a) }, // Acknowledge select - cascade 2
1051 { .response = response5, .response_n = sizeof(response5) }, // Authentication answer (random nonce)
1052 { .response = response6, .response_n = sizeof(response6) }, // dummy ATS (pseudo-ATR), answer to RATS
4c0cf2d2 1053
495d7f13 1054 { .response = response8, .response_n = sizeof(response8) } // EV1/NTAG PACK response
4c0cf2d2 1055 };
1056 //{ .response = response7_NTAG, .response_n = sizeof(response7_NTAG)}, // EV1/NTAG GET_VERSION response
2b1f4228 1057 //{ .response = response9, .response_n = sizeof(response9) } // EV1/NTAG CHK_TEAR response
4c0cf2d2 1058
7bc95e2e 1059
1060 // Allocate 512 bytes for the dynamic modulation, created when the reader queries for it
1061 // Such a response is less time critical, so we can prepare them on the fly
1062 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1063 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1064 uint8_t dynamic_response_buffer[DYNAMIC_RESPONSE_BUFFER_SIZE];
1065 uint8_t dynamic_modulation_buffer[DYNAMIC_MODULATION_BUFFER_SIZE];
1066 tag_response_info_t dynamic_response_info = {
1067 .response = dynamic_response_buffer,
1068 .response_n = 0,
1069 .modulation = dynamic_modulation_buffer,
1070 .modulation_n = 0
1071 };
ce02f6f9 1072
99cf19d9 1073 // We need to listen to the high-frequency, peak-detected path.
1074 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1075
f71f4deb 1076 BigBuf_free_keep_EM();
1077
1078 // allocate buffers:
1079 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
1080 uint8_t *receivedCmdPar = BigBuf_malloc(MAX_PARITY_SIZE);
1081 free_buffer_pointer = BigBuf_malloc(ALLOCATED_TAG_MODULATION_BUFFER_SIZE);
1082
1083 // clear trace
3000dc4e
MHS
1084 clear_trace();
1085 set_tracing(TRUE);
f71f4deb 1086
7bc95e2e 1087 // Prepare the responses of the anticollision phase
ce02f6f9 1088 // there will be not enough time to do this at the moment the reader sends it REQA
495d7f13 1089 for (size_t i=0; i<TAG_RESPONSE_COUNT; i++)
7bc95e2e 1090 prepare_allocated_tag_modulation(&responses[i]);
15c4dc5a 1091
7bc95e2e 1092 int len = 0;
15c4dc5a 1093
1094 // To control where we are in the protocol
1095 int order = 0;
1096 int lastorder;
1097
1098 // Just to allow some checks
1099 int happened = 0;
1100 int happened2 = 0;
81cd0474 1101 int cmdsRecvd = 0;
15c4dc5a 1102
254b70a4 1103 cmdsRecvd = 0;
7bc95e2e 1104 tag_response_info_t* p_response;
15c4dc5a 1105
254b70a4 1106 LED_A_ON();
1107 for(;;) {
4c0cf2d2 1108
1109 WDT_HIT();
1110
7bc95e2e 1111 // Clean receive command buffer
6a1f2d82 1112 if(!GetIso14443aCommandFromReader(receivedCmd, receivedCmdPar, &len)) {
ce02f6f9 1113 DbpString("Button press");
254b70a4 1114 break;
1115 }
7bc95e2e 1116
1117 p_response = NULL;
1118
254b70a4 1119 // Okay, look at the command now.
1120 lastorder = order;
1121 if(receivedCmd[0] == 0x26) { // Received a REQUEST
ce02f6f9 1122 p_response = &responses[0]; order = 1;
254b70a4 1123 } else if(receivedCmd[0] == 0x52) { // Received a WAKEUP
ce02f6f9 1124 p_response = &responses[0]; order = 6;
254b70a4 1125 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // Received request for UID (cascade 1)
ce02f6f9 1126 p_response = &responses[1]; order = 2;
6a1f2d82 1127 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x95) { // Received request for UID (cascade 2)
ce02f6f9 1128 p_response = &responses[2]; order = 20;
254b70a4 1129 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x93) { // Received a SELECT (cascade 1)
ce02f6f9 1130 p_response = &responses[3]; order = 3;
254b70a4 1131 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2)
ce02f6f9 1132 p_response = &responses[4]; order = 30;
254b70a4 1133 } else if(receivedCmd[0] == 0x30) { // Received a (plain) READ
32719adf 1134 uint8_t block = receivedCmd[1];
2b1f4228 1135 // if Ultralight or NTAG (4 byte blocks)
1136 if ( tagType == 7 || tagType == 2 ) {
1137 //first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1138 uint16_t start = 4 * (block+12);
5e428463 1139 uint8_t emdata[MAX_MIFARE_FRAME_SIZE];
1140 emlGetMemBt( emdata, start, 16);
1141 AppendCrc14443a(emdata, 16);
1142 EmSendCmdEx(emdata, sizeof(emdata), false);
2b1f4228 1143 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
32719adf 1144 p_response = NULL;
2b1f4228 1145 } else { // all other tags (16 byte block tags)
1146 EmSendCmdEx(data+(4*receivedCmd[1]),16,false);
32719adf 1147 // Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
1148 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1149 p_response = NULL;
1150 }
a126332a 1151 } else if(receivedCmd[0] == 0x3A) { // Received a FAST READ (ranged read)
5e428463 1152
1153 uint8_t emdata[MAX_FRAME_SIZE];
2b1f4228 1154 //first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1155 int start = (receivedCmd[1]+12) * 4;
ce3d6bd2 1156 int len = (receivedCmd[2] - receivedCmd[1] + 1) * 4;
5e428463 1157 emlGetMemBt( emdata, start, len);
1158 AppendCrc14443a(emdata, len);
1159 EmSendCmdEx(emdata, len+2, false);
1160 p_response = NULL;
1161
839a53ae 1162 } else if(receivedCmd[0] == 0x3C && tagType == 7) { // Received a READ SIGNATURE --
2b1f4228 1163 //first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1164 uint16_t start = 4 * 4;
1165 uint8_t emdata[34];
1166 emlGetMemBt( emdata, start, 32);
1167 AppendCrc14443a(emdata, 32);
1168 EmSendCmdEx(emdata, sizeof(emdata), false);
839a53ae 1169 p_response = NULL;
a126332a 1170 } else if (receivedCmd[0] == 0x39 && tagType == 7) { // Received a READ COUNTER --
e9a92fe2 1171 uint8_t index = receivedCmd[1];
a126332a 1172 uint8_t data[] = {0x00,0x00,0x00,0x14,0xa5};
e9a92fe2 1173 if ( counters[index] > 0) {
1174 num_to_bytes(counters[index], 3, data);
1175 AppendCrc14443a(data, sizeof(data)-2);
1176 }
a126332a 1177 EmSendCmdEx(data,sizeof(data),false);
1178 p_response = NULL;
1179 } else if (receivedCmd[0] == 0xA5 && tagType == 7) { // Received a INC COUNTER --
ce3d6bd2 1180 // number of counter
a126332a 1181 uint8_t counter = receivedCmd[1];
1182 uint32_t val = bytes_to_num(receivedCmd+2,4);
1183 counters[counter] = val;
1184
ce3d6bd2 1185 // send ACK
1186 uint8_t ack[] = {0x0a};
1187 EmSendCmdEx(ack,sizeof(ack),false);
1188 p_response = NULL;
1189
c9216a92 1190 } else if(receivedCmd[0] == 0x3E && tagType == 7) { // Received a CHECK_TEARING_EVENT --
2b1f4228 1191 //first 12 blocks of emu are [getversion answer - check tearing - pack - 0x00 - signature]
1192 uint8_t emdata[3];
1193 uint8_t counter=0;
1194 if (receivedCmd[1]<3) counter = receivedCmd[1];
1195 emlGetMemBt( emdata, 10+counter, 1);
1196 AppendCrc14443a(emdata, sizeof(emdata)-2);
1197 EmSendCmdEx(emdata, sizeof(emdata), false);
b0300679 1198 p_response = NULL;
254b70a4 1199 } else if(receivedCmd[0] == 0x50) { // Received a HALT
810f5379 1200 LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 1201 p_response = NULL;
254b70a4 1202 } else if(receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61) { // Received an authentication request
32719adf 1203
1204 if ( tagType == 7 ) { // IF NTAG /EV1 0x60 == GET_VERSION, not a authentication request.
2b1f4228 1205 uint8_t emdata[10];
1206 emlGetMemBt( emdata, 0, 8 );
1207 AppendCrc14443a(emdata, sizeof(emdata)-2);
1208 EmSendCmdEx(emdata, sizeof(emdata), false);
1209 p_response = NULL;
32719adf 1210 } else {
1211 p_response = &responses[5]; order = 7;
1212 }
254b70a4 1213 } else if(receivedCmd[0] == 0xE0) { // Received a RATS request
7bc95e2e 1214 if (tagType == 1 || tagType == 2) { // RATS not supported
1215 EmSend4bit(CARD_NACK_NA);
1216 p_response = NULL;
1217 } else {
1218 p_response = &responses[6]; order = 70;
1219 }
6a1f2d82 1220 } else if (order == 7 && len == 8) { // Received {nr] and {ar} (part of authentication)
810f5379 1221 LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
d26849d4 1222 uint32_t nonce = bytes_to_num(response5,4);
7bc95e2e 1223 uint32_t nr = bytes_to_num(receivedCmd,4);
1224 uint32_t ar = bytes_to_num(receivedCmd+4,4);
d26849d4 1225 //Dbprintf("Auth attempt {nonce}{nr}{ar}: %08x %08x %08x", nonce, nr, ar);
1226
1227 if(flags & FLAG_NR_AR_ATTACK )
1228 {
1229 if(ar_nr_collected < 2){
1230 // Avoid duplicates... probably not necessary, nr should vary.
1231 //if(ar_nr_responses[3] != nr){
1232 ar_nr_responses[ar_nr_collected*5] = 0;
1233 ar_nr_responses[ar_nr_collected*5+1] = 0;
1234 ar_nr_responses[ar_nr_collected*5+2] = nonce;
1235 ar_nr_responses[ar_nr_collected*5+3] = nr;
1236 ar_nr_responses[ar_nr_collected*5+4] = ar;
1237 ar_nr_collected++;
1238 //}
1239 }
1240
1241 if(ar_nr_collected > 1 ) {
1242
1243 if (MF_DBGLEVEL >= 2) {
1244 Dbprintf("Collected two pairs of AR/NR which can be used to extract keys from reader:");
1245 Dbprintf("../tools/mfkey/mfkey32 %07x%08x %08x %08x %08x %08x %08x",
1246 ar_nr_responses[0], // UID1
1247 ar_nr_responses[1], // UID2
1248 ar_nr_responses[2], // NT
1249 ar_nr_responses[3], // AR1
1250 ar_nr_responses[4], // NR1
1251 ar_nr_responses[8], // AR2
1252 ar_nr_responses[9] // NR2
1253 );
7838f4be 1254 Dbprintf("../tools/mfkey/mfkey32v2 %06x%08x %08x %08x %08x %08x %08x %08x",
1255 ar_nr_responses[0], // UID1
1256 ar_nr_responses[1], // UID2
1257 ar_nr_responses[2], // NT1
1258 ar_nr_responses[3], // AR1
1259 ar_nr_responses[4], // NR1
1260 ar_nr_responses[7], // NT2
1261 ar_nr_responses[8], // AR2
1262 ar_nr_responses[9] // NR2
1263 );
d26849d4 1264 }
1265 uint8_t len = ar_nr_collected*5*4;
1266 cmd_send(CMD_ACK,CMD_SIMULATE_MIFARE_CARD,len,0,&ar_nr_responses,len);
1267 ar_nr_collected = 0;
1268 memset(ar_nr_responses, 0x00, len);
d26849d4 1269 }
1270 }
32719adf 1271 } else if (receivedCmd[0] == 0x1a ) // ULC authentication
1272 {
1273
1274 }
1275 else if (receivedCmd[0] == 0x1b) // NTAG / EV-1 authentication
1276 {
1277 if ( tagType == 7 ) {
2b1f4228 1278 uint16_t start = 13; //first 4 blocks of emu are [getversion answer - check tearing - pack - 0x00]
1279 uint8_t emdata[4];
1280 emlGetMemBt( emdata, start, 2);
1281 AppendCrc14443a(emdata, 2);
1282 EmSendCmdEx(emdata, sizeof(emdata), false);
1283 p_response = NULL;
ce3d6bd2 1284 uint32_t pwd = bytes_to_num(receivedCmd+1,4);
e98572a1 1285
1286 if ( MF_DBGLEVEL >= 3) Dbprintf("Auth attempt: %08x", pwd);
32719adf 1287 }
2b1f4228 1288 } else {
7bc95e2e 1289 // Check for ISO 14443A-4 compliant commands, look at left nibble
1290 switch (receivedCmd[0]) {
7838f4be 1291 case 0x02:
1292 case 0x03: { // IBlock (command no CID)
1293 dynamic_response_info.response[0] = receivedCmd[0];
1294 dynamic_response_info.response[1] = 0x90;
1295 dynamic_response_info.response[2] = 0x00;
1296 dynamic_response_info.response_n = 3;
1297 } break;
7bc95e2e 1298 case 0x0B:
7838f4be 1299 case 0x0A: { // IBlock (command CID)
7bc95e2e 1300 dynamic_response_info.response[0] = receivedCmd[0];
1301 dynamic_response_info.response[1] = 0x00;
1302 dynamic_response_info.response[2] = 0x90;
1303 dynamic_response_info.response[3] = 0x00;
1304 dynamic_response_info.response_n = 4;
1305 } break;
1306
1307 case 0x1A:
1308 case 0x1B: { // Chaining command
1309 dynamic_response_info.response[0] = 0xaa | ((receivedCmd[0]) & 1);
1310 dynamic_response_info.response_n = 2;
1311 } break;
1312
1313 case 0xaa:
1314 case 0xbb: {
1315 dynamic_response_info.response[0] = receivedCmd[0] ^ 0x11;
1316 dynamic_response_info.response_n = 2;
1317 } break;
1318
7838f4be 1319 case 0xBA: { // ping / pong
1320 dynamic_response_info.response[0] = 0xAB;
1321 dynamic_response_info.response[1] = 0x00;
1322 dynamic_response_info.response_n = 2;
7bc95e2e 1323 } break;
1324
1325 case 0xCA:
1326 case 0xC2: { // Readers sends deselect command
7838f4be 1327 dynamic_response_info.response[0] = 0xCA;
1328 dynamic_response_info.response[1] = 0x00;
1329 dynamic_response_info.response_n = 2;
7bc95e2e 1330 } break;
1331
1332 default: {
1333 // Never seen this command before
810f5379 1334 LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 1335 Dbprintf("Received unknown command (len=%d):",len);
1336 Dbhexdump(len,receivedCmd,false);
1337 // Do not respond
1338 dynamic_response_info.response_n = 0;
1339 } break;
1340 }
ce02f6f9 1341
7bc95e2e 1342 if (dynamic_response_info.response_n > 0) {
1343 // Copy the CID from the reader query
1344 dynamic_response_info.response[1] = receivedCmd[1];
ce02f6f9 1345
7bc95e2e 1346 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1347 AppendCrc14443a(dynamic_response_info.response,dynamic_response_info.response_n);
1348 dynamic_response_info.response_n += 2;
ce02f6f9 1349
7bc95e2e 1350 if (prepare_tag_modulation(&dynamic_response_info,DYNAMIC_MODULATION_BUFFER_SIZE) == false) {
1351 Dbprintf("Error preparing tag response");
810f5379 1352 LogTrace(receivedCmd, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 1353 break;
1354 }
1355 p_response = &dynamic_response_info;
1356 }
81cd0474 1357 }
15c4dc5a 1358
1359 // Count number of wakeups received after a halt
1360 if(order == 6 && lastorder == 5) { happened++; }
1361
1362 // Count number of other messages after a halt
1363 if(order != 6 && lastorder == 5) { happened2++; }
1364
15c4dc5a 1365 if(cmdsRecvd > 999) {
1366 DbpString("1000 commands later...");
254b70a4 1367 break;
15c4dc5a 1368 }
ce02f6f9 1369 cmdsRecvd++;
1370
1371 if (p_response != NULL) {
7bc95e2e 1372 EmSendCmd14443aRaw(p_response->modulation, p_response->modulation_n, receivedCmd[0] == 0x52);
1373 // do the tracing for the previous reader request and this tag answer:
810f5379 1374 uint8_t par[MAX_PARITY_SIZE] = {0x00};
6a1f2d82 1375 GetParity(p_response->response, p_response->response_n, par);
3fe4ff4f 1376
7bc95e2e 1377 EmLogTrace(Uart.output,
1378 Uart.len,
1379 Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG,
1380 Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG,
6a1f2d82 1381 Uart.parity,
7bc95e2e 1382 p_response->response,
1383 p_response->response_n,
1384 LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG,
1385 (LastTimeProxToAirStart + p_response->ProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG,
6a1f2d82 1386 par);
7bc95e2e 1387 }
1388
1389 if (!tracing) {
1390 Dbprintf("Trace Full. Simulation stopped.");
1391 break;
1392 }
1393 }
15c4dc5a 1394
d26849d4 1395 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
5ee53a0e 1396 set_tracing(FALSE);
f71f4deb 1397 BigBuf_free_keep_EM();
c9216a92 1398 LED_A_OFF();
1399
0de8e387 1400 if (MF_DBGLEVEL >= 4){
5ee53a0e 1401 Dbprintf("-[ Wake ups after halt [%d]", happened);
1402 Dbprintf("-[ Messages after halt [%d]", happened2);
1403 Dbprintf("-[ Num of received cmd [%d]", cmdsRecvd);
0de8e387 1404 }
15c4dc5a 1405}
1406
9492e0b0 1407
1408// prepare a delayed transfer. This simply shifts ToSend[] by a number
1409// of bits specified in the delay parameter.
1410void PrepareDelayedTransfer(uint16_t delay)
1411{
7504dc50 1412 delay &= 0x07;
1413 if (!delay) return;
1414
9492e0b0 1415 uint8_t bitmask = 0;
1416 uint8_t bits_to_shift = 0;
1417 uint8_t bits_shifted = 0;
7504dc50 1418 uint16_t i = 0;
1419
1420 for (i = 0; i < delay; ++i)
1421 bitmask |= (0x01 << i);
2285d9dd 1422
6fc68747 1423 ToSend[++ToSendMax] = 0x00;
7504dc50 1424
1425 for (i = 0; i < ToSendMax; ++i) {
9492e0b0 1426 bits_to_shift = ToSend[i] & bitmask;
1427 ToSend[i] = ToSend[i] >> delay;
1428 ToSend[i] = ToSend[i] | (bits_shifted << (8 - delay));
1429 bits_shifted = bits_to_shift;
1430 }
1431 }
9492e0b0 1432
7bc95e2e 1433
1434//-------------------------------------------------------------------------------------
15c4dc5a 1435// Transmit the command (to the tag) that was placed in ToSend[].
9492e0b0 1436// Parameter timing:
7bc95e2e 1437// if NULL: transfer at next possible time, taking into account
1438// request guard time and frame delay time
1439// if == 0: transfer immediately and return time of transfer
9492e0b0 1440// if != 0: delay transfer until time specified
7bc95e2e 1441//-------------------------------------------------------------------------------------
6a1f2d82 1442static void TransmitFor14443a(const uint8_t *cmd, uint16_t len, uint32_t *timing)
15c4dc5a 1443{
9492e0b0 1444 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
e30c654b 1445
7bc95e2e 1446 uint32_t ThisTransferTime = 0;
e30c654b 1447
9492e0b0 1448 if (timing) {
ca5bad3d 1449 if(*timing == 0) { // Measure time
7bc95e2e 1450 *timing = (GetCountSspClk() + 8) & 0xfffffff8;
ca5bad3d 1451 } else {
1452 PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
1453 }
1454 if(MF_DBGLEVEL >= 4 && GetCountSspClk() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
1455 while(GetCountSspClk() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
7bc95e2e 1456 LastTimeProxToAirStart = *timing;
1457 } else {
1458 ThisTransferTime = ((MAX(NextTransferTime, GetCountSspClk()) & 0xfffffff8) + 8);
7504dc50 1459
7bc95e2e 1460 while(GetCountSspClk() < ThisTransferTime);
7504dc50 1461
7bc95e2e 1462 LastTimeProxToAirStart = ThisTransferTime;
9492e0b0 1463 }
1464
7bc95e2e 1465 // clear TXRDY
1466 AT91C_BASE_SSC->SSC_THR = SEC_Y;
1467
7bc95e2e 1468 uint16_t c = 0;
9492e0b0 1469 for(;;) {
1470 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1471 AT91C_BASE_SSC->SSC_THR = cmd[c];
4c0cf2d2 1472 ++c;
5ebcb867 1473 if(c >= len)
9492e0b0 1474 break;
9492e0b0 1475 }
1476 }
7bc95e2e 1477
1478 NextTransferTime = MAX(NextTransferTime, LastTimeProxToAirStart + REQUEST_GUARD_TIME);
15c4dc5a 1479}
1480
7bc95e2e 1481
15c4dc5a 1482//-----------------------------------------------------------------------------
195af472 1483// Prepare reader command (in bits, support short frames) to send to FPGA
15c4dc5a 1484//-----------------------------------------------------------------------------
6a1f2d82 1485void CodeIso14443aBitsAsReaderPar(const uint8_t *cmd, uint16_t bits, const uint8_t *parity)
15c4dc5a 1486{
7bc95e2e 1487 int i, j;
5ebcb867 1488 int last = 0;
7bc95e2e 1489 uint8_t b;
e30c654b 1490
7bc95e2e 1491 ToSendReset();
e30c654b 1492
7bc95e2e 1493 // Start of Communication (Seq. Z)
1494 ToSend[++ToSendMax] = SEC_Z;
1495 LastProxToAirDuration = 8 * (ToSendMax+1) - 6;
7bc95e2e 1496
1497 size_t bytecount = nbytes(bits);
1498 // Generate send structure for the data bits
1499 for (i = 0; i < bytecount; i++) {
1500 // Get the current byte to send
1501 b = cmd[i];
1502 size_t bitsleft = MIN((bits-(i*8)),8);
1503
1504 for (j = 0; j < bitsleft; j++) {
1505 if (b & 1) {
1506 // Sequence X
1507 ToSend[++ToSendMax] = SEC_X;
1508 LastProxToAirDuration = 8 * (ToSendMax+1) - 2;
1509 last = 1;
1510 } else {
1511 if (last == 0) {
1512 // Sequence Z
1513 ToSend[++ToSendMax] = SEC_Z;
1514 LastProxToAirDuration = 8 * (ToSendMax+1) - 6;
1515 } else {
1516 // Sequence Y
1517 ToSend[++ToSendMax] = SEC_Y;
1518 last = 0;
1519 }
1520 }
1521 b >>= 1;
1522 }
1523
6a1f2d82 1524 // Only transmit parity bit if we transmitted a complete byte
0ec548dc 1525 if (j == 8 && parity != NULL) {
7bc95e2e 1526 // Get the parity bit
6a1f2d82 1527 if (parity[i>>3] & (0x80 >> (i&0x0007))) {
7bc95e2e 1528 // Sequence X
1529 ToSend[++ToSendMax] = SEC_X;
1530 LastProxToAirDuration = 8 * (ToSendMax+1) - 2;
1531 last = 1;
1532 } else {
1533 if (last == 0) {
1534 // Sequence Z
1535 ToSend[++ToSendMax] = SEC_Z;
1536 LastProxToAirDuration = 8 * (ToSendMax+1) - 6;
1537 } else {
1538 // Sequence Y
1539 ToSend[++ToSendMax] = SEC_Y;
1540 last = 0;
1541 }
1542 }
1543 }
1544 }
e30c654b 1545
7bc95e2e 1546 // End of Communication: Logic 0 followed by Sequence Y
1547 if (last == 0) {
1548 // Sequence Z
1549 ToSend[++ToSendMax] = SEC_Z;
1550 LastProxToAirDuration = 8 * (ToSendMax+1) - 6;
1551 } else {
1552 // Sequence Y
1553 ToSend[++ToSendMax] = SEC_Y;
1554 last = 0;
1555 }
1556 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1557
7bc95e2e 1558 // Convert to length of command:
4b78d6b3 1559 ++ToSendMax;
15c4dc5a 1560}
1561
195af472 1562//-----------------------------------------------------------------------------
1563// Prepare reader command to send to FPGA
1564//-----------------------------------------------------------------------------
6a1f2d82 1565void CodeIso14443aAsReaderPar(const uint8_t *cmd, uint16_t len, const uint8_t *parity)
195af472 1566{
ca5bad3d 1567 CodeIso14443aBitsAsReaderPar(cmd, len*8, parity);
195af472 1568}
1569
0c8d25eb 1570
9ca155ba
M
1571//-----------------------------------------------------------------------------
1572// Wait for commands from reader
1573// Stop when button is pressed (return 1) or field was gone (return 2)
1574// Or return 0 when command is captured
1575//-----------------------------------------------------------------------------
6a1f2d82 1576static int EmGetCmd(uint8_t *received, uint16_t *len, uint8_t *parity)
9ca155ba
M
1577{
1578 *len = 0;
1579
1580 uint32_t timer = 0, vtime = 0;
1581 int analogCnt = 0;
1582 int analogAVG = 0;
1583
1584 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1585 // only, since we are receiving, not transmitting).
1586 // Signal field is off with the appropriate LED
1587 LED_D_OFF();
1588 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1589
1590 // Set ADC to read field strength
1591 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
1592 AT91C_BASE_ADC->ADC_MR =
0c8d25eb 1593 ADC_MODE_PRESCALE(63) |
1594 ADC_MODE_STARTUP_TIME(1) |
1595 ADC_MODE_SAMPLE_HOLD_TIME(15);
9ca155ba
M
1596 AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF);
1597 // start ADC
1598 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1599
1600 // Now run a 'software UART' on the stream of incoming samples.
6a1f2d82 1601 UartInit(received, parity);
7bc95e2e 1602
1603 // Clear RXRDY:
1604 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
0c8d25eb 1605
9ca155ba
M
1606 for(;;) {
1607 WDT_HIT();
1608
1609 if (BUTTON_PRESS()) return 1;
1610
1611 // test if the field exists
1612 if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF)) {
1613 analogCnt++;
1614 analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF];
1615 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1616 if (analogCnt >= 32) {
0c8d25eb 1617 if ((MAX_ADC_HF_VOLTAGE * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
9ca155ba
M
1618 vtime = GetTickCount();
1619 if (!timer) timer = vtime;
1620 // 50ms no field --> card to idle state
1621 if (vtime - timer > 50) return 2;
1622 } else
1623 if (timer) timer = 0;
1624 analogCnt = 0;
1625 analogAVG = 0;
1626 }
1627 }
7bc95e2e 1628
9ca155ba 1629 // receive and test the miller decoding
7bc95e2e 1630 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1631 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1632 if(MillerDecoding(b, 0)) {
1633 *len = Uart.len;
9ca155ba
M
1634 return 0;
1635 }
7bc95e2e 1636 }
1637
9ca155ba
M
1638 }
1639}
1640
9ca155ba 1641
6a1f2d82 1642static int EmSendCmd14443aRaw(uint8_t *resp, uint16_t respLen, bool correctionNeeded)
7bc95e2e 1643{
1644 uint8_t b;
1645 uint16_t i = 0;
1646 uint32_t ThisTransferTime;
1647
9ca155ba
M
1648 // Modulate Manchester
1649 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
7bc95e2e 1650
1651 // include correction bit if necessary
1652 if (Uart.parityBits & 0x01) {
1653 correctionNeeded = TRUE;
1654 }
1655 if(correctionNeeded) {
9ca155ba
M
1656 // 1236, so correction bit needed
1657 i = 0;
7bc95e2e 1658 } else {
1659 i = 1;
9ca155ba 1660 }
7bc95e2e 1661
d714d3ef 1662 // clear receiving shift register and holding register
7bc95e2e 1663 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
1664 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
1665 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
1666 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
9ca155ba 1667
7bc95e2e 1668 // wait for the FPGA to signal fdt_indicator == 1 (the FPGA is ready to queue new data in its delay line)
1669 for (uint16_t j = 0; j < 5; j++) { // allow timeout - better late than never
1670 while(!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY));
1671 if (AT91C_BASE_SSC->SSC_RHR) break;
1672 }
1673
1674 while ((ThisTransferTime = GetCountSspClk()) & 0x00000007);
1675
1676 // Clear TXRDY:
1677 AT91C_BASE_SSC->SSC_THR = SEC_F;
1678
9ca155ba 1679 // send cycle
bb42a03e 1680 for(; i < respLen; ) {
9ca155ba 1681 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
7bc95e2e 1682 AT91C_BASE_SSC->SSC_THR = resp[i++];
1683 FpgaSendQueueDelay = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
9ca155ba 1684 }
7bc95e2e 1685
17ad0e09 1686 if(BUTTON_PRESS()) break;
9ca155ba
M
1687 }
1688
7bc95e2e 1689 // Ensure that the FPGA Delay Queue is empty before we switch to TAGSIM_LISTEN again:
4b78d6b3 1690 uint8_t fpga_queued_bits = FpgaSendQueueDelay >> 3; // twich /8 ?? >>3,
0c8d25eb 1691 for (i = 0; i <= fpga_queued_bits/8 + 1; ) {
7bc95e2e 1692 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1693 AT91C_BASE_SSC->SSC_THR = SEC_F;
1694 FpgaSendQueueDelay = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1695 i++;
1696 }
1697 }
0c8d25eb 1698
7bc95e2e 1699 LastTimeProxToAirStart = ThisTransferTime + (correctionNeeded?8:0);
1700
9ca155ba
M
1701 return 0;
1702}
1703
7bc95e2e 1704int EmSend4bitEx(uint8_t resp, bool correctionNeeded){
1705 Code4bitAnswerAsTag(resp);
0a39986e 1706 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
7bc95e2e 1707 // do the tracing for the previous reader request and this tag answer:
5ebcb867 1708 uint8_t par[1] = {0x00};
6a1f2d82 1709 GetParity(&resp, 1, par);
7bc95e2e 1710 EmLogTrace(Uart.output,
1711 Uart.len,
1712 Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG,
1713 Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG,
6a1f2d82 1714 Uart.parity,
7bc95e2e 1715 &resp,
1716 1,
1717 LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG,
1718 (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG,
6a1f2d82 1719 par);
0a39986e 1720 return res;
9ca155ba
M
1721}
1722
8f51ddb0 1723int EmSend4bit(uint8_t resp){
7bc95e2e 1724 return EmSend4bitEx(resp, false);
8f51ddb0
M
1725}
1726
6a1f2d82 1727int EmSendCmdExPar(uint8_t *resp, uint16_t respLen, bool correctionNeeded, uint8_t *par){
7bc95e2e 1728 CodeIso14443aAsTagPar(resp, respLen, par);
8f51ddb0 1729 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
7bc95e2e 1730 // do the tracing for the previous reader request and this tag answer:
1731 EmLogTrace(Uart.output,
1732 Uart.len,
1733 Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG,
1734 Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG,
6a1f2d82 1735 Uart.parity,
7bc95e2e 1736 resp,
1737 respLen,
1738 LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_TAG,
1739 (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_TAG,
6a1f2d82 1740 par);
8f51ddb0
M
1741 return res;
1742}
1743
6a1f2d82 1744int EmSendCmdEx(uint8_t *resp, uint16_t respLen, bool correctionNeeded){
5ebcb867 1745 uint8_t par[MAX_PARITY_SIZE] = {0x00};
6a1f2d82 1746 GetParity(resp, respLen, par);
1747 return EmSendCmdExPar(resp, respLen, correctionNeeded, par);
8f51ddb0
M
1748}
1749
6a1f2d82 1750int EmSendCmd(uint8_t *resp, uint16_t respLen){
5ebcb867 1751 uint8_t par[MAX_PARITY_SIZE] = {0x00};
6a1f2d82 1752 GetParity(resp, respLen, par);
1753 return EmSendCmdExPar(resp, respLen, false, par);
8f51ddb0
M
1754}
1755
6a1f2d82 1756int EmSendCmdPar(uint8_t *resp, uint16_t respLen, uint8_t *par){
7bc95e2e 1757 return EmSendCmdExPar(resp, respLen, false, par);
1758}
1759
6a1f2d82 1760bool EmLogTrace(uint8_t *reader_data, uint16_t reader_len, uint32_t reader_StartTime, uint32_t reader_EndTime, uint8_t *reader_Parity,
1761 uint8_t *tag_data, uint16_t tag_len, uint32_t tag_StartTime, uint32_t tag_EndTime, uint8_t *tag_Parity)
7bc95e2e 1762{
810f5379 1763 // we cannot exactly measure the end and start of a received command from reader. However we know that the delay from
1764 // end of the received command to start of the tag's (simulated by us) answer is n*128+20 or n*128+84 resp.
1765 // with n >= 9. The start of the tags answer can be measured and therefore the end of the received command be calculated:
1766 uint16_t reader_modlen = reader_EndTime - reader_StartTime;
1767 uint16_t approx_fdt = tag_StartTime - reader_EndTime;
1768 uint16_t exact_fdt = (approx_fdt - 20 + 32)/64 * 64 + 20;
1769 reader_EndTime = tag_StartTime - exact_fdt;
1770 reader_StartTime = reader_EndTime - reader_modlen;
5ebcb867 1771
810f5379 1772 if (!LogTrace(reader_data, reader_len, reader_StartTime, reader_EndTime, reader_Parity, TRUE))
1773 return FALSE;
1774 else
1775 return(!LogTrace(tag_data, tag_len, tag_StartTime, tag_EndTime, tag_Parity, FALSE));
1776
9ca155ba
M
1777}
1778
15c4dc5a 1779//-----------------------------------------------------------------------------
1780// Wait a certain time for tag response
1781// If a response is captured return TRUE
e691fc45 1782// If it takes too long return FALSE
15c4dc5a 1783//-----------------------------------------------------------------------------
6a1f2d82 1784static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint8_t *receivedResponsePar, uint16_t offset)
15c4dc5a 1785{
46c65fed 1786 uint32_t c = 0x00;
e691fc45 1787
15c4dc5a 1788 // Set FPGA mode to "reader listen mode", no modulation (listen
534983d7 1789 // only, since we are receiving, not transmitting).
1790 // Signal field is on with the appropriate LED
1791 LED_D_ON();
1792 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1c611bbd 1793
534983d7 1794 // Now get the answer from the card
6a1f2d82 1795 DemodInit(receivedResponse, receivedResponsePar);
15c4dc5a 1796
7bc95e2e 1797 // clear RXRDY:
1798 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
0c8d25eb 1799
15c4dc5a 1800 for(;;) {
534983d7 1801 WDT_HIT();
15c4dc5a 1802
534983d7 1803 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
534983d7 1804 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
7bc95e2e 1805 if(ManchesterDecoding(b, offset, 0)) {
1806 NextTransferTime = MAX(NextTransferTime, Demod.endTime - (DELAY_AIR2ARM_AS_READER + DELAY_ARM2AIR_AS_READER)/16 + FRAME_DELAY_TIME_PICC_TO_PCD);
15c4dc5a 1807 return TRUE;
19a700a8 1808 } else if (c++ > iso14a_timeout && Demod.state == DEMOD_UNSYNCD) {
7bc95e2e 1809 return FALSE;
15c4dc5a 1810 }
534983d7 1811 }
1812 }
15c4dc5a 1813}
1814
6a1f2d82 1815void ReaderTransmitBitsPar(uint8_t* frame, uint16_t bits, uint8_t *par, uint32_t *timing)
15c4dc5a 1816{
6a1f2d82 1817 CodeIso14443aBitsAsReaderPar(frame, bits, par);
dfc3c505 1818
7bc95e2e 1819 // Send command to tag
1820 TransmitFor14443a(ToSend, ToSendMax, timing);
1821 if(trigger)
1822 LED_A_ON();
dfc3c505 1823
7bc95e2e 1824 // Log reader command in trace buffer
4b78d6b3 1825 //LogTrace(frame, nbytes(bits), LastTimeProxToAirStart*16 + DELAY_ARM2AIR_AS_READER, (LastTimeProxToAirStart + LastProxToAirDuration)*16 + DELAY_ARM2AIR_AS_READER, par, TRUE);
1826 LogTrace(frame, nbytes(bits), (LastTimeProxToAirStart<<4) + DELAY_ARM2AIR_AS_READER, ((LastTimeProxToAirStart + LastProxToAirDuration)<<4) + DELAY_ARM2AIR_AS_READER, par, TRUE);
15c4dc5a 1827}
1828
6a1f2d82 1829void ReaderTransmitPar(uint8_t* frame, uint16_t len, uint8_t *par, uint32_t *timing)
dfc3c505 1830{
ca5bad3d 1831 ReaderTransmitBitsPar(frame, len*8, par, timing);
dfc3c505 1832}
15c4dc5a 1833
6a1f2d82 1834void ReaderTransmitBits(uint8_t* frame, uint16_t len, uint32_t *timing)
e691fc45 1835{
1836 // Generate parity and redirect
5ebcb867 1837 uint8_t par[MAX_PARITY_SIZE] = {0x00};
ca5bad3d 1838 GetParity(frame, len/8, par);
6a1f2d82 1839 ReaderTransmitBitsPar(frame, len, par, timing);
e691fc45 1840}
1841
6a1f2d82 1842void ReaderTransmit(uint8_t* frame, uint16_t len, uint32_t *timing)
15c4dc5a 1843{
1844 // Generate parity and redirect
5ebcb867 1845 uint8_t par[MAX_PARITY_SIZE] = {0x00};
6a1f2d82 1846 GetParity(frame, len, par);
ca5bad3d 1847 ReaderTransmitBitsPar(frame, len*8, par, timing);
15c4dc5a 1848}
1849
6a1f2d82 1850int ReaderReceiveOffset(uint8_t* receivedAnswer, uint16_t offset, uint8_t *parity)
e691fc45 1851{
ca5bad3d 1852 if (!GetIso14443aAnswerFromTag(receivedAnswer, parity, offset)) return FALSE;
1853 //if (tracing) {
1854 LogTrace(receivedAnswer, Demod.len, Demod.startTime*16 - DELAY_AIR2ARM_AS_READER, Demod.endTime*16 - DELAY_AIR2ARM_AS_READER, parity, FALSE);
1855 //}
e691fc45 1856 return Demod.len;
1857}
1858
6a1f2d82 1859int ReaderReceive(uint8_t *receivedAnswer, uint8_t *parity)
15c4dc5a 1860{
ca5bad3d 1861 if (!GetIso14443aAnswerFromTag(receivedAnswer, parity, 0)) return FALSE;
1862 //if (tracing) {
1863 LogTrace(receivedAnswer, Demod.len, Demod.startTime*16 - DELAY_AIR2ARM_AS_READER, Demod.endTime*16 - DELAY_AIR2ARM_AS_READER, parity, FALSE);
1864 //}
e691fc45 1865 return Demod.len;
f89c7050
M
1866}
1867
c188b1b9 1868// performs iso14443a anticollision (optional) and card select procedure
1869// fills the uid and cuid pointer unless NULL
1870// fills the card info record unless NULL
1871// if anticollision is false, then the UID must be provided in uid_ptr[]
1872// and num_cascades must be set (1: 4 Byte UID, 2: 7 Byte UID, 3: 10 Byte UID)
1873int iso14443a_select_card(byte_t *uid_ptr, iso14a_card_select_t *p_hi14a_card, uint32_t *cuid_ptr, bool anticollision, uint8_t num_cascades) {
6a1f2d82 1874 uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1875 uint8_t sel_all[] = { 0x93,0x20 };
1876 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
1877 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
4c0cf2d2 1878 uint8_t resp[MAX_FRAME_SIZE] = {0}; // theoretically. A usual RATS will be much smaller
1879 uint8_t resp_par[MAX_PARITY_SIZE] = {0};
1880 byte_t uid_resp[4] = {0};
1881 size_t uid_resp_len = 0;
6a1f2d82 1882
1883 uint8_t sak = 0x04; // cascade uid
1884 int cascade_level = 0;
1885 int len;
1886
1887 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
c188b1b9 1888 ReaderTransmitBitsPar(wupa, 7, NULL, NULL);
7bc95e2e 1889
6a1f2d82 1890 // Receive the ATQA
1891 if(!ReaderReceive(resp, resp_par)) return 0;
6a1f2d82 1892
1893 if(p_hi14a_card) {
1894 memcpy(p_hi14a_card->atqa, resp, 2);
1895 p_hi14a_card->uidlen = 0;
1896 memset(p_hi14a_card->uid,0,10);
1897 }
5f6d6c90 1898
c188b1b9 1899 if (anticollision) {
4c0cf2d2 1900 // clear uid
1901 if (uid_ptr)
1902 memset(uid_ptr,0,10);
c188b1b9 1903 }
79a73ab2 1904
0ec548dc 1905 // check for proprietary anticollision:
4c0cf2d2 1906 if ((resp[0] & 0x1F) == 0) return 3;
0ec548dc 1907
6a1f2d82 1908 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1909 // which case we need to make a cascade 2 request and select - this is a long UID
1910 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1911 for(; sak & 0x04; cascade_level++) {
1912 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1913 sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
1914
c188b1b9 1915 if (anticollision) {
6a1f2d82 1916 // SELECT_ALL
4c0cf2d2 1917 ReaderTransmit(sel_all, sizeof(sel_all), NULL);
1918 if (!ReaderReceive(resp, resp_par)) return 0;
1919
1920 if (Demod.collisionPos) { // we had a collision and need to construct the UID bit by bit
1921 memset(uid_resp, 0, 4);
1922 uint16_t uid_resp_bits = 0;
1923 uint16_t collision_answer_offset = 0;
1924 // anti-collision-loop:
1925 while (Demod.collisionPos) {
1926 Dbprintf("Multiple tags detected. Collision after Bit %d", Demod.collisionPos);
1927 for (uint16_t i = collision_answer_offset; i < Demod.collisionPos; i++, uid_resp_bits++) { // add valid UID bits before collision point
1928 uint16_t UIDbit = (resp[i/8] >> (i % 8)) & 0x01;
1929 uid_resp[uid_resp_bits / 8] |= UIDbit << (uid_resp_bits % 8);
1930 }
1931 uid_resp[uid_resp_bits/8] |= 1 << (uid_resp_bits % 8); // next time select the card(s) with a 1 in the collision position
1932 uid_resp_bits++;
1933 // construct anticollosion command:
1934 sel_uid[1] = ((2 + uid_resp_bits/8) << 4) | (uid_resp_bits & 0x07); // length of data in bytes and bits
1935 for (uint16_t i = 0; i <= uid_resp_bits/8; i++) {
1936 sel_uid[2+i] = uid_resp[i];
1937 }
1938 collision_answer_offset = uid_resp_bits%8;
1939 ReaderTransmitBits(sel_uid, 16 + uid_resp_bits, NULL);
1940 if (!ReaderReceiveOffset(resp, collision_answer_offset, resp_par)) return 0;
6a1f2d82 1941 }
4c0cf2d2 1942 // finally, add the last bits and BCC of the UID
1943 for (uint16_t i = collision_answer_offset; i < (Demod.len-1)*8; i++, uid_resp_bits++) {
1944 uint16_t UIDbit = (resp[i/8] >> (i%8)) & 0x01;
1945 uid_resp[uid_resp_bits/8] |= UIDbit << (uid_resp_bits % 8);
6a1f2d82 1946 }
e691fc45 1947
4c0cf2d2 1948 } else { // no collision, use the response to SELECT_ALL as current uid
1949 memcpy(uid_resp, resp, 4);
1950 }
1951
c188b1b9 1952 } else {
1953 if (cascade_level < num_cascades - 1) {
1954 uid_resp[0] = 0x88;
1955 memcpy(uid_resp+1, uid_ptr+cascade_level*3, 3);
1956 } else {
1957 memcpy(uid_resp, uid_ptr+cascade_level*3, 4);
1958 }
1959 }
6a1f2d82 1960 uid_resp_len = 4;
5f6d6c90 1961
6a1f2d82 1962 // calculate crypto UID. Always use last 4 Bytes.
4c0cf2d2 1963 if(cuid_ptr)
6a1f2d82 1964 *cuid_ptr = bytes_to_num(uid_resp, 4);
e30c654b 1965
6a1f2d82 1966 // Construct SELECT UID command
1967 sel_uid[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
c188b1b9 1968 memcpy(sel_uid+2, uid_resp, 4); // the UID received during anticollision, or the provided UID
6a1f2d82 1969 sel_uid[6] = sel_uid[2] ^ sel_uid[3] ^ sel_uid[4] ^ sel_uid[5]; // calculate and add BCC
1970 AppendCrc14443a(sel_uid, 7); // calculate and add CRC
1971 ReaderTransmit(sel_uid, sizeof(sel_uid), NULL);
1972
1973 // Receive the SAK
1974 if (!ReaderReceive(resp, resp_par)) return 0;
4c0cf2d2 1975
6a1f2d82 1976 sak = resp[0];
1977
810f5379 1978 // Test if more parts of the uid are coming
6a1f2d82 1979 if ((sak & 0x04) /* && uid_resp[0] == 0x88 */) {
1980 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
1981 // http://www.nxp.com/documents/application_note/AN10927.pdf
6a1f2d82 1982 uid_resp[0] = uid_resp[1];
1983 uid_resp[1] = uid_resp[2];
1984 uid_resp[2] = uid_resp[3];
6a1f2d82 1985 uid_resp_len = 3;
1986 }
5f6d6c90 1987
4c0cf2d2 1988 if(uid_ptr && anticollision)
6a1f2d82 1989 memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len);
5f6d6c90 1990
6a1f2d82 1991 if(p_hi14a_card) {
1992 memcpy(p_hi14a_card->uid + (cascade_level*3), uid_resp, uid_resp_len);
1993 p_hi14a_card->uidlen += uid_resp_len;
1994 }
1995 }
79a73ab2 1996
6a1f2d82 1997 if(p_hi14a_card) {
1998 p_hi14a_card->sak = sak;
1999 p_hi14a_card->ats_len = 0;
2000 }
534983d7 2001
3fe4ff4f 2002 // non iso14443a compliant tag
2003 if( (sak & 0x20) == 0) return 2;
534983d7 2004
6a1f2d82 2005 // Request for answer to select
2006 AppendCrc14443a(rats, 2);
2007 ReaderTransmit(rats, sizeof(rats), NULL);
1c611bbd 2008
6a1f2d82 2009 if (!(len = ReaderReceive(resp, resp_par))) return 0;
3fe4ff4f 2010
6a1f2d82 2011 if(p_hi14a_card) {
2012 memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats));
2013 p_hi14a_card->ats_len = len;
2014 }
5f6d6c90 2015
6a1f2d82 2016 // reset the PCB block number
2017 iso14_pcb_blocknum = 0;
19a700a8 2018
2019 // set default timeout based on ATS
2020 iso14a_set_ATS_timeout(resp);
2021
6a1f2d82 2022 return 1;
7e758047 2023}
15c4dc5a 2024
7bc95e2e 2025void iso14443a_setup(uint8_t fpga_minor_mode) {
7cc204bf 2026 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
9492e0b0 2027 // Set up the synchronous serial port
2028 FpgaSetupSsc();
7bc95e2e 2029 // connect Demodulated Signal to ADC:
7e758047 2030 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
ca5bad3d 2031
2032 LED_D_OFF();
7e758047 2033 // Signal field is on with the appropriate LED
ca5bad3d 2034 if (fpga_minor_mode == FPGA_HF_ISO14443A_READER_MOD ||
2035 fpga_minor_mode == FPGA_HF_ISO14443A_READER_LISTEN)
7bc95e2e 2036 LED_D_ON();
6fc68747 2037
7bc95e2e 2038 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | fpga_minor_mode);
534983d7 2039
7bc95e2e 2040 DemodReset();
2041 UartReset();
6fc68747 2042
46c65fed 2043 iso14a_set_timeout(10*106); // 10ms default
6fc68747 2044
2045 // Start the timer
2046 StartCountSspClk();
2047
2048 NextTransferTime = 2*DELAY_ARM2AIR_AS_READER;
7e758047 2049}
15c4dc5a 2050
6a1f2d82 2051int iso14_apdu(uint8_t *cmd, uint16_t cmd_len, void *data) {
810f5379 2052 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
534983d7 2053 uint8_t real_cmd[cmd_len+4];
2054 real_cmd[0] = 0x0a; //I-Block
b0127e65 2055 // put block number into the PCB
2056 real_cmd[0] |= iso14_pcb_blocknum;
534983d7 2057 real_cmd[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
2058 memcpy(real_cmd+2, cmd, cmd_len);
2059 AppendCrc14443a(real_cmd,cmd_len+2);
2060
9492e0b0 2061 ReaderTransmit(real_cmd, cmd_len+4, NULL);
6a1f2d82 2062 size_t len = ReaderReceive(data, parity);
ca5bad3d 2063 //DATA LINK ERROR
2064 if (!len) return 0;
2065
6a1f2d82 2066 uint8_t *data_bytes = (uint8_t *) data;
ca5bad3d 2067
b0127e65 2068 // if we received an I- or R(ACK)-Block with a block number equal to the
2069 // current block number, toggle the current block number
ca5bad3d 2070 if (len >= 4 // PCB+CID+CRC = 4 bytes
b0127e65 2071 && ((data_bytes[0] & 0xC0) == 0 // I-Block
2072 || (data_bytes[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
2073 && (data_bytes[0] & 0x01) == iso14_pcb_blocknum) // equal block numbers
2074 {
2075 iso14_pcb_blocknum ^= 1;
2076 }
2077
534983d7 2078 return len;
2079}
2080
7e758047 2081//-----------------------------------------------------------------------------
2082// Read an ISO 14443a tag. Send out commands and store answers.
2083//
2084//-----------------------------------------------------------------------------
7bc95e2e 2085void ReaderIso14443a(UsbCommand *c)
7e758047 2086{
534983d7 2087 iso14a_command_t param = c->arg[0];
7bc95e2e 2088 uint8_t *cmd = c->d.asBytes;
04bc1c66 2089 size_t len = c->arg[1] & 0xffff;
2090 size_t lenbits = c->arg[1] >> 16;
2091 uint32_t timeout = c->arg[2];
9492e0b0 2092 uint32_t arg0 = 0;
810f5379 2093 byte_t buf[USB_CMD_DATA_SIZE] = {0x00};
2094 uint8_t par[MAX_PARITY_SIZE] = {0x00};
902cb3c0 2095
810f5379 2096 if (param & ISO14A_CONNECT)
3000dc4e 2097 clear_trace();
e691fc45 2098
3000dc4e 2099 set_tracing(TRUE);
e30c654b 2100
810f5379 2101 if (param & ISO14A_REQUEST_TRIGGER)
7bc95e2e 2102 iso14a_set_trigger(TRUE);
15c4dc5a 2103
810f5379 2104 if (param & ISO14A_CONNECT) {
7bc95e2e 2105 iso14443a_setup(FPGA_HF_ISO14443A_READER_LISTEN);
5f6d6c90 2106 if(!(param & ISO14A_NO_SELECT)) {
2107 iso14a_card_select_t *card = (iso14a_card_select_t*)buf;
c188b1b9 2108 arg0 = iso14443a_select_card(NULL,card,NULL, true, 0);
5f6d6c90 2109 cmd_send(CMD_ACK,arg0,card->uidlen,0,buf,sizeof(iso14a_card_select_t));
6fc68747 2110 // if it fails, the cmdhf14a.c client quites.. however this one still executes.
2111 if ( arg0 == 0 ) return;
5f6d6c90 2112 }
534983d7 2113 }
e30c654b 2114
810f5379 2115 if (param & ISO14A_SET_TIMEOUT)
04bc1c66 2116 iso14a_set_timeout(timeout);
e30c654b 2117
810f5379 2118 if (param & ISO14A_APDU) {
902cb3c0 2119 arg0 = iso14_apdu(cmd, len, buf);
79a73ab2 2120 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
534983d7 2121 }
e30c654b 2122
810f5379 2123 if (param & ISO14A_RAW) {
534983d7 2124 if(param & ISO14A_APPEND_CRC) {
0ec548dc 2125 if(param & ISO14A_TOPAZMODE) {
2126 AppendCrc14443b(cmd,len);
2127 } else {
d26849d4 2128 AppendCrc14443a(cmd,len);
0ec548dc 2129 }
534983d7 2130 len += 2;
c7324bef 2131 if (lenbits) lenbits += 16;
15c4dc5a 2132 }
0ec548dc 2133 if(lenbits>0) { // want to send a specific number of bits (e.g. short commands)
2134 if(param & ISO14A_TOPAZMODE) {
2135 int bits_to_send = lenbits;
2136 uint16_t i = 0;
2137 ReaderTransmitBitsPar(&cmd[i++], MIN(bits_to_send, 7), NULL, NULL); // first byte is always short (7bits) and no parity
2138 bits_to_send -= 7;
2139 while (bits_to_send > 0) {
2140 ReaderTransmitBitsPar(&cmd[i++], MIN(bits_to_send, 8), NULL, NULL); // following bytes are 8 bit and no parity
2141 bits_to_send -= 8;
2142 }
2143 } else {
6a1f2d82 2144 GetParity(cmd, lenbits/8, par);
0ec548dc 2145 ReaderTransmitBitsPar(cmd, lenbits, par, NULL); // bytes are 8 bit with odd parity
2146 }
2147 } else { // want to send complete bytes only
2148 if(param & ISO14A_TOPAZMODE) {
2149 uint16_t i = 0;
2150 ReaderTransmitBitsPar(&cmd[i++], 7, NULL, NULL); // first byte: 7 bits, no paritiy
2151 while (i < len) {
2152 ReaderTransmitBitsPar(&cmd[i++], 8, NULL, NULL); // following bytes: 8 bits, no paritiy
2153 }
5f6d6c90 2154 } else {
0ec548dc 2155 ReaderTransmit(cmd,len, NULL); // 8 bits, odd parity
2156 }
5f6d6c90 2157 }
6a1f2d82 2158 arg0 = ReaderReceive(buf, par);
9492e0b0 2159 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
534983d7 2160 }
15c4dc5a 2161
810f5379 2162 if (param & ISO14A_REQUEST_TRIGGER)
7bc95e2e 2163 iso14a_set_trigger(FALSE);
15c4dc5a 2164
810f5379 2165
2166 if (param & ISO14A_NO_DISCONNECT)
534983d7 2167 return;
15c4dc5a 2168
15c4dc5a 2169 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
5ee53a0e 2170 set_tracing(FALSE);
15c4dc5a 2171 LEDsoff();
15c4dc5a 2172}
b0127e65 2173
1c611bbd 2174
1c611bbd 2175// Determine the distance between two nonces.
2176// Assume that the difference is small, but we don't know which is first.
2177// Therefore try in alternating directions.
2178int32_t dist_nt(uint32_t nt1, uint32_t nt2) {
2179
7504dc50 2180 uint16_t i;
ca5bad3d 2181 uint32_t nttmp1, nttmp2;
7504dc50 2182
ca5bad3d 2183 if (nt1 == nt2) return 0;
7504dc50 2184
ca5bad3d 2185 nttmp1 = nt1;
2186 nttmp2 = nt2;
2187
2188 for (i = 1; i < 32768; i++) {
2189 nttmp1 = prng_successor(nttmp1, 1);
2190 if (nttmp1 == nt2) return i;
2191 nttmp2 = prng_successor(nttmp2, 1);
2192 if (nttmp2 == nt1) return -i;
810f5379 2193 }
1c611bbd 2194
2195 return(-99999); // either nt1 or nt2 are invalid nonces
e772353f 2196}
2197
e772353f 2198
1c611bbd 2199//-----------------------------------------------------------------------------
2200// Recover several bits of the cypher stream. This implements (first stages of)
2201// the algorithm described in "The Dark Side of Security by Obscurity and
2202// Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
2203// (article by Nicolas T. Courtois, 2009)
2204//-----------------------------------------------------------------------------
810f5379 2205void ReaderMifare(bool first_try, uint8_t block )
c830303d 2206{
2207 // Mifare AUTH
810f5379 2208 //uint8_t mf_auth[] = { 0x60,0x00,0xf5,0x7b };
2209 //uint8_t mf_auth[] = { 0x60,0x05, 0x58, 0x2c };
b0300679 2210 uint8_t mf_auth[] = { 0x60,0x00, 0x00, 0x00 };
2211 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
2212 uint8_t uid[10] = {0,0,0,0,0,0,0,0,0,0};
2213 uint8_t par_list[8] = {0,0,0,0,0,0,0,0};
2214 uint8_t ks_list[8] = {0,0,0,0,0,0,0,0};
495d7f13 2215 uint8_t receivedAnswer[MAX_MIFARE_FRAME_SIZE] = {0x00};
2216 uint8_t receivedAnswerPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
b0300679 2217 uint8_t par[1] = {0}; // maximum 8 Bytes to be sent here, 1 byte parity is therefore enough
2218
2219 mf_auth[1] = block;
2220 AppendCrc14443a(mf_auth, 2);
c830303d 2221
1c611bbd 2222 byte_t nt_diff = 0;
e772353f 2223
6a1f2d82 2224 uint32_t nt = 0;
b0300679 2225 uint32_t previous_nt = 0;
2226 uint32_t halt_time = 0;
2227 uint32_t cuid = 0;
2228
1c611bbd 2229 int catch_up_cycles = 0;
2230 int last_catch_up = 0;
b0300679 2231 int isOK = 0;
2232
4c0cf2d2 2233 uint16_t elapsed_prng_sequences = 1;
1c611bbd 2234 uint16_t consecutive_resyncs = 0;
0de8e387 2235 uint16_t unexpected_random = 0;
2236 uint16_t sync_tries = 0;
3bc7b13d 2237 uint16_t strategy = 0;
b0300679 2238
2239 static uint32_t nt_attacked = 0;
2240 static uint32_t sync_time = 0;
2241 static int32_t sync_cycles = 0;
2242 static uint8_t par_low = 0;
2243 static uint8_t mf_nr_ar3 = 0;
2244
2245 #define PRNG_SEQUENCE_LENGTH (1 << 16)
2246 #define MAX_UNEXPECTED_RANDOM 4 // maximum number of unexpected (i.e. real) random numbers when trying to sync. Then give up.
2247 #define MAX_SYNC_TRIES 32
2248 #define MAX_STRATEGY 3
4c0cf2d2 2249
aaa1a9a2 2250 // free eventually allocated BigBuf memory
2251 BigBuf_free(); BigBuf_Clear_ext(false);
2252
4b78d6b3 2253 clear_trace();
2254 set_tracing(TRUE);
4c0cf2d2 2255
2256 LED_A_ON();
4c0cf2d2 2257
2258 if (first_try)
2259 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
4c0cf2d2 2260
2261 if (first_try) {
2262 sync_time = GetCountSspClk() & 0xfffffff8;
b0300679 2263 sync_cycles = PRNG_SEQUENCE_LENGTH + 1100; //65536; //0x10000 // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
4c0cf2d2 2264 mf_nr_ar3 = 0;
2265 nt_attacked = 0;
b0300679 2266
4c0cf2d2 2267 } else {
b0300679 2268 // we were unsuccessful on a previous call.
2269 // Try another READER nonce (first 3 parity bits remain the same)
2270 ++mf_nr_ar3;
4c0cf2d2 2271 mf_nr_ar[3] = mf_nr_ar3;
2272 par[0] = par_low;
2273 }
1c611bbd 2274
b0300679 2275 LED_A_ON();
4c0cf2d2 2276 LED_C_ON();
2277 for(uint16_t i = 0; TRUE; ++i) {
2278
1c611bbd 2279 WDT_HIT();
e30c654b 2280
1c611bbd 2281 // Test if the action was cancelled
c830303d 2282 if(BUTTON_PRESS()) {
2283 isOK = -1;
1c611bbd 2284 break;
2285 }
2286
3bc7b13d 2287 if (strategy == 2) {
4c0cf2d2 2288 // test with additional halt command
3bc7b13d 2289 halt_time = 0;
2290 int len = mifare_sendcmd_short(NULL, false, 0x50, 0x00, receivedAnswer, receivedAnswerPar, &halt_time);
4c0cf2d2 2291
2292 if (len && MF_DBGLEVEL >= 3)
4b78d6b3 2293 Dbprintf("Unexpected response of %d bytes to halt command.", len);
3bc7b13d 2294 }
2295
2296 if (strategy == 3) {
2297 // test with FPGA power off/on
2298 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2299 SpinDelay(200);
2300 iso14443a_setup(FPGA_HF_ISO14443A_READER_MOD);
2301 SpinDelay(100);
4c0cf2d2 2302 sync_time = GetCountSspClk() & 0xfffffff8;
5ebcb867 2303 WDT_HIT();
3bc7b13d 2304 }
2305
b0300679 2306 if (!iso14443a_select_card(uid, NULL, &cuid, true, 0)) {
2307 if (MF_DBGLEVEL >= 2) Dbprintf("Mifare: Can't select card\n");
1c611bbd 2308 continue;
2309 }
b0300679 2310
2311 // Sending timeslot of ISO14443a frame
4c0cf2d2 2312
4b78d6b3 2313 sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles;
2314 catch_up_cycles = 0;
b0300679 2315
2316 //catch_up_cycles = 0;
4b78d6b3 2317
2318 // if we missed the sync time already, advance to the next nonce repeat
2319 while(GetCountSspClk() > sync_time) {
2320 ++elapsed_prng_sequences;
b0300679 2321 sync_time = (sync_time & 0xfffffff8) + sync_cycles;
4b78d6b3 2322 }
2323 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
2324 ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time);
f89c7050 2325
1c611bbd 2326 // Receive the (4 Byte) "random" nonce
4c0cf2d2 2327 if (!ReaderReceive(receivedAnswer, receivedAnswerPar))
1c611bbd 2328 continue;
1c611bbd 2329
1c611bbd 2330 // Transmit reader nonce with fake par
9492e0b0 2331 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
1c611bbd 2332
4b78d6b3 2333 previous_nt = nt;
2334 nt = bytes_to_num(receivedAnswer, 4);
2335
1c611bbd 2336 if (first_try && previous_nt && !nt_attacked) { // we didn't calibrate our clock yet
2337 int nt_distance = dist_nt(previous_nt, nt);
2338 if (nt_distance == 0) {
2339 nt_attacked = nt;
0de8e387 2340 } else {
c830303d 2341 if (nt_distance == -99999) { // invalid nonce received
0de8e387 2342 unexpected_random++;
3bc7b13d 2343 if (unexpected_random > MAX_UNEXPECTED_RANDOM) {
c830303d 2344 isOK = -3; // Card has an unpredictable PRNG. Give up
2345 break;
2346 } else {
2347 continue; // continue trying...
2348 }
1c611bbd 2349 }
4c0cf2d2 2350
0de8e387 2351 if (++sync_tries > MAX_SYNC_TRIES) {
3bc7b13d 2352 if (strategy > MAX_STRATEGY || MF_DBGLEVEL < 3) {
0de8e387 2353 isOK = -4; // Card's PRNG runs at an unexpected frequency or resets unexpectedly
2354 break;
4b78d6b3 2355 } else {
0de8e387 2356 continue;
b0300679 2357 }
0de8e387 2358 }
4c0cf2d2 2359
4b78d6b3 2360 sync_cycles = (sync_cycles - nt_distance)/elapsed_prng_sequences;
4c0cf2d2 2361 if (sync_cycles <= 0)
0de8e387 2362 sync_cycles += PRNG_SEQUENCE_LENGTH;
4c0cf2d2 2363
4b78d6b3 2364 if (MF_DBGLEVEL >= 3)
3bc7b13d 2365 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);
4c0cf2d2 2366
1c611bbd 2367 continue;
2368 }
2369 }
2370
2371 if ((nt != nt_attacked) && nt_attacked) { // we somehow lost sync. Try to catch up again...
4c0cf2d2 2372
1c611bbd 2373 catch_up_cycles = -dist_nt(nt_attacked, nt);
c830303d 2374 if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one.
1c611bbd 2375 catch_up_cycles = 0;
2376 continue;
2377 }
4c0cf2d2 2378
2379 // average?
3bc7b13d 2380 catch_up_cycles /= elapsed_prng_sequences;
4c0cf2d2 2381
1c611bbd 2382 if (catch_up_cycles == last_catch_up) {
4a71da5a 2383 ++consecutive_resyncs;
4c0cf2d2 2384 } else {
1c611bbd 2385 last_catch_up = catch_up_cycles;
2386 consecutive_resyncs = 0;
4b78d6b3 2387 }
4c0cf2d2 2388
1c611bbd 2389 if (consecutive_resyncs < 3) {
4c0cf2d2 2390 if (MF_DBGLEVEL >= 3)
2391 Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, -catch_up_cycles, consecutive_resyncs);
2392 } else {
2393 sync_cycles += catch_up_cycles;
2394
2395 if (MF_DBGLEVEL >= 3)
2396 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);
2397
3bc7b13d 2398 last_catch_up = 0;
2399 catch_up_cycles = 0;
2400 consecutive_resyncs = 0;
1c611bbd 2401 }
2402 continue;
2403 }
2404
1c611bbd 2405 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
ca5bad3d 2406 if (!ReaderReceive(receivedAnswer, receivedAnswerPar)) {
9492e0b0 2407 catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
1c611bbd 2408
495d7f13 2409 if (nt_diff == 0)
6a1f2d82 2410 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
1c611bbd 2411
6a1f2d82 2412 par_list[nt_diff] = SwapBits(par[0], 8);
1c611bbd 2413 ks_list[nt_diff] = receivedAnswer[0] ^ 0x05;
2414
2415 // Test if the information is complete
2416 if (nt_diff == 0x07) {
2417 isOK = 1;
2418 break;
2419 }
2420
2421 nt_diff = (nt_diff + 1) & 0x07;
2422 mf_nr_ar[3] = (mf_nr_ar[3] & 0x1F) | (nt_diff << 5);
6a1f2d82 2423 par[0] = par_low;
4b78d6b3 2424
1c611bbd 2425 } else {
b0300679 2426 // No NACK.
495d7f13 2427 if (nt_diff == 0 && first_try) {
6a1f2d82 2428 par[0]++;
5ebcb867 2429 if (par[0] == 0x00) { // tried all 256 possible parities without success. Card doesn't send NACK.
c830303d 2430 isOK = -2;
2431 break;
2432 }
1c611bbd 2433 } else {
b0300679 2434 // Why this?
6a1f2d82 2435 par[0] = ((par[0] & 0x1F) + 1) | par_low;
1c611bbd 2436 }
2437 }
4b78d6b3 2438
2439 consecutive_resyncs = 0;
1c611bbd 2440 }
2441
1c611bbd 2442 mf_nr_ar[3] &= 0x1F;
5ebcb867 2443
2444 WDT_HIT();
4c0cf2d2 2445
2446 // reset sync_time.
2447 if ( isOK == 1) {
2448 sync_time = 0;
2449 sync_cycles = 0;
2450 mf_nr_ar3 = 0;
2451 nt_attacked = 0;
2452 par[0] = 0;
0de8e387 2453 }
d26849d4 2454
b0300679 2455 uint8_t buf[28] = {0x00};
2456 num_to_bytes(cuid, 4, buf);
1c611bbd 2457 num_to_bytes(nt, 4, buf + 4);
2458 memcpy(buf + 8, par_list, 8);
2459 memcpy(buf + 16, ks_list, 8);
2460 memcpy(buf + 24, mf_nr_ar, 4);
2461
2462 cmd_send(CMD_ACK,isOK,0,0,buf,28);
2463
1c611bbd 2464 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2465 LEDsoff();
99cf19d9 2466 set_tracing(FALSE);
20f9a2a1 2467}
1c611bbd 2468
0de8e387 2469/**
d2f487af 2470 *MIFARE 1K simulate.
2471 *
2472 *@param flags :
2473 * FLAG_INTERACTIVE - In interactive mode, we are expected to finish the operation with an ACK
2474 * 4B_FLAG_UID_IN_DATA - means that there is a 4-byte UID in the data-section, we're expected to use that
2475 * 7B_FLAG_UID_IN_DATA - means that there is a 7-byte UID in the data-section, we're expected to use that
2476 * FLAG_NR_AR_ATTACK - means we should collect NR_AR responses for bruteforcing later
2477 *@param exitAfterNReads, exit simulation after n blocks have been read, 0 is inifite
2478 */
2479void Mifare1ksim(uint8_t flags, uint8_t exitAfterNReads, uint8_t arg2, uint8_t *datain)
20f9a2a1 2480{
50193c1e 2481 int cardSTATE = MFEMUL_NOFIELD;
8556b852 2482 int _7BUID = 0;
9ca155ba 2483 int vHf = 0; // in mV
8f51ddb0 2484 int res;
0a39986e
M
2485 uint32_t selTimer = 0;
2486 uint32_t authTimer = 0;
6a1f2d82 2487 uint16_t len = 0;
8f51ddb0 2488 uint8_t cardWRBL = 0;
9ca155ba
M
2489 uint8_t cardAUTHSC = 0;
2490 uint8_t cardAUTHKEY = 0xff; // no authentication
c3c241f3 2491// uint32_t cardRr = 0;
9ca155ba 2492 uint32_t cuid = 0;
d2f487af 2493 //uint32_t rn_enc = 0;
51969283 2494 uint32_t ans = 0;
0014cb46
M
2495 uint32_t cardINTREG = 0;
2496 uint8_t cardINTBLOCK = 0;
9ca155ba
M
2497 struct Crypto1State mpcs = {0, 0};
2498 struct Crypto1State *pcs;
2499 pcs = &mpcs;
d2f487af 2500 uint32_t numReads = 0;//Counts numer of times reader read a block
5ebcb867 2501 uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
2502 uint8_t receivedCmd_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
2503 uint8_t response[MAX_MIFARE_FRAME_SIZE] = {0x00};
2504 uint8_t response_par[MAX_MIFARE_PARITY_SIZE] = {0x00};
9ca155ba 2505
d2f487af 2506 uint8_t rATQA[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2507 uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2508 uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
94422fa2 2509 uint8_t rSAK[] = {0x08, 0xb6, 0xdd}; // Mifare Classic
2510 //uint8_t rSAK[] = {0x09, 0x3f, 0xcc }; // Mifare Mini
d2f487af 2511 uint8_t rSAK1[] = {0x04, 0xda, 0x17};
9ca155ba 2512
02a40596 2513 //uint8_t rAUTH_NT[] = {0x01, 0x01, 0x01, 0x01};
2514 uint8_t rAUTH_NT[] = {0x55, 0x41, 0x49, 0x92};
d2f487af 2515 uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
7bc95e2e 2516
2b1f4228 2517 //Here, we collect UID1,UID2,NT,AR,NR,0,0,NT2,AR2,NR2
d2f487af 2518 // This can be used in a reader-only attack.
2519 // (it can also be retrieved via 'hf 14a list', but hey...
c3c241f3 2520 uint32_t ar_nr_responses[] = {0,0,0,0,0,0,0,0,0,0};
d2f487af 2521 uint8_t ar_nr_collected = 0;
0014cb46 2522
7bc95e2e 2523 // Authenticate response - nonce
51969283 2524 uint32_t nonce = bytes_to_num(rAUTH_NT, 4);
7bc95e2e 2525
d2f487af 2526 //-- Determine the UID
2527 // Can be set from emulator memory, incoming data
2528 // and can be 7 or 4 bytes long
7bc95e2e 2529 if (flags & FLAG_4B_UID_IN_DATA)
d2f487af 2530 {
2531 // 4B uid comes from data-portion of packet
2532 memcpy(rUIDBCC1,datain,4);
8556b852 2533 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
8556b852 2534
7bc95e2e 2535 } else if (flags & FLAG_7B_UID_IN_DATA) {
d2f487af 2536 // 7B uid comes from data-portion of packet
2537 memcpy(&rUIDBCC1[1],datain,3);
2538 memcpy(rUIDBCC2, datain+3, 4);
2539 _7BUID = true;
7bc95e2e 2540 } else {
d2f487af 2541 // get UID from emul memory
2542 emlGetMemBt(receivedCmd, 7, 1);
2543 _7BUID = !(receivedCmd[0] == 0x00);
2544 if (!_7BUID) { // ---------- 4BUID
2545 emlGetMemBt(rUIDBCC1, 0, 4);
2546 } else { // ---------- 7BUID
2547 emlGetMemBt(&rUIDBCC1[1], 0, 3);
2548 emlGetMemBt(rUIDBCC2, 3, 4);
2549 }
2550 }
7bc95e2e 2551
c3c241f3 2552 // save uid.
2553 ar_nr_responses[0*5] = bytes_to_num(rUIDBCC1+1, 3);
2554 if ( _7BUID )
2555 ar_nr_responses[0*5+1] = bytes_to_num(rUIDBCC2, 4);
2556
d2f487af 2557 /*
2558 * Regardless of what method was used to set the UID, set fifth byte and modify
2559 * the ATQA for 4 or 7-byte UID
2560 */
d2f487af 2561 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
7bc95e2e 2562 if (_7BUID) {
d2f487af 2563 rATQA[0] = 0x44;
8556b852 2564 rUIDBCC1[0] = 0x88;
d26849d4 2565 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
8556b852
M
2566 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
2567 }
2568
d2f487af 2569 if (MF_DBGLEVEL >= 1) {
2570 if (!_7BUID) {
b03c0f2d 2571 Dbprintf("4B UID: %02x%02x%02x%02x",
2572 rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3]);
7bc95e2e 2573 } else {
b03c0f2d 2574 Dbprintf("7B UID: (%02x)%02x%02x%02x%02x%02x%02x%02x",
2575 rUIDBCC1[0], rUIDBCC1[1], rUIDBCC1[2], rUIDBCC1[3],
2576 rUIDBCC2[0], rUIDBCC2[1] ,rUIDBCC2[2], rUIDBCC2[3]);
d2f487af 2577 }
2578 }
7bc95e2e 2579
99cf19d9 2580 // We need to listen to the high-frequency, peak-detected path.
2581 iso14443a_setup(FPGA_HF_ISO14443A_TAGSIM_LISTEN);
2582
2583 // free eventually allocated BigBuf memory but keep Emulator Memory
2584 BigBuf_free_keep_EM();
2585
2586 // clear trace
2587 clear_trace();
2588 set_tracing(TRUE);
2589
2590
7bc95e2e 2591 bool finished = FALSE;
2b1f4228 2592 while (!BUTTON_PRESS() && !finished && !usb_poll_validate_length()) {
9ca155ba 2593 WDT_HIT();
9ca155ba
M
2594
2595 // find reader field
9ca155ba 2596 if (cardSTATE == MFEMUL_NOFIELD) {
0c8d25eb 2597 vHf = (MAX_ADC_HF_VOLTAGE * AvgAdc(ADC_CHAN_HF)) >> 10;
9ca155ba 2598 if (vHf > MF_MINFIELDV) {
0014cb46 2599 cardSTATE_TO_IDLE();
9ca155ba
M
2600 LED_A_ON();
2601 }
2602 }
d2f487af 2603 if(cardSTATE == MFEMUL_NOFIELD) continue;
9ca155ba 2604
d2f487af 2605 //Now, get data
6a1f2d82 2606 res = EmGetCmd(receivedCmd, &len, receivedCmd_par);
d2f487af 2607 if (res == 2) { //Field is off!
2608 cardSTATE = MFEMUL_NOFIELD;
2609 LEDsoff();
2610 continue;
7bc95e2e 2611 } else if (res == 1) {
2612 break; //return value 1 means button press
2613 }
2614
d2f487af 2615 // REQ or WUP request in ANY state and WUP in HALTED state
2616 if (len == 1 && ((receivedCmd[0] == 0x26 && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == 0x52)) {
2617 selTimer = GetTickCount();
2618 EmSendCmdEx(rATQA, sizeof(rATQA), (receivedCmd[0] == 0x52));
2619 cardSTATE = MFEMUL_SELECT1;
2620
2621 // init crypto block
2622 LED_B_OFF();
2623 LED_C_OFF();
2624 crypto1_destroy(pcs);
2625 cardAUTHKEY = 0xff;
2626 continue;
0a39986e 2627 }
7bc95e2e 2628
50193c1e 2629 switch (cardSTATE) {
d2f487af 2630 case MFEMUL_NOFIELD:
2631 case MFEMUL_HALTED:
50193c1e 2632 case MFEMUL_IDLE:{
6a1f2d82 2633 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
50193c1e
M
2634 break;
2635 }
2636 case MFEMUL_SELECT1:{
9ca155ba
M
2637 // select all
2638 if (len == 2 && (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x20)) {
d2f487af 2639 if (MF_DBGLEVEL >= 4) Dbprintf("SELECT ALL received");
9ca155ba 2640 EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
0014cb46 2641 break;
9ca155ba
M
2642 }
2643
d2f487af 2644 if (MF_DBGLEVEL >= 4 && len == 9 && receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 )
2645 {
2646 Dbprintf("SELECT %02x%02x%02x%02x received",receivedCmd[2],receivedCmd[3],receivedCmd[4],receivedCmd[5]);
2647 }
9ca155ba 2648 // select card
0a39986e
M
2649 if (len == 9 &&
2650 (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
bfb6a143 2651 EmSendCmd(_7BUID?rSAK1:rSAK, _7BUID?sizeof(rSAK1):sizeof(rSAK));
9ca155ba 2652 cuid = bytes_to_num(rUIDBCC1, 4);
8556b852
M
2653 if (!_7BUID) {
2654 cardSTATE = MFEMUL_WORK;
0014cb46
M
2655 LED_B_ON();
2656 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
2657 break;
8556b852
M
2658 } else {
2659 cardSTATE = MFEMUL_SELECT2;
8556b852 2660 }
9ca155ba 2661 }
50193c1e
M
2662 break;
2663 }
d2f487af 2664 case MFEMUL_AUTH1:{
495d7f13 2665 if( len != 8) {
d2f487af 2666 cardSTATE_TO_IDLE();
6a1f2d82 2667 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
d2f487af 2668 break;
2669 }
0c8d25eb 2670
d2f487af 2671 uint32_t ar = bytes_to_num(receivedCmd, 4);
6a1f2d82 2672 uint32_t nr = bytes_to_num(&receivedCmd[4], 4);
d2f487af 2673
2674 //Collect AR/NR
46cd801c 2675 //if(ar_nr_collected < 2 && cardAUTHSC == 2){
495d7f13 2676 if(ar_nr_collected < 2) {
2677 if(ar_nr_responses[2] != ar) {
2678 // Avoid duplicates... probably not necessary, ar should vary.
c3c241f3 2679 //ar_nr_responses[ar_nr_collected*5] = 0;
2680 //ar_nr_responses[ar_nr_collected*5+1] = 0;
2681 ar_nr_responses[ar_nr_collected*5+2] = nonce;
2682 ar_nr_responses[ar_nr_collected*5+3] = nr;
2683 ar_nr_responses[ar_nr_collected*5+4] = ar;
273b57a7 2684 ar_nr_collected++;
12d708fe 2685 }
2686 // Interactive mode flag, means we need to send ACK
2687 if(flags & FLAG_INTERACTIVE && ar_nr_collected == 2)
12d708fe 2688 finished = true;
d2f487af 2689 }
2690
2691 // --- crypto
c3c241f3 2692 //crypto1_word(pcs, ar , 1);
2693 //cardRr = nr ^ crypto1_word(pcs, 0, 0);
2694
2695 //test if auth OK
2696 //if (cardRr != prng_successor(nonce, 64)){
2697
2698 //if (MF_DBGLEVEL >= 4) Dbprintf("AUTH FAILED for sector %d with key %c. cardRr=%08x, succ=%08x",
2699 // cardAUTHSC, cardAUTHKEY == 0 ? 'A' : 'B',
2700 // cardRr, prng_successor(nonce, 64));
7bc95e2e 2701 // Shouldn't we respond anything here?
d2f487af 2702 // Right now, we don't nack or anything, which causes the
2703 // reader to do a WUPA after a while. /Martin
b03c0f2d 2704 // -- which is the correct response. /piwi
c3c241f3 2705 //cardSTATE_TO_IDLE();
2706 //LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
2707 //break;
2708 //}
d2f487af 2709
2710 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2711
2712 num_to_bytes(ans, 4, rAUTH_AT);
2713 // --- crypto
2714 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2715 LED_C_ON();
2716 cardSTATE = MFEMUL_WORK;
495d7f13 2717 if (MF_DBGLEVEL >= 4) {
2718 Dbprintf("AUTH COMPLETED for sector %d with key %c. time=%d",
2719 cardAUTHSC,
2720 cardAUTHKEY == 0 ? 'A' : 'B',
2721 GetTickCount() - authTimer
2722 );
2723 }
d2f487af 2724 break;
2725 }
50193c1e 2726 case MFEMUL_SELECT2:{
7bc95e2e 2727 if (!len) {
6a1f2d82 2728 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 2729 break;
2730 }
8556b852 2731 if (len == 2 && (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x20)) {
9ca155ba 2732 EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
8556b852
M
2733 break;
2734 }
9ca155ba 2735
8556b852
M
2736 // select 2 card
2737 if (len == 9 &&
495d7f13 2738 (receivedCmd[0] == 0x95 &&
2739 receivedCmd[1] == 0x70 &&
2740 memcmp(&receivedCmd[2], rUIDBCC2, 4) == 0) ) {
8556b852 2741 EmSendCmd(rSAK, sizeof(rSAK));
8556b852
M
2742 cuid = bytes_to_num(rUIDBCC2, 4);
2743 cardSTATE = MFEMUL_WORK;
2744 LED_B_ON();
0014cb46 2745 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer);
8556b852
M
2746 break;
2747 }
0014cb46
M
2748
2749 // i guess there is a command). go into the work state.
7bc95e2e 2750 if (len != 4) {
6a1f2d82 2751 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 2752 break;
2753 }
0014cb46 2754 cardSTATE = MFEMUL_WORK;
d2f487af 2755 //goto lbWORK;
2756 //intentional fall-through to the next case-stmt
50193c1e 2757 }
51969283 2758
7bc95e2e 2759 case MFEMUL_WORK:{
2760 if (len == 0) {
6a1f2d82 2761 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 2762 break;
2763 }
2764
d2f487af 2765 bool encrypted_data = (cardAUTHKEY != 0xFF) ;
2766
495d7f13 2767 // decrypt seqence
2768 if(encrypted_data)
51969283 2769 mf_crypto1_decrypt(pcs, receivedCmd, len);
7bc95e2e 2770
d2f487af 2771 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2772 authTimer = GetTickCount();
2773 cardAUTHSC = receivedCmd[1] / 4; // received block num
2774 cardAUTHKEY = receivedCmd[0] - 0x60;
2775 crypto1_destroy(pcs);//Added by martin
2776 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
51969283 2777
d2f487af 2778 if (!encrypted_data) { // first authentication
b03c0f2d 2779 if (MF_DBGLEVEL >= 4) Dbprintf("Reader authenticating for block %d (0x%02x) with key %d",receivedCmd[1] ,receivedCmd[1],cardAUTHKEY );
51969283 2780
d2f487af 2781 crypto1_word(pcs, cuid ^ nonce, 0);//Update crypto state
2782 num_to_bytes(nonce, 4, rAUTH_AT); // Send nonce
7bc95e2e 2783 } else { // nested authentication
b03c0f2d 2784 if (MF_DBGLEVEL >= 4) Dbprintf("Reader doing nested authentication for block %d (0x%02x) with key %d",receivedCmd[1] ,receivedCmd[1],cardAUTHKEY );
7bc95e2e 2785 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
d2f487af 2786 num_to_bytes(ans, 4, rAUTH_AT);
2787 }
0c8d25eb 2788
d2f487af 2789 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2790 //Dbprintf("Sending rAUTH %02x%02x%02x%02x", rAUTH_AT[0],rAUTH_AT[1],rAUTH_AT[2],rAUTH_AT[3]);
2791 cardSTATE = MFEMUL_AUTH1;
2792 break;
51969283 2793 }
7bc95e2e 2794
8f51ddb0
M
2795 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2796 // BUT... ACK --> NACK
2797 if (len == 1 && receivedCmd[0] == CARD_ACK) {
2798 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2799 break;
2800 }
2801
2802 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2803 if (len == 1 && receivedCmd[0] == CARD_NACK_NA) {
2804 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2805 break;
0a39986e
M
2806 }
2807
7bc95e2e 2808 if(len != 4) {
6a1f2d82 2809 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
7bc95e2e 2810 break;
2811 }
d2f487af 2812
2813 if(receivedCmd[0] == 0x30 // read block
2814 || receivedCmd[0] == 0xA0 // write block
b03c0f2d 2815 || receivedCmd[0] == 0xC0 // inc
2816 || receivedCmd[0] == 0xC1 // dec
2817 || receivedCmd[0] == 0xC2 // restore
7bc95e2e 2818 || receivedCmd[0] == 0xB0) { // transfer
2819 if (receivedCmd[1] >= 16 * 4) {
d2f487af 2820 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
c3c241f3 2821 if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) on out of range block: %d (0x%02x), nacking",receivedCmd[0],receivedCmd[1],receivedCmd[1]);
d2f487af 2822 break;
2823 }
2824
7bc95e2e 2825 if (receivedCmd[1] / 4 != cardAUTHSC) {
8f51ddb0 2826 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
c3c241f3 2827 if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate (0x%02) on block (0x%02x) not authenticated for (0x%02x), nacking",receivedCmd[0],receivedCmd[1],cardAUTHSC);
8f51ddb0
M
2828 break;
2829 }
d2f487af 2830 }
2831 // read block
2832 if (receivedCmd[0] == 0x30) {
495d7f13 2833 if (MF_DBGLEVEL >= 4) Dbprintf("Reader reading block %d (0x%02x)",receivedCmd[1],receivedCmd[1]);
2834
8f51ddb0
M
2835 emlGetMem(response, receivedCmd[1], 1);
2836 AppendCrc14443a(response, 16);
6a1f2d82 2837 mf_crypto1_encrypt(pcs, response, 18, response_par);
2838 EmSendCmdPar(response, 18, response_par);
d2f487af 2839 numReads++;
12d708fe 2840 if(exitAfterNReads > 0 && numReads >= exitAfterNReads) {
d2f487af 2841 Dbprintf("%d reads done, exiting", numReads);
2842 finished = true;
2843 }
0a39986e
M
2844 break;
2845 }
0a39986e 2846 // write block
d2f487af 2847 if (receivedCmd[0] == 0xA0) {
b03c0f2d 2848 if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0xA0 write block %d (%02x)",receivedCmd[1],receivedCmd[1]);
8f51ddb0 2849 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
8f51ddb0
M
2850 cardSTATE = MFEMUL_WRITEBL2;
2851 cardWRBL = receivedCmd[1];
0a39986e 2852 break;
7bc95e2e 2853 }
0014cb46 2854 // increment, decrement, restore
d2f487af 2855 if (receivedCmd[0] == 0xC0 || receivedCmd[0] == 0xC1 || receivedCmd[0] == 0xC2) {
b03c0f2d 2856 if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x inc(0xC1)/dec(0xC0)/restore(0xC2) block %d (%02x)",receivedCmd[0],receivedCmd[1],receivedCmd[1]);
d2f487af 2857 if (emlCheckValBl(receivedCmd[1])) {
c3c241f3 2858 if (MF_DBGLEVEL >= 4) Dbprintf("Reader tried to operate on block, but emlCheckValBl failed, nacking");
0014cb46
M
2859 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2860 break;
2861 }
2862 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2863 if (receivedCmd[0] == 0xC1)
2864 cardSTATE = MFEMUL_INTREG_INC;
2865 if (receivedCmd[0] == 0xC0)
2866 cardSTATE = MFEMUL_INTREG_DEC;
2867 if (receivedCmd[0] == 0xC2)
2868 cardSTATE = MFEMUL_INTREG_REST;
2869 cardWRBL = receivedCmd[1];
0014cb46
M
2870 break;
2871 }
0014cb46 2872 // transfer
d2f487af 2873 if (receivedCmd[0] == 0xB0) {
b03c0f2d 2874 if (MF_DBGLEVEL >= 4) Dbprintf("RECV 0x%02x transfer block %d (%02x)",receivedCmd[0],receivedCmd[1],receivedCmd[1]);
0014cb46
M
2875 if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd[1]))
2876 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2877 else
2878 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
0014cb46
M
2879 break;
2880 }
9ca155ba 2881 // halt
d2f487af 2882 if (receivedCmd[0] == 0x50 && receivedCmd[1] == 0x00) {
9ca155ba 2883 LED_B_OFF();
0a39986e 2884 LED_C_OFF();
0014cb46
M
2885 cardSTATE = MFEMUL_HALTED;
2886 if (MF_DBGLEVEL >= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
6a1f2d82 2887 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
0a39986e 2888 break;
9ca155ba 2889 }
d2f487af 2890 // RATS
2891 if (receivedCmd[0] == 0xe0) {//RATS
8f51ddb0
M
2892 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2893 break;
2894 }
d2f487af 2895 // command not allowed
2896 if (MF_DBGLEVEL >= 4) Dbprintf("Received command not allowed, nacking");
2897 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
51969283 2898 break;
8f51ddb0
M
2899 }
2900 case MFEMUL_WRITEBL2:{
495d7f13 2901 if (len == 18) {
8f51ddb0
M
2902 mf_crypto1_decrypt(pcs, receivedCmd, len);
2903 emlSetMem(receivedCmd, cardWRBL, 1);
2904 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2905 cardSTATE = MFEMUL_WORK;
51969283 2906 } else {
0014cb46 2907 cardSTATE_TO_IDLE();
6a1f2d82 2908 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
8f51ddb0 2909 }
8f51ddb0 2910 break;
50193c1e 2911 }
0014cb46
M
2912
2913 case MFEMUL_INTREG_INC:{
2914 mf_crypto1_decrypt(pcs, receivedCmd, len);
2915 memcpy(&ans, receivedCmd, 4);
2916 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2917 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2918 cardSTATE_TO_IDLE();
2919 break;
7bc95e2e 2920 }
6a1f2d82 2921 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
0014cb46
M
2922 cardINTREG = cardINTREG + ans;
2923 cardSTATE = MFEMUL_WORK;
2924 break;
2925 }
2926 case MFEMUL_INTREG_DEC:{
2927 mf_crypto1_decrypt(pcs, receivedCmd, len);
2928 memcpy(&ans, receivedCmd, 4);
2929 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2930 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2931 cardSTATE_TO_IDLE();
2932 break;
2933 }
6a1f2d82 2934 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
0014cb46
M
2935 cardINTREG = cardINTREG - ans;
2936 cardSTATE = MFEMUL_WORK;
2937 break;
2938 }
2939 case MFEMUL_INTREG_REST:{
2940 mf_crypto1_decrypt(pcs, receivedCmd, len);
2941 memcpy(&ans, receivedCmd, 4);
2942 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2943 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2944 cardSTATE_TO_IDLE();
2945 break;
2946 }
6a1f2d82 2947 LogTrace(Uart.output, Uart.len, Uart.startTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.endTime*16 - DELAY_AIR2ARM_AS_TAG, Uart.parity, TRUE);
0014cb46
M
2948 cardSTATE = MFEMUL_WORK;
2949 break;
2950 }
50193c1e 2951 }
50193c1e
M
2952 }
2953
9ca155ba
M
2954 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2955 LEDsoff();
2956
810f5379 2957 // Interactive mode flag, means we need to send ACK
2958 if(flags & FLAG_INTERACTIVE) {
d2f487af 2959 //May just aswell send the collected ar_nr in the response aswell
c3c241f3 2960 uint8_t len = ar_nr_collected*5*4;
2961 cmd_send(CMD_ACK, CMD_SIMULATE_MIFARE_CARD, len, 0, &ar_nr_responses, len);
d2f487af 2962 }
d714d3ef 2963
810f5379 2964 if(flags & FLAG_NR_AR_ATTACK && MF_DBGLEVEL >= 1 ) {
12d708fe 2965 if(ar_nr_collected > 1 ) {
d2f487af 2966 Dbprintf("Collected two pairs of AR/NR which can be used to extract keys from reader:");
c3c241f3 2967 Dbprintf("../tools/mfkey/mfkey32 %06x%08x %08x %08x %08x %08x %08x",
2968 ar_nr_responses[0], // UID1
2969 ar_nr_responses[1], // UID2
2970 ar_nr_responses[2], // NT
2971 ar_nr_responses[3], // AR1
2972 ar_nr_responses[4], // NR1
2973 ar_nr_responses[8], // AR2
2974 ar_nr_responses[9] // NR2
d2f487af 2975 );
7838f4be 2976 Dbprintf("../tools/mfkey/mfkey32v2 %06x%08x %08x %08x %08x %08x %08x %08x",
2977 ar_nr_responses[0], // UID1
2978 ar_nr_responses[1], // UID2
2979 ar_nr_responses[2], // NT1
2980 ar_nr_responses[3], // AR1
2981 ar_nr_responses[4], // NR1
2982 ar_nr_responses[7], // NT2
2983 ar_nr_responses[8], // AR2
2984 ar_nr_responses[9] // NR2
2985 );
7bc95e2e 2986 } else {
d2f487af 2987 Dbprintf("Failed to obtain two AR/NR pairs!");
12d708fe 2988 if(ar_nr_collected > 0 ) {
2b1f4228 2989 Dbprintf("Only got these: UID=%06x%08x, nonce=%08x, AR1=%08x, NR1=%08x",
c3c241f3 2990 ar_nr_responses[0], // UID1
2991 ar_nr_responses[1], // UID2
2992 ar_nr_responses[2], // NT
2993 ar_nr_responses[3], // AR1
2994 ar_nr_responses[4] // NR1
d2f487af 2995 );
2996 }
2997 }
2998 }
c3c241f3 2999 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, BigBuf_get_traceLen());
5ee53a0e 3000
3001 set_tracing(FALSE);
15c4dc5a 3002}
b62a5a84 3003
d2f487af 3004
b62a5a84
M
3005//-----------------------------------------------------------------------------
3006// MIFARE sniffer.
3007//
3008//-----------------------------------------------------------------------------
5cd9ec01
M
3009void RAMFUNC SniffMifare(uint8_t param) {
3010 // param:
3011 // bit 0 - trigger from first card answer
3012 // bit 1 - trigger from first reader 7-bit request
b62a5a84 3013 LEDsoff();
810f5379 3014
aaa1a9a2 3015 // free eventually allocated BigBuf memory
3016 BigBuf_free(); BigBuf_Clear_ext(false);
3017
b62a5a84 3018 // init trace buffer
3000dc4e
MHS
3019 clear_trace();
3020 set_tracing(TRUE);
b62a5a84 3021
b62a5a84
M
3022 // The command (reader -> tag) that we're receiving.
3023 // The length of a received command will in most cases be no more than 18 bytes.
3024 // So 32 should be enough!
810f5379 3025 uint8_t receivedCmd[MAX_MIFARE_FRAME_SIZE] = {0x00};
495d7f13 3026 uint8_t receivedCmdPar[MAX_MIFARE_PARITY_SIZE] = {0x00};
810f5379 3027
b62a5a84 3028 // The response (tag -> reader) that we're receiving.
495d7f13 3029 uint8_t receivedResponse[MAX_MIFARE_FRAME_SIZE] = {0x00};
3030 uint8_t receivedResponsePar[MAX_MIFARE_PARITY_SIZE] = {0x00};
b62a5a84 3031
99cf19d9 3032 iso14443a_setup(FPGA_HF_ISO14443A_SNIFFER);
3033
f71f4deb 3034 // allocate the DMA buffer, used to stream samples from the FPGA
3035 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
7bc95e2e 3036 uint8_t *data = dmaBuf;
3037 uint8_t previous_data = 0;
5cd9ec01
M
3038 int maxDataLen = 0;
3039 int dataLen = 0;
7bc95e2e 3040 bool ReaderIsActive = FALSE;
3041 bool TagIsActive = FALSE;
3042
b62a5a84 3043 // Set up the demodulator for tag -> reader responses.
6a1f2d82 3044 DemodInit(receivedResponse, receivedResponsePar);
b62a5a84
M
3045
3046 // Set up the demodulator for the reader -> tag commands
6a1f2d82 3047 UartInit(receivedCmd, receivedCmdPar);
b62a5a84
M
3048
3049 // Setup for the DMA.
7bc95e2e 3050 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); // set transfer address and number of bytes. Start transfer.
b62a5a84 3051
b62a5a84 3052 LED_D_OFF();
39864b0b
M
3053
3054 // init sniffer
3055 MfSniffInit();
b62a5a84 3056
b62a5a84 3057 // And now we loop, receiving samples.
7bc95e2e 3058 for(uint32_t sniffCounter = 0; TRUE; ) {
3059
5cd9ec01
M
3060 if(BUTTON_PRESS()) {
3061 DbpString("cancelled by button");
7bc95e2e 3062 break;
5cd9ec01
M
3063 }
3064
b62a5a84
M
3065 LED_A_ON();
3066 WDT_HIT();
39864b0b 3067
7bc95e2e 3068 if ((sniffCounter & 0x0000FFFF) == 0) { // from time to time
3069 // check if a transaction is completed (timeout after 2000ms).
3070 // if yes, stop the DMA transfer and send what we have so far to the client
3071 if (MfSniffSend(2000)) {
3072 // Reset everything - we missed some sniffed data anyway while the DMA was stopped
3073 sniffCounter = 0;
3074 data = dmaBuf;
3075 maxDataLen = 0;
3076 ReaderIsActive = FALSE;
3077 TagIsActive = FALSE;
3078 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE); // set transfer address and number of bytes. Start transfer.
39864b0b 3079 }
39864b0b 3080 }
7bc95e2e 3081
3082 int register readBufDataP = data - dmaBuf; // number of bytes we have processed so far
3083 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR; // number of bytes already transferred
495d7f13 3084
3085 if (readBufDataP <= dmaBufDataP) // we are processing the same block of data which is currently being transferred
7bc95e2e 3086 dataLen = dmaBufDataP - readBufDataP; // number of bytes still to be processed
495d7f13 3087 else
7bc95e2e 3088 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP; // number of bytes still to be processed
495d7f13 3089
5cd9ec01 3090 // test for length of buffer
7bc95e2e 3091 if(dataLen > maxDataLen) { // we are more behind than ever...
3092 maxDataLen = dataLen;
f71f4deb 3093 if(dataLen > (9 * DMA_BUFFER_SIZE / 10)) {
5cd9ec01 3094 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen);
7bc95e2e 3095 break;
b62a5a84
M
3096 }
3097 }
5cd9ec01 3098 if(dataLen < 1) continue;
b62a5a84 3099
7bc95e2e 3100 // primary buffer was stopped ( <-- we lost data!
5cd9ec01
M
3101 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
3102 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
3103 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
55acbb2a 3104 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen); // temporary
5cd9ec01
M
3105 }
3106 // secondary buffer sets as primary, secondary buffer was stopped
3107 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
3108 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
b62a5a84
M
3109 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
3110 }
5cd9ec01
M
3111
3112 LED_A_OFF();
b62a5a84 3113
7bc95e2e 3114 if (sniffCounter & 0x01) {
b62a5a84 3115
495d7f13 3116 // no need to try decoding tag data if the reader is sending
3117 if(!TagIsActive) {
7bc95e2e 3118 uint8_t readerdata = (previous_data & 0xF0) | (*data >> 4);
3119 if(MillerDecoding(readerdata, (sniffCounter-1)*4)) {
3120 LED_C_INV();
495d7f13 3121
6a1f2d82 3122 if (MfSniffLogic(receivedCmd, Uart.len, Uart.parity, Uart.bitCount, TRUE)) break;
b62a5a84 3123
7bc95e2e 3124 /* And ready to receive another command. */
f8ada309 3125 UartInit(receivedCmd, receivedCmdPar);
7bc95e2e 3126
3127 /* And also reset the demod code */
3128 DemodReset();
3129 }
3130 ReaderIsActive = (Uart.state != STATE_UNSYNCD);
3131 }
3132
495d7f13 3133 // no need to try decoding tag data if the reader is sending
3134 if(!ReaderIsActive) {
7bc95e2e 3135 uint8_t tagdata = (previous_data << 4) | (*data & 0x0F);
3136 if(ManchesterDecoding(tagdata, 0, (sniffCounter-1)*4)) {
3137 LED_C_INV();
b62a5a84 3138
6a1f2d82 3139 if (MfSniffLogic(receivedResponse, Demod.len, Demod.parity, Demod.bitCount, FALSE)) break;
39864b0b 3140
7bc95e2e 3141 // And ready to receive another response.
3142 DemodReset();
495d7f13 3143
0ec548dc 3144 // And reset the Miller decoder including its (now outdated) input buffer
3145 UartInit(receivedCmd, receivedCmdPar);
7bc95e2e 3146 }
3147 TagIsActive = (Demod.state != DEMOD_UNSYNCD);
3148 }
b62a5a84
M
3149 }
3150
7bc95e2e 3151 previous_data = *data;
3152 sniffCounter++;
5cd9ec01 3153 data++;
495d7f13 3154
3155 if(data == dmaBuf + DMA_BUFFER_SIZE)
5cd9ec01 3156 data = dmaBuf;
7bc95e2e 3157
b62a5a84
M
3158 } // main cycle
3159
55acbb2a 3160 FpgaDisableSscDma();
39864b0b 3161 MfSniffEnd();
b62a5a84 3162 LEDsoff();
7838f4be 3163 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.len=%x", maxDataLen, Uart.state, Uart.len);
5ee53a0e 3164 set_tracing(FALSE);
3803d529 3165}
Impressum, Datenschutz