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