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