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