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