]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iclass.c
CHG: Added support for tnp3xx in lua scripts.
[proxmark3-svn] / armsrc / iclass.c
1 //-----------------------------------------------------------------------------
2 // Gerhard de Koning Gans - May 2008
3 // Hagen Fritsch - June 2010
4 // Gerhard de Koning Gans - May 2011
5 // Gerhard de Koning Gans - June 2012 - Added iClass card and reader emulation
6 //
7 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
8 // at your option, any later version. See the LICENSE.txt file for the text of
9 // the license.
10 //-----------------------------------------------------------------------------
11 // Routines to support iClass.
12 //-----------------------------------------------------------------------------
13 // Based on ISO14443a implementation. Still in experimental phase.
14 // Contribution made during a security research at Radboud University Nijmegen
15 //
16 // Please feel free to contribute and extend iClass support!!
17 //-----------------------------------------------------------------------------
18 //
19 // FIX:
20 // ====
21 // We still have sometimes a demodulation error when snooping iClass communication.
22 // The resulting trace of a read-block-03 command may look something like this:
23 //
24 // + 22279: : 0c 03 e8 01
25 //
26 // ...with an incorrect answer...
27 //
28 // + 85: 0: TAG ff! ff! ff! ff! ff! ff! ff! ff! bb 33 bb 00 01! 0e! 04! bb !crc
29 //
30 // We still left the error signalling bytes in the traces like 0xbb
31 //
32 // A correct trace should look like this:
33 //
34 // + 21112: : 0c 03 e8 01
35 // + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5
36 //
37 //-----------------------------------------------------------------------------
38
39 #include "proxmark3.h"
40 #include "apps.h"
41 #include "util.h"
42 #include "string.h"
43 #include "common.h"
44 #include "cmd.h"
45 // Needed for CRC in emulation mode;
46 // same construction as in ISO 14443;
47 // different initial value (CRC_ICLASS)
48 #include "iso14443crc.h"
49 #include "iso15693tools.h"
50
51 static int timeout = 4096;
52
53
54 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay);
55
56 //-----------------------------------------------------------------------------
57 // The software UART that receives commands from the reader, and its state
58 // variables.
59 //-----------------------------------------------------------------------------
60 static struct {
61 enum {
62 STATE_UNSYNCD,
63 STATE_START_OF_COMMUNICATION,
64 STATE_RECEIVING
65 } state;
66 uint16_t shiftReg;
67 int bitCnt;
68 int byteCnt;
69 int byteCntMax;
70 int posCnt;
71 int nOutOfCnt;
72 int OutOfCnt;
73 int syncBit;
74 int samples;
75 int highCnt;
76 int swapper;
77 int counter;
78 int bitBuffer;
79 int dropPosition;
80 uint8_t *output;
81 } Uart;
82
83 static RAMFUNC int OutOfNDecoding(int bit)
84 {
85 //int error = 0;
86 int bitright;
87
88 if(!Uart.bitBuffer) {
89 Uart.bitBuffer = bit ^ 0xFF0;
90 return FALSE;
91 }
92 else {
93 Uart.bitBuffer <<= 4;
94 Uart.bitBuffer ^= bit;
95 }
96
97 /*if(Uart.swapper) {
98 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
99 Uart.byteCnt++;
100 Uart.swapper = 0;
101 if(Uart.byteCnt > 15) { return TRUE; }
102 }
103 else {
104 Uart.swapper = 1;
105 }*/
106
107 if(Uart.state != STATE_UNSYNCD) {
108 Uart.posCnt++;
109
110 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
111 bit = 0x00;
112 }
113 else {
114 bit = 0x01;
115 }
116 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
117 bitright = 0x00;
118 }
119 else {
120 bitright = 0x01;
121 }
122 if(bit != bitright) { bit = bitright; }
123
124
125 // So, now we only have to deal with *bit*, lets see...
126 if(Uart.posCnt == 1) {
127 // measurement first half bitperiod
128 if(!bit) {
129 // Drop in first half means that we are either seeing
130 // an SOF or an EOF.
131
132 if(Uart.nOutOfCnt == 1) {
133 // End of Communication
134 Uart.state = STATE_UNSYNCD;
135 Uart.highCnt = 0;
136 if(Uart.byteCnt == 0) {
137 // Its not straightforward to show single EOFs
138 // So just leave it and do not return TRUE
139 Uart.output[0] = 0xf0;
140 Uart.byteCnt++;
141 }
142 else {
143 return TRUE;
144 }
145 }
146 else if(Uart.state != STATE_START_OF_COMMUNICATION) {
147 // When not part of SOF or EOF, it is an error
148 Uart.state = STATE_UNSYNCD;
149 Uart.highCnt = 0;
150 //error = 4;
151 }
152 }
153 }
154 else {
155 // measurement second half bitperiod
156 // Count the bitslot we are in... (ISO 15693)
157 Uart.nOutOfCnt++;
158
159 if(!bit) {
160 if(Uart.dropPosition) {
161 if(Uart.state == STATE_START_OF_COMMUNICATION) {
162 //error = 1;
163 }
164 else {
165 //error = 7;
166 }
167 // It is an error if we already have seen a drop in current frame
168 Uart.state = STATE_UNSYNCD;
169 Uart.highCnt = 0;
170 }
171 else {
172 Uart.dropPosition = Uart.nOutOfCnt;
173 }
174 }
175
176 Uart.posCnt = 0;
177
178
179 if(Uart.nOutOfCnt == Uart.OutOfCnt && Uart.OutOfCnt == 4) {
180 Uart.nOutOfCnt = 0;
181
182 if(Uart.state == STATE_START_OF_COMMUNICATION) {
183 if(Uart.dropPosition == 4) {
184 Uart.state = STATE_RECEIVING;
185 Uart.OutOfCnt = 256;
186 }
187 else if(Uart.dropPosition == 3) {
188 Uart.state = STATE_RECEIVING;
189 Uart.OutOfCnt = 4;
190 //Uart.output[Uart.byteCnt] = 0xdd;
191 //Uart.byteCnt++;
192 }
193 else {
194 Uart.state = STATE_UNSYNCD;
195 Uart.highCnt = 0;
196 }
197 Uart.dropPosition = 0;
198 }
199 else {
200 // RECEIVING DATA
201 // 1 out of 4
202 if(!Uart.dropPosition) {
203 Uart.state = STATE_UNSYNCD;
204 Uart.highCnt = 0;
205 //error = 9;
206 }
207 else {
208 Uart.shiftReg >>= 2;
209
210 // Swap bit order
211 Uart.dropPosition--;
212 //if(Uart.dropPosition == 1) { Uart.dropPosition = 2; }
213 //else if(Uart.dropPosition == 2) { Uart.dropPosition = 1; }
214
215 Uart.shiftReg ^= ((Uart.dropPosition & 0x03) << 6);
216 Uart.bitCnt += 2;
217 Uart.dropPosition = 0;
218
219 if(Uart.bitCnt == 8) {
220 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
221 Uart.byteCnt++;
222 Uart.bitCnt = 0;
223 Uart.shiftReg = 0;
224 }
225 }
226 }
227 }
228 else if(Uart.nOutOfCnt == Uart.OutOfCnt) {
229 // RECEIVING DATA
230 // 1 out of 256
231 if(!Uart.dropPosition) {
232 Uart.state = STATE_UNSYNCD;
233 Uart.highCnt = 0;
234 //error = 3;
235 }
236 else {
237 Uart.dropPosition--;
238 Uart.output[Uart.byteCnt] = (Uart.dropPosition & 0xff);
239 Uart.byteCnt++;
240 Uart.bitCnt = 0;
241 Uart.shiftReg = 0;
242 Uart.nOutOfCnt = 0;
243 Uart.dropPosition = 0;
244 }
245 }
246
247 /*if(error) {
248 Uart.output[Uart.byteCnt] = 0xAA;
249 Uart.byteCnt++;
250 Uart.output[Uart.byteCnt] = error & 0xFF;
251 Uart.byteCnt++;
252 Uart.output[Uart.byteCnt] = 0xAA;
253 Uart.byteCnt++;
254 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
255 Uart.byteCnt++;
256 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
257 Uart.byteCnt++;
258 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
259 Uart.byteCnt++;
260 Uart.output[Uart.byteCnt] = 0xAA;
261 Uart.byteCnt++;
262 return TRUE;
263 }*/
264 }
265
266 }
267 else {
268 bit = Uart.bitBuffer & 0xf0;
269 bit >>= 4;
270 bit ^= 0x0F; // drops become 1s ;-)
271 if(bit) {
272 // should have been high or at least (4 * 128) / fc
273 // according to ISO this should be at least (9 * 128 + 20) / fc
274 if(Uart.highCnt == 8) {
275 // we went low, so this could be start of communication
276 // it turns out to be safer to choose a less significant
277 // syncbit... so we check whether the neighbour also represents the drop
278 Uart.posCnt = 1; // apparently we are busy with our first half bit period
279 Uart.syncBit = bit & 8;
280 Uart.samples = 3;
281 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
282 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
283 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
284 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
285 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
286 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
287 Uart.syncBit = 8;
288
289 // the first half bit period is expected in next sample
290 Uart.posCnt = 0;
291 Uart.samples = 3;
292 }
293 }
294 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
295
296 Uart.syncBit <<= 4;
297 Uart.state = STATE_START_OF_COMMUNICATION;
298 Uart.bitCnt = 0;
299 Uart.byteCnt = 0;
300 Uart.nOutOfCnt = 0;
301 Uart.OutOfCnt = 4; // Start at 1/4, could switch to 1/256
302 Uart.dropPosition = 0;
303 Uart.shiftReg = 0;
304 //error = 0;
305 }
306 else {
307 Uart.highCnt = 0;
308 }
309 }
310 else {
311 if(Uart.highCnt < 8) {
312 Uart.highCnt++;
313 }
314 }
315 }
316
317 return FALSE;
318 }
319
320 //=============================================================================
321 // Manchester
322 //=============================================================================
323
324 static struct {
325 enum {
326 DEMOD_UNSYNCD,
327 DEMOD_START_OF_COMMUNICATION,
328 DEMOD_START_OF_COMMUNICATION2,
329 DEMOD_START_OF_COMMUNICATION3,
330 DEMOD_SOF_COMPLETE,
331 DEMOD_MANCHESTER_D,
332 DEMOD_MANCHESTER_E,
333 DEMOD_END_OF_COMMUNICATION,
334 DEMOD_END_OF_COMMUNICATION2,
335 DEMOD_MANCHESTER_F,
336 DEMOD_ERROR_WAIT
337 } state;
338 int bitCount;
339 int posCount;
340 int syncBit;
341 uint16_t shiftReg;
342 int buffer;
343 int buffer2;
344 int buffer3;
345 int buff;
346 int samples;
347 int len;
348 enum {
349 SUB_NONE,
350 SUB_FIRST_HALF,
351 SUB_SECOND_HALF,
352 SUB_BOTH
353 } sub;
354 uint8_t *output;
355 } Demod;
356
357 static RAMFUNC int ManchesterDecoding(int v)
358 {
359 int bit;
360 int modulation;
361 int error = 0;
362
363 bit = Demod.buffer;
364 Demod.buffer = Demod.buffer2;
365 Demod.buffer2 = Demod.buffer3;
366 Demod.buffer3 = v;
367
368 if(Demod.buff < 3) {
369 Demod.buff++;
370 return FALSE;
371 }
372
373 if(Demod.state==DEMOD_UNSYNCD) {
374 Demod.output[Demod.len] = 0xfa;
375 Demod.syncBit = 0;
376 //Demod.samples = 0;
377 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
378
379 if(bit & 0x08) {
380 Demod.syncBit = 0x08;
381 }
382
383 if(bit & 0x04) {
384 if(Demod.syncBit) {
385 bit <<= 4;
386 }
387 Demod.syncBit = 0x04;
388 }
389
390 if(bit & 0x02) {
391 if(Demod.syncBit) {
392 bit <<= 2;
393 }
394 Demod.syncBit = 0x02;
395 }
396
397 if(bit & 0x01 && Demod.syncBit) {
398 Demod.syncBit = 0x01;
399 }
400
401 if(Demod.syncBit) {
402 Demod.len = 0;
403 Demod.state = DEMOD_START_OF_COMMUNICATION;
404 Demod.sub = SUB_FIRST_HALF;
405 Demod.bitCount = 0;
406 Demod.shiftReg = 0;
407 Demod.samples = 0;
408 if(Demod.posCount) {
409 //if(trigger) LED_A_OFF(); // Not useful in this case...
410 switch(Demod.syncBit) {
411 case 0x08: Demod.samples = 3; break;
412 case 0x04: Demod.samples = 2; break;
413 case 0x02: Demod.samples = 1; break;
414 case 0x01: Demod.samples = 0; break;
415 }
416 // SOF must be long burst... otherwise stay unsynced!!!
417 if(!(Demod.buffer & Demod.syncBit) || !(Demod.buffer2 & Demod.syncBit)) {
418 Demod.state = DEMOD_UNSYNCD;
419 }
420 }
421 else {
422 // SOF must be long burst... otherwise stay unsynced!!!
423 if(!(Demod.buffer2 & Demod.syncBit) || !(Demod.buffer3 & Demod.syncBit)) {
424 Demod.state = DEMOD_UNSYNCD;
425 error = 0x88;
426 }
427
428 }
429 error = 0;
430
431 }
432 }
433 else {
434 modulation = bit & Demod.syncBit;
435 modulation |= ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
436
437 Demod.samples += 4;
438
439 if(Demod.posCount==0) {
440 Demod.posCount = 1;
441 if(modulation) {
442 Demod.sub = SUB_FIRST_HALF;
443 }
444 else {
445 Demod.sub = SUB_NONE;
446 }
447 }
448 else {
449 Demod.posCount = 0;
450 /*(modulation && (Demod.sub == SUB_FIRST_HALF)) {
451 if(Demod.state!=DEMOD_ERROR_WAIT) {
452 Demod.state = DEMOD_ERROR_WAIT;
453 Demod.output[Demod.len] = 0xaa;
454 error = 0x01;
455 }
456 }*/
457 //else if(modulation) {
458 if(modulation) {
459 if(Demod.sub == SUB_FIRST_HALF) {
460 Demod.sub = SUB_BOTH;
461 }
462 else {
463 Demod.sub = SUB_SECOND_HALF;
464 }
465 }
466 else if(Demod.sub == SUB_NONE) {
467 if(Demod.state == DEMOD_SOF_COMPLETE) {
468 Demod.output[Demod.len] = 0x0f;
469 Demod.len++;
470 Demod.state = DEMOD_UNSYNCD;
471 // error = 0x0f;
472 return TRUE;
473 }
474 else {
475 Demod.state = DEMOD_ERROR_WAIT;
476 error = 0x33;
477 }
478 /*if(Demod.state!=DEMOD_ERROR_WAIT) {
479 Demod.state = DEMOD_ERROR_WAIT;
480 Demod.output[Demod.len] = 0xaa;
481 error = 0x01;
482 }*/
483 }
484
485 switch(Demod.state) {
486 case DEMOD_START_OF_COMMUNICATION:
487 if(Demod.sub == SUB_BOTH) {
488 //Demod.state = DEMOD_MANCHESTER_D;
489 Demod.state = DEMOD_START_OF_COMMUNICATION2;
490 Demod.posCount = 1;
491 Demod.sub = SUB_NONE;
492 }
493 else {
494 Demod.output[Demod.len] = 0xab;
495 Demod.state = DEMOD_ERROR_WAIT;
496 error = 0xd2;
497 }
498 break;
499 case DEMOD_START_OF_COMMUNICATION2:
500 if(Demod.sub == SUB_SECOND_HALF) {
501 Demod.state = DEMOD_START_OF_COMMUNICATION3;
502 }
503 else {
504 Demod.output[Demod.len] = 0xab;
505 Demod.state = DEMOD_ERROR_WAIT;
506 error = 0xd3;
507 }
508 break;
509 case DEMOD_START_OF_COMMUNICATION3:
510 if(Demod.sub == SUB_SECOND_HALF) {
511 // Demod.state = DEMOD_MANCHESTER_D;
512 Demod.state = DEMOD_SOF_COMPLETE;
513 //Demod.output[Demod.len] = Demod.syncBit & 0xFF;
514 //Demod.len++;
515 }
516 else {
517 Demod.output[Demod.len] = 0xab;
518 Demod.state = DEMOD_ERROR_WAIT;
519 error = 0xd4;
520 }
521 break;
522 case DEMOD_SOF_COMPLETE:
523 case DEMOD_MANCHESTER_D:
524 case DEMOD_MANCHESTER_E:
525 // OPPOSITE FROM ISO14443 - 11110000 = 0 (1 in 14443)
526 // 00001111 = 1 (0 in 14443)
527 if(Demod.sub == SUB_SECOND_HALF) { // SUB_FIRST_HALF
528 Demod.bitCount++;
529 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
530 Demod.state = DEMOD_MANCHESTER_D;
531 }
532 else if(Demod.sub == SUB_FIRST_HALF) { // SUB_SECOND_HALF
533 Demod.bitCount++;
534 Demod.shiftReg >>= 1;
535 Demod.state = DEMOD_MANCHESTER_E;
536 }
537 else if(Demod.sub == SUB_BOTH) {
538 Demod.state = DEMOD_MANCHESTER_F;
539 }
540 else {
541 Demod.state = DEMOD_ERROR_WAIT;
542 error = 0x55;
543 }
544 break;
545
546 case DEMOD_MANCHESTER_F:
547 // Tag response does not need to be a complete byte!
548 if(Demod.len > 0 || Demod.bitCount > 0) {
549 if(Demod.bitCount > 1) { // was > 0, do not interpret last closing bit, is part of EOF
550 Demod.shiftReg >>= (9 - Demod.bitCount); // right align data
551 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
552 Demod.len++;
553 }
554
555 Demod.state = DEMOD_UNSYNCD;
556 return TRUE;
557 }
558 else {
559 Demod.output[Demod.len] = 0xad;
560 Demod.state = DEMOD_ERROR_WAIT;
561 error = 0x03;
562 }
563 break;
564
565 case DEMOD_ERROR_WAIT:
566 Demod.state = DEMOD_UNSYNCD;
567 break;
568
569 default:
570 Demod.output[Demod.len] = 0xdd;
571 Demod.state = DEMOD_UNSYNCD;
572 break;
573 }
574
575 /*if(Demod.bitCount>=9) {
576 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
577 Demod.len++;
578
579 Demod.parityBits <<= 1;
580 Demod.parityBits ^= ((Demod.shiftReg >> 8) & 0x01);
581
582 Demod.bitCount = 0;
583 Demod.shiftReg = 0;
584 }*/
585 if(Demod.bitCount>=8) {
586 Demod.shiftReg >>= 1;
587 Demod.output[Demod.len] = (Demod.shiftReg & 0xff);
588 Demod.len++;
589 Demod.bitCount = 0;
590 Demod.shiftReg = 0;
591 }
592
593 if(error) {
594 Demod.output[Demod.len] = 0xBB;
595 Demod.len++;
596 Demod.output[Demod.len] = error & 0xFF;
597 Demod.len++;
598 Demod.output[Demod.len] = 0xBB;
599 Demod.len++;
600 Demod.output[Demod.len] = bit & 0xFF;
601 Demod.len++;
602 Demod.output[Demod.len] = Demod.buffer & 0xFF;
603 Demod.len++;
604 // Look harder ;-)
605 Demod.output[Demod.len] = Demod.buffer2 & 0xFF;
606 Demod.len++;
607 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
608 Demod.len++;
609 Demod.output[Demod.len] = 0xBB;
610 Demod.len++;
611 return TRUE;
612 }
613
614 }
615
616 } // end (state != UNSYNCED)
617
618 return FALSE;
619 }
620
621 //=============================================================================
622 // Finally, a `sniffer' for iClass communication
623 // Both sides of communication!
624 //=============================================================================
625
626 //-----------------------------------------------------------------------------
627 // Record the sequence of commands sent by the reader to the tag, with
628 // triggering so that we start recording at the point that the tag is moved
629 // near the reader.
630 //-----------------------------------------------------------------------------
631 void RAMFUNC SnoopIClass(void)
632 {
633
634
635 // We won't start recording the frames that we acquire until we trigger;
636 // a good trigger condition to get started is probably when we see a
637 // response from the tag.
638 //int triggered = FALSE; // FALSE to wait first for card
639
640 // The command (reader -> tag) that we're receiving.
641 // The length of a received command will in most cases be no more than 18 bytes.
642 // So 32 should be enough!
643 uint8_t *readerToTagCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
644 // The response (tag -> reader) that we're receiving.
645 uint8_t *tagToReaderResponse = (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);
646
647 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
648
649 // reset traceLen to 0
650 iso14a_set_tracing(TRUE);
651 iso14a_clear_trace();
652 iso14a_set_trigger(FALSE);
653
654 // The DMA buffer, used to stream samples from the FPGA
655 int8_t *dmaBuf = ((int8_t *)BigBuf) + DMA_BUFFER_OFFSET;
656 int lastRxCounter;
657 int8_t *upTo;
658 int smpl;
659 int maxBehindBy = 0;
660
661 // Count of samples received so far, so that we can include timing
662 // information in the trace buffer.
663 int samples = 0;
664 rsamples = 0;
665
666 // Set up the demodulator for tag -> reader responses.
667 Demod.output = tagToReaderResponse;
668 Demod.len = 0;
669 Demod.state = DEMOD_UNSYNCD;
670
671 // Setup for the DMA.
672 FpgaSetupSsc();
673 upTo = dmaBuf;
674 lastRxCounter = DMA_BUFFER_SIZE;
675 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
676
677 // And the reader -> tag commands
678 memset(&Uart, 0, sizeof(Uart));
679 Uart.output = readerToTagCmd;
680 Uart.byteCntMax = 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
681 Uart.state = STATE_UNSYNCD;
682
683 // And put the FPGA in the appropriate mode
684 // Signal field is off with the appropriate LED
685 LED_D_OFF();
686 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
687 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
688
689 uint32_t time_0 = GetCountSspClk();
690
691
692 int div = 0;
693 //int div2 = 0;
694 int decbyte = 0;
695 int decbyter = 0;
696
697 // And now we loop, receiving samples.
698 for(;;) {
699 LED_A_ON();
700 WDT_HIT();
701 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
702 (DMA_BUFFER_SIZE-1);
703 if(behindBy > maxBehindBy) {
704 maxBehindBy = behindBy;
705 if(behindBy > 400) {
706 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
707 goto done;
708 }
709 }
710 if(behindBy < 1) continue;
711
712 LED_A_OFF();
713 smpl = upTo[0];
714 upTo++;
715 lastRxCounter -= 1;
716 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
717 upTo -= DMA_BUFFER_SIZE;
718 lastRxCounter += DMA_BUFFER_SIZE;
719 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
720 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
721 }
722
723 //samples += 4;
724 samples += 1;
725
726 if(smpl & 0xF) {
727 decbyte ^= (1 << (3 - div));
728 }
729
730 // FOR READER SIDE COMMUMICATION...
731
732 decbyter <<= 2;
733 decbyter ^= (smpl & 0x30);
734
735 div++;
736
737 if((div + 1) % 2 == 0) {
738 smpl = decbyter;
739 if(OutOfNDecoding((smpl & 0xF0) >> 4)) {
740 rsamples = samples - Uart.samples;
741 LED_C_ON();
742
743 //if(!LogTrace(Uart.output,Uart.byteCnt, rsamples, Uart.parityBits,TRUE)) break;
744 //if(!LogTrace(NULL, 0, Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, 0, TRUE)) break;
745 if(tracing) {
746 uint8_t parity[MAX_PARITY_SIZE];
747 GetParity(Uart.output, Uart.byteCnt, parity);
748 LogTrace(Uart.output,Uart.byteCnt, (GetCountSspClk()-time_0) << 4, (GetCountSspClk()-time_0) << 4, parity, TRUE);
749 }
750
751
752 /* And ready to receive another command. */
753 Uart.state = STATE_UNSYNCD;
754 /* And also reset the demod code, which might have been */
755 /* false-triggered by the commands from the reader. */
756 Demod.state = DEMOD_UNSYNCD;
757 LED_B_OFF();
758 Uart.byteCnt = 0;
759 }
760 decbyter = 0;
761 }
762
763 if(div > 3) {
764 smpl = decbyte;
765 if(ManchesterDecoding(smpl & 0x0F)) {
766 rsamples = samples - Demod.samples;
767 LED_B_ON();
768
769 if(tracing) {
770 uint8_t parity[MAX_PARITY_SIZE];
771 GetParity(Demod.output, Demod.len, parity);
772 LogTrace(Demod.output, Demod.len, (GetCountSspClk()-time_0) << 4, (GetCountSspClk()-time_0) << 4, parity, FALSE);
773 }
774
775
776 // And ready to receive another response.
777 memset(&Demod, 0, sizeof(Demod));
778 Demod.output = tagToReaderResponse;
779 Demod.state = DEMOD_UNSYNCD;
780 LED_C_OFF();
781 }
782
783 div = 0;
784 decbyte = 0x00;
785 }
786 //}
787
788 if(BUTTON_PRESS()) {
789 DbpString("cancelled_a");
790 goto done;
791 }
792 }
793
794 DbpString("COMMAND FINISHED");
795
796 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
797 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
798
799 done:
800 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
801 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
802 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
803 LED_A_OFF();
804 LED_B_OFF();
805 LED_C_OFF();
806 LED_D_OFF();
807 }
808
809 void rotateCSN(uint8_t* originalCSN, uint8_t* rotatedCSN) {
810 int i;
811 for(i = 0; i < 8; i++) {
812 rotatedCSN[i] = (originalCSN[i] >> 3) | (originalCSN[(i+1)%8] << 5);
813 }
814 }
815
816 //-----------------------------------------------------------------------------
817 // Wait for commands from reader
818 // Stop when button is pressed
819 // Or return TRUE when command is captured
820 //-----------------------------------------------------------------------------
821 static int GetIClassCommandFromReader(uint8_t *received, int *len, int maxLen)
822 {
823 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
824 // only, since we are receiving, not transmitting).
825 // Signal field is off with the appropriate LED
826 LED_D_OFF();
827 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
828
829 // Now run a `software UART' on the stream of incoming samples.
830 Uart.output = received;
831 Uart.byteCntMax = maxLen;
832 Uart.state = STATE_UNSYNCD;
833
834 for(;;) {
835 WDT_HIT();
836
837 if(BUTTON_PRESS()) return FALSE;
838
839 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
840 AT91C_BASE_SSC->SSC_THR = 0x00;
841 }
842 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
843 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
844
845 if(OutOfNDecoding(b & 0x0f)) {
846 *len = Uart.byteCnt;
847 return TRUE;
848 }
849 }
850 }
851 }
852
853
854 //-----------------------------------------------------------------------------
855 // Prepare tag messages
856 //-----------------------------------------------------------------------------
857 static void CodeIClassTagAnswer(const uint8_t *cmd, int len)
858 {
859 //So far a dummy implementation, not used
860 //int lastProxToAirDuration =0;
861 int i;
862
863 ToSendReset();
864
865 // Send SOF
866 ToSend[++ToSendMax] = 0x00;
867 ToSend[++ToSendMax] = 0x00;
868 ToSend[++ToSendMax] = 0x00;
869 ToSend[++ToSendMax] = 0xff;//Proxtoair duration starts here
870 ToSend[++ToSendMax] = 0xff;
871 ToSend[++ToSendMax] = 0xff;
872 ToSend[++ToSendMax] = 0x00;
873 ToSend[++ToSendMax] = 0xff;
874
875 for(i = 0; i < len; i++) {
876 int j;
877 uint8_t b = cmd[i];
878
879 // Data bits
880 for(j = 0; j < 8; j++) {
881 if(b & 1) {
882 ToSend[++ToSendMax] = 0x00;
883 ToSend[++ToSendMax] = 0xff;
884 } else {
885 ToSend[++ToSendMax] = 0xff;
886 ToSend[++ToSendMax] = 0x00;
887 }
888 b >>= 1;
889 }
890 }
891
892 // Send EOF
893 ToSend[++ToSendMax] = 0xff;
894 ToSend[++ToSendMax] = 0x00;
895 ToSend[++ToSendMax] = 0xff;
896 ToSend[++ToSendMax] = 0xff;
897 ToSend[++ToSendMax] = 0xff;
898 ToSend[++ToSendMax] = 0x00;
899 ToSend[++ToSendMax] = 0x00;
900 ToSend[++ToSendMax] = 0x00;
901
902 //lastProxToAirDuration = 8*ToSendMax - 3*8 - 3*8;//Not counting zeroes in the beginning or end
903
904 // Convert from last byte pos to length
905 ToSendMax++;
906 }
907
908 // Only SOF
909 static void CodeIClassTagSOF()
910 {
911 //So far a dummy implementation, not used
912 //int lastProxToAirDuration =0;
913
914 ToSendReset();
915 // Send SOF
916 ToSend[++ToSendMax] = 0x00;
917 ToSend[++ToSendMax] = 0x00;
918 ToSend[++ToSendMax] = 0x00;
919 ToSend[++ToSendMax] = 0xff;
920 ToSend[++ToSendMax] = 0xff;
921 ToSend[++ToSendMax] = 0xff;
922 ToSend[++ToSendMax] = 0x00;
923 ToSend[++ToSendMax] = 0xff;
924
925 // lastProxToAirDuration = 8*ToSendMax - 3*8;//Not counting zeroes in the beginning
926
927
928 // Convert from last byte pos to length
929 ToSendMax++;
930 }
931 int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf);
932 /**
933 * @brief SimulateIClass simulates an iClass card.
934 * @param arg0 type of simulation
935 * - 0 uses the first 8 bytes in usb data as CSN
936 * - 2 "dismantling iclass"-attack. This mode iterates through all CSN's specified
937 * in the usb data. This mode collects MAC from the reader, in order to do an offline
938 * attack on the keys. For more info, see "dismantling iclass" and proxclone.com.
939 * - Other : Uses the default CSN (031fec8af7ff12e0)
940 * @param arg1 - number of CSN's contained in datain (applicable for mode 2 only)
941 * @param arg2
942 * @param datain
943 */
944 void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
945 {
946 uint32_t simType = arg0;
947 uint32_t numberOfCSNS = arg1;
948 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
949
950 // Enable and clear the trace
951 iso14a_set_tracing(TRUE);
952 iso14a_clear_trace();
953
954 uint8_t csn_crc[] = { 0x03, 0x1f, 0xec, 0x8a, 0xf7, 0xff, 0x12, 0xe0, 0x00, 0x00 };
955 if(simType == 0) {
956 // Use the CSN from commandline
957 memcpy(csn_crc, datain, 8);
958 doIClassSimulation(csn_crc,0,NULL);
959 }else if(simType == 1)
960 {
961 doIClassSimulation(csn_crc,0,NULL);
962 }
963 else if(simType == 2)
964 {
965
966 uint8_t mac_responses[64] = { 0 };
967 Dbprintf("Going into attack mode, %d CSNS sent", numberOfCSNS);
968 // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
969 // in order to collect MAC's from the reader. This can later be used in an offlne-attack
970 // in order to obtain the keys, as in the "dismantling iclass"-paper.
971 int i = 0;
972 for( ; i < numberOfCSNS && i*8+8 < USB_CMD_DATA_SIZE; i++)
973 {
974 // The usb data is 512 bytes, fitting 65 8-byte CSNs in there.
975
976 memcpy(csn_crc, datain+(i*8), 8);
977 if(doIClassSimulation(csn_crc,1,mac_responses+i*8))
978 {
979 return; // Button pressed
980 }
981 }
982 cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
983
984 }
985 else{
986 // We may want a mode here where we hardcode the csns to use (from proxclone).
987 // That will speed things up a little, but not required just yet.
988 Dbprintf("The mode is not implemented, reserved for future use");
989 }
990 Dbprintf("Done...");
991
992 }
993 /**
994 * @brief Does the actual simulation
995 * @param csn - csn to use
996 * @param breakAfterMacReceived if true, returns after reader MAC has been received.
997 */
998 int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf)
999 {
1000 // CSN followed by two CRC bytes
1001 uint8_t response2[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1002 uint8_t response3[] = { 0,0,0,0,0,0,0,0,0,0};
1003 memcpy(response3,csn,sizeof(response3));
1004 Dbprintf("Simulating CSN %02x%02x%02x%02x%02x%02x%02x%02x",csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]);
1005 // e-Purse
1006 uint8_t response4[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1007
1008 // Construct anticollision-CSN
1009 rotateCSN(response3,response2);
1010
1011 // Compute CRC on both CSNs
1012 ComputeCrc14443(CRC_ICLASS, response2, 8, &response2[8], &response2[9]);
1013 ComputeCrc14443(CRC_ICLASS, response3, 8, &response3[8], &response3[9]);
1014
1015 int exitLoop = 0;
1016 // Reader 0a
1017 // Tag 0f
1018 // Reader 0c
1019 // Tag anticoll. CSN
1020 // Reader 81 anticoll. CSN
1021 // Tag CSN
1022
1023 uint8_t *resp;
1024 int respLen;
1025 uint8_t* respdata = NULL;
1026 int respsize = 0;
1027 uint8_t sof = 0x0f;
1028
1029 // Respond SOF -- takes 8 bytes
1030 uint8_t *resp1 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET);
1031 int resp1Len;
1032
1033 // Anticollision CSN (rotated CSN)
1034 // 176: Takes 16 bytes for SOF/EOF and 10 * 16 = 160 bytes (2 bytes/bit)
1035 uint8_t *resp2 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 10);
1036 int resp2Len;
1037
1038 // CSN
1039 // 176: Takes 16 bytes for SOF/EOF and 10 * 16 = 160 bytes (2 bytes/bit)
1040 uint8_t *resp3 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 190);
1041 int resp3Len;
1042
1043 // e-Purse
1044 // 144: Takes 16 bytes for SOF/EOF and 8 * 16 = 128 bytes (2 bytes/bit)
1045 uint8_t *resp4 = (((uint8_t *)BigBuf) + FREE_BUFFER_OFFSET + 370);
1046 int resp4Len;
1047
1048 // + 1720..
1049 uint8_t *receivedCmd = (((uint8_t *)BigBuf) + RECV_CMD_OFFSET);
1050 memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
1051 int len;
1052
1053 // Prepare card messages
1054 ToSendMax = 0;
1055
1056 // First card answer: SOF
1057 CodeIClassTagSOF();
1058 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
1059
1060 // Anticollision CSN
1061 CodeIClassTagAnswer(response2, sizeof(response2));
1062 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
1063
1064 // CSN
1065 CodeIClassTagAnswer(response3, sizeof(response3));
1066 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
1067
1068 // e-Purse
1069 CodeIClassTagAnswer(response4, sizeof(response4));
1070 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1071
1072
1073 // Start from off (no field generated)
1074 //FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1075 //SpinDelay(200);
1076 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1077 SpinDelay(100);
1078 StartCountSspClk();
1079 // We need to listen to the high-frequency, peak-detected path.
1080 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1081 FpgaSetupSsc();
1082
1083 // To control where we are in the protocol
1084 int cmdsRecvd = 0;
1085 uint32_t time_0 = GetCountSspClk();
1086 uint32_t t2r_time =0;
1087 uint32_t r2t_time =0;
1088
1089 LED_A_ON();
1090 bool buttonPressed = false;
1091
1092 /** Hack for testing
1093 memcpy(reader_mac_buf,csn,8);
1094 exitLoop = true;
1095 end hack **/
1096
1097 while(!exitLoop) {
1098
1099 LED_B_OFF();
1100 //Signal tracer
1101 // Can be used to get a trigger for an oscilloscope..
1102 LED_C_OFF();
1103
1104 if(!GetIClassCommandFromReader(receivedCmd, &len, 100)) {
1105 buttonPressed = true;
1106 break;
1107 }
1108 r2t_time = GetCountSspClk();
1109 //Signal tracer
1110 LED_C_ON();
1111
1112 // Okay, look at the command now.
1113 if(receivedCmd[0] == 0x0a ) {
1114 // Reader in anticollission phase
1115 resp = resp1; respLen = resp1Len; //order = 1;
1116 respdata = &sof;
1117 respsize = sizeof(sof);
1118 } else if(receivedCmd[0] == 0x0c) {
1119 // Reader asks for anticollission CSN
1120 resp = resp2; respLen = resp2Len; //order = 2;
1121 respdata = response2;
1122 respsize = sizeof(response2);
1123 //DbpString("Reader requests anticollission CSN:");
1124 } else if(receivedCmd[0] == 0x81) {
1125 // Reader selects anticollission CSN.
1126 // Tag sends the corresponding real CSN
1127 resp = resp3; respLen = resp3Len; //order = 3;
1128 respdata = response3;
1129 respsize = sizeof(response3);
1130 //DbpString("Reader selects anticollission CSN:");
1131 } else if(receivedCmd[0] == 0x88) {
1132 // Read e-purse (88 02)
1133 resp = resp4; respLen = resp4Len; //order = 4;
1134 respdata = response4;
1135 respsize = sizeof(response4);
1136 LED_B_ON();
1137 } else if(receivedCmd[0] == 0x05) {
1138 // Reader random and reader MAC!!!
1139 // Do not respond
1140 // We do not know what to answer, so lets keep quiet
1141 resp = resp1; respLen = 0; //order = 5;
1142 respdata = NULL;
1143 respsize = 0;
1144 if (breakAfterMacReceived){
1145 // dbprintf:ing ...
1146 Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x"
1147 ,csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]);
1148 Dbprintf("RDR: (len=%02d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",len,
1149 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1150 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1151 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1152 if (reader_mac_buf != NULL)
1153 {
1154 memcpy(reader_mac_buf,receivedCmd+1,8);
1155 }
1156 exitLoop = true;
1157 }
1158 } else if(receivedCmd[0] == 0x00 && len == 1) {
1159 // Reader ends the session
1160 resp = resp1; respLen = 0; //order = 0;
1161 respdata = NULL;
1162 respsize = 0;
1163 } else {
1164 //#db# Unknown command received from reader (len=5): 26 1 0 f6 a 44 44 44 44
1165 // Never seen this command before
1166 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1167 len,
1168 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1169 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1170 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1171 // Do not respond
1172 resp = resp1; respLen = 0; //order = 0;
1173 respdata = NULL;
1174 respsize = 0;
1175 }
1176
1177 if(cmdsRecvd > 100) {
1178 //DbpString("100 commands later...");
1179 //break;
1180 }
1181 else {
1182 cmdsRecvd++;
1183 }
1184
1185 if(respLen > 0) {
1186 SendIClassAnswer(resp, respLen, 21);
1187 t2r_time = GetCountSspClk();
1188 }
1189
1190 if (tracing) {
1191 uint8_t parity[MAX_PARITY_SIZE];
1192 GetParity(receivedCmd, len, parity);
1193 LogTrace(receivedCmd,len, (r2t_time-time_0)<< 4, (r2t_time-time_0) << 4, parity, TRUE);
1194
1195 if (respdata != NULL) {
1196 GetParity(respdata, respsize, parity);
1197 LogTrace(respdata, respsize, (t2r_time-time_0) << 4, (t2r_time-time_0) << 4, parity, FALSE);
1198 }
1199 if(!tracing) {
1200 DbpString("Trace full");
1201 //break;
1202 }
1203
1204 }
1205 memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
1206 }
1207
1208 //Dbprintf("%x", cmdsRecvd);
1209 LED_A_OFF();
1210 LED_B_OFF();
1211 if(buttonPressed)
1212 {
1213 DbpString("Button pressed");
1214 }
1215 return buttonPressed;
1216 }
1217
1218 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay)
1219 {
1220 int i = 0, d=0;//, u = 0, d = 0;
1221 uint8_t b = 0;
1222
1223 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K);
1224
1225 AT91C_BASE_SSC->SSC_THR = 0x00;
1226 FpgaSetupSsc();
1227 while(!BUTTON_PRESS()) {
1228 if((AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)){
1229 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
1230 }
1231 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)){
1232 b = 0x00;
1233 if(d < delay) {
1234 d++;
1235 }
1236 else {
1237 if( i < respLen){
1238 b = resp[i];
1239 //Hack
1240 //b = 0xAC;
1241 }
1242 i++;
1243 }
1244 AT91C_BASE_SSC->SSC_THR = b;
1245 }
1246
1247 if (i > respLen +4) break;
1248 }
1249
1250 return 0;
1251 }
1252
1253 /// THE READER CODE
1254
1255 //-----------------------------------------------------------------------------
1256 // Transmit the command (to the tag) that was placed in ToSend[].
1257 //-----------------------------------------------------------------------------
1258 static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait)
1259 {
1260 int c;
1261 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1262 AT91C_BASE_SSC->SSC_THR = 0x00;
1263 FpgaSetupSsc();
1264
1265 if (wait)
1266 {
1267 if(*wait < 10) *wait = 10;
1268
1269 for(c = 0; c < *wait;) {
1270 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1271 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1272 c++;
1273 }
1274 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1275 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1276 (void)r;
1277 }
1278 WDT_HIT();
1279 }
1280
1281 }
1282
1283
1284 uint8_t sendbyte;
1285 bool firstpart = TRUE;
1286 c = 0;
1287 for(;;) {
1288 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1289
1290 // DOUBLE THE SAMPLES!
1291 if(firstpart) {
1292 sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4);
1293 }
1294 else {
1295 sendbyte = (cmd[c] & 0x0f) | (cmd[c] << 4);
1296 c++;
1297 }
1298 if(sendbyte == 0xff) {
1299 sendbyte = 0xfe;
1300 }
1301 AT91C_BASE_SSC->SSC_THR = sendbyte;
1302 firstpart = !firstpart;
1303
1304 if(c >= len) {
1305 break;
1306 }
1307 }
1308 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1309 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1310 (void)r;
1311 }
1312 WDT_HIT();
1313 }
1314 if (samples) *samples = (c + *wait) << 3;
1315 }
1316
1317
1318 //-----------------------------------------------------------------------------
1319 // Prepare iClass reader command to send to FPGA
1320 //-----------------------------------------------------------------------------
1321 void CodeIClassCommand(const uint8_t * cmd, int len)
1322 {
1323 int i, j, k;
1324 uint8_t b;
1325
1326 ToSendReset();
1327
1328 // Start of Communication: 1 out of 4
1329 ToSend[++ToSendMax] = 0xf0;
1330 ToSend[++ToSendMax] = 0x00;
1331 ToSend[++ToSendMax] = 0x0f;
1332 ToSend[++ToSendMax] = 0x00;
1333
1334 // Modulate the bytes
1335 for (i = 0; i < len; i++) {
1336 b = cmd[i];
1337 for(j = 0; j < 4; j++) {
1338 for(k = 0; k < 4; k++) {
1339 if(k == (b & 3)) {
1340 ToSend[++ToSendMax] = 0x0f;
1341 }
1342 else {
1343 ToSend[++ToSendMax] = 0x00;
1344 }
1345 }
1346 b >>= 2;
1347 }
1348 }
1349
1350 // End of Communication
1351 ToSend[++ToSendMax] = 0x00;
1352 ToSend[++ToSendMax] = 0x00;
1353 ToSend[++ToSendMax] = 0xf0;
1354 ToSend[++ToSendMax] = 0x00;
1355
1356 // Convert from last character reference to length
1357 ToSendMax++;
1358 }
1359
1360 void ReaderTransmitIClass(uint8_t* frame, int len)
1361 {
1362 int wait = 0;
1363 int samples = 0;
1364
1365 // This is tied to other size changes
1366 CodeIClassCommand(frame,len);
1367
1368 // Select the card
1369 TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
1370 if(trigger)
1371 LED_A_ON();
1372
1373 // Store reader command in buffer
1374 if (tracing) {
1375 uint8_t par[MAX_PARITY_SIZE];
1376 GetParity(frame, len, par);
1377 LogTrace(frame, len, rsamples, rsamples, par, TRUE);
1378 }
1379 }
1380
1381 //-----------------------------------------------------------------------------
1382 // Wait a certain time for tag response
1383 // If a response is captured return TRUE
1384 // If it takes too long return FALSE
1385 //-----------------------------------------------------------------------------
1386 static int GetIClassAnswer(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
1387 {
1388 // buffer needs to be 512 bytes
1389 int c;
1390
1391 // Set FPGA mode to "reader listen mode", no modulation (listen
1392 // only, since we are receiving, not transmitting).
1393 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1394
1395 // Now get the answer from the card
1396 Demod.output = receivedResponse;
1397 Demod.len = 0;
1398 Demod.state = DEMOD_UNSYNCD;
1399
1400 uint8_t b;
1401 if (elapsed) *elapsed = 0;
1402
1403 bool skip = FALSE;
1404
1405 c = 0;
1406 for(;;) {
1407 WDT_HIT();
1408
1409 if(BUTTON_PRESS()) return FALSE;
1410
1411 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1412 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1413 if (elapsed) (*elapsed)++;
1414 }
1415 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1416 if(c < timeout) { c++; } else { return FALSE; }
1417 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1418 skip = !skip;
1419 if(skip) continue;
1420
1421 if(ManchesterDecoding(b & 0x0f)) {
1422 *samples = c << 3;
1423 return TRUE;
1424 }
1425 }
1426 }
1427 }
1428
1429 int ReaderReceiveIClass(uint8_t* receivedAnswer)
1430 {
1431 int samples = 0;
1432 if (!GetIClassAnswer(receivedAnswer,160,&samples,0)) return FALSE;
1433 rsamples += samples;
1434 if (tracing) {
1435 uint8_t parity[MAX_PARITY_SIZE];
1436 GetParity(receivedAnswer, Demod.len, parity);
1437 LogTrace(receivedAnswer,Demod.len,rsamples,rsamples,parity,FALSE);
1438 }
1439 if(samples == 0) return FALSE;
1440 return Demod.len;
1441 }
1442
1443 void setupIclassReader()
1444 {
1445 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1446 // Reset trace buffer
1447 iso14a_set_tracing(TRUE);
1448 iso14a_clear_trace();
1449
1450 // Setup SSC
1451 FpgaSetupSsc();
1452 // Start from off (no field generated)
1453 // Signal field is off with the appropriate LED
1454 LED_D_OFF();
1455 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1456 SpinDelay(200);
1457
1458 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1459
1460 // Now give it time to spin up.
1461 // Signal field is on with the appropriate LED
1462 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1463 SpinDelay(200);
1464 LED_A_ON();
1465
1466 }
1467
1468 size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries)
1469 {
1470 while(retries-- > 0)
1471 {
1472 ReaderTransmitIClass(command, cmdsize);
1473 if(expected_size == ReaderReceiveIClass(resp)){
1474 return 0;
1475 }
1476 }
1477 return 1;//Error
1478 }
1479
1480 /**
1481 * @brief Talks to an iclass tag, sends the commands to get CSN and CC.
1482 * @param card_data where the CSN and CC are stored for return
1483 * @return 0 = fail
1484 * 1 = Got CSN
1485 * 2 = Got CSN and CC
1486 */
1487 uint8_t handshakeIclassTag(uint8_t *card_data)
1488 {
1489 static uint8_t act_all[] = { 0x0a };
1490 static uint8_t identify[] = { 0x0c };
1491 static uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1492 static uint8_t readcheck_cc[]= { 0x88, 0x02 };
1493 uint8_t *resp = (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);
1494
1495 uint8_t read_status = 0;
1496
1497 // Send act_all
1498 ReaderTransmitIClass(act_all, 1);
1499 // Card present?
1500 if(!ReaderReceiveIClass(resp)) return read_status;//Fail
1501 //Send Identify
1502 ReaderTransmitIClass(identify, 1);
1503 //We expect a 10-byte response here, 8 byte anticollision-CSN and 2 byte CRC
1504 uint8_t len = ReaderReceiveIClass(resp);
1505 if(len != 10) return read_status;//Fail
1506
1507 //Copy the Anti-collision CSN to our select-packet
1508 memcpy(&select[1],resp,8);
1509 //Select the card
1510 ReaderTransmitIClass(select, sizeof(select));
1511 //We expect a 10-byte response here, 8 byte CSN and 2 byte CRC
1512 len = ReaderReceiveIClass(resp);
1513 if(len != 10) return read_status;//Fail
1514
1515 //Success - level 1, we got CSN
1516 //Save CSN in response data
1517 memcpy(card_data,resp,8);
1518
1519 //Flag that we got to at least stage 1, read CSN
1520 read_status = 1;
1521
1522 // Card selected, now read e-purse (cc)
1523 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1524 if(ReaderReceiveIClass(resp) == 8) {
1525 //Save CC (e-purse) in response data
1526 memcpy(card_data+8,resp,8);
1527
1528 //Got both
1529 read_status = 2;
1530 }
1531
1532 return read_status;
1533 }
1534
1535 // Reader iClass Anticollission
1536 void ReaderIClass(uint8_t arg0) {
1537
1538 uint8_t card_data[24]={0};
1539 uint8_t last_csn[8]={0};
1540
1541 int read_status= 0;
1542 bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE;
1543 bool get_cc = arg0 & FLAG_ICLASS_READER_GET_CC;
1544
1545 setupIclassReader();
1546
1547 size_t datasize = 0;
1548 while(!BUTTON_PRESS())
1549 {
1550
1551 if(traceLen > TRACE_SIZE) {
1552 DbpString("Trace full");
1553 break;
1554 }
1555 WDT_HIT();
1556
1557 read_status = handshakeIclassTag(card_data);
1558
1559 if(read_status == 0) continue;
1560 if(read_status == 1) datasize = 8;
1561 if(read_status == 2) datasize = 16;
1562
1563 LED_B_ON();
1564 //Send back to client, but don't bother if we already sent this
1565 if(memcmp(last_csn, card_data, 8) != 0)
1566 {
1567
1568 if(!get_cc || (get_cc && read_status == 2))
1569 {
1570 cmd_send(CMD_ACK,read_status,0,0,card_data,datasize);
1571 if(abort_after_read) {
1572 LED_A_OFF();
1573 return;
1574 }
1575 //Save that we already sent this....
1576 memcpy(last_csn, card_data, 8);
1577 }
1578 //If 'get_cc' was specified and we didn't get a CC, we'll just keep trying...
1579 }
1580 LED_B_OFF();
1581 }
1582 cmd_send(CMD_ACK,0,0,0,card_data, 0);
1583 LED_A_OFF();
1584 }
1585
1586 void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
1587
1588 uint8_t card_data[USB_CMD_DATA_SIZE]={0};
1589 uint16_t block_crc_LUT[255] = {0};
1590
1591 {//Generate a lookup table for block crc
1592 for(int block = 0; block < 255; block++){
1593 char bl = block;
1594 block_crc_LUT[block] = iclass_crc16(&bl ,1);
1595 }
1596 }
1597 //Dbprintf("Lookup table: %02x %02x %02x" ,block_crc_LUT[0],block_crc_LUT[1],block_crc_LUT[2]);
1598
1599 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1600 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1601
1602 uint16_t crc = 0;
1603 uint8_t cardsize=0;
1604 uint8_t mem=0;
1605
1606 static struct memory_t{
1607 int k16;
1608 int book;
1609 int k2;
1610 int lockauth;
1611 int keyaccess;
1612 } memory;
1613
1614 uint8_t* resp = (((uint8_t *)BigBuf) + RECV_RESP_OFFSET);
1615
1616 setupIclassReader();
1617
1618
1619 while(!BUTTON_PRESS()) {
1620
1621 WDT_HIT();
1622
1623 if(traceLen > TRACE_SIZE) {
1624 DbpString("Trace full");
1625 break;
1626 }
1627
1628 uint8_t read_status = handshakeIclassTag(card_data);
1629 if(read_status < 2) continue;
1630
1631 //for now replay captured auth (as cc not updated)
1632 memcpy(check+5,MAC,4);
1633
1634 if(sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5))
1635 {
1636 Dbprintf("Error: Authentication Fail!");
1637 continue;
1638 }
1639
1640 //first get configuration block (block 1)
1641 crc = block_crc_LUT[1];
1642 read[1]=1;
1643 read[2] = crc >> 8;
1644 read[3] = crc & 0xff;
1645
1646 if(sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10))
1647 {
1648 Dbprintf("Dump config (block 1) failed");
1649 continue;
1650 }
1651
1652 mem=resp[5];
1653 memory.k16= (mem & 0x80);
1654 memory.book= (mem & 0x20);
1655 memory.k2= (mem & 0x8);
1656 memory.lockauth= (mem & 0x2);
1657 memory.keyaccess= (mem & 0x1);
1658
1659 cardsize = memory.k16 ? 255 : 32;
1660 WDT_HIT();
1661 //Set card_data to all zeroes, we'll fill it with data
1662 memset(card_data,0x0,USB_CMD_DATA_SIZE);
1663 uint8_t failedRead =0;
1664 uint8_t stored_data_length =0;
1665 //then loop around remaining blocks
1666 for(int block=0; block < cardsize; block++){
1667
1668 read[1]= block;
1669 crc = block_crc_LUT[block];
1670 read[2] = crc >> 8;
1671 read[3] = crc & 0xff;
1672
1673 if(!sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10))
1674 {
1675 Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
1676 block, resp[0], resp[1], resp[2],
1677 resp[3], resp[4], resp[5],
1678 resp[6], resp[7]);
1679
1680 //Fill up the buffer
1681 memcpy(card_data+stored_data_length,resp,8);
1682 stored_data_length += 8;
1683
1684 if(stored_data_length +8 > USB_CMD_DATA_SIZE)
1685 {//Time to send this off and start afresh
1686 cmd_send(CMD_ACK,
1687 stored_data_length,//data length
1688 failedRead,//Failed blocks?
1689 0,//Not used ATM
1690 card_data, stored_data_length);
1691 //reset
1692 stored_data_length = 0;
1693 failedRead = 0;
1694 }
1695
1696 }else{
1697 failedRead = 1;
1698 stored_data_length +=8;//Otherwise, data becomes misaligned
1699 Dbprintf("Failed to dump block %d", block);
1700 }
1701 }
1702 //Send off any remaining data
1703 if(stored_data_length > 0)
1704 {
1705 cmd_send(CMD_ACK,
1706 stored_data_length,//data length
1707 failedRead,//Failed blocks?
1708 0,//Not used ATM
1709 card_data, stored_data_length);
1710 }
1711 //If we got here, let's break
1712 break;
1713 }
1714 //Signal end of transmission
1715 cmd_send(CMD_ACK,
1716 0,//data length
1717 0,//Failed blocks?
1718 0,//Not used ATM
1719 card_data, 0);
1720
1721 LED_A_OFF();
1722 }
1723
1724 //2. Create Read method (cut-down from above) based off responses from 1.
1725 // Since we have the MAC could continue to use replay function.
1726 //3. Create Write method
1727 /*
1728 void IClass_iso14443A_write(uint8_t arg0, uint8_t blockNo, uint8_t *data, uint8_t *MAC) {
1729 uint8_t act_all[] = { 0x0a };
1730 uint8_t identify[] = { 0x0c };
1731 uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1732 uint8_t readcheck_cc[]= { 0x88, 0x02 };
1733 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1734 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1735 uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1736
1737 uint16_t crc = 0;
1738
1739 uint8_t* resp = (((uint8_t *)BigBuf) + 3560);
1740
1741 // Reset trace buffer
1742 memset(trace, 0x44, RECV_CMD_OFFSET);
1743 traceLen = 0;
1744
1745 // Setup SSC
1746 FpgaSetupSsc();
1747 // Start from off (no field generated)
1748 // Signal field is off with the appropriate LED
1749 LED_D_OFF();
1750 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1751 SpinDelay(200);
1752
1753 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1754
1755 // Now give it time to spin up.
1756 // Signal field is on with the appropriate LED
1757 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1758 SpinDelay(200);
1759
1760 LED_A_ON();
1761
1762 for(int i=0;i<1;i++) {
1763
1764 if(traceLen > TRACE_SIZE) {
1765 DbpString("Trace full");
1766 break;
1767 }
1768
1769 if (BUTTON_PRESS()) break;
1770
1771 // Send act_all
1772 ReaderTransmitIClass(act_all, 1);
1773 // Card present?
1774 if(ReaderReceiveIClass(resp)) {
1775 ReaderTransmitIClass(identify, 1);
1776 if(ReaderReceiveIClass(resp) == 10) {
1777 // Select card
1778 memcpy(&select[1],resp,8);
1779 ReaderTransmitIClass(select, sizeof(select));
1780
1781 if(ReaderReceiveIClass(resp) == 10) {
1782 Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1783 resp[0], resp[1], resp[2],
1784 resp[3], resp[4], resp[5],
1785 resp[6], resp[7]);
1786 }
1787 // Card selected
1788 Dbprintf("Readcheck on Sector 2");
1789 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1790 if(ReaderReceiveIClass(resp) == 8) {
1791 Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x",
1792 resp[0], resp[1], resp[2],
1793 resp[3], resp[4], resp[5],
1794 resp[6], resp[7]);
1795 }else return;
1796 Dbprintf("Authenticate");
1797 //for now replay captured auth (as cc not updated)
1798 memcpy(check+5,MAC,4);
1799 Dbprintf(" AA: %02x %02x %02x %02x",
1800 check[5], check[6], check[7],check[8]);
1801 ReaderTransmitIClass(check, sizeof(check));
1802 if(ReaderReceiveIClass(resp) == 4) {
1803 Dbprintf(" AR: %02x %02x %02x %02x",
1804 resp[0], resp[1], resp[2],resp[3]);
1805 }else {
1806 Dbprintf("Error: Authentication Fail!");
1807 return;
1808 }
1809 Dbprintf("Write Block");
1810
1811 //read configuration for max block number
1812 read_success=false;
1813 read[1]=1;
1814 uint8_t *blockno=&read[1];
1815 crc = iclass_crc16((char *)blockno,1);
1816 read[2] = crc >> 8;
1817 read[3] = crc & 0xff;
1818 while(!read_success){
1819 ReaderTransmitIClass(read, sizeof(read));
1820 if(ReaderReceiveIClass(resp) == 10) {
1821 read_success=true;
1822 mem=resp[5];
1823 memory.k16= (mem & 0x80);
1824 memory.book= (mem & 0x20);
1825 memory.k2= (mem & 0x8);
1826 memory.lockauth= (mem & 0x2);
1827 memory.keyaccess= (mem & 0x1);
1828
1829 }
1830 }
1831 if (memory.k16){
1832 cardsize=255;
1833 }else cardsize=32;
1834 //check card_size
1835
1836 memcpy(write+1,blockNo,1);
1837 memcpy(write+2,data,8);
1838 memcpy(write+10,mac,4);
1839 while(!send_success){
1840 ReaderTransmitIClass(write, sizeof(write));
1841 if(ReaderReceiveIClass(resp) == 10) {
1842 write_success=true;
1843 }
1844 }//
1845 }
1846 WDT_HIT();
1847 }
1848
1849 LED_A_OFF();
1850 }*/
Impressum, Datenschutz