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