]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/iclass.c
1a3751182f6e9553bb944ba405fe081861e4d3c8
[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 #define ICLASS_BUFFER_SIZE 32
644 uint8_t readerToTagCmd[ICLASS_BUFFER_SIZE];
645 // The response (tag -> reader) that we're receiving.
646 uint8_t tagToReaderResponse[ICLASS_BUFFER_SIZE];
647
648 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
649
650 // free all BigBuf memory
651 BigBuf_free();
652 // The DMA buffer, used to stream samples from the FPGA
653 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
654
655 // reset traceLen to 0
656 iso14a_set_tracing(TRUE);
657 iso14a_clear_trace();
658 iso14a_set_trigger(FALSE);
659
660 int lastRxCounter;
661 uint8_t *upTo;
662 int smpl;
663 int maxBehindBy = 0;
664
665 // Count of samples received so far, so that we can include timing
666 // information in the trace buffer.
667 int samples = 0;
668 rsamples = 0;
669
670 // Set up the demodulator for tag -> reader responses.
671 Demod.output = tagToReaderResponse;
672 Demod.len = 0;
673 Demod.state = DEMOD_UNSYNCD;
674
675 // Setup for the DMA.
676 FpgaSetupSsc();
677 upTo = dmaBuf;
678 lastRxCounter = DMA_BUFFER_SIZE;
679 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
680
681 // And the reader -> tag commands
682 memset(&Uart, 0, sizeof(Uart));
683 Uart.output = readerToTagCmd;
684 Uart.byteCntMax = 32; // was 100 (greg)////////////////////////////////////////////////////////////////////////
685 Uart.state = STATE_UNSYNCD;
686
687 // And put the FPGA in the appropriate mode
688 // Signal field is off with the appropriate LED
689 LED_D_OFF();
690 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_SNIFFER);
691 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
692
693 uint32_t time_0 = GetCountSspClk();
694 uint32_t time_start = 0;
695 uint32_t time_stop = 0;
696
697 int div = 0;
698 //int div2 = 0;
699 int decbyte = 0;
700 int decbyter = 0;
701
702 // And now we loop, receiving samples.
703 for(;;) {
704 LED_A_ON();
705 WDT_HIT();
706 int behindBy = (lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR) &
707 (DMA_BUFFER_SIZE-1);
708 if(behindBy > maxBehindBy) {
709 maxBehindBy = behindBy;
710 if(behindBy > (9 * DMA_BUFFER_SIZE / 10)) {
711 Dbprintf("blew circular buffer! behindBy=0x%x", behindBy);
712 goto done;
713 }
714 }
715 if(behindBy < 1) continue;
716
717 LED_A_OFF();
718 smpl = upTo[0];
719 upTo++;
720 lastRxCounter -= 1;
721 if(upTo - dmaBuf > DMA_BUFFER_SIZE) {
722 upTo -= DMA_BUFFER_SIZE;
723 lastRxCounter += DMA_BUFFER_SIZE;
724 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
725 AT91C_BASE_PDC_SSC->PDC_RNCR = DMA_BUFFER_SIZE;
726 }
727
728 //samples += 4;
729 samples += 1;
730
731 if(smpl & 0xF) {
732 decbyte ^= (1 << (3 - div));
733 }
734
735 // FOR READER SIDE COMMUMICATION...
736
737 decbyter <<= 2;
738 decbyter ^= (smpl & 0x30);
739
740 div++;
741
742 if((div + 1) % 2 == 0) {
743 smpl = decbyter;
744 if(OutOfNDecoding((smpl & 0xF0) >> 4)) {
745 rsamples = samples - Uart.samples;
746 time_stop = (GetCountSspClk()-time_0) << 4;
747 LED_C_ON();
748
749 //if(!LogTrace(Uart.output,Uart.byteCnt, rsamples, Uart.parityBits,TRUE)) break;
750 //if(!LogTrace(NULL, 0, Uart.endTime*16 - DELAY_READER_AIR2ARM_AS_SNIFFER, 0, TRUE)) break;
751 if(tracing) {
752 uint8_t parity[MAX_PARITY_SIZE];
753 GetParity(Uart.output, Uart.byteCnt, parity);
754 LogTrace(Uart.output,Uart.byteCnt, time_start, time_stop, parity, TRUE);
755 }
756
757
758 /* And ready to receive another command. */
759 Uart.state = STATE_UNSYNCD;
760 /* And also reset the demod code, which might have been */
761 /* false-triggered by the commands from the reader. */
762 Demod.state = DEMOD_UNSYNCD;
763 LED_B_OFF();
764 Uart.byteCnt = 0;
765 }else{
766 time_start = (GetCountSspClk()-time_0) << 4;
767 }
768 decbyter = 0;
769 }
770
771 if(div > 3) {
772 smpl = decbyte;
773 if(ManchesterDecoding(smpl & 0x0F)) {
774 time_stop = (GetCountSspClk()-time_0) << 4;
775
776 rsamples = samples - Demod.samples;
777 LED_B_ON();
778
779 if(tracing) {
780 uint8_t parity[MAX_PARITY_SIZE];
781 GetParity(Demod.output, Demod.len, parity);
782 LogTrace(Demod.output, Demod.len, time_start, time_stop, parity, FALSE);
783 }
784
785 // And ready to receive another response.
786 memset(&Demod, 0, sizeof(Demod));
787 Demod.output = tagToReaderResponse;
788 Demod.state = DEMOD_UNSYNCD;
789 LED_C_OFF();
790 }else{
791 time_start = (GetCountSspClk()-time_0) << 4;
792 }
793
794 div = 0;
795 decbyte = 0x00;
796 }
797 //}
798
799 if(BUTTON_PRESS()) {
800 DbpString("cancelled_a");
801 goto done;
802 }
803 }
804
805 DbpString("COMMAND FINISHED");
806
807 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
808 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
809
810 done:
811 AT91C_BASE_PDC_SSC->PDC_PTCR = AT91C_PDC_RXTDIS;
812 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
813 Dbprintf("%x %x %x", Uart.byteCntMax, traceLen, (int)Uart.output[0]);
814 LED_A_OFF();
815 LED_B_OFF();
816 LED_C_OFF();
817 LED_D_OFF();
818 }
819
820 void rotateCSN(uint8_t* originalCSN, uint8_t* rotatedCSN) {
821 int i;
822 for(i = 0; i < 8; i++) {
823 rotatedCSN[i] = (originalCSN[i] >> 3) | (originalCSN[(i+1)%8] << 5);
824 }
825 }
826
827 //-----------------------------------------------------------------------------
828 // Wait for commands from reader
829 // Stop when button is pressed
830 // Or return TRUE when command is captured
831 //-----------------------------------------------------------------------------
832 static int GetIClassCommandFromReader(uint8_t *received, int *len, int maxLen)
833 {
834 // Set FPGA mode to "simulated ISO 14443 tag", no modulation (listen
835 // only, since we are receiving, not transmitting).
836 // Signal field is off with the appropriate LED
837 LED_D_OFF();
838 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
839
840 // Now run a `software UART' on the stream of incoming samples.
841 Uart.output = received;
842 Uart.byteCntMax = maxLen;
843 Uart.state = STATE_UNSYNCD;
844
845 for(;;) {
846 WDT_HIT();
847
848 if(BUTTON_PRESS()) return FALSE;
849
850 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
851 AT91C_BASE_SSC->SSC_THR = 0x00;
852 }
853 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
854 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
855
856 if(OutOfNDecoding(b & 0x0f)) {
857 *len = Uart.byteCnt;
858 return TRUE;
859 }
860 }
861 }
862 }
863
864 static uint8_t encode4Bits(const uint8_t b)
865 {
866 uint8_t c = b & 0xF;
867 // OTA, the least significant bits first
868 // The columns are
869 // 1 - Bit value to send
870 // 2 - Reversed (big-endian)
871 // 3 - Encoded
872 // 4 - Hex values
873
874 switch(c){
875 // 1 2 3 4
876 case 15: return 0x55; // 1111 -> 1111 -> 01010101 -> 0x55
877 case 14: return 0x95; // 1110 -> 0111 -> 10010101 -> 0x95
878 case 13: return 0x65; // 1101 -> 1011 -> 01100101 -> 0x65
879 case 12: return 0xa5; // 1100 -> 0011 -> 10100101 -> 0xa5
880 case 11: return 0x59; // 1011 -> 1101 -> 01011001 -> 0x59
881 case 10: return 0x99; // 1010 -> 0101 -> 10011001 -> 0x99
882 case 9: return 0x69; // 1001 -> 1001 -> 01101001 -> 0x69
883 case 8: return 0xa9; // 1000 -> 0001 -> 10101001 -> 0xa9
884 case 7: return 0x56; // 0111 -> 1110 -> 01010110 -> 0x56
885 case 6: return 0x96; // 0110 -> 0110 -> 10010110 -> 0x96
886 case 5: return 0x66; // 0101 -> 1010 -> 01100110 -> 0x66
887 case 4: return 0xa6; // 0100 -> 0010 -> 10100110 -> 0xa6
888 case 3: return 0x5a; // 0011 -> 1100 -> 01011010 -> 0x5a
889 case 2: return 0x9a; // 0010 -> 0100 -> 10011010 -> 0x9a
890 case 1: return 0x6a; // 0001 -> 1000 -> 01101010 -> 0x6a
891 default: return 0xaa; // 0000 -> 0000 -> 10101010 -> 0xaa
892
893 }
894 }
895
896 //-----------------------------------------------------------------------------
897 // Prepare tag messages
898 //-----------------------------------------------------------------------------
899 static void CodeIClassTagAnswer(const uint8_t *cmd, int len)
900 {
901
902 /*
903 * SOF comprises 3 parts;
904 * * An unmodulated time of 56.64 us
905 * * 24 pulses of 423.75 KHz (fc/32)
906 * * A logic 1, which starts with an unmodulated time of 18.88us
907 * followed by 8 pulses of 423.75kHz (fc/32)
908 *
909 *
910 * EOF comprises 3 parts:
911 * - A logic 0 (which starts with 8 pulses of fc/32 followed by an unmodulated
912 * time of 18.88us.
913 * - 24 pulses of fc/32
914 * - An unmodulated time of 56.64 us
915 *
916 *
917 * A logic 0 starts with 8 pulses of fc/32
918 * followed by an unmodulated time of 256/fc (~18,88us).
919 *
920 * A logic 0 starts with unmodulated time of 256/fc (~18,88us) followed by
921 * 8 pulses of fc/32 (also 18.88us)
922 *
923 * The mode FPGA_HF_SIMULATOR_MODULATE_424K_8BIT which we use to simulate tag,
924 * works like this.
925 * - A 1-bit input to the FPGA becomes 8 pulses on 423.5kHz (fc/32) (18.88us).
926 * - A 0-bit inptu to the FPGA becomes an unmodulated time of 18.88us
927 *
928 * In this mode the SOF can be written as 00011101 = 0x1D
929 * The EOF can be written as 10111000 = 0xb8
930 * A logic 1 is 01
931 * A logic 0 is 10
932 *
933 * */
934
935 int i;
936
937 ToSendReset();
938
939 // Send SOF
940 ToSend[++ToSendMax] = 0x1D;
941
942 for(i = 0; i < len; i++) {
943 uint8_t b = cmd[i];
944 ToSend[++ToSendMax] = encode4Bits(b & 0xF); //Least significant half
945 ToSend[++ToSendMax] = encode4Bits((b >>4) & 0xF);//Most significant half
946 }
947
948 // Send EOF
949 ToSend[++ToSendMax] = 0xB8;
950 //lastProxToAirDuration = 8*ToSendMax - 3*8 - 3*8;//Not counting zeroes in the beginning or end
951 // Convert from last byte pos to length
952 ToSendMax++;
953 }
954
955 // Only SOF
956 static void CodeIClassTagSOF()
957 {
958 //So far a dummy implementation, not used
959 //int lastProxToAirDuration =0;
960
961 ToSendReset();
962 // Send SOF
963 ToSend[++ToSendMax] = 0x1D;
964 // lastProxToAirDuration = 8*ToSendMax - 3*8;//Not counting zeroes in the beginning
965
966 // Convert from last byte pos to length
967 ToSendMax++;
968 }
969
970 int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf);
971 /**
972 * @brief SimulateIClass simulates an iClass card.
973 * @param arg0 type of simulation
974 * - 0 uses the first 8 bytes in usb data as CSN
975 * - 2 "dismantling iclass"-attack. This mode iterates through all CSN's specified
976 * in the usb data. This mode collects MAC from the reader, in order to do an offline
977 * attack on the keys. For more info, see "dismantling iclass" and proxclone.com.
978 * - Other : Uses the default CSN (031fec8af7ff12e0)
979 * @param arg1 - number of CSN's contained in datain (applicable for mode 2 only)
980 * @param arg2
981 * @param datain
982 */
983 void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
984 {
985 uint32_t simType = arg0;
986 uint32_t numberOfCSNS = arg1;
987 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
988
989 // Enable and clear the trace
990 iso14a_set_tracing(TRUE);
991 iso14a_clear_trace();
992
993 uint8_t csn_crc[] = { 0x03, 0x1f, 0xec, 0x8a, 0xf7, 0xff, 0x12, 0xe0, 0x00, 0x00 };
994 if(simType == 0) {
995 // Use the CSN from commandline
996 memcpy(csn_crc, datain, 8);
997 doIClassSimulation(csn_crc,0,NULL);
998 }else if(simType == 1)
999 {
1000 doIClassSimulation(csn_crc,0,NULL);
1001 }
1002 else if(simType == 2)
1003 {
1004
1005 uint8_t mac_responses[USB_CMD_DATA_SIZE] = { 0 };
1006 Dbprintf("Going into attack mode, %d CSNS sent", numberOfCSNS);
1007 // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
1008 // in order to collect MAC's from the reader. This can later be used in an offlne-attack
1009 // in order to obtain the keys, as in the "dismantling iclass"-paper.
1010 int i = 0;
1011 for( ; i < numberOfCSNS && i*8+8 < USB_CMD_DATA_SIZE; i++)
1012 {
1013 // The usb data is 512 bytes, fitting 65 8-byte CSNs in there.
1014
1015 memcpy(csn_crc, datain+(i*8), 8);
1016 if(doIClassSimulation(csn_crc,1,mac_responses+i*8))
1017 {
1018 cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
1019 return; // Button pressed
1020 }
1021 }
1022 cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
1023
1024 }
1025 else{
1026 // We may want a mode here where we hardcode the csns to use (from proxclone).
1027 // That will speed things up a little, but not required just yet.
1028 Dbprintf("The mode is not implemented, reserved for future use");
1029 }
1030 Dbprintf("Done...");
1031
1032 }
1033 /**
1034 * @brief Does the actual simulation
1035 * @param csn - csn to use
1036 * @param breakAfterMacReceived if true, returns after reader MAC has been received.
1037 */
1038 int doIClassSimulation(uint8_t csn[], int breakAfterMacReceived, uint8_t *reader_mac_buf)
1039 {
1040
1041 // CSN followed by two CRC bytes
1042 uint8_t response1[] = { 0x0F} ;
1043 uint8_t response2[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1044 uint8_t response3[] = { 0,0,0,0,0,0,0,0,0,0};
1045 memcpy(response3,csn,sizeof(response3));
1046 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]);
1047 // e-Purse
1048 uint8_t response4[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1049
1050 // Construct anticollision-CSN
1051 rotateCSN(response3,response2);
1052
1053 // Compute CRC on both CSNs
1054 ComputeCrc14443(CRC_ICLASS, response2, 8, &response2[8], &response2[9]);
1055 ComputeCrc14443(CRC_ICLASS, response3, 8, &response3[8], &response3[9]);
1056
1057 int exitLoop = 0;
1058 // Reader 0a
1059 // Tag 0f
1060 // Reader 0c
1061 // Tag anticoll. CSN
1062 // Reader 81 anticoll. CSN
1063 // Tag CSN
1064
1065 uint8_t *modulated_response;
1066 int modulated_response_size;
1067 uint8_t* trace_data = NULL;
1068 int trace_data_size = 0;
1069 //uint8_t sof = 0x0f;
1070
1071 // free eventually allocated BigBuf memory
1072 BigBuf_free();
1073 // Respond SOF -- takes 1 bytes
1074 uint8_t *resp1 = BigBuf_malloc(2);
1075 int resp1Len;
1076
1077 // Anticollision CSN (rotated CSN)
1078 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
1079 uint8_t *resp2 = BigBuf_malloc(28);
1080 int resp2Len;
1081
1082 // CSN
1083 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
1084 uint8_t *resp3 = BigBuf_malloc(30);
1085 int resp3Len;
1086
1087 // e-Purse
1088 // 18: Takes 2 bytes for SOF/EOF and 8 * 2 = 16 bytes (2 bytes/bit)
1089 uint8_t *resp4 = BigBuf_malloc(20);
1090 int resp4Len;
1091
1092 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
1093 memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
1094 int len;
1095
1096 // Prepare card messages
1097 ToSendMax = 0;
1098
1099 // First card answer: SOF
1100 CodeIClassTagSOF();
1101 memcpy(resp1, ToSend, ToSendMax); resp1Len = ToSendMax;
1102
1103 // Anticollision CSN
1104 CodeIClassTagAnswer(response2, sizeof(response2));
1105 memcpy(resp2, ToSend, ToSendMax); resp2Len = ToSendMax;
1106
1107 // CSN
1108 CodeIClassTagAnswer(response3, sizeof(response3));
1109 memcpy(resp3, ToSend, ToSendMax); resp3Len = ToSendMax;
1110
1111 // e-Purse
1112 CodeIClassTagAnswer(response4, sizeof(response4));
1113 memcpy(resp4, ToSend, ToSendMax); resp4Len = ToSendMax;
1114
1115
1116 // Start from off (no field generated)
1117 //FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1118 //SpinDelay(200);
1119 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1120 SpinDelay(100);
1121 StartCountSspClk();
1122 // We need to listen to the high-frequency, peak-detected path.
1123 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1124 FpgaSetupSsc();
1125
1126 // To control where we are in the protocol
1127 int cmdsRecvd = 0;
1128 uint32_t time_0 = GetCountSspClk();
1129 uint32_t t2r_time =0;
1130 uint32_t r2t_time =0;
1131
1132 LED_A_ON();
1133 bool buttonPressed = false;
1134
1135 while(!exitLoop) {
1136
1137 LED_B_OFF();
1138 //Signal tracer
1139 // Can be used to get a trigger for an oscilloscope..
1140 LED_C_OFF();
1141
1142 if(!GetIClassCommandFromReader(receivedCmd, &len, 100)) {
1143 buttonPressed = true;
1144 break;
1145 }
1146 r2t_time = GetCountSspClk();
1147 //Signal tracer
1148 LED_C_ON();
1149
1150 // Okay, look at the command now.
1151 if(receivedCmd[0] == 0x0a ) {
1152 // Reader in anticollission phase
1153 modulated_response = resp1; modulated_response_size = resp1Len; //order = 1;
1154 trace_data = response1;
1155 trace_data_size = sizeof(response1);
1156 } else if(receivedCmd[0] == 0x0c) {
1157 // Reader asks for anticollission CSN
1158 modulated_response = resp2; modulated_response_size = resp2Len; //order = 2;
1159 trace_data = response2;
1160 trace_data_size = sizeof(response2);
1161 //DbpString("Reader requests anticollission CSN:");
1162 } else if(receivedCmd[0] == 0x81) {
1163 // Reader selects anticollission CSN.
1164 // Tag sends the corresponding real CSN
1165 modulated_response = resp3; modulated_response_size = resp3Len; //order = 3;
1166 trace_data = response3;
1167 trace_data_size = sizeof(response3);
1168 //DbpString("Reader selects anticollission CSN:");
1169 } else if(receivedCmd[0] == 0x88) {
1170 // Read e-purse (88 02)
1171 modulated_response = resp4; modulated_response_size = resp4Len; //order = 4;
1172 trace_data = response4;
1173 trace_data_size = sizeof(response4);
1174 LED_B_ON();
1175 } else if(receivedCmd[0] == 0x05) {
1176 // Reader random and reader MAC!!!
1177 // Do not respond
1178 // We do not know what to answer, so lets keep quiet
1179 modulated_response = resp1; modulated_response_size = 0; //order = 5;
1180 trace_data = NULL;
1181 trace_data_size = 0;
1182 if (breakAfterMacReceived){
1183 // dbprintf:ing ...
1184 Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x"
1185 ,csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]);
1186 Dbprintf("RDR: (len=%02d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",len,
1187 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1188 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1189 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1190 if (reader_mac_buf != NULL)
1191 {
1192 memcpy(reader_mac_buf,receivedCmd+1,8);
1193 }
1194 exitLoop = true;
1195 }
1196 } else if(receivedCmd[0] == 0x00 && len == 1) {
1197 // Reader ends the session
1198 modulated_response = resp1; modulated_response_size = 0; //order = 0;
1199 trace_data = NULL;
1200 trace_data_size = 0;
1201 } else {
1202 //#db# Unknown command received from reader (len=5): 26 1 0 f6 a 44 44 44 44
1203 // Never seen this command before
1204 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1205 len,
1206 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1207 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1208 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1209 // Do not respond
1210 modulated_response = resp1; modulated_response_size = 0; //order = 0;
1211 trace_data = NULL;
1212 trace_data_size = 0;
1213 }
1214
1215 if(cmdsRecvd > 100) {
1216 //DbpString("100 commands later...");
1217 //break;
1218 }
1219 else {
1220 cmdsRecvd++;
1221 }
1222 /**
1223 A legit tag has about 380us delay between reader EOT and tag SOF.
1224 **/
1225 if(modulated_response_size > 0) {
1226 SendIClassAnswer(modulated_response, modulated_response_size, 1);
1227 t2r_time = GetCountSspClk();
1228 }
1229
1230 if (tracing) {
1231 uint8_t parity[MAX_PARITY_SIZE];
1232 GetParity(receivedCmd, len, parity);
1233 LogTrace(receivedCmd,len, (r2t_time-time_0)<< 4, (r2t_time-time_0) << 4, parity, TRUE);
1234
1235 if (trace_data != NULL) {
1236 GetParity(trace_data, trace_data_size, parity);
1237 LogTrace(trace_data, trace_data_size, (t2r_time-time_0) << 4, (t2r_time-time_0) << 4, parity, FALSE);
1238 }
1239 if(!tracing) {
1240 DbpString("Trace full");
1241 //break;
1242 }
1243
1244 }
1245 memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
1246 }
1247
1248 //Dbprintf("%x", cmdsRecvd);
1249 LED_A_OFF();
1250 LED_B_OFF();
1251 LED_C_OFF();
1252
1253 if(buttonPressed)
1254 {
1255 DbpString("Button pressed");
1256 }
1257 return buttonPressed;
1258 }
1259
1260 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay)
1261 {
1262 int i = 0, d=0;//, u = 0, d = 0;
1263 uint8_t b = 0;
1264
1265 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K);
1266 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K_8BIT);
1267
1268 AT91C_BASE_SSC->SSC_THR = 0x00;
1269 FpgaSetupSsc();
1270 while(!BUTTON_PRESS()) {
1271 if((AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)){
1272 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
1273 }
1274 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)){
1275 b = 0x00;
1276 if(d < delay) {
1277 d++;
1278 }
1279 else {
1280 if( i < respLen){
1281 b = resp[i];
1282 //Hack
1283 //b = 0xAC;
1284 }
1285 i++;
1286 }
1287 AT91C_BASE_SSC->SSC_THR = b;
1288 }
1289
1290 // if (i > respLen +4) break;
1291 if (i > respLen +1) break;
1292 }
1293
1294 return 0;
1295 }
1296
1297 /// THE READER CODE
1298
1299 //-----------------------------------------------------------------------------
1300 // Transmit the command (to the tag) that was placed in ToSend[].
1301 //-----------------------------------------------------------------------------
1302 static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait)
1303 {
1304 int c;
1305 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1306 AT91C_BASE_SSC->SSC_THR = 0x00;
1307 FpgaSetupSsc();
1308
1309 if (wait)
1310 {
1311 if(*wait < 10) *wait = 10;
1312
1313 for(c = 0; c < *wait;) {
1314 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1315 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1316 c++;
1317 }
1318 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1319 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1320 (void)r;
1321 }
1322 WDT_HIT();
1323 }
1324
1325 }
1326
1327
1328 uint8_t sendbyte;
1329 bool firstpart = TRUE;
1330 c = 0;
1331 for(;;) {
1332 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1333
1334 // DOUBLE THE SAMPLES!
1335 if(firstpart) {
1336 sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4);
1337 }
1338 else {
1339 sendbyte = (cmd[c] & 0x0f) | (cmd[c] << 4);
1340 c++;
1341 }
1342 if(sendbyte == 0xff) {
1343 sendbyte = 0xfe;
1344 }
1345 AT91C_BASE_SSC->SSC_THR = sendbyte;
1346 firstpart = !firstpart;
1347
1348 if(c >= len) {
1349 break;
1350 }
1351 }
1352 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1353 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1354 (void)r;
1355 }
1356 WDT_HIT();
1357 }
1358 if (samples) *samples = (c + *wait) << 3;
1359 }
1360
1361
1362 //-----------------------------------------------------------------------------
1363 // Prepare iClass reader command to send to FPGA
1364 //-----------------------------------------------------------------------------
1365 void CodeIClassCommand(const uint8_t * cmd, int len)
1366 {
1367 int i, j, k;
1368 uint8_t b;
1369
1370 ToSendReset();
1371
1372 // Start of Communication: 1 out of 4
1373 ToSend[++ToSendMax] = 0xf0;
1374 ToSend[++ToSendMax] = 0x00;
1375 ToSend[++ToSendMax] = 0x0f;
1376 ToSend[++ToSendMax] = 0x00;
1377
1378 // Modulate the bytes
1379 for (i = 0; i < len; i++) {
1380 b = cmd[i];
1381 for(j = 0; j < 4; j++) {
1382 for(k = 0; k < 4; k++) {
1383 if(k == (b & 3)) {
1384 ToSend[++ToSendMax] = 0x0f;
1385 }
1386 else {
1387 ToSend[++ToSendMax] = 0x00;
1388 }
1389 }
1390 b >>= 2;
1391 }
1392 }
1393
1394 // End of Communication
1395 ToSend[++ToSendMax] = 0x00;
1396 ToSend[++ToSendMax] = 0x00;
1397 ToSend[++ToSendMax] = 0xf0;
1398 ToSend[++ToSendMax] = 0x00;
1399
1400 // Convert from last character reference to length
1401 ToSendMax++;
1402 }
1403
1404 void ReaderTransmitIClass(uint8_t* frame, int len)
1405 {
1406 int wait = 0;
1407 int samples = 0;
1408
1409 // This is tied to other size changes
1410 CodeIClassCommand(frame,len);
1411
1412 // Select the card
1413 TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
1414 if(trigger)
1415 LED_A_ON();
1416
1417 // Store reader command in buffer
1418 if (tracing) {
1419 uint8_t par[MAX_PARITY_SIZE];
1420 GetParity(frame, len, par);
1421 LogTrace(frame, len, rsamples, rsamples, par, TRUE);
1422 }
1423 }
1424
1425 //-----------------------------------------------------------------------------
1426 // Wait a certain time for tag response
1427 // If a response is captured return TRUE
1428 // If it takes too long return FALSE
1429 //-----------------------------------------------------------------------------
1430 static int GetIClassAnswer(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
1431 {
1432 // buffer needs to be 512 bytes
1433 int c;
1434
1435 // Set FPGA mode to "reader listen mode", no modulation (listen
1436 // only, since we are receiving, not transmitting).
1437 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1438
1439 // Now get the answer from the card
1440 Demod.output = receivedResponse;
1441 Demod.len = 0;
1442 Demod.state = DEMOD_UNSYNCD;
1443
1444 uint8_t b;
1445 if (elapsed) *elapsed = 0;
1446
1447 bool skip = FALSE;
1448
1449 c = 0;
1450 for(;;) {
1451 WDT_HIT();
1452
1453 if(BUTTON_PRESS()) return FALSE;
1454
1455 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1456 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1457 if (elapsed) (*elapsed)++;
1458 }
1459 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1460 if(c < timeout) { c++; } else { return FALSE; }
1461 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1462 skip = !skip;
1463 if(skip) continue;
1464
1465 if(ManchesterDecoding(b & 0x0f)) {
1466 *samples = c << 3;
1467 return TRUE;
1468 }
1469 }
1470 }
1471 }
1472
1473 int ReaderReceiveIClass(uint8_t* receivedAnswer)
1474 {
1475 int samples = 0;
1476 if (!GetIClassAnswer(receivedAnswer,160,&samples,0)) return FALSE;
1477 rsamples += samples;
1478 if (tracing) {
1479 uint8_t parity[MAX_PARITY_SIZE];
1480 GetParity(receivedAnswer, Demod.len, parity);
1481 LogTrace(receivedAnswer,Demod.len,rsamples,rsamples,parity,FALSE);
1482 }
1483 if(samples == 0) return FALSE;
1484 return Demod.len;
1485 }
1486
1487 void setupIclassReader()
1488 {
1489 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1490 // Reset trace buffer
1491 iso14a_set_tracing(TRUE);
1492 iso14a_clear_trace();
1493
1494 // Setup SSC
1495 FpgaSetupSsc();
1496 // Start from off (no field generated)
1497 // Signal field is off with the appropriate LED
1498 LED_D_OFF();
1499 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1500 SpinDelay(200);
1501
1502 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1503
1504 // Now give it time to spin up.
1505 // Signal field is on with the appropriate LED
1506 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1507 SpinDelay(200);
1508 LED_A_ON();
1509
1510 }
1511
1512 size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries)
1513 {
1514 while(retries-- > 0)
1515 {
1516 ReaderTransmitIClass(command, cmdsize);
1517 if(expected_size == ReaderReceiveIClass(resp)){
1518 return 0;
1519 }
1520 }
1521 return 1;//Error
1522 }
1523
1524 /**
1525 * @brief Talks to an iclass tag, sends the commands to get CSN and CC.
1526 * @param card_data where the CSN and CC are stored for return
1527 * @return 0 = fail
1528 * 1 = Got CSN
1529 * 2 = Got CSN and CC
1530 */
1531 uint8_t handshakeIclassTag(uint8_t *card_data)
1532 {
1533 static uint8_t act_all[] = { 0x0a };
1534 static uint8_t identify[] = { 0x0c };
1535 static uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1536 static uint8_t readcheck_cc[]= { 0x88, 0x02 };
1537 uint8_t resp[ICLASS_BUFFER_SIZE];
1538
1539 uint8_t read_status = 0;
1540
1541 // Send act_all
1542 ReaderTransmitIClass(act_all, 1);
1543 // Card present?
1544 if(!ReaderReceiveIClass(resp)) return read_status;//Fail
1545 //Send Identify
1546 ReaderTransmitIClass(identify, 1);
1547 //We expect a 10-byte response here, 8 byte anticollision-CSN and 2 byte CRC
1548 uint8_t len = ReaderReceiveIClass(resp);
1549 if(len != 10) return read_status;//Fail
1550
1551 //Copy the Anti-collision CSN to our select-packet
1552 memcpy(&select[1],resp,8);
1553 //Select the card
1554 ReaderTransmitIClass(select, sizeof(select));
1555 //We expect a 10-byte response here, 8 byte CSN and 2 byte CRC
1556 len = ReaderReceiveIClass(resp);
1557 if(len != 10) return read_status;//Fail
1558
1559 //Success - level 1, we got CSN
1560 //Save CSN in response data
1561 memcpy(card_data,resp,8);
1562
1563 //Flag that we got to at least stage 1, read CSN
1564 read_status = 1;
1565
1566 // Card selected, now read e-purse (cc)
1567 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1568 if(ReaderReceiveIClass(resp) == 8) {
1569 //Save CC (e-purse) in response data
1570 memcpy(card_data+8,resp,8);
1571
1572 //Got both
1573 read_status = 2;
1574 }
1575
1576 return read_status;
1577 }
1578
1579 // Reader iClass Anticollission
1580 void ReaderIClass(uint8_t arg0) {
1581
1582 uint8_t card_data[24]={0};
1583 uint8_t last_csn[8]={0};
1584
1585 int read_status= 0;
1586 bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE;
1587 bool get_cc = arg0 & FLAG_ICLASS_READER_GET_CC;
1588
1589 setupIclassReader();
1590
1591 size_t datasize = 0;
1592 while(!BUTTON_PRESS())
1593 {
1594
1595 if(traceLen > BigBuf_max_traceLen()) {
1596 DbpString("Trace full");
1597 break;
1598 }
1599 WDT_HIT();
1600
1601 read_status = handshakeIclassTag(card_data);
1602
1603 if(read_status == 0) continue;
1604 if(read_status == 1) datasize = 8;
1605 if(read_status == 2) datasize = 16;
1606
1607 LED_B_ON();
1608 //Send back to client, but don't bother if we already sent this
1609 if(memcmp(last_csn, card_data, 8) != 0)
1610 {
1611
1612 if(!get_cc || (get_cc && read_status == 2))
1613 {
1614 cmd_send(CMD_ACK,read_status,0,0,card_data,datasize);
1615 if(abort_after_read) {
1616 LED_A_OFF();
1617 return;
1618 }
1619 //Save that we already sent this....
1620 memcpy(last_csn, card_data, 8);
1621 }
1622 //If 'get_cc' was specified and we didn't get a CC, we'll just keep trying...
1623 }
1624 LED_B_OFF();
1625 }
1626 cmd_send(CMD_ACK,0,0,0,card_data, 0);
1627 LED_A_OFF();
1628 }
1629
1630 void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
1631
1632 uint8_t card_data[USB_CMD_DATA_SIZE]={0};
1633 uint16_t block_crc_LUT[255] = {0};
1634
1635 {//Generate a lookup table for block crc
1636 for(int block = 0; block < 255; block++){
1637 char bl = block;
1638 block_crc_LUT[block] = iclass_crc16(&bl ,1);
1639 }
1640 }
1641 //Dbprintf("Lookup table: %02x %02x %02x" ,block_crc_LUT[0],block_crc_LUT[1],block_crc_LUT[2]);
1642
1643 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1644 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1645
1646 uint16_t crc = 0;
1647 uint8_t cardsize=0;
1648 uint8_t mem=0;
1649
1650 static struct memory_t{
1651 int k16;
1652 int book;
1653 int k2;
1654 int lockauth;
1655 int keyaccess;
1656 } memory;
1657
1658 uint8_t resp[ICLASS_BUFFER_SIZE];
1659
1660 setupIclassReader();
1661
1662
1663 while(!BUTTON_PRESS()) {
1664
1665 WDT_HIT();
1666
1667 if(traceLen > BigBuf_max_traceLen()) {
1668 DbpString("Trace full");
1669 break;
1670 }
1671
1672 uint8_t read_status = handshakeIclassTag(card_data);
1673 if(read_status < 2) continue;
1674
1675 //for now replay captured auth (as cc not updated)
1676 memcpy(check+5,MAC,4);
1677
1678 if(sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5))
1679 {
1680 Dbprintf("Error: Authentication Fail!");
1681 continue;
1682 }
1683
1684 //first get configuration block (block 1)
1685 crc = block_crc_LUT[1];
1686 read[1]=1;
1687 read[2] = crc >> 8;
1688 read[3] = crc & 0xff;
1689
1690 if(sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10))
1691 {
1692 Dbprintf("Dump config (block 1) failed");
1693 continue;
1694 }
1695
1696 mem=resp[5];
1697 memory.k16= (mem & 0x80);
1698 memory.book= (mem & 0x20);
1699 memory.k2= (mem & 0x8);
1700 memory.lockauth= (mem & 0x2);
1701 memory.keyaccess= (mem & 0x1);
1702
1703 cardsize = memory.k16 ? 255 : 32;
1704 WDT_HIT();
1705 //Set card_data to all zeroes, we'll fill it with data
1706 memset(card_data,0x0,USB_CMD_DATA_SIZE);
1707 uint8_t failedRead =0;
1708 uint8_t stored_data_length =0;
1709 //then loop around remaining blocks
1710 for(int block=0; block < cardsize; block++){
1711
1712 read[1]= block;
1713 crc = block_crc_LUT[block];
1714 read[2] = crc >> 8;
1715 read[3] = crc & 0xff;
1716
1717 if(!sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10))
1718 {
1719 Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
1720 block, resp[0], resp[1], resp[2],
1721 resp[3], resp[4], resp[5],
1722 resp[6], resp[7]);
1723
1724 //Fill up the buffer
1725 memcpy(card_data+stored_data_length,resp,8);
1726 stored_data_length += 8;
1727
1728 if(stored_data_length +8 > USB_CMD_DATA_SIZE)
1729 {//Time to send this off and start afresh
1730 cmd_send(CMD_ACK,
1731 stored_data_length,//data length
1732 failedRead,//Failed blocks?
1733 0,//Not used ATM
1734 card_data, stored_data_length);
1735 //reset
1736 stored_data_length = 0;
1737 failedRead = 0;
1738 }
1739
1740 }else{
1741 failedRead = 1;
1742 stored_data_length +=8;//Otherwise, data becomes misaligned
1743 Dbprintf("Failed to dump block %d", block);
1744 }
1745 }
1746 //Send off any remaining data
1747 if(stored_data_length > 0)
1748 {
1749 cmd_send(CMD_ACK,
1750 stored_data_length,//data length
1751 failedRead,//Failed blocks?
1752 0,//Not used ATM
1753 card_data, stored_data_length);
1754 }
1755 //If we got here, let's break
1756 break;
1757 }
1758 //Signal end of transmission
1759 cmd_send(CMD_ACK,
1760 0,//data length
1761 0,//Failed blocks?
1762 0,//Not used ATM
1763 card_data, 0);
1764
1765 LED_A_OFF();
1766 }
1767
1768 //2. Create Read method (cut-down from above) based off responses from 1.
1769 // Since we have the MAC could continue to use replay function.
1770 //3. Create Write method
1771 /*
1772 void IClass_iso14443A_write(uint8_t arg0, uint8_t blockNo, uint8_t *data, uint8_t *MAC) {
1773 uint8_t act_all[] = { 0x0a };
1774 uint8_t identify[] = { 0x0c };
1775 uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1776 uint8_t readcheck_cc[]= { 0x88, 0x02 };
1777 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1778 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1779 uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1780
1781 uint16_t crc = 0;
1782
1783 uint8_t* resp = (((uint8_t *)BigBuf) + 3560);
1784
1785 // Reset trace buffer
1786 memset(trace, 0x44, RECV_CMD_OFFSET);
1787 traceLen = 0;
1788
1789 // Setup SSC
1790 FpgaSetupSsc();
1791 // Start from off (no field generated)
1792 // Signal field is off with the appropriate LED
1793 LED_D_OFF();
1794 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1795 SpinDelay(200);
1796
1797 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1798
1799 // Now give it time to spin up.
1800 // Signal field is on with the appropriate LED
1801 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1802 SpinDelay(200);
1803
1804 LED_A_ON();
1805
1806 for(int i=0;i<1;i++) {
1807
1808 if(traceLen > TRACE_SIZE) {
1809 DbpString("Trace full");
1810 break;
1811 }
1812
1813 if (BUTTON_PRESS()) break;
1814
1815 // Send act_all
1816 ReaderTransmitIClass(act_all, 1);
1817 // Card present?
1818 if(ReaderReceiveIClass(resp)) {
1819 ReaderTransmitIClass(identify, 1);
1820 if(ReaderReceiveIClass(resp) == 10) {
1821 // Select card
1822 memcpy(&select[1],resp,8);
1823 ReaderTransmitIClass(select, sizeof(select));
1824
1825 if(ReaderReceiveIClass(resp) == 10) {
1826 Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1827 resp[0], resp[1], resp[2],
1828 resp[3], resp[4], resp[5],
1829 resp[6], resp[7]);
1830 }
1831 // Card selected
1832 Dbprintf("Readcheck on Sector 2");
1833 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1834 if(ReaderReceiveIClass(resp) == 8) {
1835 Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x",
1836 resp[0], resp[1], resp[2],
1837 resp[3], resp[4], resp[5],
1838 resp[6], resp[7]);
1839 }else return;
1840 Dbprintf("Authenticate");
1841 //for now replay captured auth (as cc not updated)
1842 memcpy(check+5,MAC,4);
1843 Dbprintf(" AA: %02x %02x %02x %02x",
1844 check[5], check[6], check[7],check[8]);
1845 ReaderTransmitIClass(check, sizeof(check));
1846 if(ReaderReceiveIClass(resp) == 4) {
1847 Dbprintf(" AR: %02x %02x %02x %02x",
1848 resp[0], resp[1], resp[2],resp[3]);
1849 }else {
1850 Dbprintf("Error: Authentication Fail!");
1851 return;
1852 }
1853 Dbprintf("Write Block");
1854
1855 //read configuration for max block number
1856 read_success=false;
1857 read[1]=1;
1858 uint8_t *blockno=&read[1];
1859 crc = iclass_crc16((char *)blockno,1);
1860 read[2] = crc >> 8;
1861 read[3] = crc & 0xff;
1862 while(!read_success){
1863 ReaderTransmitIClass(read, sizeof(read));
1864 if(ReaderReceiveIClass(resp) == 10) {
1865 read_success=true;
1866 mem=resp[5];
1867 memory.k16= (mem & 0x80);
1868 memory.book= (mem & 0x20);
1869 memory.k2= (mem & 0x8);
1870 memory.lockauth= (mem & 0x2);
1871 memory.keyaccess= (mem & 0x1);
1872
1873 }
1874 }
1875 if (memory.k16){
1876 cardsize=255;
1877 }else cardsize=32;
1878 //check card_size
1879
1880 memcpy(write+1,blockNo,1);
1881 memcpy(write+2,data,8);
1882 memcpy(write+10,mac,4);
1883 while(!send_success){
1884 ReaderTransmitIClass(write, sizeof(write));
1885 if(ReaderReceiveIClass(resp) == 10) {
1886 write_success=true;
1887 }
1888 }//
1889 }
1890 WDT_HIT();
1891 }
1892
1893 LED_A_OFF();
1894 }*/
Impressum, Datenschutz