]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iso14443a.c
00dc622fdf0e1fd1d164b3e0e51378635334e007
[proxmark3-svn] / armsrc / iso14443a.c
1 //-----------------------------------------------------------------------------
2 // Merlok - June 2011, 2012
3 // Gerhard de Koning Gans - May 2008
4 // Hagen Fritsch - June 2010
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.
9 //-----------------------------------------------------------------------------
10 // Routines to support ISO 14443 type A.
11 //-----------------------------------------------------------------------------
12
13 #include "proxmark3.h"
14 #include "apps.h"
15 #include "util.h"
16 #include "string.h"
17 #include "cmd.h"
18
19 #include "iso14443crc.h"
20 #include "iso14443a.h"
21 #include "crapto1.h"
22 #include "mifareutil.h"
23
24 static uint32_t iso14a_timeout;
25 uint8_t *trace = (uint8_t *) BigBuf+TRACE_OFFSET;
26 int traceLen = 0;
27 int rsamples = 0;
28 int tracing = TRUE;
29 uint8_t trigger = 0;
30 // the block number for the ISO14443-4 PCB
31 static uint8_t iso14_pcb_blocknum = 0;
32
33 // CARD TO READER - manchester
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
37 // READER TO CARD - miller
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
47
48 const uint8_t OddByteParity[256] = {
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
67
68 void iso14a_set_trigger(bool enable) {
69 trigger = enable;
70 }
71
72 void iso14a_clear_trace() {
73 memset(trace, 0x44, TRACE_SIZE);
74 traceLen = 0;
75 }
76
77 void iso14a_set_tracing(bool enable) {
78 tracing = enable;
79 }
80
81 void iso14a_set_timeout(uint32_t timeout) {
82 iso14a_timeout = timeout;
83 }
84
85 //-----------------------------------------------------------------------------
86 // Generate the parity value for a byte sequence
87 //
88 //-----------------------------------------------------------------------------
89 byte_t oddparity (const byte_t bt)
90 {
91 return OddByteParity[bt];
92 }
93
94 uint32_t GetParity(const uint8_t * pbtCmd, int iLen)
95 {
96 int i;
97 uint32_t dwPar = 0;
98
99 // Generate the parity bits
100 for (i = 0; i < iLen; i++) {
101 // and save them to a 32Bit word
102 dwPar |= ((OddByteParity[pbtCmd[i]]) << i);
103 }
104 return dwPar;
105 }
106
107 void AppendCrc14443a(uint8_t* data, int len)
108 {
109 ComputeCrc14443(CRC_14443_A,data,len,data+len,data+len+1);
110 }
111
112 // The function LogTrace() is also used by the iClass implementation in iClass.c
113 int RAMFUNC LogTrace(const uint8_t * btBytes, int iLen, int iSamples, uint32_t dwParity, int bReader)
114 {
115 // Return when trace is full
116 if (traceLen >= TRACE_SIZE) return FALSE;
117
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
137 //-----------------------------------------------------------------------------
138 // The software UART that receives commands from the reader, and its state
139 // variables.
140 //-----------------------------------------------------------------------------
141 static tUart Uart;
142
143 static RAMFUNC int MillerDecoding(int bit)
144 {
145 //int error = 0;
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
157 int EOC = FALSE;
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;
191 //error = 0x01;
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;
202 //error = 0x02;
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;
240 //error = 0x03;
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;
345 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
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;
361 //error = 0;
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 //=============================================================================
378 // ISO 14443 Type A - Manchester decoder
379 //=============================================================================
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)
391 static tDemod Demod;
392
393 inline RAMFUNC bool IsModulation(byte_t b)
394 {
395 if (b >= 5 || b == 3) // majority decision: 2 or more bits are set
396 return true;
397 else
398 return false;
399
400 }
401
402 inline RAMFUNC bool IsModulationNibble1(byte_t b)
403 {
404 return IsModulation((b & 0xE0) >> 5);
405 }
406
407 inline RAMFUNC bool IsModulationNibble2(byte_t b)
408 {
409 return IsModulation((b & 0x0E) >> 1);
410 }
411
412 static 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;
432 }
433 break;
434
435
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;
445 }
446 }
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;
465 }
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;
470 }
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;
485 }
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
496 }
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;
501 }
502 break;
503
504
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;
511 }
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;
532 }
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;
539 }
540 Demod.state = DEMOD_UNSYNCD; // start from the beginning
541 return TRUE; // we are finished with decoding the raw data sequence
542 }
543 }
544
545 }
546
547 return FALSE; // not finished yet, need more data
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 //-----------------------------------------------------------------------------
560 void 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
567 iso14a_clear_trace();
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.
576 // The length of a received command will in most cases be no more than 18 bytes.
577 // So 32 should be enough!
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);
581
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;
591
592 // Set up the demodulator for tag -> reader responses.
593 Demod.output = receivedResponse;
594 Demod.len = 0;
595 Demod.state = DEMOD_UNSYNCD;
596
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;
602
603 // Setup for the DMA.
604 FpgaSetupSsc();
605 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
606
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);
612
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 }
622
623 LED_A_ON();
624 WDT_HIT();
625
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;
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
674 if(ManchesterDecoding(data[0], 0)) {
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");
695
696 done:
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();
701 }
702
703 //-----------------------------------------------------------------------------
704 // Prepare tag messages
705 //-----------------------------------------------------------------------------
706 static void CodeIso14443aAsTagPar(const uint8_t *cmd, int len, uint32_t dwParity)
707 {
708 int i;
709
710 ToSendReset();
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);
721
722 // Send startbit
723 ToSend[++ToSendMax] = SEC_D;
724
725 for(i = 0; i < len; i++) {
726 int j;
727 uint8_t b = cmd[i];
728
729 // Data bits
730 for(j = 0; j < 8; j++) {
731 if(b & 1) {
732 ToSend[++ToSendMax] = SEC_D;
733 } else {
734 ToSend[++ToSendMax] = SEC_E;
735 }
736 b >>= 1;
737 }
738
739 // Get the parity bit
740 if ((dwParity >> i) & 0x01) {
741 ToSend[++ToSendMax] = SEC_D;
742 } else {
743 ToSend[++ToSendMax] = SEC_E;
744 }
745 }
746
747 // Send stopbit
748 ToSend[++ToSendMax] = SEC_F;
749
750 // Convert from last byte pos to length
751 ToSendMax++;
752 }
753
754 static void CodeIso14443aAsTag(const uint8_t *cmd, int len){
755 CodeIso14443aAsTagPar(cmd, len, GetParity(cmd, len));
756 }
757
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 //}
800
801 static void Code4bitAnswerAsTag(uint8_t cmd)
802 {
803 int i;
804
805 ToSendReset();
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
838 // Convert from last byte pos to length
839 ToSendMax++;
840 }
841
842 //-----------------------------------------------------------------------------
843 // Wait for commands from reader
844 // Stop when button is pressed
845 // Or return TRUE when command is captured
846 //-----------------------------------------------------------------------------
847 static int GetIso14443aCommandFromReader(uint8_t *received, int *len, int maxLen)
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)) {
869 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
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 }
881
882 static int EmSendCmd14443aRaw(uint8_t *resp, int respLen, int correctionNeeded);
883 int EmSend4bitEx(uint8_t resp, int correctionNeeded);
884 int EmSend4bit(uint8_t resp);
885 int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par);
886 int EmSendCmdExPar(uint8_t *resp, int respLen, int correctionNeeded, uint32_t par);
887 int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded);
888 int EmSendCmd(uint8_t *resp, int respLen);
889 int EmSendCmdPar(uint8_t *resp, int respLen, uint32_t par);
890
891 static uint8_t* free_buffer_pointer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
892
893 typedef 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
900 void reset_free_buffer() {
901 free_buffer_pointer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
902 }
903
904 bool 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
935 bool 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
952 //-----------------------------------------------------------------------------
953 // Main loop of simulated tag: receive commands from reader, decide what
954 // response to send, and send it.
955 //-----------------------------------------------------------------------------
956 void SimulateIso14443aTag(int tagType, int uid_1st, int uid_2nd, byte_t* data)
957 {
958 // Enable and clear the trace
959 tracing = TRUE;
960 iso14a_clear_trace();
961
962 // This function contains the tag emulation
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
1033 uint8_t response5[] = { 0x00, 0x00, 0x00, 0x00 }; // Very random tag nonce
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 }
1069
1070 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
1071 int len;
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;
1080 int cmdsRecvd = 0;
1081
1082 // We need to listen to the high-frequency, peak-detected path.
1083 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1084 FpgaSetupSsc();
1085
1086 cmdsRecvd = 0;
1087 tag_response_info_t* p_response;
1088
1089 LED_A_ON();
1090 for(;;) {
1091 // Clean receive command buffer
1092 memset(receivedCmd, 0x44, RECV_CMD_SIZE);
1093
1094 if(!GetIso14443aCommandFromReader(receivedCmd, &len, RECV_CMD_SIZE)) {
1095 DbpString("Button press");
1096 break;
1097 }
1098
1099 if (tracing) {
1100 LogTrace(receivedCmd,len, 0, Uart.parityBits, TRUE);
1101 }
1102
1103 p_response = NULL;
1104
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
1109 p_response = &responses[0]; order = 1;
1110 } else if(receivedCmd[0] == 0x52) { // Received a WAKEUP
1111 p_response = &responses[0]; order = 6;
1112 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x93) { // Received request for UID (cascade 1)
1113 p_response = &responses[1]; order = 2;
1114 } else if(receivedCmd[1] == 0x20 && receivedCmd[0] == 0x95) { // Received request for UID (cascade 2)
1115 p_response = &responses[2]; order = 20;
1116 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x93) { // Received a SELECT (cascade 1)
1117 p_response = &responses[3]; order = 3;
1118 } else if(receivedCmd[1] == 0x70 && receivedCmd[0] == 0x95) { // Received a SELECT (cascade 2)
1119 p_response = &responses[4]; order = 30;
1120 } else if(receivedCmd[0] == 0x30) { // Received a (plain) READ
1121 EmSendCmdEx(data+(4*receivedCmd[0]),16,false);
1122 Dbprintf("Read request from reader: %x %x",receivedCmd[0],receivedCmd[1]);
1123 // We already responded, do not send anything with the EmSendCmd14443aRaw() that is called below
1124 p_response = NULL;
1125 } else if(receivedCmd[0] == 0x50) { // Received a HALT
1126 // DbpString("Reader requested we HALT!:");
1127 p_response = NULL;
1128 } else if(receivedCmd[0] == 0x60 || receivedCmd[0] == 0x61) { // Received an authentication request
1129 p_response = &responses[5]; order = 7;
1130 } else if(receivedCmd[0] == 0xE0) { // Received a RATS request
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;
1194 }
1195 }
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
1206 //i = 0;
1207 }
1208
1209 if(cmdsRecvd > 999) {
1210 DbpString("1000 commands later...");
1211 break;
1212 }
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 }
1225 }
1226
1227 Dbprintf("%x %x %x", happened, happened2, cmdsRecvd);
1228 LED_A_OFF();
1229 }
1230
1231
1232 // prepare a delayed transfer. This simply shifts ToSend[] by a number
1233 // of bits specified in the delay parameter.
1234 void 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
1255 //-----------------------------------------------------------------------------
1256 // Transmit the command (to the tag) that was placed in ToSend[].
1257 // Parameter timing:
1258 // if NULL: ignored
1259 // if == 0: return time of transfer
1260 // if != 0: delay transfer until time specified
1261 //-----------------------------------------------------------------------------
1262 static void TransmitFor14443a(const uint8_t *cmd, int len, uint32_t *timing)
1263 {
1264 int c;
1265
1266 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1267
1268
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
1279 for(c = 0; c < 10;) { // standard delay for each transfer (allow tag to be ready after last transmission?)
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 }
1296
1297 }
1298
1299 //-----------------------------------------------------------------------------
1300 // Prepare reader command (in bits, support short frames) to send to FPGA
1301 //-----------------------------------------------------------------------------
1302 void CodeIso14443aBitsAsReaderPar(const uint8_t * cmd, int bits, uint32_t dwParity)
1303 {
1304 int i, j;
1305 int last;
1306 uint8_t b;
1307
1308 ToSendReset();
1309
1310 // Start of Communication (Seq. Z)
1311 ToSend[++ToSendMax] = SEC_Z;
1312 last = 0;
1313
1314 size_t bytecount = nbytes(bits);
1315 // Generate send structure for the data bits
1316 for (i = 0; i < bytecount; i++) {
1317 // Get the current byte to send
1318 b = cmd[i];
1319 size_t bitsleft = MIN((bits-(i*8)),8);
1320
1321 for (j = 0; j < bitsleft; j++) {
1322 if (b & 1) {
1323 // Sequence X
1324 ToSend[++ToSendMax] = SEC_X;
1325 last = 1;
1326 } else {
1327 if (last == 0) {
1328 // Sequence Z
1329 ToSend[++ToSendMax] = SEC_Z;
1330 } else {
1331 // Sequence Y
1332 ToSend[++ToSendMax] = SEC_Y;
1333 last = 0;
1334 }
1335 }
1336 b >>= 1;
1337 }
1338
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;
1346 } else {
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 }
1355 }
1356 }
1357 }
1358
1359 // End of Communication
1360 if (last == 0) {
1361 // Sequence Z
1362 ToSend[++ToSendMax] = SEC_Z;
1363 } else {
1364 // Sequence Y
1365 ToSend[++ToSendMax] = SEC_Y;
1366 last = 0;
1367 }
1368 // Sequence Y
1369 ToSend[++ToSendMax] = SEC_Y;
1370
1371 // Just to be sure!
1372 ToSend[++ToSendMax] = SEC_Y;
1373 ToSend[++ToSendMax] = SEC_Y;
1374 ToSend[++ToSendMax] = SEC_Y;
1375
1376 // Convert from last character reference to length
1377 ToSendMax++;
1378 }
1379
1380 //-----------------------------------------------------------------------------
1381 // Prepare reader command to send to FPGA
1382 //-----------------------------------------------------------------------------
1383 void CodeIso14443aAsReaderPar(const uint8_t * cmd, int len, uint32_t dwParity)
1384 {
1385 CodeIso14443aBitsAsReaderPar(cmd,len*8,dwParity);
1386 }
1387
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 //-----------------------------------------------------------------------------
1393 static 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;
1453 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
1454 return 0;
1455 }
1456 if(MillerDecoding(b & 0x0f)) {
1457 *len = Uart.byteCnt;
1458 if (tracing) LogTrace(received, *len, GetDeltaCountUS(), Uart.parityBits, TRUE);
1459 return 0;
1460 }
1461 }
1462 }
1463 }
1464
1465 static 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) {
1490 b = 0xff; // was 0x00
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
1508 int EmSend4bitEx(uint8_t resp, int correctionNeeded){
1509 Code4bitAnswerAsTag(resp);
1510 int res = EmSendCmd14443aRaw(ToSend, ToSendMax, correctionNeeded);
1511 if (tracing) LogTrace(&resp, 1, GetDeltaCountUS(), GetParity(&resp, 1), FALSE);
1512 return res;
1513 }
1514
1515 int EmSend4bit(uint8_t resp){
1516 return EmSend4bitEx(resp, 0);
1517 }
1518
1519 int 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
1526 int EmSendCmdEx(uint8_t *resp, int respLen, int correctionNeeded){
1527 return EmSendCmdExPar(resp, respLen, correctionNeeded, GetParity(resp, respLen));
1528 }
1529
1530 int EmSendCmd(uint8_t *resp, int respLen){
1531 return EmSendCmdExPar(resp, respLen, 0, GetParity(resp, respLen));
1532 }
1533
1534 int EmSendCmdPar(uint8_t *resp, int respLen, uint32_t par){
1535 return EmSendCmdExPar(resp, respLen, 0, par);
1536 }
1537
1538 //-----------------------------------------------------------------------------
1539 // Wait a certain time for tag response
1540 // If a response is captured return TRUE
1541 // If it takes too long return FALSE
1542 //-----------------------------------------------------------------------------
1543 static int GetIso14443aAnswerFromTag(uint8_t *receivedResponse, uint16_t offset, int maxLen, int *samples)
1544 {
1545 int c;
1546
1547 // Set FPGA mode to "reader listen mode", no modulation (listen
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);
1552
1553 // Now get the answer from the card
1554 Demod.output = receivedResponse;
1555 Demod.len = 0;
1556 Demod.state = DEMOD_UNSYNCD;
1557
1558 uint8_t b;
1559
1560 c = 0;
1561 for(;;) {
1562 WDT_HIT();
1563
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 // }
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;
1571 if(ManchesterDecoding(b, offset)) {
1572 *samples = Demod.samples;
1573 return TRUE;
1574 }
1575 }
1576 }
1577 }
1578
1579 void ReaderTransmitBitsPar(uint8_t* frame, int bits, uint32_t par, uint32_t *timing)
1580 {
1581
1582 CodeIso14443aBitsAsReaderPar(frame,bits,par);
1583
1584 // Send command to tag
1585 TransmitFor14443a(ToSend, ToSendMax, timing);
1586 if(trigger)
1587 LED_A_ON();
1588
1589 // Log reader command in trace buffer
1590 if (tracing) LogTrace(frame,nbytes(bits),0,par,TRUE);
1591 }
1592
1593 void ReaderTransmitPar(uint8_t* frame, int len, uint32_t par, uint32_t *timing)
1594 {
1595 ReaderTransmitBitsPar(frame,len*8,par, timing);
1596 }
1597
1598 void 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
1604 void ReaderTransmit(uint8_t* frame, int len, uint32_t *timing)
1605 {
1606 // Generate parity and redirect
1607 ReaderTransmitBitsPar(frame,len*8,GetParity(frame,len), timing);
1608 }
1609
1610 int 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
1619 int ReaderReceive(uint8_t* receivedAnswer)
1620 {
1621 return ReaderReceiveOffset(receivedAnswer, 0);
1622 }
1623
1624 int ReaderReceivePar(uint8_t *receivedAnswer, uint32_t *parptr)
1625 {
1626 int samples = 0;
1627 if (!GetIso14443aAnswerFromTag(receivedAnswer,0,160,&samples)) return FALSE;
1628 if (tracing) LogTrace(receivedAnswer,Demod.len,samples,Demod.parityBits,FALSE);
1629 *parptr = Demod.parityBits;
1630 if(samples == 0) return FALSE;
1631 return Demod.len;
1632 }
1633
1634 /* performs iso14443a anticollision procedure
1635 * fills the uid pointer unless NULL
1636 * fills resp_data unless NULL */
1637 int iso14443a_select_card(byte_t* uid_ptr, iso14a_card_select_t* p_hi14a_card, uint32_t* cuid_ptr) {
1638 uint8_t wupa[] = { 0x52 }; // 0x26 - REQA 0x52 - WAKE-UP
1639 uint8_t sel_all[] = { 0x93,0x20 };
1640 uint8_t sel_uid[] = { 0x93,0x70,0x00,0x00,0x00,0x00,0x00,0x00,0x00};
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
1643 byte_t uid_resp[4];
1644 size_t uid_resp_len;
1645
1646 uint8_t sak = 0x04; // cascade uid
1647 int cascade_level = 0;
1648 int len;
1649
1650 // Broadcast for a card, WUPA (0x52) will force response from all cards in the field
1651 ReaderTransmitBitsPar(wupa,7,0, NULL);
1652 // Receive the ATQA
1653 if(!ReaderReceive(resp)) return 0;
1654 // Dbprintf("atqa: %02x %02x",resp[0],resp[1]);
1655
1656 if(p_hi14a_card) {
1657 memcpy(p_hi14a_card->atqa, resp, 2);
1658 p_hi14a_card->uidlen = 0;
1659 memset(p_hi14a_card->uid,0,10);
1660 }
1661
1662 // clear uid
1663 if (uid_ptr) {
1664 memset(uid_ptr,0,10);
1665 }
1666
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
1675 ReaderTransmit(sel_all,sizeof(sel_all), NULL);
1676 if (!ReaderReceive(resp)) return 0;
1677
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;
1710 // Dbprintf("uid: %02x %02x %02x %02x",uid_resp[0],uid_resp[1],uid_resp[2],uid_resp[3]);
1711
1712 // calculate crypto UID. Always use last 4 Bytes.
1713 if(cuid_ptr) {
1714 *cuid_ptr = bytes_to_num(uid_resp, 4);
1715 }
1716
1717 // Construct SELECT UID command
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
1722 ReaderTransmit(sel_uid,sizeof(sel_uid), NULL);
1723
1724 // Receive the SAK
1725 if (!ReaderReceive(resp)) return 0;
1726 sak = resp[0];
1727
1728 // Test if more parts of the uid are comming
1729 if ((sak & 0x04) /* && uid_resp[0] == 0x88 */) {
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
1732 memcpy(uid_resp, uid_resp + 1, 3);
1733 uid_resp_len = 3;
1734 }
1735
1736 if(uid_ptr) {
1737 memcpy(uid_ptr + (cascade_level*3), uid_resp, uid_resp_len);
1738 }
1739
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 }
1744 }
1745
1746 if(p_hi14a_card) {
1747 p_hi14a_card->sak = sak;
1748 p_hi14a_card->ats_len = 0;
1749 }
1750
1751 if( (sak & 0x20) == 0) {
1752 return 2; // non iso14443a compliant tag
1753 }
1754
1755 // Request for answer to select
1756 AppendCrc14443a(rats, 2);
1757 ReaderTransmit(rats, sizeof(rats), NULL);
1758
1759 if (!(len = ReaderReceive(resp))) return 0;
1760
1761 if(p_hi14a_card) {
1762 memcpy(p_hi14a_card->ats, resp, sizeof(p_hi14a_card->ats));
1763 p_hi14a_card->ats_len = len;
1764 }
1765
1766 // reset the PCB block number
1767 iso14_pcb_blocknum = 0;
1768 return 1;
1769 }
1770
1771 void iso14443a_setup() {
1772 // Set up the synchronous serial port
1773 FpgaSetupSsc();
1774 // Start from off (no field generated)
1775 // Signal field is off with the appropriate LED
1776 // LED_D_OFF();
1777 // FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1778 // SpinDelay(50);
1779
1780 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1781
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);
1786 SpinDelay(7); // iso14443-3 specifies 5ms max.
1787
1788 Demod.state = DEMOD_UNSYNCD;
1789 iso14a_timeout = 2048; //default
1790 }
1791
1792 int 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
1795 // put block number into the PCB
1796 real_cmd[0] |= iso14_pcb_blocknum;
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
1801 ReaderTransmit(real_cmd, cmd_len+4, NULL);
1802 size_t len = ReaderReceive(data);
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
1816 return len;
1817 }
1818
1819 //-----------------------------------------------------------------------------
1820 // Read an ISO 14443a tag. Send out commands and store answers.
1821 //
1822 //-----------------------------------------------------------------------------
1823 void ReaderIso14443a(UsbCommand * c)
1824 {
1825 iso14a_command_t param = c->arg[0];
1826 uint8_t * cmd = c->d.asBytes;
1827 size_t len = c->arg[1];
1828 size_t lenbits = c->arg[2];
1829 uint32_t arg0 = 0;
1830 byte_t buf[USB_CMD_DATA_SIZE];
1831
1832 if(param & ISO14A_CONNECT) {
1833 iso14a_clear_trace();
1834 }
1835
1836 iso14a_set_tracing(true);
1837
1838 if(param & ISO14A_REQUEST_TRIGGER) {
1839 iso14a_set_trigger(1);
1840 }
1841
1842 if(param & ISO14A_CONNECT) {
1843 iso14443a_setup();
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 }
1849 }
1850
1851 if(param & ISO14A_SET_TIMEOUT) {
1852 iso14a_timeout = c->arg[2];
1853 }
1854
1855 if(param & ISO14A_SET_TIMEOUT) {
1856 iso14a_timeout = c->arg[2];
1857 }
1858
1859 if(param & ISO14A_APDU) {
1860 arg0 = iso14_apdu(cmd, len, buf);
1861 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
1862 }
1863
1864 if(param & ISO14A_RAW) {
1865 if(param & ISO14A_APPEND_CRC) {
1866 AppendCrc14443a(cmd,len);
1867 len += 2;
1868 }
1869 if(lenbits>0) {
1870 ReaderTransmitBitsPar(cmd,lenbits,GetParity(cmd,lenbits/8), NULL);
1871 } else {
1872 ReaderTransmit(cmd,len, NULL);
1873 }
1874 arg0 = ReaderReceive(buf);
1875 cmd_send(CMD_ACK,arg0,0,0,buf,sizeof(buf));
1876 }
1877
1878 if(param & ISO14A_REQUEST_TRIGGER) {
1879 iso14a_set_trigger(0);
1880 }
1881
1882 if(param & ISO14A_NO_DISCONNECT) {
1883 return;
1884 }
1885
1886 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1887 LEDsoff();
1888 }
1889
1890
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.
1894 int32_t dist_nt(uint32_t nt1, uint32_t nt2) {
1895
1896 uint16_t i;
1897 uint32_t nttmp1, nttmp2;
1898
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
1912 }
1913
1914
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 //-----------------------------------------------------------------------------
1921 void 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;
1927
1928 uint8_t* receivedAnswer = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
1929 traceLen = 0;
1930 tracing = false;
1931
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;
1939
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};
1944
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;
1951
1952
1953
1954 if (first_try) {
1955 StartCountMifare();
1956 mf_nr_ar3 = 0;
1957 iso14443a_setup();
1958 while((GetCountMifare() & 0xffff0000) != 0x10000); // wait for counter to reset and "warm up"
1959 sync_time = GetCountMifare() & 0xfffffff8;
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 }
1972
1973 LED_A_ON();
1974 LED_B_OFF();
1975 LED_C_OFF();
1976
1977
1978 for(uint16_t i = 0; TRUE; i++) {
1979
1980 WDT_HIT();
1981
1982 // Test if the action was cancelled
1983 if(BUTTON_PRESS()) {
1984 break;
1985 }
1986
1987 LED_C_ON();
1988
1989 if(!iso14443a_select_card(uid, NULL, &cuid)) {
1990 if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Can't select card");
1991 continue;
1992 }
1993
1994 //keep the card active
1995 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1996
1997 sync_time = (sync_time & 0xfffffff8) + sync_cycles + catch_up_cycles;
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) {
2002 sync_time = (sync_time & 0xfffffff8) + sync_cycles;
2003 }
2004
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);
2007
2008 // Receive the (4 Byte) "random" nonce
2009 if (!ReaderReceive(receivedAnswer)) {
2010 if (MF_DBGLEVEL >= 1) Dbprintf("Mifare: Couldn't receive tag nonce");
2011 continue;
2012 }
2013
2014 previous_nt = nt;
2015 nt = bytes_to_num(receivedAnswer, 4);
2016
2017 // Transmit reader nonce with fake par
2018 ReaderTransmitPar(mf_nr_ar, sizeof(mf_nr_ar), par, NULL);
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);
2030 if (MF_DBGLEVEL >= 3) Dbprintf("calibrating in cycle %d. nt_distance=%d, Sync_cycles: %d\n", i, nt_distance, sync_cycles);
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) {
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);
2050 }
2051 else {
2052 sync_cycles = sync_cycles + catch_up_cycles;
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);
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 {
2063 catch_up_cycles = 8; // the PRNG is delayed by 8 cycles due to the NAC (4Bits = 0x05 encrypted) transfer
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;
2114 }
2115
2116 //-----------------------------------------------------------------------------
2117 // MIFARE 1K simulate.
2118 //
2119 //-----------------------------------------------------------------------------
2120 void Mifare1ksim(uint8_t arg0, uint8_t arg1, uint8_t arg2, uint8_t *datain)
2121 {
2122 int cardSTATE = MFEMUL_NOFIELD;
2123 int _7BUID = 0;
2124 int vHf = 0; // in mV
2125 //int nextCycleTimeout = 0;
2126 int res;
2127 // uint32_t timer = 0;
2128 uint32_t selTimer = 0;
2129 uint32_t authTimer = 0;
2130 uint32_t par = 0;
2131 int len = 0;
2132 uint8_t cardWRBL = 0;
2133 uint8_t cardAUTHSC = 0;
2134 uint8_t cardAUTHKEY = 0xff; // no authentication
2135 //uint32_t cardRn = 0;
2136 uint32_t cardRr = 0;
2137 uint32_t cuid = 0;
2138 //uint32_t rn_enc = 0;
2139 uint32_t ans = 0;
2140 uint32_t cardINTREG = 0;
2141 uint8_t cardINTBLOCK = 0;
2142 struct Crypto1State mpcs = {0, 0};
2143 struct Crypto1State *pcs;
2144 pcs = &mpcs;
2145
2146 uint8_t* receivedCmd = eml_get_bigbufptr_recbuf();
2147 uint8_t *response = eml_get_bigbufptr_sendbuf();
2148
2149 static uint8_t rATQA[] = {0x04, 0x00}; // Mifare classic 1k 4BUID
2150
2151 static uint8_t rUIDBCC1[] = {0xde, 0xad, 0xbe, 0xaf, 0x62};
2152 static uint8_t rUIDBCC2[] = {0xde, 0xad, 0xbe, 0xaf, 0x62}; // !!!
2153
2154 static uint8_t rSAK[] = {0x08, 0xb6, 0xdd};
2155 static uint8_t rSAK1[] = {0x04, 0xda, 0x17};
2156
2157 static uint8_t rAUTH_NT[] = {0x01, 0x02, 0x03, 0x04};
2158 // static uint8_t rAUTH_NT[] = {0x1a, 0xac, 0xff, 0x4f};
2159 static uint8_t rAUTH_AT[] = {0x00, 0x00, 0x00, 0x00};
2160
2161 // clear trace
2162 traceLen = 0;
2163 tracing = true;
2164
2165 // Authenticate response - nonce
2166 uint32_t nonce = bytes_to_num(rAUTH_NT, 4);
2167
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
2186 // -------------------------------------- test area
2187
2188 // -------------------------------------- END test area
2189 // start mkseconds counter
2190 StartCountUS();
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
2199 if (MF_DBGLEVEL >= 1) Dbprintf("Started. 7buid=%d", _7BUID);
2200 // calibrate mkseconds counter
2201 GetDeltaCountUS();
2202 while (true) {
2203 WDT_HIT();
2204
2205 if(BUTTON_PRESS()) {
2206 break;
2207 }
2208
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) {
2215 cardSTATE_TO_IDLE();
2216 LED_A_ON();
2217 }
2218 }
2219
2220 if (cardSTATE != MFEMUL_NOFIELD) {
2221 res = EmGetCmd(receivedCmd, &len, RECV_CMD_SIZE); // (+ nextCycleTimeout)
2222 if (res == 2) {
2223 cardSTATE = MFEMUL_NOFIELD;
2224 LEDsoff();
2225 continue;
2226 }
2227 if(res) break;
2228 }
2229
2230 //nextCycleTimeout = 0;
2231
2232 // if (len) Dbprintf("len:%d cmd: %02x %02x %02x %02x", len, receivedCmd[0], receivedCmd[1], receivedCmd[2], receivedCmd[3]);
2233
2234 if (len != 4 && cardSTATE != MFEMUL_NOFIELD) { // len != 4 <---- speed up the code 4 authentication
2235 // REQ or WUP request in ANY state and WUP in HALTED state
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 }
2248
2249 switch (cardSTATE) {
2250 case MFEMUL_NOFIELD:{
2251 break;
2252 }
2253 case MFEMUL_HALTED:{
2254 break;
2255 }
2256 case MFEMUL_IDLE:{
2257 break;
2258 }
2259 case MFEMUL_SELECT1:{
2260 // select all
2261 if (len == 2 && (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x20)) {
2262 EmSendCmd(rUIDBCC1, sizeof(rUIDBCC1));
2263 break;
2264 }
2265
2266 // select card
2267 if (len == 9 &&
2268 (receivedCmd[0] == 0x93 && receivedCmd[1] == 0x70 && memcmp(&receivedCmd[2], rUIDBCC1, 4) == 0)) {
2269 if (!_7BUID)
2270 EmSendCmd(rSAK, sizeof(rSAK));
2271 else
2272 EmSendCmd(rSAK1, sizeof(rSAK1));
2273
2274 cuid = bytes_to_num(rUIDBCC1, 4);
2275 if (!_7BUID) {
2276 cardSTATE = MFEMUL_WORK;
2277 LED_B_ON();
2278 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol1 time: %d", GetTickCount() - selTimer);
2279 break;
2280 } else {
2281 cardSTATE = MFEMUL_SELECT2;
2282 break;
2283 }
2284 }
2285
2286 break;
2287 }
2288 case MFEMUL_SELECT2:{
2289 if (!len) break;
2290
2291 if (len == 2 && (receivedCmd[0] == 0x95 && receivedCmd[1] == 0x20)) {
2292 EmSendCmd(rUIDBCC2, sizeof(rUIDBCC2));
2293 break;
2294 }
2295
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();
2304 if (MF_DBGLEVEL >= 4) Dbprintf("--> WORK. anticol2 time: %d", GetTickCount() - selTimer);
2305 break;
2306 }
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;
2312 }
2313 case MFEMUL_AUTH1:{
2314 if (len == 8) {
2315 // --- crypto
2316 //rn_enc = bytes_to_num(receivedCmd, 4);
2317 //cardRn = rn_enc ^ crypto1_word(pcs, rn_enc , 1);
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)){
2321 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH FAILED. cardRr=%08x, succ=%08x", cardRr, prng_successor(nonce, 64));
2322 cardSTATE_TO_IDLE();
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));
2329 cardSTATE = MFEMUL_AUTH2;
2330 } else {
2331 cardSTATE_TO_IDLE();
2332 }
2333 if (cardSTATE != MFEMUL_AUTH2) break;
2334 }
2335 case MFEMUL_AUTH2:{
2336 LED_C_ON();
2337 cardSTATE = MFEMUL_WORK;
2338 if (MF_DBGLEVEL >= 4) Dbprintf("AUTH COMPLETED. sec=%d, key=%d time=%d", cardAUTHSC, cardAUTHKEY, GetTickCount() - authTimer);
2339 break;
2340 }
2341 case MFEMUL_WORK:{
2342 lbWORK: if (len == 0) break;
2343
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;
2364 //nextCycleTimeout = 10;
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;
2386 //nextCycleTimeout = 10;
2387 break;
2388 }
2389 }
2390
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;
2402 }
2403
2404 // read block
2405 if (len == 4 && receivedCmd[0] == 0x30) {
2406 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
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);
2414 break;
2415 }
2416
2417 // write block
2418 if (len == 4 && receivedCmd[0] == 0xA0) {
2419 if (receivedCmd[1] >= 16 * 4 || receivedCmd[1] / 4 != cardAUTHSC) {
2420 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2421 break;
2422 }
2423 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_ACK));
2424 //nextCycleTimeout = 50;
2425 cardSTATE = MFEMUL_WRITEBL2;
2426 cardWRBL = receivedCmd[1];
2427 break;
2428 }
2429
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
2468 // halt
2469 if (len == 4 && (receivedCmd[0] == 0x50 && receivedCmd[1] == 0x00)) {
2470 LED_B_OFF();
2471 LED_C_OFF();
2472 cardSTATE = MFEMUL_HALTED;
2473 if (MF_DBGLEVEL >= 4) Dbprintf("--> HALTED. Selected time: %d ms", GetTickCount() - selTimer);
2474 break;
2475 }
2476
2477 // command not allowed
2478 if (len == 4) {
2479 EmSend4bit(mf_crypto1_encrypt4bit(pcs, CARD_NACK_NA));
2480 break;
2481 }
2482
2483 // case break
2484 break;
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;
2493 } else {
2494 cardSTATE_TO_IDLE();
2495 break;
2496 }
2497 break;
2498 }
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 }
2535 }
2536 }
2537
2538 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
2539 LEDsoff();
2540
2541 // add trace trailer
2542 memset(rAUTH_NT, 0x44, 4);
2543 LogTrace(rAUTH_NT, 4, 0, 0, TRUE);
2544
2545 if (MF_DBGLEVEL >= 1) Dbprintf("Emulator stopped. Tracing: %d trace length: %d ", tracing, traceLen);
2546 }
2547
2548 //-----------------------------------------------------------------------------
2549 // MIFARE sniffer.
2550 //
2551 //-----------------------------------------------------------------------------
2552 void 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
2556
2557 // C(red) A(yellow) B(green)
2558 LEDsoff();
2559 // init trace buffer
2560 iso14a_clear_trace();
2561
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;
2575 int8_t *data = dmaBuf;
2576 int maxDataLen = 0;
2577 int dataLen = 0;
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();
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);
2599
2600 // init sniffer
2601 MfSniffInit();
2602 int sniffCounter = 0;
2603
2604 // And now we loop, receiving samples.
2605 while(true) {
2606 if(BUTTON_PRESS()) {
2607 DbpString("cancelled by button");
2608 goto done;
2609 }
2610
2611 LED_A_ON();
2612 WDT_HIT();
2613
2614 if (++sniffCounter > 65) {
2615 if (MfSniffSend(2000)) {
2616 FpgaEnableSscDma();
2617 }
2618 sniffCounter = 0;
2619 }
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);
2633 goto done;
2634 }
2635 }
2636 if(dataLen < 1) continue;
2637
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;
2642 Dbprintf("RxEmpty ERROR!!! data length:%d", dataLen); // temporary
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;
2647 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
2648 }
2649
2650 LED_A_OFF();
2651
2652 if(MillerDecoding((data[0] & 0xF0) >> 4)) {
2653 LED_C_INV();
2654 // check - if there is a short 7bit request from reader
2655 if (MfSniffLogic(receivedCmd, Uart.byteCnt, Uart.parityBits, Uart.bitCnt, TRUE)) break;
2656
2657 /* And ready to receive another command. */
2658 Uart.state = STATE_UNSYNCD;
2659
2660 /* And also reset the demod code */
2661 Demod.state = DEMOD_UNSYNCD;
2662 }
2663
2664 if(ManchesterDecoding(data[0], 0)) {
2665 LED_C_INV();
2666
2667 if (MfSniffLogic(receivedResponse, Demod.len, Demod.parityBits, Demod.bitCount, FALSE)) break;
2668
2669 // And ready to receive another response.
2670 memset(&Demod, 0, sizeof(Demod));
2671 Demod.output = receivedResponse;
2672 Demod.state = DEMOD_UNSYNCD;
2673
2674 /* And also reset the uart code */
2675 Uart.state = STATE_UNSYNCD;
2676 }
2677
2678 data++;
2679 if(data > dmaBuf + DMA_BUFFER_SIZE) {
2680 data = dmaBuf;
2681 }
2682 } // main cycle
2683
2684 DbpString("COMMAND FINISHED");
2685
2686 done:
2687 FpgaDisableSscDma();
2688 MfSniffEnd();
2689
2690 Dbprintf("maxDataLen=%x, Uart.state=%x, Uart.byteCnt=%x Uart.byteCntMax=%x", maxDataLen, Uart.state, Uart.byteCnt, Uart.byteCntMax);
2691 LEDsoff();
2692 }
Impressum, Datenschutz