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