]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso14443a.c
Fixed (?) issue with mifare simulation auth failed. See http://www.proxmark.org/forum...
[proxmark3-svn] / armsrc / iso14443a.c
CommitLineData
15c4dc5a 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"
9ab7a6c7 18
15c4dc5a 19#include "iso14443crc.h"
534983d7 20#include "iso14443a.h"
20f9a2a1
M
21#include "crapto1.h"
22#include "mifareutil.h"
15c4dc5a 23
534983d7 24static uint32_t iso14a_timeout;
d19929cb 25uint8_t *trace = (uint8_t *) BigBuf+TRACE_OFFSET;
1e262141 26int traceLen = 0;
27int rsamples = 0;
28int tracing = TRUE;
29uint8_t trigger = 0;
b0127e65 30// the block number for the ISO14443-4 PCB
31static uint8_t iso14_pcb_blocknum = 0;
15c4dc5a 32
8f51ddb0 33// CARD TO READER - manchester
72934aa3 34// Sequence D: 11110000 modulation with subcarrier during first half
35// Sequence E: 00001111 modulation with subcarrier during second half
36// Sequence F: 00000000 no modulation with subcarrier
8f51ddb0 37// READER TO CARD - miller
72934aa3 38// Sequence X: 00001100 drop after half a period
39// Sequence Y: 00000000 no drop
40// Sequence Z: 11000000 drop at start
41#define SEC_D 0xf0
42#define SEC_E 0x0f
43#define SEC_F 0x00
44#define SEC_X 0x0c
45#define SEC_Y 0x00
46#define SEC_Z 0xc0
15c4dc5a 47
1e262141 48const uint8_t OddByteParity[256] = {
15c4dc5a 49 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
50 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
51 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
52 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
53 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
54 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
55 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
56 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
57 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
58 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
59 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
60 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
61 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,
62 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
63 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0,
64 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1
65};
66
1e262141 67
902cb3c0 68void iso14a_set_trigger(bool enable) {
534983d7 69 trigger = enable;
70}
71
902cb3c0 72void iso14a_clear_trace() {
73 memset(trace, 0x44, TRACE_SIZE);
8556b852
M
74 traceLen = 0;
75}
d19929cb 76
902cb3c0 77void iso14a_set_tracing(bool enable) {
8556b852
M
78 tracing = enable;
79}
d19929cb 80
b0127e65 81void iso14a_set_timeout(uint32_t timeout) {
82 iso14a_timeout = timeout;
83}
8556b852 84
15c4dc5a 85//-----------------------------------------------------------------------------
86// Generate the parity value for a byte sequence
e30c654b 87//
15c4dc5a 88//-----------------------------------------------------------------------------
20f9a2a1
M
89byte_t oddparity (const byte_t bt)
90{
5f6d6c90 91 return OddByteParity[bt];
20f9a2a1
M
92}
93
f7e3ed82 94uint32_t GetParity(const uint8_t * pbtCmd, int iLen)
15c4dc5a 95{
5f6d6c90 96 int i;
97 uint32_t dwPar = 0;
72934aa3 98
e691fc45 99 // Generate the parity bits
5f6d6c90 100 for (i = 0; i < iLen; i++) {
e691fc45 101 // and save them to a 32Bit word
5f6d6c90 102 dwPar |= ((OddByteParity[pbtCmd[i]]) << i);
103 }
104 return dwPar;
15c4dc5a 105}
106
534983d7 107void AppendCrc14443a(uint8_t* data, int len)
15c4dc5a 108{
5f6d6c90 109 ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
15c4dc5a 110}
111
1e262141 112// The function LogTrace() is also used by the iClass implementation in iClass.c
5cd9ec01 113int RAMFUNC LogTrace(const uint8_t * btBytes, int iLen, int iSamples, uint32_t dwParity, int bReader)
15c4dc5a 114{
115 // Return when trace is full
81cd0474 116 if (traceLen >= TRACE_SIZE) return FALSE;
e30c654b 117
15c4dc5a 118 // Trace the random, i'm curious
119 rsamples += iSamples;
120 trace[traceLen++] = ((rsamples >> 0) & 0xff);
121 trace[traceLen++] = ((rsamples >> 8) & 0xff);
122 trace[traceLen++] = ((rsamples >> 16) & 0xff);
123 trace[traceLen++] = ((rsamples >> 24) & 0xff);
124 if (!bReader) {
125 trace[traceLen - 1] |= 0x80;
126 }
127 trace[traceLen++] = ((dwParity >> 0) & 0xff);
128 trace[traceLen++] = ((dwParity >> 8) & 0xff);
129 trace[traceLen++] = ((dwParity >> 16) & 0xff);
130 trace[traceLen++] = ((dwParity >> 24) & 0xff);
131 trace[traceLen++] = iLen;
132 memcpy(trace + traceLen, btBytes, iLen);
133 traceLen += iLen;
134 return TRUE;
135}
136
15c4dc5a 137//-----------------------------------------------------------------------------
138// The software UART that receives commands from the reader, and its state
139// variables.
140//-----------------------------------------------------------------------------
b62a5a84 141static tUart Uart;
15c4dc5a 142
6c1e2d95 143static RAMFUNC int MillerDecoding(int bit)
15c4dc5a 144{
9f693930 145 //int error = 0;
15c4dc5a 146 int bitright;
147
148 if(!Uart.bitBuffer) {
149 Uart.bitBuffer = bit ^ 0xFF0;
150 return FALSE;
151 }
152 else {
153 Uart.bitBuffer <<= 4;
154 Uart.bitBuffer ^= bit;
155 }
156
f7e3ed82 157 int EOC = FALSE;
15c4dc5a 158
159 if(Uart.state != STATE_UNSYNCD) {
160 Uart.posCnt++;
161
162 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
163 bit = 0x00;
164 }
165 else {
166 bit = 0x01;
167 }
168 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
169 bitright = 0x00;
170 }
171 else {
172 bitright = 0x01;
173 }
174 if(bit != bitright) { bit = bitright; }
175
176 if(Uart.posCnt == 1) {
177 // measurement first half bitperiod
178 if(!bit) {
179 Uart.drop = DROP_FIRST_HALF;
180 }
181 }
182 else {
183 // measurement second half bitperiod
184 if(!bit & (Uart.drop == DROP_NONE)) {
185 Uart.drop = DROP_SECOND_HALF;
186 }
187 else if(!bit) {
188 // measured a drop in first and second half
189 // which should not be possible
190 Uart.state = STATE_ERROR_WAIT;
9f693930 191 //error = 0x01;
15c4dc5a 192 }
193
194 Uart.posCnt = 0;
195
196 switch(Uart.state) {
197 case STATE_START_OF_COMMUNICATION:
198 Uart.shiftReg = 0;
199 if(Uart.drop == DROP_SECOND_HALF) {
200 // error, should not happen in SOC
201 Uart.state = STATE_ERROR_WAIT;
9f693930 202 //error = 0x02;
15c4dc5a 203 }
204 else {
205 // correct SOC
206 Uart.state = STATE_MILLER_Z;
207 }
208 break;
209
210 case STATE_MILLER_Z:
211 Uart.bitCnt++;
212 Uart.shiftReg >>= 1;
213 if(Uart.drop == DROP_NONE) {
214 // logic '0' followed by sequence Y
215 // end of communication
216 Uart.state = STATE_UNSYNCD;
217 EOC = TRUE;
218 }
219 // if(Uart.drop == DROP_FIRST_HALF) {
220 // Uart.state = STATE_MILLER_Z; stay the same
221 // we see a logic '0' }
222 if(Uart.drop == DROP_SECOND_HALF) {
223 // we see a logic '1'
224 Uart.shiftReg |= 0x100;
225 Uart.state = STATE_MILLER_X;
226 }
227 break;
228
229 case STATE_MILLER_X:
230 Uart.shiftReg >>= 1;
231 if(Uart.drop == DROP_NONE) {
232 // sequence Y, we see a '0'
233 Uart.state = STATE_MILLER_Y;
234 Uart.bitCnt++;
235 }
236 if(Uart.drop == DROP_FIRST_HALF) {
237 // Would be STATE_MILLER_Z
238 // but Z does not follow X, so error
239 Uart.state = STATE_ERROR_WAIT;
9f693930 240 //error = 0x03;
15c4dc5a 241 }
242 if(Uart.drop == DROP_SECOND_HALF) {
243 // We see a '1' and stay in state X
244 Uart.shiftReg |= 0x100;
245 Uart.bitCnt++;
246 }
247 break;
248
249 case STATE_MILLER_Y:
250 Uart.bitCnt++;
251 Uart.shiftReg >>= 1;
252 if(Uart.drop == DROP_NONE) {
253 // logic '0' followed by sequence Y
254 // end of communication
255 Uart.state = STATE_UNSYNCD;
256 EOC = TRUE;
257 }
258 if(Uart.drop == DROP_FIRST_HALF) {
259 // we see a '0'
260 Uart.state = STATE_MILLER_Z;
261 }
262 if(Uart.drop == DROP_SECOND_HALF) {
263 // We see a '1' and go to state X
264 Uart.shiftReg |= 0x100;
265 Uart.state = STATE_MILLER_X;
266 }
267 break;
268
269 case STATE_ERROR_WAIT:
270 // That went wrong. Now wait for at least two bit periods
271 // and try to sync again
272 if(Uart.drop == DROP_NONE) {
273 Uart.highCnt = 6;
274 Uart.state = STATE_UNSYNCD;
275 }
276 break;
277
278 default:
279 Uart.state = STATE_UNSYNCD;
280 Uart.highCnt = 0;
281 break;
282 }
283
284 Uart.drop = DROP_NONE;
285
286 // should have received at least one whole byte...
287 if((Uart.bitCnt == 2) && EOC && (Uart.byteCnt > 0)) {
288 return TRUE;
289 }
290
291 if(Uart.bitCnt == 9) {
292 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
293 Uart.byteCnt++;
294
295 Uart.parityBits <<= 1;
296 Uart.parityBits ^= ((Uart.shiftReg >> 8) & 0x01);
297
298 if(EOC) {
299 // when End of Communication received and
300 // all data bits processed..
301 return TRUE;
302 }
303 Uart.bitCnt = 0;
304 }
305
306 /*if(error) {
307 Uart.output[Uart.byteCnt] = 0xAA;
308 Uart.byteCnt++;
309 Uart.output[Uart.byteCnt] = error & 0xFF;
310 Uart.byteCnt++;
311 Uart.output[Uart.byteCnt] = 0xAA;
312 Uart.byteCnt++;
313 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
314 Uart.byteCnt++;
315 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
316 Uart.byteCnt++;
317 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
318 Uart.byteCnt++;
319 Uart.output[Uart.byteCnt] = 0xAA;
320 Uart.byteCnt++;
321 return TRUE;
322 }*/
323 }
324
325 }
326 else {
327 bit = Uart.bitBuffer & 0xf0;
328 bit >>= 4;
329 bit ^= 0x0F;
330 if(bit) {
331 // should have been high or at least (4 * 128) / fc
332 // according to ISO this should be at least (9 * 128 + 20) / fc
333 if(Uart.highCnt == 8) {
334 // we went low, so this could be start of communication
335 // it turns out to be safer to choose a less significant
336 // syncbit... so we check whether the neighbour also represents the drop
337 Uart.posCnt = 1; // apparently we are busy with our first half bit period
338 Uart.syncBit = bit & 8;
339 Uart.samples = 3;
340 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
341 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
342 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
343 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
344 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
2f2d9fc5 345 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
15c4dc5a 346 Uart.syncBit = 8;
347
348 // the first half bit period is expected in next sample
349 Uart.posCnt = 0;
350 Uart.samples = 3;
351 }
352 }
353 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
354
355 Uart.syncBit <<= 4;
356 Uart.state = STATE_START_OF_COMMUNICATION;
357 Uart.drop = DROP_FIRST_HALF;
358 Uart.bitCnt = 0;
359 Uart.byteCnt = 0;
360 Uart.parityBits = 0;
9f693930 361 //error = 0;
15c4dc5a 362 }
363 else {
364 Uart.highCnt = 0;
365 }
366 }
367 else {
368 if(Uart.highCnt < 8) {
369 Uart.highCnt++;
370 }
371 }
372 }
373
374 return FALSE;
375}
376
377//=============================================================================
e691fc45 378// ISO 14443 Type A - Manchester decoder
15c4dc5a 379//=============================================================================
e691fc45 380// Basics:
381// The tag will modulate the reader field by asserting different loads to it. As a consequence, the voltage
382// at the reader antenna will be modulated as well. The FPGA detects the modulation for us and would deliver e.g. the following:
383// ........ 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .......
384// The Manchester decoder needs to identify the following sequences:
385// 4 ticks modulated followed by 4 ticks unmodulated: Sequence D = 1 (also used as "start of communication")
386// 4 ticks unmodulated followed by 4 ticks modulated: Sequence E = 0
387// 8 ticks unmodulated: Sequence F = end of communication
388// 8 ticks modulated: A collision. Save the collision position and treat as Sequence D
389// Note 1: the bitstream may start at any time (either in first or second nibble within the parameter bit). We therefore need to sync.
390// Note 2: parameter offset is used to determine the position of the parity bits (required for the anticollision command only)
b62a5a84 391static tDemod Demod;
15c4dc5a 392
e691fc45 393inline RAMFUNC bool IsModulation(byte_t b)
15c4dc5a 394{
e691fc45 395 if (b >= 5 || b == 3) // majority decision: 2 or more bits are set
396 return true;
397 else
398 return false;
399
400}
15c4dc5a 401
e691fc45 402inline RAMFUNC bool IsModulationNibble1(byte_t b)
403{
404 return IsModulation((b & 0xE0) >> 5);
405}
2f2d9fc5 406
e691fc45 407inline RAMFUNC bool IsModulationNibble2(byte_t b)
408{
409 return IsModulation((b & 0x0E) >> 1);
410}
15c4dc5a 411
e691fc45 412static RAMFUNC int ManchesterDecoding(int bit, uint16_t offset)
413{
414
415 switch (Demod.state) {
416
417 case DEMOD_UNSYNCD: // not yet synced
418 Demod.len = 0; // initialize number of decoded data bytes
419 Demod.bitCount = offset; // initialize number of decoded data bits
420 Demod.shiftReg = 0; // initialize shiftreg to hold decoded data bits
421 Demod.parityBits = 0; // initialize parity bits
422 Demod.collisionPos = 0; // Position of collision bit
423
424 if (IsModulationNibble1(bit)
425 && !IsModulationNibble2(bit)) { // this is the start bit
426 Demod.samples = 8;
427 if(trigger) LED_A_OFF();
428 Demod.state = DEMOD_MANCHESTER_DATA;
429 } else if (!IsModulationNibble1(bit) && IsModulationNibble2(bit)) { // this may be the first half of the start bit
430 Demod.samples = 4;
431 Demod.state = DEMOD_HALF_SYNCD;
2f2d9fc5 432 }
e691fc45 433 break;
15c4dc5a 434
15c4dc5a 435
e691fc45 436 case DEMOD_HALF_SYNCD:
437 Demod.samples += 8;
438 if (IsModulationNibble1(bit)) { // error: this was not a start bit.
439 Demod.state = DEMOD_UNSYNCD;
440 } else {
441 if (IsModulationNibble2(bit)) { // modulation in first half
442 Demod.state = DEMOD_MOD_FIRST_HALF;
443 } else { // no modulation in first half
444 Demod.state = DEMOD_NOMOD_FIRST_HALF;
15c4dc5a 445 }
446 }
e691fc45 447 break;
448
449
450 case DEMOD_MOD_FIRST_HALF:
451 Demod.samples += 8;
452 Demod.bitCount++;
453 if (IsModulationNibble1(bit)) { // modulation in both halfs - collision
454 if (!Demod.collisionPos) {
455 Demod.collisionPos = (Demod.len << 3) + Demod.bitCount;
456 }
457 } // modulation in first half only - Sequence D = 1
458 Demod.shiftReg = (Demod.shiftReg >> 1) | 0x100; // add a 1 to the shiftreg
459 if(Demod.bitCount >= 9) { // if we decoded a full byte (including parity)
460 Demod.parityBits <<= 1; // make room for the parity bit
461 Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
462 Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
463 Demod.bitCount = 0;
464 Demod.shiftReg = 0;
15c4dc5a 465 }
e691fc45 466 if (IsModulationNibble2(bit)) { // modulation in first half
467 Demod.state = DEMOD_MOD_FIRST_HALF;
468 } else { // no modulation in first half
469 Demod.state = DEMOD_NOMOD_FIRST_HALF;
15c4dc5a 470 }
e691fc45 471 break;
472
473
474 case DEMOD_NOMOD_FIRST_HALF:
475 if (IsModulationNibble1(bit)) { // modulation in second half only - Sequence E = 0
476 Demod.bitCount++;
477 Demod.samples += 8;
478 Demod.shiftReg = (Demod.shiftReg >> 1); // add a 0 to the shiftreg
479 if(Demod.bitCount >= 9) { // if we decoded a full byte (including parity)
480 Demod.parityBits <<= 1; // make room for the new parity bit
481 Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
482 Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
483 Demod.bitCount = 0;
484 Demod.shiftReg = 0;
15c4dc5a 485 }
e691fc45 486 } else { // no modulation in both halves - End of communication
487 Demod.samples += 4;
488 if(Demod.bitCount > 0) { // if we decoded bits
489 Demod.shiftReg >>= (9 - Demod.bitCount); // add the remaining decoded bits to the output
490 Demod.output[Demod.len++] = Demod.shiftReg & 0xff;
491 // No parity bit, so just shift a 0
492 Demod.parityBits <<= 1;
493 }
494 Demod.state = DEMOD_UNSYNCD; // start from the beginning
495 return TRUE; // we are finished with decoding the raw data sequence
15c4dc5a 496 }
e691fc45 497 if (IsModulationNibble2(bit)) { // modulation in first half
498 Demod.state = DEMOD_MOD_FIRST_HALF;
499 } else { // no modulation in first half
500 Demod.state = DEMOD_NOMOD_FIRST_HALF;
15c4dc5a 501 }
e691fc45 502 break;
503
15c4dc5a 504
e691fc45 505 case DEMOD_MANCHESTER_DATA:
506 Demod.samples += 8;
507 if (IsModulationNibble1(bit)) { // modulation in first half
508 if (IsModulationNibble2(bit) & 0x0f) { // ... and in second half = collision
509 if (!Demod.collisionPos) {
510 Demod.collisionPos = (Demod.len << 3) + Demod.bitCount;
15c4dc5a 511 }
e691fc45 512 } // modulation in first half only - Sequence D = 1
513 Demod.bitCount++;
514 Demod.shiftReg = (Demod.shiftReg >> 1) | 0x100; // in both cases, add a 1 to the shiftreg
515 if(Demod.bitCount >= 9) { // if we decoded a full byte (including parity)
516 Demod.parityBits <<= 1; // make room for the parity bit
517 Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
518 Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
519 Demod.bitCount = 0;
520 Demod.shiftReg = 0;
521 }
522 } else { // no modulation in first half
523 if (IsModulationNibble2(bit)) { // and modulation in second half = Sequence E = 0
524 Demod.bitCount++;
525 Demod.shiftReg = (Demod.shiftReg >> 1); // add a 0 to the shiftreg
526 if(Demod.bitCount >= 9) { // if we decoded a full byte (including parity)
527 Demod.parityBits <<= 1; // make room for the new parity bit
528 Demod.output[Demod.len++] = (Demod.shiftReg & 0xff);
529 Demod.parityBits |= ((Demod.shiftReg >> 8) & 0x01); // store parity bit
530 Demod.bitCount = 0;
531 Demod.shiftReg = 0;
15c4dc5a 532 }
e691fc45 533 } else { // no modulation in both halves - End of communication
534 if(Demod.bitCount > 0) { // if we decoded bits
535 Demod.shiftReg >>= (9 - Demod.bitCount); // add the remaining decoded bits to the output
536 Demod.output[Demod.len++] = Demod.shiftReg & 0xff;
537 // No parity bit, so just shift a 0
538 Demod.parityBits <<= 1;
15c4dc5a 539 }
e691fc45 540 Demod.state = DEMOD_UNSYNCD; // start from the beginning
541 return TRUE; // we are finished with decoding the raw data sequence
542 }
15c4dc5a 543 }
e691fc45 544
545 }
15c4dc5a 546
e691fc45 547 return FALSE; // not finished yet, need more data
15c4dc5a 548}
549
550//=============================================================================
551// Finally, a `sniffer' for ISO 14443 Type A
552// Both sides of communication!
553//=============================================================================
554
555//-----------------------------------------------------------------------------
556// Record the sequence of commands sent by the reader to the tag, with
557// triggering so that we start recording at the point that the tag is moved
558// near the reader.
559//-----------------------------------------------------------------------------
5cd9ec01
M
560void RAMFUNC SnoopIso14443a(uint8_t param) {
561 // param:
562 // bit 0 - trigger from first card answer
563 // bit 1 - trigger from first reader 7-bit request
564
565 LEDsoff();
566 // init trace buffer
5f6d6c90 567 iso14a_clear_trace();
5cd9ec01
M
568
569 // We won't start recording the frames that we acquire until we trigger;
570 // a good trigger condition to get started is probably when we see a
571 // response from the tag.
572 // triggered == FALSE -- to wait first for card
573 int triggered = !(param & 0x03);
574
575 // The command (reader -> tag) that we're receiving.
15c4dc5a 576 // The length of a received command will in most cases be no more than 18 bytes.
577 // So 32 should be enough!
5cd9ec01
M
578 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
579 // The response (tag -> reader) that we're receiving.
580 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
15c4dc5a 581
5cd9ec01
M
582 // As we receive stuff, we copy it from receivedCmd or receivedResponse
583 // into trace, along with its length and other annotations.
584 //uint8_t *trace = (uint8_t *)BigBuf;
585
586 // The DMA buffer, used to stream samples from the FPGA
587 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
588 int8_t *data = dmaBuf;
589 int maxDataLen = 0;
590 int dataLen = 0;
15c4dc5a 591
5cd9ec01
M
592 // Set up the demodulator for tag -> reader responses.
593 Demod.output = receivedResponse;
594 Demod.len = 0;
595 Demod.state = DEMOD_UNSYNCD;
15c4dc5a 596
5cd9ec01
M
597 // Set up the demodulator for the reader -> tag commands
598 memset(&Uart, 0, sizeof(Uart));
599 Uart.output = receivedCmd;
600 Uart.byteCntMax = 32; // was 100 (greg)//////////////////
601 Uart.state = STATE_UNSYNCD;
15c4dc5a 602
5cd9ec01
M
603 // Setup for the DMA.
604 FpgaSetupSsc();
605 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
15c4dc5a 606
5cd9ec01
M
607 // And put the FPGA in the appropriate mode
608 // Signal field is off with the appropriate LED
609 LED_D_OFF();
610 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
611 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
7e758047 612
5cd9ec01
M
613 // Count of samples received so far, so that we can include timing
614 // information in the trace buffer.
615 rsamples = 0;
616 // And now we loop, receiving samples.
617 while(true) {
618 if(BUTTON_PRESS()) {
619 DbpString("cancelled by button");
620 goto done;
621 }
15c4dc5a 622
5cd9ec01
M
623 LED_A_ON();
624 WDT_HIT();
15c4dc5a 625
5cd9ec01
M
626 int register readBufDataP = data - dmaBuf;
627 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
628 if (readBufDataP <= dmaBufDataP){
629 dataLen = dmaBufDataP - readBufDataP;
630 } else {
631 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP + 1;
632 }
633 // test for length of buffer
634 if(dataLen > maxDataLen) {
635 maxDataLen = dataLen;
636 if(dataLen > 400) {
637 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen);
638 goto done;
639 }
640 }
641 if(dataLen < 1) continue;
642
643 // primary buffer was stopped( <-- we lost data!
644 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
645 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
646 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
5cd9ec01
M
647 }
648 // secondary buffer sets as primary, secondary buffer was stopped
649 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
650 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
651 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
652 }
653
654 LED_A_OFF();
655
656 rsamples += 4;
657 if(MillerDecoding((data[0] & 0xF0) >> 4)) {
658 LED_C_ON();
659
660 // check - if there is a short 7bit request from reader
661 if ((!triggered) && (param & 0x02) && (Uart.byteCnt == 1) && (Uart.bitCnt = 9)) triggered = TRUE;
662
663 if(triggered) {
664 if (!LogTrace(receivedCmd, Uart.byteCnt, 0 - Uart.samples, Uart.parityBits, TRUE)) break;
665 }
666 /* And ready to receive another command. */
667 Uart.state = STATE_UNSYNCD;
668 /* And also reset the demod code, which might have been */
669 /* false-triggered by the commands from the reader. */
670 Demod.state = DEMOD_UNSYNCD;
671 LED_B_OFF();
672 }
673
e691fc45 674 if(ManchesterDecoding(data[0], 0)) {
5cd9ec01
M
675 LED_B_ON();
676
677 if (!LogTrace(receivedResponse, Demod.len, 0 - Demod.samples, Demod.parityBits, FALSE)) break;
678
679 if ((!triggered) && (param & 0x01)) triggered = TRUE;
680
681 // And ready to receive another response.
682 memset(&Demod, 0, sizeof(Demod));
683 Demod.output = receivedResponse;
684 Demod.state = DEMOD_UNSYNCD;
685 LED_C_OFF();
686 }
687
688 data++;
689 if(data > dmaBuf + DMA_BUFFER_SIZE) {
690 data = dmaBuf;
691 }
692 } // main cycle
693
694 DbpString("COMMAND FINISHED");
15c4dc5a 695
15c4dc5a 696done:
5cd9ec01
M
697 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
698 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x", maxDataLen, Uart.state, Uart.byteCnt);
699 Dbprintf("Uart.byteCntMax=%x, traceLen=%x, Uart.output[0]=%08x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
700 LEDsoff();
15c4dc5a 701}
702
15c4dc5a 703//-----------------------------------------------------------------------------
704// Prepare tag messages
705//-----------------------------------------------------------------------------
8f51ddb0 706static void CodeIso14443aAsTagPar(const uint8_t *cmd, int len, uint32_t dwParity)
15c4dc5a 707{
8f51ddb0 708 int i;
15c4dc5a 709
8f51ddb0 710 ToSendReset();
15c4dc5a 711
712 // Correction bit, might be removed when not needed
713 ToSendStuffBit(0);
714 ToSendStuffBit(0);
715 ToSendStuffBit(0);
716 ToSendStuffBit(0);
717 ToSendStuffBit(1); // 1
718 ToSendStuffBit(0);
719 ToSendStuffBit(0);
720 ToSendStuffBit(0);
8f51ddb0 721
15c4dc5a 722 // Send startbit
72934aa3 723 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 724
8f51ddb0
M
725 for(i = 0; i < len; i++) {
726 int j;
727 uint8_t b = cmd[i];
15c4dc5a 728
729 // Data bits
15c4dc5a 730 for(j = 0; j < 8; j++) {
15c4dc5a 731 if(b & 1) {
72934aa3 732 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 733 } else {
72934aa3 734 ToSend[++ToSendMax] = SEC_E;
8f51ddb0
M
735 }
736 b >>= 1;
737 }
15c4dc5a 738
0014cb46 739 // Get the parity bit
8f51ddb0
M
740 if ((dwParity >> i) & 0x01) {
741 ToSend[++ToSendMax] = SEC_D;
15c4dc5a 742 } else {
72934aa3 743 ToSend[++ToSendMax] = SEC_E;
15c4dc5a 744 }
8f51ddb0 745 }
15c4dc5a 746
8f51ddb0
M
747 // Send stopbit
748 ToSend[++ToSendMax] = SEC_F;
15c4dc5a 749
8f51ddb0
M
750 // Convert from last byte pos to length
751 ToSendMax++;
8f51ddb0
M
752}
753
754static void CodeIso14443aAsTag(const uint8_t *cmd, int len){
755 CodeIso14443aAsTagPar(cmd, len, GetParity(cmd, len));
15c4dc5a 756}
757
ce02f6f9 758////-----------------------------------------------------------------------------
759//// This is to send a NACK kind of answer, its only 3 bits, I know it should be 4
760////-----------------------------------------------------------------------------
761//static void CodeStrangeAnswerAsTag()
762//{
763// int i;
764//
765// ToSendReset();
766//
767// // Correction bit, might be removed when not needed
768// ToSendStuffBit(0);
769// ToSendStuffBit(0);
770// ToSendStuffBit(0);
771// ToSendStuffBit(0);
772// ToSendStuffBit(1); // 1
773// ToSendStuffBit(0);
774// ToSendStuffBit(0);
775// ToSendStuffBit(0);
776//
777// // Send startbit
778// ToSend[++ToSendMax] = SEC_D;
779//
780// // 0
781// ToSend[++ToSendMax] = SEC_E;
782//
783// // 0
784// ToSend[++ToSendMax] = SEC_E;
785//
786// // 1
787// ToSend[++ToSendMax] = SEC_D;
788//
789// // Send stopbit
790// ToSend[++ToSendMax] = SEC_F;
791//
792// // Flush the buffer in FPGA!!
793// for(i = 0; i < 5; i++) {
794// ToSend[++ToSendMax] = SEC_F;
795// }
796//
797// // Convert from last byte pos to length
798// ToSendMax++;
799//}
15c4dc5a 800
8f51ddb0
M
801static void Code4bitAnswerAsTag(uint8_t cmd)
802{
803 int i;
804
5f6d6c90 805 ToSendReset();
8f51ddb0
M
806
807 // Correction bit, might be removed when not needed
808 ToSendStuffBit(0);
809 ToSendStuffBit(0);
810 ToSendStuffBit(0);
811 ToSendStuffBit(0);
812 ToSendStuffBit(1); // 1
813 ToSendStuffBit(0);
814 ToSendStuffBit(0);
815 ToSendStuffBit(0);
816
817 // Send startbit
818 ToSend[++ToSendMax] = SEC_D;
819
820 uint8_t b = cmd;
821 for(i = 0; i < 4; i++) {
822 if(b & 1) {
823 ToSend[++ToSendMax] = SEC_D;
824 } else {
825 ToSend[++ToSendMax] = SEC_E;
826 }
827 b >>= 1;
828 }
829
830 // Send stopbit
831 ToSend[++ToSendMax] = SEC_F;
832
833 // Flush the buffer in FPGA!!
834 for(i = 0; i < 5; i++) {
835 ToSend[++ToSendMax] = SEC_F;
836 }
837
5f6d6c90 838 // Convert from last byte pos to length
839 ToSendMax++;
15c4dc5a 840}
841
842//-----------------------------------------------------------------------------
843// Wait for commands from reader
844// Stop when button is pressed
845// Or return TRUE when command is captured
846//-----------------------------------------------------------------------------
f7e3ed82 847static int GetIso14443aCommandFromReader(uint8_t *received, int *len, int maxLen)
15c4dc5a 848{
849 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
850 // only, since we are receiving, not transmitting).
851 // Signal field is off with the appropriate LED
852 LED_D_OFF();
853 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
854
855 // Now run a `software UART' on the stream of incoming samples.
856 Uart.output = received;
857 Uart.byteCntMax = maxLen;
858 Uart.state = STATE_UNSYNCD;
859
860 for(;;) {
861 WDT_HIT();
862
863 if(BUTTON_PRESS()) return FALSE;
864
865 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
866 AT91C_BASE_SSC->SSC_THR = 0x00;
867 }
868 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
f7e3ed82 869 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
15c4dc5a 870 if(MillerDecoding((b & 0xf0) >> 4)) {
871 *len = Uart.byteCnt;
872 return TRUE;
873 }
874 if(MillerDecoding(b & 0x0f)) {
875 *len = Uart.byteCnt;
876 return TRUE;
877 }
878 }
879 }
880}
28afbd2b 881
9ca155ba 882static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded);
28afbd2b 883int EmSend4bitEx(uint8_t resp, int correctionNeeded);
884int EmSend4bit(uint8_t resp);
885int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par);
886int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par);
887int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded);
888int EmSendCmd(uint8_t *resp, int respLen);
889int EmSendCmdPar(uint8_t *resp, int respLen, uint32_t par);
15c4dc5a 890
ce02f6f9 891static uint8_t* free_buffer_pointer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
892
893typedef struct {
894 uint8_t* response;
895 size_t response_n;
896 uint8_t* modulation;
897 size_t modulation_n;
898} tag_response_info_t;
899
900void reset_free_buffer() {
901 free_buffer_pointer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
902}
903
904bool prepare_tag_modulation(tag_response_info_t* response_info, size_t max_buffer_size) {
905 // Exmaple response, answer to MIFARE Classic read block will be 16 bytes + 2 CRC = 18 bytes
906 // This will need the following byte array for a modulation sequence
907 // 144 data bits (18 * 8)
908 // 18 parity bits
909 // 2 Start and stop
910 // 1 Correction bit (Answer in 1172 or 1236 periods, see FPGA)
911 // 1 just for the case
912 // ----------- +
913 // 166 bytes, since every bit that needs to be send costs us a byte
914 //
915
916 // Prepare the tag modulation bits from the message
917 CodeIso14443aAsTag(response_info->response,response_info->response_n);
918
919 // Make sure we do not exceed the free buffer space
920 if (ToSendMax > max_buffer_size) {
921 Dbprintf("Out of memory, when modulating bits for tag answer:");
922 Dbhexdump(response_info->response_n,response_info->response,false);
923 return false;
924 }
925
926 // Copy the byte array, used for this modulation to the buffer position
927 memcpy(response_info->modulation,ToSend,ToSendMax);
928
929 // Store the number of bytes that were used for encoding/modulation
930 response_info->modulation_n = ToSendMax;
931
932 return true;
933}
934
935bool prepare_allocated_tag_modulation(tag_response_info_t* response_info) {
936 // Retrieve and store the current buffer index
937 response_info->modulation = free_buffer_pointer;
938
939 // Determine the maximum size we can use from our buffer
940 size_t max_buffer_size = (((uint8_t *)BigBuf)+FREE_BUFFER_OFFSET+FREE_BUFFER_SIZE)-free_buffer_pointer;
941
942 // Forward the prepare tag modulation function to the inner function
943 if (prepare_tag_modulation(response_info,max_buffer_size)) {
944 // Update the free buffer offset
945 free_buffer_pointer += ToSendMax;
946 return true;
947 } else {
948 return false;
949 }
950}
951
15c4dc5a 952//-----------------------------------------------------------------------------
953// Main loop of simulated tag: receive commands from reader, decide what
954// response to send, and send it.
955//-----------------------------------------------------------------------------
28afbd2b 956void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data)
15c4dc5a 957{
5f6d6c90 958 // Enable and clear the trace
81cd0474 959 tracing = TRUE;
5f6d6c90 960 iso14a_clear_trace();
81cd0474 961
15c4dc5a 962 // This function contains the tag emulation
81cd0474 963 uint8_t sak;
964
965 // The first response contains the ATQA (note: bytes are transmitted in reverse order).
966 uint8_t response1[2];
967
968 switch (tagType) {
969 case 1: { // MIFARE Classic
970 // Says: I am Mifare 1k - original line
971 response1[0] = 0x04;
972 response1[1] = 0x00;
973 sak = 0x08;
974 } break;
975 case 2: { // MIFARE Ultralight
976 // Says: I am a stupid memory tag, no crypto
977 response1[0] = 0x04;
978 response1[1] = 0x00;
979 sak = 0x00;
980 } break;
981 case 3: { // MIFARE DESFire
982 // Says: I am a DESFire tag, ph33r me
983 response1[0] = 0x04;
984 response1[1] = 0x03;
985 sak = 0x20;
986 } break;
987 case 4: { // ISO/IEC 14443-4
988 // Says: I am a javacard (JCOP)
989 response1[0] = 0x04;
990 response1[1] = 0x00;
991 sak = 0x28;
992 } break;
993 default: {
994 Dbprintf("Error: unkown tagtype (%d)",tagType);
995 return;
996 } break;
997 }
998
999 // The second response contains the (mandatory) first 24 bits of the UID
1000 uint8_t response2[5];
1001
1002 // Check if the uid uses the (optional) part
1003 uint8_t response2a[5];
1004 if (uid_2nd) {
1005 response2[0] = 0x88;
1006 num_to_bytes(uid_1st,3,response2+1);
1007 num_to_bytes(uid_2nd,4,response2a);
1008 response2a[4] = response2a[0] ^ response2a[1] ^ response2a[2] ^ response2a[3];
1009
1010 // Configure the ATQA and SAK accordingly
1011 response1[0] |= 0x40;
1012 sak |= 0x04;
1013 } else {
1014 num_to_bytes(uid_1st,4,response2);
1015 // Configure the ATQA and SAK accordingly
1016 response1[0] &= 0xBF;
1017 sak &= 0xFB;
1018 }
1019
1020 // Calculate the BitCountCheck (BCC) for the first 4 bytes of the UID.
1021 response2[4] = response2[0] ^ response2[1] ^ response2[2] ^ response2[3];
1022
1023 // Prepare the mandatory SAK (for 4 and 7 byte UID)
1024 uint8_t response3[3];
1025 response3[0] = sak;
1026 ComputeCrc14443(CRC_14443_A, response3, 1, &response3[1], &response3[2]);
1027
1028 // Prepare the optional second SAK (for 7 byte UID), drop the cascade bit
1029 uint8_t response3a[3];
1030 response3a[0] = sak & 0xFB;
1031 ComputeCrc14443(CRC_14443_A, response3a, 1, &response3a[1], &response3a[2]);
1032
254b70a4 1033 uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
ce02f6f9 1034 uint8_t response6[] = { 0x04, 0x58, 0x00, 0x02, 0x00, 0x00 }; // dummy ATS (pseudo-ATR), answer to RATS
1035 ComputeCrc14443(CRC_14443_A, response6, 4, &response6[4], &response6[5]);
1036
1037 #define TAG_RESPONSE_COUNT 7
1038 tag_response_info_t responses[TAG_RESPONSE_COUNT] = {
1039 { .response = response1, .response_n = sizeof(response1) }, // Answer to request - respond with card type
1040 { .response = response2, .response_n = sizeof(response2) }, // Anticollision cascade1 - respond with uid
1041 { .response = response2a, .response_n = sizeof(response2a) }, // Anticollision cascade2 - respond with 2nd half of uid if asked
1042 { .response = response3, .response_n = sizeof(response3) }, // Acknowledge select - cascade 1
1043 { .response = response3a, .response_n = sizeof(response3a) }, // Acknowledge select - cascade 2
1044 { .response = response5, .response_n = sizeof(response5) }, // Authentication answer (random nonce)
1045 { .response = response6, .response_n = sizeof(response6) }, // dummy ATS (pseudo-ATR), answer to RATS
1046 };
1047
1048 // Allocate 512 bytes for the dynamic modulation, created when the reader querries for it
1049 // Such a response is less time critical, so we can prepare them on the fly
1050 #define DYNAMIC_RESPONSE_BUFFER_SIZE 64
1051 #define DYNAMIC_MODULATION_BUFFER_SIZE 512
1052 uint8_t dynamic_response_buffer[DYNAMIC_RESPONSE_BUFFER_SIZE];
1053 uint8_t dynamic_modulation_buffer[DYNAMIC_MODULATION_BUFFER_SIZE];
1054 tag_response_info_t dynamic_response_info = {
1055 .response = dynamic_response_buffer,
1056 .response_n = 0,
1057 .modulation = dynamic_modulation_buffer,
1058 .modulation_n = 0
1059 };
1060
1061 // Reset the offset pointer of the free buffer
1062 reset_free_buffer();
1063
1064 // Prepare the responses of the anticollision phase
1065 // there will be not enough time to do this at the moment the reader sends it REQA
1066 for (size_t i=0; i<TAG_RESPONSE_COUNT; i++) {
1067 prepare_allocated_tag_modulation(&responses[i]);
1068 }
15c4dc5a 1069
254b70a4 1070 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
1071 int len;
15c4dc5a 1072
1073 // To control where we are in the protocol
1074 int order = 0;
1075 int lastorder;
1076
1077 // Just to allow some checks
1078 int happened = 0;
1079 int happened2 = 0;
81cd0474 1080 int cmdsRecvd = 0;
15c4dc5a 1081
254b70a4 1082 // We need to listen to the high-frequency, peak-detected path.
1083 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1084 FpgaSetupSsc();
15c4dc5a 1085
254b70a4 1086 cmdsRecvd = 0;
ce02f6f9 1087 tag_response_info_t* p_response;
15c4dc5a 1088
254b70a4 1089 LED_A_ON();
1090 for(;;) {
ce02f6f9 1091 // Clean receive command buffer
1092 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
254b70a4 1093
81cd0474 1094 if(!GetIso14443aCommandFromReader(receivedCmd, &len, RECV_CMD_SIZE)) {
ce02f6f9 1095 DbpString("Button press");
254b70a4 1096 break;
1097 }
28afbd2b 1098
5f6d6c90 1099 if (tracing) {
28afbd2b 1100 LogTrace(receivedCmd,len, 0, Uart.parityBits, TRUE);
5f6d6c90 1101 }
28afbd2b 1102
ce02f6f9 1103 p_response = NULL;
1104
254b70a4 1105 // doob - added loads of debug strings so we can see what the reader is saying to us during the sim as hi14alist is not populated
1106 // Okay, look at the command now.
1107 lastorder = order;
1108 if(receivedCmd[0] == 0x26) { // Received a REQUEST
ce02f6f9 1109 p_response = &responses[0]; order = 1;
254b70a4 1110 } else if(receivedCmd[0] == 0x52) { // Received a WAKEUP
ce02f6f9 1111 p_response = &responses[0]; order = 6;
254b70a4 1112 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // Received request for UID (cascade 1)
ce02f6f9 1113 p_response = &responses[1]; order = 2;
254b70a4 1114 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x95) { // Received request for UID (cascade 2)
ce02f6f9 1115 p_response = &responses[2]; order = 20;
254b70a4 1116 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x93) { // Received a SELECT (cascade 1)
ce02f6f9 1117 p_response = &responses[3]; order = 3;
254b70a4 1118 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2)
ce02f6f9 1119 p_response = &responses[4]; order = 30;
254b70a4 1120 } else if(receivedCmd[0] == 0x30) { // Received a (plain) READ
5f6d6c90 1121 EmSendCmdEx(data+(4*receivedCmd[0]),16,false);
254b70a4 1122 Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
5f6d6c90 1123 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
ce02f6f9 1124 p_response = NULL;
254b70a4 1125 } else if(receivedCmd[0] == 0x50) { // Received a HALT
17331e14 1126// DbpString("Reader requested we HALT!:");
ce02f6f9 1127 p_response = NULL;
254b70a4 1128 } else if(receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61) { // Received an authentication request
ce02f6f9 1129 p_response = &responses[5]; order = 7;
254b70a4 1130 } else if(receivedCmd[0] == 0xE0) { // Received a RATS request
ce02f6f9 1131 p_response = &responses[6]; order = 70;
1132 } else if (order == 7 && len ==8) { // Received authentication request
1133 uint32_t nr = bytes_to_num(receivedCmd,4);
1134 uint32_t ar = bytes_to_num(receivedCmd+4,4);
1135 Dbprintf("Auth attempt {nr}{ar}: %08x %08x",nr,ar);
1136 } else {
1137 // Check for ISO 14443A-4 compliant commands, look at left nibble
1138 switch (receivedCmd[0]) {
1139
1140 case 0x0B:
1141 case 0x0A: { // IBlock (command)
1142 dynamic_response_info.response[0] = receivedCmd[0];
1143 dynamic_response_info.response[1] = 0x00;
1144 dynamic_response_info.response[2] = 0x90;
1145 dynamic_response_info.response[3] = 0x00;
1146 dynamic_response_info.response_n = 4;
1147 } break;
1148
1149 case 0x1A:
1150 case 0x1B: { // Chaining command
1151 dynamic_response_info.response[0] = 0xaa | ((receivedCmd[0]) & 1);
1152 dynamic_response_info.response_n = 2;
1153 } break;
1154
1155 case 0xaa:
1156 case 0xbb: {
1157 dynamic_response_info.response[0] = receivedCmd[0] ^ 0x11;
1158 dynamic_response_info.response_n = 2;
1159 } break;
1160
1161 case 0xBA: { //
1162 memcpy(dynamic_response_info.response,"\xAB\x00",2);
1163 dynamic_response_info.response_n = 2;
1164 } break;
1165
1166 case 0xCA:
1167 case 0xC2: { // Readers sends deselect command
1168 memcpy(dynamic_response_info.response,"\xCA\x00",2);
1169 dynamic_response_info.response_n = 2;
1170 } break;
1171
1172 default: {
1173 // Never seen this command before
1174 Dbprintf("Received unknown command (len=%d):",len);
1175 Dbhexdump(len,receivedCmd,false);
1176 // Do not respond
1177 dynamic_response_info.response_n = 0;
1178 } break;
1179 }
1180
1181 if (dynamic_response_info.response_n > 0) {
1182 // Copy the CID from the reader query
1183 dynamic_response_info.response[1] = receivedCmd[1];
1184
1185 // Add CRC bytes, always used in ISO 14443A-4 compliant cards
1186 AppendCrc14443a(dynamic_response_info.response,dynamic_response_info.response_n);
1187 dynamic_response_info.response_n += 2;
1188
1189 if (prepare_tag_modulation(&dynamic_response_info,DYNAMIC_MODULATION_BUFFER_SIZE) == false) {
1190 Dbprintf("Error preparing tag response");
1191 break;
1192 }
1193 p_response = &dynamic_response_info;
17331e14 1194 }
81cd0474 1195 }
15c4dc5a 1196
1197 // Count number of wakeups received after a halt
1198 if(order == 6 && lastorder == 5) { happened++; }
1199
1200 // Count number of other messages after a halt
1201 if(order != 6 && lastorder == 5) { happened2++; }
1202
1203 // Look at last parity bit to determine timing of answer
1204 if((Uart.parityBits & 0x01) || receivedCmd[0] == 0x52) {
1205 // 1236, so correction bit needed
9f693930 1206 //i = 0;
15c4dc5a 1207 }
1208
15c4dc5a 1209 if(cmdsRecvd > 999) {
1210 DbpString("1000 commands later...");
254b70a4 1211 break;
15c4dc5a 1212 }
ce02f6f9 1213 cmdsRecvd++;
1214
1215 if (p_response != NULL) {
1216 EmSendCmd14443aRaw(p_response->modulation, p_response->modulation_n, receivedCmd[0] == 0x52);
1217 if (tracing) {
1218 LogTrace(p_response->response,p_response->response_n,0,SwapBits(GetParity(p_response->response,p_response->response_n),p_response->response_n),FALSE);
1219 if(traceLen > TRACE_SIZE) {
1220 DbpString("Trace full");
1221// break;
1222 }
1223 }
1224 }
254b70a4 1225 }
15c4dc5a 1226
1227 Dbprintf("%x %x %x", happened, happened2, cmdsRecvd);
1228 LED_A_OFF();
1229}
1230
9492e0b0 1231
1232// prepare a delayed transfer. This simply shifts ToSend[] by a number
1233// of bits specified in the delay parameter.
1234void PrepareDelayedTransfer(uint16_t delay)
1235{
1236 uint8_t bitmask = 0;
1237 uint8_t bits_to_shift = 0;
1238 uint8_t bits_shifted = 0;
1239
1240 delay &= 0x07;
1241 if (delay) {
1242 for (uint16_t i = 0; i < delay; i++) {
1243 bitmask |= (0x01 << i);
1244 }
1245 ToSend[++ToSendMax] = 0x00;
1246 for (uint16_t i = 0; i < ToSendMax; i++) {
1247 bits_to_shift = ToSend[i] & bitmask;
1248 ToSend[i] = ToSend[i] >> delay;
1249 ToSend[i] = ToSend[i] | (bits_shifted << (8 - delay));
1250 bits_shifted = bits_to_shift;
1251 }
1252 }
1253}
1254
15c4dc5a 1255//-----------------------------------------------------------------------------
1256// Transmit the command (to the tag) that was placed in ToSend[].
9492e0b0 1257// Parameter timing:
1258// if NULL: ignored
1259// if == 0: return time of transfer
1260// if != 0: delay transfer until time specified
15c4dc5a 1261//-----------------------------------------------------------------------------
9492e0b0 1262static void TransmitFor14443a(const uint8_t *cmd, int len, uint32_t *timing)
15c4dc5a 1263{
9492e0b0 1264 int c;
e30c654b 1265
9492e0b0 1266 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
e30c654b 1267
e30c654b 1268
9492e0b0 1269 if (timing) {
1270 if(*timing == 0) { // Measure time
1271 *timing = (GetCountMifare() + 8) & 0xfffffff8;
1272 } else {
1273 PrepareDelayedTransfer(*timing & 0x00000007); // Delay transfer (fine tuning - up to 7 MF clock ticks)
1274 }
1275 if(MF_DBGLEVEL >= 4 && GetCountMifare() >= (*timing & 0xfffffff8)) Dbprintf("TransmitFor14443a: Missed timing");
1276 while(GetCountMifare() < (*timing & 0xfffffff8)); // Delay transfer (multiple of 8 MF clock ticks)
1277 }
1278
e691fc45 1279 for(c = 0; c < 10;) { // standard delay for each transfer (allow tag to be ready after last transmission?)
9492e0b0 1280 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1281 AT91C_BASE_SSC->SSC_THR = 0x00;
1282 c++;
1283 }
1284 }
1285
1286 c = 0;
1287 for(;;) {
1288 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1289 AT91C_BASE_SSC->SSC_THR = cmd[c];
1290 c++;
1291 if(c >= len) {
1292 break;
1293 }
1294 }
1295 }
e30c654b 1296
15c4dc5a 1297}
1298
15c4dc5a 1299//-----------------------------------------------------------------------------
195af472 1300// Prepare reader command (in bits, support short frames) to send to FPGA
15c4dc5a 1301//-----------------------------------------------------------------------------
195af472 1302void CodeIso14443aBitsAsReaderPar(const uint8_t * cmd, int bits, uint32_t dwParity)
15c4dc5a 1303{
1304 int i, j;
1305 int last;
f7e3ed82 1306 uint8_t b;
e30c654b 1307
15c4dc5a 1308 ToSendReset();
e30c654b 1309
15c4dc5a 1310 // Start of Communication (Seq. Z)
72934aa3 1311 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1312 last = 0;
e30c654b 1313
195af472 1314 size_t bytecount = nbytes(bits);
15c4dc5a 1315 // Generate send structure for the data bits
195af472 1316 for (i = 0; i < bytecount; i++) {
15c4dc5a 1317 // Get the current byte to send
1318 b = cmd[i];
195af472 1319 size_t bitsleft = MIN((bits-(i*8)),8);
e30c654b 1320
195af472 1321 for (j = 0; j < bitsleft; j++) {
15c4dc5a 1322 if (b & 1) {
1323 // Sequence X
72934aa3 1324 ToSend[++ToSendMax] = SEC_X;
15c4dc5a 1325 last = 1;
1326 } else {
1327 if (last == 0) {
1328 // Sequence Z
72934aa3 1329 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1330 } else {
1331 // Sequence Y
72934aa3 1332 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1333 last = 0;
1334 }
1335 }
1336 b >>= 1;
1337 }
e30c654b 1338
195af472 1339 // Only transmit (last) parity bit if we transmitted a complete byte
1340 if (j == 8) {
1341 // Get the parity bit
1342 if ((dwParity >> i) & 0x01) {
1343 // Sequence X
1344 ToSend[++ToSendMax] = SEC_X;
1345 last = 1;
15c4dc5a 1346 } else {
195af472 1347 if (last == 0) {
1348 // Sequence Z
1349 ToSend[++ToSendMax] = SEC_Z;
1350 } else {
1351 // Sequence Y
1352 ToSend[++ToSendMax] = SEC_Y;
1353 last = 0;
1354 }
15c4dc5a 1355 }
1356 }
1357 }
e30c654b 1358
15c4dc5a 1359 // End of Communication
1360 if (last == 0) {
1361 // Sequence Z
72934aa3 1362 ToSend[++ToSendMax] = SEC_Z;
15c4dc5a 1363 } else {
1364 // Sequence Y
72934aa3 1365 ToSend[++ToSendMax] = SEC_Y;
15c4dc5a 1366 last = 0;
1367 }
1368 // Sequence Y
72934aa3 1369 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1370
15c4dc5a 1371 // Just to be sure!
72934aa3 1372 ToSend[++ToSendMax] = SEC_Y;
1373 ToSend[++ToSendMax] = SEC_Y;
1374 ToSend[++ToSendMax] = SEC_Y;
e30c654b 1375
15c4dc5a 1376 // Convert from last character reference to length
1377 ToSendMax++;
1378}
1379
195af472 1380//-----------------------------------------------------------------------------
1381// Prepare reader command to send to FPGA
1382//-----------------------------------------------------------------------------
1383void CodeIso14443aAsReaderPar(const uint8_t * cmd, int len, uint32_t dwParity)
1384{
1385 CodeIso14443aBitsAsReaderPar(cmd,len*8,dwParity);
1386}
1387
9ca155ba
M
1388//-----------------------------------------------------------------------------
1389// Wait for commands from reader
1390// Stop when button is pressed (return 1) or field was gone (return 2)
1391// Or return 0 when command is captured
1392//-----------------------------------------------------------------------------
1393static int EmGetCmd(uint8_t *received, int *len, int maxLen)
1394{
1395 *len = 0;
1396
1397 uint32_t timer = 0, vtime = 0;
1398 int analogCnt = 0;
1399 int analogAVG = 0;
1400
1401 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
1402 // only, since we are receiving, not transmitting).
1403 // Signal field is off with the appropriate LED
1404 LED_D_OFF();
1405 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1406
1407 // Set ADC to read field strength
1408 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_SWRST;
1409 AT91C_BASE_ADC->ADC_MR =
1410 ADC_MODE_PRESCALE(32) |
1411 ADC_MODE_STARTUP_TIME(16) |
1412 ADC_MODE_SAMPLE_HOLD_TIME(8);
1413 AT91C_BASE_ADC->ADC_CHER = ADC_CHANNEL(ADC_CHAN_HF);
1414 // start ADC
1415 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1416
1417 // Now run a 'software UART' on the stream of incoming samples.
1418 Uart.output = received;
1419 Uart.byteCntMax = maxLen;
1420 Uart.state = STATE_UNSYNCD;
1421
1422 for(;;) {
1423 WDT_HIT();
1424
1425 if (BUTTON_PRESS()) return 1;
1426
1427 // test if the field exists
1428 if (AT91C_BASE_ADC->ADC_SR & ADC_END_OF_CONVERSION(ADC_CHAN_HF)) {
1429 analogCnt++;
1430 analogAVG += AT91C_BASE_ADC->ADC_CDR[ADC_CHAN_HF];
1431 AT91C_BASE_ADC->ADC_CR = AT91C_ADC_START;
1432 if (analogCnt >= 32) {
1433 if ((33000 * (analogAVG / analogCnt) >> 10) < MF_MINFIELDV) {
1434 vtime = GetTickCount();
1435 if (!timer) timer = vtime;
1436 // 50ms no field --> card to idle state
1437 if (vtime - timer > 50) return 2;
1438 } else
1439 if (timer) timer = 0;
1440 analogCnt = 0;
1441 analogAVG = 0;
1442 }
1443 }
1444 // transmit none
1445 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1446 AT91C_BASE_SSC->SSC_THR = 0x00;
1447 }
1448 // receive and test the miller decoding
1449 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1450 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1451 if(MillerDecoding((b & 0xf0) >> 4)) {
1452 *len = Uart.byteCnt;
8f51ddb0 1453 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
9ca155ba
M
1454 return 0;
1455 }
1456 if(MillerDecoding(b & 0x0f)) {
1457 *len = Uart.byteCnt;
8f51ddb0 1458 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
9ca155ba
M
1459 return 0;
1460 }
1461 }
1462 }
1463}
1464
1465static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded)
1466{
1467 int i, u = 0;
1468 uint8_t b = 0;
1469
1470 // Modulate Manchester
1471 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_MOD);
1472 AT91C_BASE_SSC->SSC_THR = 0x00;
1473 FpgaSetupSsc();
1474
1475 // include correction bit
1476 i = 1;
1477 if((Uart.parityBits & 0x01) || correctionNeeded) {
1478 // 1236, so correction bit needed
1479 i = 0;
1480 }
1481
1482 // send cycle
1483 for(;;) {
1484 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1485 volatile uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1486 (void)b;
1487 }
1488 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1489 if(i > respLen) {
8f51ddb0 1490 b = 0xff; // was 0x00
9ca155ba
M
1491 u++;
1492 } else {
1493 b = resp[i];
1494 i++;
1495 }
1496 AT91C_BASE_SSC->SSC_THR = b;
1497
1498 if(u > 4) break;
1499 }
1500 if(BUTTON_PRESS()) {
1501 break;
1502 }
1503 }
1504
1505 return 0;
1506}
1507
8f51ddb0
M
1508int EmSend4bitEx(uint8_t resp, int correctionNeeded){
1509 Code4bitAnswerAsTag(resp);
0a39986e 1510 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
8f51ddb0 1511 if (tracing) LogTrace(&resp, 1, GetDeltaCountUS(), GetParity(&resp, 1), FALSE);
0a39986e 1512 return res;
9ca155ba
M
1513}
1514
8f51ddb0
M
1515int EmSend4bit(uint8_t resp){
1516 return EmSend4bitEx(resp, 0);
1517}
1518
1519int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par){
1520 CodeIso14443aAsTagPar(resp, respLen, par);
1521 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
1522 if (tracing) LogTrace(resp, respLen, GetDeltaCountUS(), par, FALSE);
1523 return res;
1524}
1525
1526int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded){
1527 return EmSendCmdExPar(resp, respLen, correctionNeeded, GetParity(resp, respLen));
1528}
1529
1530int EmSendCmd(uint8_t *resp, int respLen){
1531 return EmSendCmdExPar(resp, respLen, 0, GetParity(resp, respLen));
1532}
1533
1534int EmSendCmdPar(uint8_t *resp, int respLen, uint32_t par){
1535 return EmSendCmdExPar(resp, respLen, 0, par);
9ca155ba
M
1536}
1537
15c4dc5a 1538//-----------------------------------------------------------------------------
1539// Wait a certain time for tag response
1540// If a response is captured return TRUE
e691fc45 1541// If it takes too long return FALSE
15c4dc5a 1542//-----------------------------------------------------------------------------
e691fc45 1543static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint16_t offset, int maxLen, int *samples)
15c4dc5a 1544{
15c4dc5a 1545 int c;
e691fc45 1546
15c4dc5a 1547 // Set FPGA mode to "reader listen mode", no modulation (listen
534983d7 1548 // only, since we are receiving, not transmitting).
1549 // Signal field is on with the appropriate LED
1550 LED_D_ON();
1551 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1c611bbd 1552
534983d7 1553 // Now get the answer from the card
1554 Demod.output = receivedResponse;
1555 Demod.len = 0;
1556 Demod.state = DEMOD_UNSYNCD;
15c4dc5a 1557
f7e3ed82 1558 uint8_t b;
15c4dc5a 1559
1560 c = 0;
1561 for(;;) {
534983d7 1562 WDT_HIT();
15c4dc5a 1563
9492e0b0 1564 // if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1565 // AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1566 // if (elapsed) (*elapsed)++;
1567 // }
534983d7 1568 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1569 if(c < iso14a_timeout) { c++; } else { return FALSE; }
1570 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
e691fc45 1571 if(ManchesterDecoding(b, offset)) {
1572 *samples = Demod.samples;
15c4dc5a 1573 return TRUE;
1574 }
534983d7 1575 }
1576 }
15c4dc5a 1577}
1578
9492e0b0 1579void ReaderTransmitBitsPar(uint8_t* frame, int bits, uint32_t par, uint32_t *timing)
15c4dc5a 1580{
981bd429 1581
dfc3c505 1582 CodeIso14443aBitsAsReaderPar(frame,bits,par);
1583
e691fc45 1584 // Send command to tag
9492e0b0 1585 TransmitFor14443a(ToSend, ToSendMax, timing);
534983d7 1586 if(trigger)
1587 LED_A_ON();
dfc3c505 1588
e691fc45 1589 // Log reader command in trace buffer
dfc3c505 1590 if (tracing) LogTrace(frame,nbytes(bits),0,par,TRUE);
15c4dc5a 1591}
1592
9492e0b0 1593void ReaderTransmitPar(uint8_t* frame, int len, uint32_t par, uint32_t *timing)
dfc3c505 1594{
9492e0b0 1595 ReaderTransmitBitsPar(frame,len*8,par, timing);
dfc3c505 1596}
15c4dc5a 1597
e691fc45 1598void ReaderTransmitBits(uint8_t* frame, int len, uint32_t *timing)
1599{
1600 // Generate parity and redirect
1601 ReaderTransmitBitsPar(frame,len,GetParity(frame,len/8), timing);
1602}
1603
9492e0b0 1604void ReaderTransmit(uint8_t* frame, int len, uint32_t *timing)
15c4dc5a 1605{
1606 // Generate parity and redirect
9492e0b0 1607 ReaderTransmitBitsPar(frame,len*8,GetParity(frame,len), timing);
15c4dc5a 1608}
1609
e691fc45 1610int ReaderReceiveOffset(uint8_t* receivedAnswer, uint16_t offset)
1611{
1612 int samples = 0;
1613 if (!GetIso14443aAnswerFromTag(receivedAnswer,offset,160,&samples)) return FALSE;
1614 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1615 if(samples == 0) return FALSE;
1616 return Demod.len;
1617}
1618
f7e3ed82 1619int ReaderReceive(uint8_t* receivedAnswer)
15c4dc5a 1620{
e691fc45 1621 return ReaderReceiveOffset(receivedAnswer, 0);
15c4dc5a 1622}
1623
e691fc45 1624int ReaderReceivePar(uint8_t *receivedAnswer, uint32_t *parptr)
f89c7050 1625{
e691fc45 1626 int samples = 0;
1627 if (!GetIso14443aAnswerFromTag(receivedAnswer,0,160,&samples)) return FALSE;
1628 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
f89c7050 1629 *parptr = Demod.parityBits;
e691fc45 1630 if(samples == 0) return FALSE;
1631 return Demod.len;
f89c7050
M
1632}
1633
e691fc45 1634/* performs iso14443a anticollision procedure
534983d7 1635 * fills the uid pointer unless NULL
1636 * fills resp_data unless NULL */
79a73ab2 1637int iso14443a_select_card(byte_t* uid_ptr, iso14a_card_select_t* p_hi14a_card, uint32_t* cuid_ptr) {
ed258538 1638 uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1639 uint8_t sel_all[] = { 0x93,0x20 };
e691fc45 1640 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
ed258538 1641 uint8_t rats[] = { 0xE0,0x80,0x00,0x00 }; // FSD=256, FSDI=8, CID=0
1642 uint8_t* resp = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET); // was 3560 - tied to other size changes
79a73ab2 1643 byte_t uid_resp[4];
1644 size_t uid_resp_len;
15c4dc5a 1645
ed258538 1646 uint8_t sak = 0x04; // cascade uid
1647 int cascade_level = 0;
1648 int len;
79a73ab2 1649
ed258538 1650 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
9492e0b0 1651 ReaderTransmitBitsPar(wupa,7,0, NULL);
ed258538 1652 // Receive the ATQA
1653 if(!ReaderReceive(resp)) return 0;
e691fc45 1654 // Dbprintf("atqa: %02x %02x",resp[0],resp[1]);
1c611bbd 1655
ed258538 1656 if(p_hi14a_card) {
1657 memcpy(p_hi14a_card->atqa, resp, 2);
79a73ab2 1658 p_hi14a_card->uidlen = 0;
1659 memset(p_hi14a_card->uid,0,10);
1660 }
5f6d6c90 1661
79a73ab2 1662 // clear uid
1663 if (uid_ptr) {
1c611bbd 1664 memset(uid_ptr,0,10);
79a73ab2 1665 }
1666
ed258538 1667 // OK we will select at least at cascade 1, lets see if first byte of UID was 0x88 in
1668 // which case we need to make a cascade 2 request and select - this is a long UID
1669 // While the UID is not complete, the 3nd bit (from the right) is set in the SAK.
1670 for(; sak & 0x04; cascade_level++) {
1671 // SELECT_* (L1: 0x93, L2: 0x95, L3: 0x97)
1672 sel_uid[0] = sel_all[0] = 0x93 + cascade_level * 2;
1673
1674 // SELECT_ALL
9492e0b0 1675 ReaderTransmit(sel_all,sizeof(sel_all), NULL);
ed258538 1676 if (!ReaderReceive(resp)) return 0;
5f6d6c90 1677
e691fc45 1678 if (Demod.collisionPos) { // we had a collision and need to construct the UID bit by bit
1679 memset(uid_resp, 0, 4);
1680 uint16_t uid_resp_bits = 0;
1681 uint16_t collision_answer_offset = 0;
1682 // anti-collision-loop:
1683 while (Demod.collisionPos) {
1684 Dbprintf("Multiple tags detected. Collision after Bit %d", Demod.collisionPos);
1685 for (uint16_t i = collision_answer_offset; i < Demod.collisionPos; i++, uid_resp_bits++) { // add valid UID bits before collision point
1686 uint16_t UIDbit = (resp[i/8] >> (i % 8)) & 0x01;
1687 uid_resp[uid_resp_bits & 0xf8] |= UIDbit << (uid_resp_bits % 8);
1688 }
1689 uid_resp[uid_resp_bits/8] |= 1 << (uid_resp_bits % 8); // next time select the card(s) with a 1 in the collision position
1690 uid_resp_bits++;
1691 // construct anticollosion command:
1692 sel_uid[1] = ((2 + uid_resp_bits/8) << 4) | (uid_resp_bits & 0x07); // length of data in bytes and bits
1693 for (uint16_t i = 0; i <= uid_resp_bits/8; i++) {
1694 sel_uid[2+i] = uid_resp[i];
1695 }
1696 collision_answer_offset = uid_resp_bits%8;
1697 ReaderTransmitBits(sel_uid, 16 + uid_resp_bits, NULL);
1698 if (!ReaderReceiveOffset(resp, collision_answer_offset)) return 0;
1699 }
1700 // finally, add the last bits and BCC of the UID
1701 for (uint16_t i = collision_answer_offset; i < (Demod.len-1)*8; i++, uid_resp_bits++) {
1702 uint16_t UIDbit = (resp[i/8] >> (i%8)) & 0x01;
1703 uid_resp[uid_resp_bits/8] |= UIDbit << (uid_resp_bits % 8);
1704 }
1705
1706 } else { // no collision, use the response to SELECT_ALL as current uid
1707 memcpy(uid_resp,resp,4);
1708 }
1709 uid_resp_len = 4;
79a73ab2 1710 // Dbprintf("uid: %02x %02x %02x %02x",uid_resp[0],uid_resp[1],uid_resp[2],uid_resp[3]);
5f6d6c90 1711
e691fc45 1712 // calculate crypto UID. Always use last 4 Bytes.
5f6d6c90 1713 if(cuid_ptr) {
1714 *cuid_ptr = bytes_to_num(uid_resp, 4);
79a73ab2 1715 }
e30c654b 1716
ed258538 1717 // Construct SELECT UID command
e691fc45 1718 sel_uid[1] = 0x70; // transmitting a full UID (1 Byte cmd, 1 Byte NVB, 4 Byte UID, 1 Byte BCC, 2 Bytes CRC)
1719 memcpy(sel_uid+2,uid_resp,4); // the UID
1720 sel_uid[6] = sel_uid[2] ^ sel_uid[3] ^ sel_uid[4] ^ sel_uid[5]; // calculate and add BCC
1721 AppendCrc14443a(sel_uid,7); // calculate and add CRC
9492e0b0 1722 ReaderTransmit(sel_uid,sizeof(sel_uid), NULL);
534983d7 1723
ed258538 1724 // Receive the SAK
1725 if (!ReaderReceive(resp)) return 0;
1726 sak = resp[0];
79a73ab2 1727
1728 // Test if more parts of the uid are comming
e691fc45 1729 if ((sak & 0x04) /* && uid_resp[0] == 0x88 */) {
79a73ab2 1730 // Remove first byte, 0x88 is not an UID byte, it CT, see page 3 of:
1731 // http://www.nxp.com/documents/application_note/AN10927.pdf
ed258538 1732 memcpy(uid_resp, uid_resp + 1, 3);
79a73ab2 1733 uid_resp_len = 3;
1734 }
5f6d6c90 1735
79a73ab2 1736 if(uid_ptr) {
1737 memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len);
1738 }
5f6d6c90 1739
79a73ab2 1740 if(p_hi14a_card) {
1741 memcpy(p_hi14a_card->uid + (cascade_level*3), uid_resp, uid_resp_len);
1742 p_hi14a_card->uidlen += uid_resp_len;
1743 }
ed258538 1744 }
79a73ab2 1745
ed258538 1746 if(p_hi14a_card) {
1747 p_hi14a_card->sak = sak;
1748 p_hi14a_card->ats_len = 0;
1749 }
534983d7 1750
ed258538 1751 if( (sak & 0x20) == 0) {
1752 return 2; // non iso14443a compliant tag
79a73ab2 1753 }
534983d7 1754
ed258538 1755 // Request for answer to select
5191b3d1 1756 AppendCrc14443a(rats, 2);
9492e0b0 1757 ReaderTransmit(rats, sizeof(rats), NULL);
1c611bbd 1758
5191b3d1 1759 if (!(len = ReaderReceive(resp))) return 0;
1760
1761 if(p_hi14a_card) {
ed258538 1762 memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats));
1763 p_hi14a_card->ats_len = len;
1764 }
5f6d6c90 1765
ed258538 1766 // reset the PCB block number
1767 iso14_pcb_blocknum = 0;
1768 return 1;
7e758047 1769}
15c4dc5a 1770
7e758047 1771void iso14443a_setup() {
9492e0b0 1772 // Set up the synchronous serial port
1773 FpgaSetupSsc();
7e758047 1774 // Start from off (no field generated)
1775 // Signal field is off with the appropriate LED
9492e0b0 1776// LED_D_OFF();
1777// FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1778 // SpinDelay(50);
15c4dc5a 1779
7e758047 1780 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
e30c654b 1781
7e758047 1782 // Now give it time to spin up.
1783 // Signal field is on with the appropriate LED
1784 LED_D_ON();
1785 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
9492e0b0 1786 SpinDelay(7); // iso14443-3 specifies 5ms max.
534983d7 1787
e691fc45 1788 Demod.state = DEMOD_UNSYNCD;
534983d7 1789 iso14a_timeout = 2048; //default
7e758047 1790}
15c4dc5a 1791
534983d7 1792int iso14_apdu(uint8_t * cmd, size_t cmd_len, void * data) {
1793 uint8_t real_cmd[cmd_len+4];
1794 real_cmd[0] = 0x0a; //I-Block
b0127e65 1795 // put block number into the PCB
1796 real_cmd[0] |= iso14_pcb_blocknum;
534983d7 1797 real_cmd[1] = 0x00; //CID: 0 //FIXME: allow multiple selected cards
1798 memcpy(real_cmd+2, cmd, cmd_len);
1799 AppendCrc14443a(real_cmd,cmd_len+2);
1800
9492e0b0 1801 ReaderTransmit(real_cmd, cmd_len+4, NULL);
534983d7 1802 size_t len = ReaderReceive(data);
b0127e65 1803 uint8_t * data_bytes = (uint8_t *) data;
1804 if (!len)
1805 return 0; //DATA LINK ERROR
1806 // if we received an I- or R(ACK)-Block with a block number equal to the
1807 // current block number, toggle the current block number
1808 else if (len >= 4 // PCB+CID+CRC = 4 bytes
1809 && ((data_bytes[0] & 0xC0) == 0 // I-Block
1810 || (data_bytes[0] & 0xD0) == 0x80) // R-Block with ACK bit set to 0
1811 && (data_bytes[0] & 0x01) == iso14_pcb_blocknum) // equal block numbers
1812 {
1813 iso14_pcb_blocknum ^= 1;
1814 }
1815
534983d7 1816 return len;
1817}
1818
7e758047 1819//-----------------------------------------------------------------------------
1820// Read an ISO 14443a tag. Send out commands and store answers.
1821//
1822//-----------------------------------------------------------------------------
902cb3c0 1823void ReaderIso14443a(UsbCommand * c)
7e758047 1824{
534983d7 1825 iso14a_command_t param = c->arg[0];
1826 uint8_t * cmd = c->d.asBytes;
1827 size_t len = c->arg[1];
5f6d6c90 1828 size_t lenbits = c->arg[2];
9492e0b0 1829 uint32_t arg0 = 0;
1830 byte_t buf[USB_CMD_DATA_SIZE];
902cb3c0 1831
5f6d6c90 1832 if(param & ISO14A_CONNECT) {
1833 iso14a_clear_trace();
1834 }
e691fc45 1835
9492e0b0 1836 iso14a_set_tracing(true);
e30c654b 1837
79a73ab2 1838 if(param & ISO14A_REQUEST_TRIGGER) {
9492e0b0 1839 iso14a_set_trigger(1);
1840 }
15c4dc5a 1841
534983d7 1842 if(param & ISO14A_CONNECT) {
1843 iso14443a_setup();
5f6d6c90 1844 if(!(param & ISO14A_NO_SELECT)) {
1845 iso14a_card_select_t *card = (iso14a_card_select_t*)buf;
1846 arg0 = iso14443a_select_card(NULL,card,NULL);
1847 cmd_send(CMD_ACK,arg0,card->uidlen,0,buf,sizeof(iso14a_card_select_t));
1848 }
534983d7 1849 }
e30c654b 1850
534983d7 1851 if(param & ISO14A_SET_TIMEOUT) {
1852 iso14a_timeout = c->arg[2];
1853 }
e30c654b 1854
534983d7 1855 if(param & ISO14A_SET_TIMEOUT) {
1856 iso14a_timeout = c->arg[2];
1857 }
e30c654b 1858
534983d7 1859 if(param & ISO14A_APDU) {
902cb3c0 1860 arg0 = iso14_apdu(cmd, len, buf);
79a73ab2 1861 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
534983d7 1862 }
e30c654b 1863
534983d7 1864 if(param & ISO14A_RAW) {
1865 if(param & ISO14A_APPEND_CRC) {
1866 AppendCrc14443a(cmd,len);
1867 len += 2;
15c4dc5a 1868 }
5f6d6c90 1869 if(lenbits>0) {
1870 ReaderTransmitBitsPar(cmd,lenbits,GetParity(cmd,lenbits/8), NULL);
1871 } else {
1872 ReaderTransmit(cmd,len, NULL);
1873 }
902cb3c0 1874 arg0 = ReaderReceive(buf);
9492e0b0 1875 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
534983d7 1876 }
15c4dc5a 1877
79a73ab2 1878 if(param & ISO14A_REQUEST_TRIGGER) {
9492e0b0 1879 iso14a_set_trigger(0);
1880 }
15c4dc5a 1881
79a73ab2 1882 if(param & ISO14A_NO_DISCONNECT) {
534983d7 1883 return;
9492e0b0 1884 }
15c4dc5a 1885
15c4dc5a 1886 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1887 LEDsoff();
15c4dc5a 1888}
b0127e65 1889
1c611bbd 1890
1c611bbd 1891// Determine the distance between two nonces.
1892// Assume that the difference is small, but we don't know which is first.
1893// Therefore try in alternating directions.
1894int32_t dist_nt(uint32_t nt1, uint32_t nt2) {
1895
1896 uint16_t i;
1897 uint32_t nttmp1, nttmp2;
e772353f 1898
1c611bbd 1899 if (nt1 == nt2) return 0;
1900
1901 nttmp1 = nt1;
1902 nttmp2 = nt2;
1903
1904 for (i = 1; i < 32768; i++) {
1905 nttmp1 = prng_successor(nttmp1, 1);
1906 if (nttmp1 == nt2) return i;
1907 nttmp2 = prng_successor(nttmp2, 1);
1908 if (nttmp2 == nt1) return -i;
1909 }
1910
1911 return(-99999); // either nt1 or nt2 are invalid nonces
e772353f 1912}
1913
e772353f 1914
1c611bbd 1915//-----------------------------------------------------------------------------
1916// Recover several bits of the cypher stream. This implements (first stages of)
1917// the algorithm described in "The Dark Side of Security by Obscurity and
1918// Cloning MiFare Classic Rail and Building Passes, Anywhere, Anytime"
1919// (article by Nicolas T. Courtois, 2009)
1920//-----------------------------------------------------------------------------
1921void ReaderMifare(bool first_try)
1922{
1923 // Mifare AUTH
1924 uint8_t mf_auth[] = { 0x60,0x00,0xf5,0x7b };
1925 uint8_t mf_nr_ar[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 };
1926 static uint8_t mf_nr_ar3;
e772353f 1927
1c611bbd 1928 uint8_t* receivedAnswer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
1929 traceLen = 0;
1930 tracing = false;
e772353f 1931
1c611bbd 1932 byte_t nt_diff = 0;
1933 byte_t par = 0;
1934 //byte_t par_mask = 0xff;
1935 static byte_t par_low = 0;
1936 bool led_on = TRUE;
1937 uint8_t uid[10];
1938 uint32_t cuid;
e772353f 1939
1c611bbd 1940 uint32_t nt, previous_nt;
1941 static uint32_t nt_attacked = 0;
1942 byte_t par_list[8] = {0,0,0,0,0,0,0,0};
1943 byte_t ks_list[8] = {0,0,0,0,0,0,0,0};
e772353f 1944
1c611bbd 1945 static uint32_t sync_time;
1946 static uint32_t sync_cycles;
1947 int catch_up_cycles = 0;
1948 int last_catch_up = 0;
1949 uint16_t consecutive_resyncs = 0;
1950 int isOK = 0;
e772353f 1951
e772353f 1952
e772353f 1953
1c611bbd 1954 if (first_try) {
1955 StartCountMifare();
1956 mf_nr_ar3 = 0;
1957 iso14443a_setup();
1c611bbd 1958 while((GetCountMifare() & 0xffff0000) != 0x10000); // wait for counter to reset and "warm up"
9492e0b0 1959 sync_time = GetCountMifare() & 0xfffffff8;
1c611bbd 1960 sync_cycles = 65536; // theory: Mifare Classic's random generator repeats every 2^16 cycles (and so do the nonces).
1961 nt_attacked = 0;
1962 nt = 0;
1963 par = 0;
1964 }
1965 else {
1966 // we were unsuccessful on a previous call. Try another READER nonce (first 3 parity bits remain the same)
1967 // nt_attacked = prng_successor(nt_attacked, 1);
1968 mf_nr_ar3++;
1969 mf_nr_ar[3] = mf_nr_ar3;
1970 par = par_low;
1971 }
e30c654b 1972
15c4dc5a 1973 LED_A_ON();
1974 LED_B_OFF();
1975 LED_C_OFF();
1c611bbd 1976
1977
1978 for(uint16_t i = 0; TRUE; i++) {
1979
1980 WDT_HIT();
e30c654b 1981
1c611bbd 1982 // Test if the action was cancelled
1983 if(BUTTON_PRESS()) {
1984 break;
1985 }
1986
1987 LED_C_ON();
e30c654b 1988
1c611bbd 1989 if(!iso14443a_select_card(uid, NULL, &cuid)) {
9492e0b0 1990 if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card");
1c611bbd 1991 continue;
1992 }
1993
1994 //keep the card active
f89c7050 1995 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
e30c654b 1996
9492e0b0 1997 sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles;
1c611bbd 1998 catch_up_cycles = 0;
1999
2000 // if we missed the sync time already, advance to the next nonce repeat
2001 while(GetCountMifare() > sync_time) {
9492e0b0 2002 sync_time = (sync_time & 0xfffffff8) + sync_cycles;
1c611bbd 2003 }
e30c654b 2004
9492e0b0 2005 // Transmit MIFARE_CLASSIC_AUTH at synctime. Should result in returning the same tag nonce (== nt_attacked)
2006 ReaderTransmit(mf_auth, sizeof(mf_auth), &sync_time);
f89c7050 2007
1c611bbd 2008 // Receive the (4 Byte) "random" nonce
2009 if (!ReaderReceive(receivedAnswer)) {
9492e0b0 2010 if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Couldn't receive tag nonce");
1c611bbd 2011 continue;
2012 }
2013
1c611bbd 2014 previous_nt = nt;
2015 nt = bytes_to_num(receivedAnswer, 4);
2016
2017 // Transmit reader nonce with fake par
9492e0b0 2018 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
1c611bbd 2019
2020 if (first_try && previous_nt && !nt_attacked) { // we didn't calibrate our clock yet
2021 int nt_distance = dist_nt(previous_nt, nt);
2022 if (nt_distance == 0) {
2023 nt_attacked = nt;
2024 }
2025 else {
2026 if (nt_distance == -99999) { // invalid nonce received, try again
2027 continue;
2028 }
2029 sync_cycles = (sync_cycles - nt_distance);
9492e0b0 2030 if (MF_DBGLEVEL >= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i, nt_distance, sync_cycles);
1c611bbd 2031 continue;
2032 }
2033 }
2034
2035 if ((nt != nt_attacked) && nt_attacked) { // we somehow lost sync. Try to catch up again...
2036 catch_up_cycles = -dist_nt(nt_attacked, nt);
2037 if (catch_up_cycles == 99999) { // invalid nonce received. Don't resync on that one.
2038 catch_up_cycles = 0;
2039 continue;
2040 }
2041 if (catch_up_cycles == last_catch_up) {
2042 consecutive_resyncs++;
2043 }
2044 else {
2045 last_catch_up = catch_up_cycles;
2046 consecutive_resyncs = 0;
2047 }
2048 if (consecutive_resyncs < 3) {
9492e0b0 2049 if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d. nt_distance=%d. Consecutive Resyncs = %d. Trying one time catch up...\n", i, -catch_up_cycles, consecutive_resyncs);
1c611bbd 2050 }
2051 else {
2052 sync_cycles = sync_cycles + catch_up_cycles;
9492e0b0 2053 if (MF_DBGLEVEL >= 3) Dbprintf("Lost sync in cycle %d for the fourth time consecutively (nt_distance = %d). Adjusting sync_cycles to %d.\n", i, -catch_up_cycles, sync_cycles);
1c611bbd 2054 }
2055 continue;
2056 }
2057
2058 consecutive_resyncs = 0;
2059
2060 // Receive answer. This will be a 4 Bit NACK when the 8 parity bits are OK after decoding
2061 if (ReaderReceive(receivedAnswer))
2062 {
9492e0b0 2063 catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
1c611bbd 2064
2065 if (nt_diff == 0)
2066 {
2067 par_low = par & 0x07; // there is no need to check all parities for other nt_diff. Parity Bits for mf_nr_ar[0..2] won't change
2068 }
2069
2070 led_on = !led_on;
2071 if(led_on) LED_B_ON(); else LED_B_OFF();
2072
2073 par_list[nt_diff] = par;
2074 ks_list[nt_diff] = receivedAnswer[0] ^ 0x05;
2075
2076 // Test if the information is complete
2077 if (nt_diff == 0x07) {
2078 isOK = 1;
2079 break;
2080 }
2081
2082 nt_diff = (nt_diff + 1) & 0x07;
2083 mf_nr_ar[3] = (mf_nr_ar[3] & 0x1F) | (nt_diff << 5);
2084 par = par_low;
2085 } else {
2086 if (nt_diff == 0 && first_try)
2087 {
2088 par++;
2089 } else {
2090 par = (((par >> 3) + 1) << 3) | par_low;
2091 }
2092 }
2093 }
2094
2095 LogTrace((const uint8_t *)&nt, 4, 0, GetParity((const uint8_t *)&nt, 4), TRUE);
2096 LogTrace(par_list, 8, 0, GetParity(par_list, 8), TRUE);
2097 LogTrace(ks_list, 8, 0, GetParity(ks_list, 8), TRUE);
2098
2099 mf_nr_ar[3] &= 0x1F;
2100
2101 byte_t buf[28];
2102 memcpy(buf + 0, uid, 4);
2103 num_to_bytes(nt, 4, buf + 4);
2104 memcpy(buf + 8, par_list, 8);
2105 memcpy(buf + 16, ks_list, 8);
2106 memcpy(buf + 24, mf_nr_ar, 4);
2107
2108 cmd_send(CMD_ACK,isOK,0,0,buf,28);
2109
2110 // Thats it...
2111 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2112 LEDsoff();
2113 tracing = TRUE;
20f9a2a1 2114}
1c611bbd 2115
20f9a2a1
M
2116//-----------------------------------------------------------------------------
2117// MIFARE 1K simulate.
2118//
2119//-----------------------------------------------------------------------------
2120void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
2121{
50193c1e 2122 int cardSTATE = MFEMUL_NOFIELD;
8556b852 2123 int _7BUID = 0;
9ca155ba 2124 int vHf = 0; // in mV
9f693930 2125 //int nextCycleTimeout = 0;
8f51ddb0 2126 int res;
51969283 2127// uint32_t timer = 0;
0a39986e
M
2128 uint32_t selTimer = 0;
2129 uint32_t authTimer = 0;
2130 uint32_t par = 0;
9ca155ba 2131 int len = 0;
8f51ddb0 2132 uint8_t cardWRBL = 0;
9ca155ba
M
2133 uint8_t cardAUTHSC = 0;
2134 uint8_t cardAUTHKEY = 0xff; // no authentication
9f693930 2135 //uint32_t cardRn = 0;
51969283 2136 uint32_t cardRr = 0;
9ca155ba 2137 uint32_t cuid = 0;
af1caf6e 2138 uint32_t rn_enc = 0;
51969283 2139 uint32_t ans = 0;
0014cb46
M
2140 uint32_t cardINTREG = 0;
2141 uint8_t cardINTBLOCK = 0;
9ca155ba
M
2142 struct Crypto1State mpcs = {0, 0};
2143 struct Crypto1State *pcs;
2144 pcs = &mpcs;
2145
8f51ddb0
M
2146 uint8_t* receivedCmd = eml_get_bigbufptr_recbuf();
2147 uint8_t *response = eml_get_bigbufptr_sendbuf();
9ca155ba 2148
8556b852 2149 static uint8_t rATQA[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
9ca155ba 2150
0a39986e
M
2151 static uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2152 static uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
9ca155ba 2153
0a39986e 2154 static uint8_t rSAK[] = {0x08, 0xb6, 0xdd};
8556b852 2155 static uint8_t rSAK1[] = {0x04, 0xda, 0x17};
9ca155ba 2156
0014cb46
M
2157 static uint8_t rAUTH_NT[] = {0x01, 0x02, 0x03, 0x04};
2158// static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
0a39986e 2159 static uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
0014cb46 2160
0a39986e
M
2161 // clear trace
2162 traceLen = 0;
2163 tracing = true;
51969283
M
2164
2165 // Authenticate response - nonce
2166 uint32_t nonce = bytes_to_num(rAUTH_NT, 4);
9ca155ba 2167
8556b852
M
2168 // get UID from emul memory
2169 emlGetMemBt(receivedCmd, 7, 1);
2170 _7BUID = !(receivedCmd[0] == 0x00);
2171 if (!_7BUID) { // ---------- 4BUID
2172 rATQA[0] = 0x04;
2173
2174 emlGetMemBt(rUIDBCC1, 0, 4);
2175 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
2176 } else { // ---------- 7BUID
2177 rATQA[0] = 0x44;
2178
2179 rUIDBCC1[0] = 0x88;
2180 emlGetMemBt(&rUIDBCC1[1], 0, 3);
2181 rUIDBCC1[4] = rUIDBCC1[0] ^ rUIDBCC1[1] ^ rUIDBCC1[2] ^ rUIDBCC1[3];
2182 emlGetMemBt(rUIDBCC2, 3, 4);
2183 rUIDBCC2[4] = rUIDBCC2[0] ^ rUIDBCC2[1] ^ rUIDBCC2[2] ^ rUIDBCC2[3];
2184 }
2185
9ca155ba 2186// -------------------------------------- test area
50193c1e 2187
9ca155ba 2188// -------------------------------------- END test area
8f51ddb0
M
2189 // start mkseconds counter
2190 StartCountUS();
9ca155ba
M
2191
2192 // We need to listen to the high-frequency, peak-detected path.
2193 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
2194 FpgaSetupSsc();
2195
2196 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
2197 SpinDelay(200);
2198
0014cb46 2199 if (MF_DBGLEVEL >= 1) Dbprintf("Started. 7buid=%d", _7BUID);
8f51ddb0
M
2200 // calibrate mkseconds counter
2201 GetDeltaCountUS();
9ca155ba
M
2202 while (true) {
2203 WDT_HIT();
9ca155ba 2204
8f51ddb0
M
2205 if(BUTTON_PRESS()) {
2206 break;
2207 }
2208
9ca155ba
M
2209 // find reader field
2210 // Vref = 3300mV, and an 10:1 voltage divider on the input
2211 // can measure voltages up to 33000 mV
2212 if (cardSTATE == MFEMUL_NOFIELD) {
2213 vHf = (33000 * AvgAdc(ADC_CHAN_HF)) >> 10;
2214 if (vHf > MF_MINFIELDV) {
0014cb46 2215 cardSTATE_TO_IDLE();
9ca155ba
M
2216 LED_A_ON();
2217 }
2218 }
2219
2220 if (cardSTATE != MFEMUL_NOFIELD) {
81cd0474 2221 res = EmGetCmd(receivedCmd, &len, RECV_CMD_SIZE); // (+ nextCycleTimeout)
9ca155ba
M
2222 if (res == 2) {
2223 cardSTATE = MFEMUL_NOFIELD;
2224 LEDsoff();
2225 continue;
2226 }
2227 if(res) break;
2228 }
2229
9f693930 2230 //nextCycleTimeout = 0;
8f51ddb0 2231
9ca155ba 2232// if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
0a39986e
M
2233
2234 if (len != 4 && cardSTATE != MFEMUL_NOFIELD) { // len != 4 <---- speed up the code 4 authentication
8f51ddb0 2235 // REQ or WUP request in ANY state and WUP in HALTED state
0a39986e
M
2236 if (len == 1 && ((receivedCmd[0] == 0x26 && cardSTATE != MFEMUL_HALTED) || receivedCmd[0] == 0x52)) {
2237 selTimer = GetTickCount();
2238 EmSendCmdEx(rATQA, sizeof(rATQA), (receivedCmd[0] == 0x52));
2239 cardSTATE = MFEMUL_SELECT1;
2240
2241 // init crypto block
2242 LED_B_OFF();
2243 LED_C_OFF();
2244 crypto1_destroy(pcs);
2245 cardAUTHKEY = 0xff;
2246 }
2247 }
9ca155ba 2248
50193c1e
M
2249 switch (cardSTATE) {
2250 case MFEMUL_NOFIELD:{
2251 break;
2252 }
9ca155ba 2253 case MFEMUL_HALTED:{
0a39986e 2254 break;
9ca155ba 2255 }
50193c1e
M
2256 case MFEMUL_IDLE:{
2257 break;
2258 }
2259 case MFEMUL_SELECT1:{
9ca155ba
M
2260 // select all
2261 if (len == 2 && (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x20)) {
2262 EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
0014cb46 2263 break;
9ca155ba
M
2264 }
2265
2266 // select card
0a39986e
M
2267 if (len == 9 &&
2268 (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
8556b852
M
2269 if (!_7BUID)
2270 EmSendCmd(rSAK, sizeof(rSAK));
2271 else
2272 EmSendCmd(rSAK1, sizeof(rSAK1));
9ca155ba
M
2273
2274 cuid = bytes_to_num(rUIDBCC1, 4);
8556b852
M
2275 if (!_7BUID) {
2276 cardSTATE = MFEMUL_WORK;
0014cb46
M
2277 LED_B_ON();
2278 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
2279 break;
8556b852
M
2280 } else {
2281 cardSTATE = MFEMUL_SELECT2;
2282 break;
2283 }
9ca155ba
M
2284 }
2285
50193c1e
M
2286 break;
2287 }
2288 case MFEMUL_SELECT2:{
0014cb46
M
2289 if (!len) break;
2290
8556b852 2291 if (len == 2 && (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x20)) {
9ca155ba 2292 EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
8556b852
M
2293 break;
2294 }
9ca155ba 2295
8556b852
M
2296 // select 2 card
2297 if (len == 9 &&
2298 (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC2, 4) == 0)) {
2299 EmSendCmd(rSAK, sizeof(rSAK));
2300
2301 cuid = bytes_to_num(rUIDBCC2, 4);
2302 cardSTATE = MFEMUL_WORK;
2303 LED_B_ON();
0014cb46 2304 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer);
8556b852
M
2305 break;
2306 }
0014cb46
M
2307
2308 // i guess there is a command). go into the work state.
2309 if (len != 4) break;
2310 cardSTATE = MFEMUL_WORK;
2311 goto lbWORK;
50193c1e
M
2312 }
2313 case MFEMUL_AUTH1:{
9ca155ba 2314 if (len == 8) {
51969283 2315 // --- crypto
af1caf6e 2316 rn_enc = bytes_to_num(receivedCmd, 4);
2317 crypto1_word(pcs, rn_enc , 1);
51969283
M
2318 cardRr = bytes_to_num(&receivedCmd[4], 4) ^ crypto1_word(pcs, 0, 0);
2319 // test if auth OK
2320 if (cardRr != prng_successor(nonce, 64)){
0014cb46
M
2321 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr, prng_successor(nonce, 64));
2322 cardSTATE_TO_IDLE();
51969283
M
2323 break;
2324 }
2325 ans = prng_successor(nonce, 96) ^ crypto1_word(pcs, 0, 0);
2326 num_to_bytes(ans, 4, rAUTH_AT);
2327 // --- crypto
2328 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
0a39986e
M
2329 cardSTATE = MFEMUL_AUTH2;
2330 } else {
0014cb46 2331 cardSTATE_TO_IDLE();
9ca155ba 2332 }
0a39986e 2333 if (cardSTATE != MFEMUL_AUTH2) break;
50193c1e
M
2334 }
2335 case MFEMUL_AUTH2:{
9ca155ba 2336 LED_C_ON();
0a39986e 2337 cardSTATE = MFEMUL_WORK;
0014cb46 2338 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC, cardAUTHKEY, GetTickCount() - authTimer);
50193c1e
M
2339 break;
2340 }
9ca155ba 2341 case MFEMUL_WORK:{
0014cb46 2342lbWORK: if (len == 0) break;
0a39986e 2343
51969283
M
2344 if (cardAUTHKEY == 0xff) {
2345 // first authentication
2346 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2347 authTimer = GetTickCount();
2348
2349 cardAUTHSC = receivedCmd[1] / 4; // received block num
2350 cardAUTHKEY = receivedCmd[0] - 0x60;
2351
2352 // --- crypto
2353 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
2354 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
2355 num_to_bytes(nonce, 4, rAUTH_AT);
2356 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2357 // --- crypto
2358
2359// last working revision
2360// EmSendCmd14443aRaw(resp1, resp1Len, 0);
2361// LogTrace(NULL, 0, GetDeltaCountUS(), 0, true);
2362
2363 cardSTATE = MFEMUL_AUTH1;
9f693930 2364 //nextCycleTimeout = 10;
51969283
M
2365 break;
2366 }
2367 } else {
2368 // decrypt seqence
2369 mf_crypto1_decrypt(pcs, receivedCmd, len);
2370
2371 // nested authentication
2372 if (len == 4 && (receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61)) {
2373 authTimer = GetTickCount();
2374
2375 cardAUTHSC = receivedCmd[1] / 4; // received block num
2376 cardAUTHKEY = receivedCmd[0] - 0x60;
2377
2378 // --- crypto
2379 crypto1_create(pcs, emlGetKey(cardAUTHSC, cardAUTHKEY));
2380 ans = nonce ^ crypto1_word(pcs, cuid ^ nonce, 0);
2381 num_to_bytes(ans, 4, rAUTH_AT);
2382 EmSendCmd(rAUTH_AT, sizeof(rAUTH_AT));
2383 // --- crypto
2384
2385 cardSTATE = MFEMUL_AUTH1;
9f693930 2386 //nextCycleTimeout = 10;
51969283
M
2387 break;
2388 }
2389 }
0a39986e 2390
8f51ddb0
M
2391 // rule 13 of 7.5.3. in ISO 14443-4. chaining shall be continued
2392 // BUT... ACK --> NACK
2393 if (len == 1 && receivedCmd[0] == CARD_ACK) {
2394 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2395 break;
2396 }
2397
2398 // rule 12 of 7.5.3. in ISO 14443-4. R(NAK) --> R(ACK)
2399 if (len == 1 && receivedCmd[0] == CARD_NACK_NA) {
2400 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2401 break;
0a39986e
M
2402 }
2403
2404 // read block
2405 if (len == 4 && receivedCmd[0] == 0x30) {
51969283 2406 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
8f51ddb0
M
2407 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2408 break;
2409 }
2410 emlGetMem(response, receivedCmd[1], 1);
2411 AppendCrc14443a(response, 16);
2412 mf_crypto1_encrypt(pcs, response, 18, &par);
2413 EmSendCmdPar(response, 18, par);
0a39986e
M
2414 break;
2415 }
2416
2417 // write block
2418 if (len == 4 && receivedCmd[0] == 0xA0) {
51969283 2419 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
8f51ddb0
M
2420 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2421 break;
2422 }
2423 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
9f693930 2424 //nextCycleTimeout = 50;
8f51ddb0
M
2425 cardSTATE = MFEMUL_WRITEBL2;
2426 cardWRBL = receivedCmd[1];
0a39986e 2427 break;
9ca155ba 2428 }
8f51ddb0 2429
0014cb46
M
2430 // works with cardINTREG
2431
2432 // increment, decrement, restore
2433 if (len == 4 && (receivedCmd[0] == 0xC0 || receivedCmd[0] == 0xC1 || receivedCmd[0] == 0xC2)) {
2434 if (receivedCmd[1] >= 16 * 4 ||
2435 receivedCmd[1] / 4 != cardAUTHSC ||
2436 emlCheckValBl(receivedCmd[1])) {
2437 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2438 break;
2439 }
2440 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2441 if (receivedCmd[0] == 0xC1)
2442 cardSTATE = MFEMUL_INTREG_INC;
2443 if (receivedCmd[0] == 0xC0)
2444 cardSTATE = MFEMUL_INTREG_DEC;
2445 if (receivedCmd[0] == 0xC2)
2446 cardSTATE = MFEMUL_INTREG_REST;
2447 cardWRBL = receivedCmd[1];
2448
2449 break;
2450 }
2451
2452
2453 // transfer
2454 if (len == 4 && receivedCmd[0] == 0xB0) {
2455 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
2456 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2457 break;
2458 }
2459
2460 if (emlSetValBl(cardINTREG, cardINTBLOCK, receivedCmd[1]))
2461 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2462 else
2463 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2464
2465 break;
2466 }
2467
9ca155ba 2468 // halt
0a39986e 2469 if (len == 4 && (receivedCmd[0] == 0x50 && receivedCmd[1] == 0x00)) {
9ca155ba 2470 LED_B_OFF();
0a39986e 2471 LED_C_OFF();
0014cb46
M
2472 cardSTATE = MFEMUL_HALTED;
2473 if (MF_DBGLEVEL >= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
0a39986e 2474 break;
9ca155ba 2475 }
51969283 2476
8f51ddb0
M
2477 // command not allowed
2478 if (len == 4) {
2479 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2480 break;
2481 }
51969283
M
2482
2483 // case break
2484 break;
8f51ddb0
M
2485 }
2486 case MFEMUL_WRITEBL2:{
2487 if (len == 18){
2488 mf_crypto1_decrypt(pcs, receivedCmd, len);
2489 emlSetMem(receivedCmd, cardWRBL, 1);
2490 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2491 cardSTATE = MFEMUL_WORK;
2492 break;
51969283 2493 } else {
0014cb46 2494 cardSTATE_TO_IDLE();
51969283 2495 break;
8f51ddb0 2496 }
8f51ddb0 2497 break;
50193c1e 2498 }
0014cb46
M
2499
2500 case MFEMUL_INTREG_INC:{
2501 mf_crypto1_decrypt(pcs, receivedCmd, len);
2502 memcpy(&ans, receivedCmd, 4);
2503 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2504 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2505 cardSTATE_TO_IDLE();
2506 break;
2507 }
2508 cardINTREG = cardINTREG + ans;
2509 cardSTATE = MFEMUL_WORK;
2510 break;
2511 }
2512 case MFEMUL_INTREG_DEC:{
2513 mf_crypto1_decrypt(pcs, receivedCmd, len);
2514 memcpy(&ans, receivedCmd, 4);
2515 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2516 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2517 cardSTATE_TO_IDLE();
2518 break;
2519 }
2520 cardINTREG = cardINTREG - ans;
2521 cardSTATE = MFEMUL_WORK;
2522 break;
2523 }
2524 case MFEMUL_INTREG_REST:{
2525 mf_crypto1_decrypt(pcs, receivedCmd, len);
2526 memcpy(&ans, receivedCmd, 4);
2527 if (emlGetValBl(&cardINTREG, &cardINTBLOCK, cardWRBL)) {
2528 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2529 cardSTATE_TO_IDLE();
2530 break;
2531 }
2532 cardSTATE = MFEMUL_WORK;
2533 break;
2534 }
50193c1e 2535 }
50193c1e
M
2536 }
2537
9ca155ba
M
2538 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2539 LEDsoff();
2540
0a39986e 2541 // add trace trailer
8f51ddb0 2542 memset(rAUTH_NT, 0x44, 4);
0a39986e
M
2543 LogTrace(rAUTH_NT, 4, 0, 0, TRUE);
2544
0014cb46 2545 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, traceLen);
15c4dc5a 2546}
b62a5a84
M
2547
2548//-----------------------------------------------------------------------------
2549// MIFARE sniffer.
2550//
2551//-----------------------------------------------------------------------------
5cd9ec01
M
2552void RAMFUNC SniffMifare(uint8_t param) {
2553 // param:
2554 // bit 0 - trigger from first card answer
2555 // bit 1 - trigger from first reader 7-bit request
39864b0b
M
2556
2557 // C(red) A(yellow) B(green)
b62a5a84
M
2558 LEDsoff();
2559 // init trace buffer
d19929cb 2560 iso14a_clear_trace();
b62a5a84 2561
b62a5a84
M
2562 // The command (reader -> tag) that we're receiving.
2563 // The length of a received command will in most cases be no more than 18 bytes.
2564 // So 32 should be enough!
2565 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
2566 // The response (tag -> reader) that we're receiving.
2567 uint8_t *receivedResponse = (((uint8_t *)BigBuf) + RECV_RES_OFFSET);
2568
2569 // As we receive stuff, we copy it from receivedCmd or receivedResponse
2570 // into trace, along with its length and other annotations.
2571 //uint8_t *trace = (uint8_t *)BigBuf;
2572
2573 // The DMA buffer, used to stream samples from the FPGA
2574 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
5cd9ec01
M
2575 int8_t *data = dmaBuf;
2576 int maxDataLen = 0;
2577 int dataLen = 0;
b62a5a84
M
2578
2579 // Set up the demodulator for tag -> reader responses.
2580 Demod.output = receivedResponse;
2581 Demod.len = 0;
2582 Demod.state = DEMOD_UNSYNCD;
2583
2584 // Set up the demodulator for the reader -> tag commands
2585 memset(&Uart, 0, sizeof(Uart));
2586 Uart.output = receivedCmd;
2587 Uart.byteCntMax = 32; // was 100 (greg)//////////////////
2588 Uart.state = STATE_UNSYNCD;
2589
2590 // Setup for the DMA.
2591 FpgaSetupSsc();
b62a5a84
M
2592 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
2593
2594 // And put the FPGA in the appropriate mode
2595 // Signal field is off with the appropriate LED
2596 LED_D_OFF();
2597 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
2598 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
39864b0b
M
2599
2600 // init sniffer
2601 MfSniffInit();
2602 int sniffCounter = 0;
b62a5a84 2603
b62a5a84
M
2604 // And now we loop, receiving samples.
2605 while(true) {
5cd9ec01
M
2606 if(BUTTON_PRESS()) {
2607 DbpString("cancelled by button");
2608 goto done;
2609 }
2610
b62a5a84
M
2611 LED_A_ON();
2612 WDT_HIT();
39864b0b
M
2613
2614 if (++sniffCounter > 65) {
2615 if (MfSniffSend(2000)) {
55acbb2a 2616 FpgaEnableSscDma();
39864b0b
M
2617 }
2618 sniffCounter = 0;
2619 }
5cd9ec01
M
2620
2621 int register readBufDataP = data - dmaBuf;
2622 int register dmaBufDataP = DMA_BUFFER_SIZE - AT91C_BASE_PDC_SSC->PDC_RCR;
2623 if (readBufDataP <= dmaBufDataP){
2624 dataLen = dmaBufDataP - readBufDataP;
2625 } else {
2626 dataLen = DMA_BUFFER_SIZE - readBufDataP + dmaBufDataP + 1;
2627 }
2628 // test for length of buffer
2629 if(dataLen > maxDataLen) {
2630 maxDataLen = dataLen;
2631 if(dataLen > 400) {
2632 Dbprintf("blew circular buffer! dataLen=0x%x", dataLen);
b62a5a84
M
2633 goto done;
2634 }
2635 }
5cd9ec01 2636 if(dataLen < 1) continue;
b62a5a84 2637
5cd9ec01
M
2638 // primary buffer was stopped( <-- we lost data!
2639 if (!AT91C_BASE_PDC_SSC->PDC_RCR) {
2640 AT91C_BASE_PDC_SSC->PDC_RPR = (uint32_t) dmaBuf;
2641 AT91C_BASE_PDC_SSC->PDC_RCR = DMA_BUFFER_SIZE;
55acbb2a 2642 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen); // temporary
5cd9ec01
M
2643 }
2644 // secondary buffer sets as primary, secondary buffer was stopped
2645 if (!AT91C_BASE_PDC_SSC->PDC_RNCR) {
2646 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf;
b62a5a84
M
2647 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
2648 }
5cd9ec01
M
2649
2650 LED_A_OFF();
b62a5a84 2651
5cd9ec01 2652 if(MillerDecoding((data[0] & 0xF0) >> 4)) {
39864b0b 2653 LED_C_INV();
5cd9ec01 2654 // check - if there is a short 7bit request from reader
71d90e54 2655 if (MfSniffLogic(receivedCmd, Uart.byteCnt, Uart.parityBits, Uart.bitCnt, TRUE)) break;
5cd9ec01 2656
b62a5a84
M
2657 /* And ready to receive another command. */
2658 Uart.state = STATE_UNSYNCD;
39864b0b
M
2659
2660 /* And also reset the demod code */
b62a5a84 2661 Demod.state = DEMOD_UNSYNCD;
b62a5a84
M
2662 }
2663
e691fc45 2664 if(ManchesterDecoding(data[0], 0)) {
39864b0b 2665 LED_C_INV();
b62a5a84 2666
71d90e54 2667 if (MfSniffLogic(receivedResponse, Demod.len, Demod.parityBits, Demod.bitCount, FALSE)) break;
b62a5a84
M
2668
2669 // And ready to receive another response.
2670 memset(&Demod, 0, sizeof(Demod));
2671 Demod.output = receivedResponse;
2672 Demod.state = DEMOD_UNSYNCD;
39864b0b
M
2673
2674 /* And also reset the uart code */
2675 Uart.state = STATE_UNSYNCD;
b62a5a84
M
2676 }
2677
5cd9ec01
M
2678 data++;
2679 if(data > dmaBuf + DMA_BUFFER_SIZE) {
2680 data = dmaBuf;
b62a5a84
M
2681 }
2682 } // main cycle
2683
2684 DbpString("COMMAND FINISHED");
2685
2686done:
55acbb2a 2687 FpgaDisableSscDma();
39864b0b
M
2688 MfSniffEnd();
2689
55acbb2a 2690 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen, Uart.state, Uart.byteCnt, Uart.byteCntMax);
b62a5a84 2691 LEDsoff();
3803d529 2692}
Impressum, Datenschutz