Fixed minor bugs in iclass fullsim, does not work yet though
[legacy-proxmark3.git] / armsrc / iclass.c
blob81ecd01bfed79d938c055af2a7f46c48dd2e8d44
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 //-----------------------------------------------------------------------------
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:
24 // + 22279: : 0c 03 e8 01
26 // ...with an incorrect answer...
28 // + 85: 0: TAG ff! ff! ff! ff! ff! ff! ff! ff! bb 33 bb 00 01! 0e! 04! bb !crc
30 // We still left the error signalling bytes in the traces like 0xbb
32 // A correct trace should look like this:
34 // + 21112: : 0c 03 e8 01
35 // + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5
37 //-----------------------------------------------------------------------------
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 #include "cipher.h"
51 #include "protocols.h"
52 static int timeout = 4096;
55 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay);
57 //-----------------------------------------------------------------------------
58 // The software UART that receives commands from the reader, and its state
59 // variables.
60 //-----------------------------------------------------------------------------
61 static struct {
62 enum {
63 STATE_UNSYNCD,
64 STATE_START_OF_COMMUNICATION,
65 STATE_RECEIVING
66 } state;
67 uint16_t shiftReg;
68 int bitCnt;
69 int byteCnt;
70 int byteCntMax;
71 int posCnt;
72 int nOutOfCnt;
73 int OutOfCnt;
74 int syncBit;
75 int samples;
76 int highCnt;
77 int swapper;
78 int counter;
79 int bitBuffer;
80 int dropPosition;
81 uint8_t *output;
82 } Uart;
84 static RAMFUNC int OutOfNDecoding(int bit)
86 //int error = 0;
87 int bitright;
89 if(!Uart.bitBuffer) {
90 Uart.bitBuffer = bit ^ 0xFF0;
91 return FALSE;
93 else {
94 Uart.bitBuffer <<= 4;
95 Uart.bitBuffer ^= bit;
98 /*if(Uart.swapper) {
99 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
100 Uart.byteCnt++;
101 Uart.swapper = 0;
102 if(Uart.byteCnt > 15) { return TRUE; }
104 else {
105 Uart.swapper = 1;
108 if(Uart.state != STATE_UNSYNCD) {
109 Uart.posCnt++;
111 if((Uart.bitBuffer & Uart.syncBit) ^ Uart.syncBit) {
112 bit = 0x00;
114 else {
115 bit = 0x01;
117 if(((Uart.bitBuffer << 1) & Uart.syncBit) ^ Uart.syncBit) {
118 bitright = 0x00;
120 else {
121 bitright = 0x01;
123 if(bit != bitright) { bit = bitright; }
126 // So, now we only have to deal with *bit*, lets see...
127 if(Uart.posCnt == 1) {
128 // measurement first half bitperiod
129 if(!bit) {
130 // Drop in first half means that we are either seeing
131 // an SOF or an EOF.
133 if(Uart.nOutOfCnt == 1) {
134 // End of Communication
135 Uart.state = STATE_UNSYNCD;
136 Uart.highCnt = 0;
137 if(Uart.byteCnt == 0) {
138 // Its not straightforward to show single EOFs
139 // So just leave it and do not return TRUE
140 Uart.output[0] = 0xf0;
141 Uart.byteCnt++;
143 else {
144 return TRUE;
147 else if(Uart.state != STATE_START_OF_COMMUNICATION) {
148 // When not part of SOF or EOF, it is an error
149 Uart.state = STATE_UNSYNCD;
150 Uart.highCnt = 0;
151 //error = 4;
155 else {
156 // measurement second half bitperiod
157 // Count the bitslot we are in... (ISO 15693)
158 Uart.nOutOfCnt++;
160 if(!bit) {
161 if(Uart.dropPosition) {
162 if(Uart.state == STATE_START_OF_COMMUNICATION) {
163 //error = 1;
165 else {
166 //error = 7;
168 // It is an error if we already have seen a drop in current frame
169 Uart.state = STATE_UNSYNCD;
170 Uart.highCnt = 0;
172 else {
173 Uart.dropPosition = Uart.nOutOfCnt;
177 Uart.posCnt = 0;
180 if(Uart.nOutOfCnt == Uart.OutOfCnt && Uart.OutOfCnt == 4) {
181 Uart.nOutOfCnt = 0;
183 if(Uart.state == STATE_START_OF_COMMUNICATION) {
184 if(Uart.dropPosition == 4) {
185 Uart.state = STATE_RECEIVING;
186 Uart.OutOfCnt = 256;
188 else if(Uart.dropPosition == 3) {
189 Uart.state = STATE_RECEIVING;
190 Uart.OutOfCnt = 4;
191 //Uart.output[Uart.byteCnt] = 0xdd;
192 //Uart.byteCnt++;
194 else {
195 Uart.state = STATE_UNSYNCD;
196 Uart.highCnt = 0;
198 Uart.dropPosition = 0;
200 else {
201 // RECEIVING DATA
202 // 1 out of 4
203 if(!Uart.dropPosition) {
204 Uart.state = STATE_UNSYNCD;
205 Uart.highCnt = 0;
206 //error = 9;
208 else {
209 Uart.shiftReg >>= 2;
211 // Swap bit order
212 Uart.dropPosition--;
213 //if(Uart.dropPosition == 1) { Uart.dropPosition = 2; }
214 //else if(Uart.dropPosition == 2) { Uart.dropPosition = 1; }
216 Uart.shiftReg ^= ((Uart.dropPosition & 0x03) << 6);
217 Uart.bitCnt += 2;
218 Uart.dropPosition = 0;
220 if(Uart.bitCnt == 8) {
221 Uart.output[Uart.byteCnt] = (Uart.shiftReg & 0xff);
222 Uart.byteCnt++;
223 Uart.bitCnt = 0;
224 Uart.shiftReg = 0;
229 else if(Uart.nOutOfCnt == Uart.OutOfCnt) {
230 // RECEIVING DATA
231 // 1 out of 256
232 if(!Uart.dropPosition) {
233 Uart.state = STATE_UNSYNCD;
234 Uart.highCnt = 0;
235 //error = 3;
237 else {
238 Uart.dropPosition--;
239 Uart.output[Uart.byteCnt] = (Uart.dropPosition & 0xff);
240 Uart.byteCnt++;
241 Uart.bitCnt = 0;
242 Uart.shiftReg = 0;
243 Uart.nOutOfCnt = 0;
244 Uart.dropPosition = 0;
248 /*if(error) {
249 Uart.output[Uart.byteCnt] = 0xAA;
250 Uart.byteCnt++;
251 Uart.output[Uart.byteCnt] = error & 0xFF;
252 Uart.byteCnt++;
253 Uart.output[Uart.byteCnt] = 0xAA;
254 Uart.byteCnt++;
255 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
256 Uart.byteCnt++;
257 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
258 Uart.byteCnt++;
259 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
260 Uart.byteCnt++;
261 Uart.output[Uart.byteCnt] = 0xAA;
262 Uart.byteCnt++;
263 return TRUE;
268 else {
269 bit = Uart.bitBuffer & 0xf0;
270 bit >>= 4;
271 bit ^= 0x0F; // drops become 1s ;-)
272 if(bit) {
273 // should have been high or at least (4 * 128) / fc
274 // according to ISO this should be at least (9 * 128 + 20) / fc
275 if(Uart.highCnt == 8) {
276 // we went low, so this could be start of communication
277 // it turns out to be safer to choose a less significant
278 // syncbit... so we check whether the neighbour also represents the drop
279 Uart.posCnt = 1; // apparently we are busy with our first half bit period
280 Uart.syncBit = bit & 8;
281 Uart.samples = 3;
282 if(!Uart.syncBit) { Uart.syncBit = bit & 4; Uart.samples = 2; }
283 else if(bit & 4) { Uart.syncBit = bit & 4; Uart.samples = 2; bit <<= 2; }
284 if(!Uart.syncBit) { Uart.syncBit = bit & 2; Uart.samples = 1; }
285 else if(bit & 2) { Uart.syncBit = bit & 2; Uart.samples = 1; bit <<= 1; }
286 if(!Uart.syncBit) { Uart.syncBit = bit & 1; Uart.samples = 0;
287 if(Uart.syncBit && (Uart.bitBuffer & 8)) {
288 Uart.syncBit = 8;
290 // the first half bit period is expected in next sample
291 Uart.posCnt = 0;
292 Uart.samples = 3;
295 else if(bit & 1) { Uart.syncBit = bit & 1; Uart.samples = 0; }
297 Uart.syncBit <<= 4;
298 Uart.state = STATE_START_OF_COMMUNICATION;
299 Uart.bitCnt = 0;
300 Uart.byteCnt = 0;
301 Uart.nOutOfCnt = 0;
302 Uart.OutOfCnt = 4; // Start at 1/4, could switch to 1/256
303 Uart.dropPosition = 0;
304 Uart.shiftReg = 0;
305 //error = 0;
307 else {
308 Uart.highCnt = 0;
311 else {
312 if(Uart.highCnt < 8) {
313 Uart.highCnt++;
318 return FALSE;
321 //=============================================================================
322 // Manchester
323 //=============================================================================
325 static struct {
326 enum {
327 DEMOD_UNSYNCD,
328 DEMOD_START_OF_COMMUNICATION,
329 DEMOD_START_OF_COMMUNICATION2,
330 DEMOD_START_OF_COMMUNICATION3,
331 DEMOD_SOF_COMPLETE,
332 DEMOD_MANCHESTER_D,
333 DEMOD_MANCHESTER_E,
334 DEMOD_END_OF_COMMUNICATION,
335 DEMOD_END_OF_COMMUNICATION2,
336 DEMOD_MANCHESTER_F,
337 DEMOD_ERROR_WAIT
338 } state;
339 int bitCount;
340 int posCount;
341 int syncBit;
342 uint16_t shiftReg;
343 int buffer;
344 int buffer2;
345 int buffer3;
346 int buff;
347 int samples;
348 int len;
349 enum {
350 SUB_NONE,
351 SUB_FIRST_HALF,
352 SUB_SECOND_HALF,
353 SUB_BOTH
354 } sub;
355 uint8_t *output;
356 } Demod;
358 static RAMFUNC int ManchesterDecoding(int v)
360 int bit;
361 int modulation;
362 int error = 0;
364 bit = Demod.buffer;
365 Demod.buffer = Demod.buffer2;
366 Demod.buffer2 = Demod.buffer3;
367 Demod.buffer3 = v;
369 if(Demod.buff < 3) {
370 Demod.buff++;
371 return FALSE;
374 if(Demod.state==DEMOD_UNSYNCD) {
375 Demod.output[Demod.len] = 0xfa;
376 Demod.syncBit = 0;
377 //Demod.samples = 0;
378 Demod.posCount = 1; // This is the first half bit period, so after syncing handle the second part
380 if(bit & 0x08) {
381 Demod.syncBit = 0x08;
384 if(bit & 0x04) {
385 if(Demod.syncBit) {
386 bit <<= 4;
388 Demod.syncBit = 0x04;
391 if(bit & 0x02) {
392 if(Demod.syncBit) {
393 bit <<= 2;
395 Demod.syncBit = 0x02;
398 if(bit & 0x01 && Demod.syncBit) {
399 Demod.syncBit = 0x01;
402 if(Demod.syncBit) {
403 Demod.len = 0;
404 Demod.state = DEMOD_START_OF_COMMUNICATION;
405 Demod.sub = SUB_FIRST_HALF;
406 Demod.bitCount = 0;
407 Demod.shiftReg = 0;
408 Demod.samples = 0;
409 if(Demod.posCount) {
410 //if(trigger) LED_A_OFF(); // Not useful in this case...
411 switch(Demod.syncBit) {
412 case 0x08: Demod.samples = 3; break;
413 case 0x04: Demod.samples = 2; break;
414 case 0x02: Demod.samples = 1; break;
415 case 0x01: Demod.samples = 0; break;
417 // SOF must be long burst... otherwise stay unsynced!!!
418 if(!(Demod.buffer & Demod.syncBit) || !(Demod.buffer2 & Demod.syncBit)) {
419 Demod.state = DEMOD_UNSYNCD;
422 else {
423 // SOF must be long burst... otherwise stay unsynced!!!
424 if(!(Demod.buffer2 & Demod.syncBit) || !(Demod.buffer3 & Demod.syncBit)) {
425 Demod.state = DEMOD_UNSYNCD;
426 error = 0x88;
430 error = 0;
434 else {
435 modulation = bit & Demod.syncBit;
436 modulation |= ((bit << 1) ^ ((Demod.buffer & 0x08) >> 3)) & Demod.syncBit;
438 Demod.samples += 4;
440 if(Demod.posCount==0) {
441 Demod.posCount = 1;
442 if(modulation) {
443 Demod.sub = SUB_FIRST_HALF;
445 else {
446 Demod.sub = SUB_NONE;
449 else {
450 Demod.posCount = 0;
451 /*(modulation && (Demod.sub == SUB_FIRST_HALF)) {
452 if(Demod.state!=DEMOD_ERROR_WAIT) {
453 Demod.state = DEMOD_ERROR_WAIT;
454 Demod.output[Demod.len] = 0xaa;
455 error = 0x01;
458 //else if(modulation) {
459 if(modulation) {
460 if(Demod.sub == SUB_FIRST_HALF) {
461 Demod.sub = SUB_BOTH;
463 else {
464 Demod.sub = SUB_SECOND_HALF;
467 else if(Demod.sub == SUB_NONE) {
468 if(Demod.state == DEMOD_SOF_COMPLETE) {
469 Demod.output[Demod.len] = 0x0f;
470 Demod.len++;
471 Demod.state = DEMOD_UNSYNCD;
472 // error = 0x0f;
473 return TRUE;
475 else {
476 Demod.state = DEMOD_ERROR_WAIT;
477 error = 0x33;
479 /*if(Demod.state!=DEMOD_ERROR_WAIT) {
480 Demod.state = DEMOD_ERROR_WAIT;
481 Demod.output[Demod.len] = 0xaa;
482 error = 0x01;
486 switch(Demod.state) {
487 case DEMOD_START_OF_COMMUNICATION:
488 if(Demod.sub == SUB_BOTH) {
489 //Demod.state = DEMOD_MANCHESTER_D;
490 Demod.state = DEMOD_START_OF_COMMUNICATION2;
491 Demod.posCount = 1;
492 Demod.sub = SUB_NONE;
494 else {
495 Demod.output[Demod.len] = 0xab;
496 Demod.state = DEMOD_ERROR_WAIT;
497 error = 0xd2;
499 break;
500 case DEMOD_START_OF_COMMUNICATION2:
501 if(Demod.sub == SUB_SECOND_HALF) {
502 Demod.state = DEMOD_START_OF_COMMUNICATION3;
504 else {
505 Demod.output[Demod.len] = 0xab;
506 Demod.state = DEMOD_ERROR_WAIT;
507 error = 0xd3;
509 break;
510 case DEMOD_START_OF_COMMUNICATION3:
511 if(Demod.sub == SUB_SECOND_HALF) {
512 // Demod.state = DEMOD_MANCHESTER_D;
513 Demod.state = DEMOD_SOF_COMPLETE;
514 //Demod.output[Demod.len] = Demod.syncBit & 0xFF;
515 //Demod.len++;
517 else {
518 Demod.output[Demod.len] = 0xab;
519 Demod.state = DEMOD_ERROR_WAIT;
520 error = 0xd4;
522 break;
523 case DEMOD_SOF_COMPLETE:
524 case DEMOD_MANCHESTER_D:
525 case DEMOD_MANCHESTER_E:
526 // OPPOSITE FROM ISO14443 - 11110000 = 0 (1 in 14443)
527 // 00001111 = 1 (0 in 14443)
528 if(Demod.sub == SUB_SECOND_HALF) { // SUB_FIRST_HALF
529 Demod.bitCount++;
530 Demod.shiftReg = (Demod.shiftReg >> 1) ^ 0x100;
531 Demod.state = DEMOD_MANCHESTER_D;
533 else if(Demod.sub == SUB_FIRST_HALF) { // SUB_SECOND_HALF
534 Demod.bitCount++;
535 Demod.shiftReg >>= 1;
536 Demod.state = DEMOD_MANCHESTER_E;
538 else if(Demod.sub == SUB_BOTH) {
539 Demod.state = DEMOD_MANCHESTER_F;
541 else {
542 Demod.state = DEMOD_ERROR_WAIT;
543 error = 0x55;
545 break;
547 case DEMOD_MANCHESTER_F:
548 // Tag response does not need to be a complete byte!
549 if(Demod.len > 0 || Demod.bitCount > 0) {
550 if(Demod.bitCount > 1) { // was > 0, do not interpret last closing bit, is part of EOF
551 Demod.shiftReg >>= (9 - Demod.bitCount); // right align data
552 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
553 Demod.len++;
556 Demod.state = DEMOD_UNSYNCD;
557 return TRUE;
559 else {
560 Demod.output[Demod.len] = 0xad;
561 Demod.state = DEMOD_ERROR_WAIT;
562 error = 0x03;
564 break;
566 case DEMOD_ERROR_WAIT:
567 Demod.state = DEMOD_UNSYNCD;
568 break;
570 default:
571 Demod.output[Demod.len] = 0xdd;
572 Demod.state = DEMOD_UNSYNCD;
573 break;
576 /*if(Demod.bitCount>=9) {
577 Demod.output[Demod.len] = Demod.shiftReg & 0xff;
578 Demod.len++;
580 Demod.parityBits <<= 1;
581 Demod.parityBits ^= ((Demod.shiftReg >> 8) & 0x01);
583 Demod.bitCount = 0;
584 Demod.shiftReg = 0;
586 if(Demod.bitCount>=8) {
587 Demod.shiftReg >>= 1;
588 Demod.output[Demod.len] = (Demod.shiftReg & 0xff);
589 Demod.len++;
590 Demod.bitCount = 0;
591 Demod.shiftReg = 0;
594 if(error) {
595 Demod.output[Demod.len] = 0xBB;
596 Demod.len++;
597 Demod.output[Demod.len] = error & 0xFF;
598 Demod.len++;
599 Demod.output[Demod.len] = 0xBB;
600 Demod.len++;
601 Demod.output[Demod.len] = bit & 0xFF;
602 Demod.len++;
603 Demod.output[Demod.len] = Demod.buffer & 0xFF;
604 Demod.len++;
605 // Look harder ;-)
606 Demod.output[Demod.len] = Demod.buffer2 & 0xFF;
607 Demod.len++;
608 Demod.output[Demod.len] = Demod.syncBit & 0xFF;
609 Demod.len++;
610 Demod.output[Demod.len] = 0xBB;
611 Demod.len++;
612 return TRUE;
617 } // end (state != UNSYNCED)
619 return FALSE;
622 //=============================================================================
623 // Finally, a `sniffer' for iClass communication
624 // Both sides of communication!
625 //=============================================================================
627 //-----------------------------------------------------------------------------
628 // Record the sequence of commands sent by the reader to the tag, with
629 // triggering so that we start recording at the point that the tag is moved
630 // near the reader.
631 //-----------------------------------------------------------------------------
632 void RAMFUNC SnoopIClass(void)
636 // We won't start recording the frames that we acquire until we trigger;
637 // a good trigger condition to get started is probably when we see a
638 // response from the tag.
639 //int triggered = FALSE; // FALSE to wait first for card
641 // The command (reader -> tag) that we're receiving.
642 // The length of a received command will in most cases be no more than 18 bytes.
643 // So 32 should be enough!
644 #define ICLASS_BUFFER_SIZE 32
645 uint8_t readerToTagCmd[ICLASS_BUFFER_SIZE];
646 // The response (tag -> reader) that we're receiving.
647 uint8_t tagToReaderResponse[ICLASS_BUFFER_SIZE];
649 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
651 // free all BigBuf memory
652 BigBuf_free();
653 // The DMA buffer, used to stream samples from the FPGA
654 uint8_t *dmaBuf = BigBuf_malloc(DMA_BUFFER_SIZE);
656 set_tracing(TRUE);
657 clear_trace();
658 iso14a_set_trigger(FALSE);
660 int lastRxCounter;
661 uint8_t *upTo;
662 int smpl;
663 int maxBehindBy = 0;
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;
670 // Set up the demodulator for tag -> reader responses.
671 Demod.output = tagToReaderResponse;
672 Demod.len = 0;
673 Demod.state = DEMOD_UNSYNCD;
675 // Setup for the DMA.
676 FpgaSetupSsc();
677 upTo = dmaBuf;
678 lastRxCounter = DMA_BUFFER_SIZE;
679 FpgaSetupSscDma((uint8_t *)dmaBuf, DMA_BUFFER_SIZE);
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;
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);
693 uint32_t time_0 = GetCountSspClk();
694 uint32_t time_start = 0;
695 uint32_t time_stop = 0;
697 int div = 0;
698 //int div2 = 0;
699 int decbyte = 0;
700 int decbyter = 0;
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;
715 if(behindBy < 1) continue;
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;
728 //samples += 4;
729 samples += 1;
731 if(smpl & 0xF) {
732 decbyte ^= (1 << (3 - div));
735 // FOR READER SIDE COMMUMICATION...
737 decbyter <<= 2;
738 decbyter ^= (smpl & 0x30);
740 div++;
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();
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);
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;
768 decbyter = 0;
771 if(div > 3) {
772 smpl = decbyte;
773 if(ManchesterDecoding(smpl & 0x0F)) {
774 time_stop = (GetCountSspClk()-time_0) << 4;
776 rsamples = samples - Demod.samples;
777 LED_B_ON();
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);
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;
794 div = 0;
795 decbyte = 0x00;
799 if(BUTTON_PRESS()) {
800 DbpString("cancelled_a");
801 goto done;
805 DbpString("COMMAND FINISHED");
807 Dbprintf("%x %x %x", maxBehindBy, Uart.state, Uart.byteCnt);
808 Dbprintf("%x %x %x", Uart.byteCntMax, BigBuf_get_traceLen(), (int)Uart.output[0]);
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, BigBuf_get_traceLen(), (int)Uart.output[0]);
814 LED_A_OFF();
815 LED_B_OFF();
816 LED_C_OFF();
817 LED_D_OFF();
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);
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)
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);
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;
845 for(;;) {
846 WDT_HIT();
848 if(BUTTON_PRESS()) return FALSE;
850 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
851 AT91C_BASE_SSC->SSC_THR = 0x00;
853 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
854 uint8_t b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
856 if(OutOfNDecoding(b & 0x0f)) {
857 *len = Uart.byteCnt;
858 return TRUE;
864 static uint8_t encode4Bits(const uint8_t b)
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
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
896 //-----------------------------------------------------------------------------
897 // Prepare tag messages
898 //-----------------------------------------------------------------------------
899 static void CodeIClassTagAnswer(const uint8_t *cmd, int len)
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)
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
917 * A logic 0 starts with 8 pulses of fc/32
918 * followed by an unmodulated time of 256/fc (~18,88us).
920 * A logic 0 starts with unmodulated time of 256/fc (~18,88us) followed by
921 * 8 pulses of fc/32 (also 18.88us)
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
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
933 * */
935 int i;
937 ToSendReset();
939 // Send SOF
940 ToSend[++ToSendMax] = 0x1D;
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
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++;
955 // Only SOF
956 static void CodeIClassTagSOF()
958 //So far a dummy implementation, not used
959 //int lastProxToAirDuration =0;
961 ToSendReset();
962 // Send SOF
963 ToSend[++ToSendMax] = 0x1D;
964 // lastProxToAirDuration = 8*ToSendMax - 3*8;//Not counting zeroes in the beginning
966 // Convert from last byte pos to length
967 ToSendMax++;
969 #define MODE_SIM_CSN 0
970 #define MODE_EXIT_AFTER_MAC 1
971 #define MODE_FULLSIM 2
973 int doIClassSimulation(int simulationMode, uint8_t *reader_mac_buf);
975 * @brief SimulateIClass simulates an iClass card.
976 * @param arg0 type of simulation
977 * - 0 uses the first 8 bytes in usb data as CSN
978 * - 2 "dismantling iclass"-attack. This mode iterates through all CSN's specified
979 * in the usb data. This mode collects MAC from the reader, in order to do an offline
980 * attack on the keys. For more info, see "dismantling iclass" and proxclone.com.
981 * - Other : Uses the default CSN (031fec8af7ff12e0)
982 * @param arg1 - number of CSN's contained in datain (applicable for mode 2 only)
983 * @param arg2
984 * @param datain
986 void SimulateIClass(uint32_t arg0, uint32_t arg1, uint32_t arg2, uint8_t *datain)
988 uint32_t simType = arg0;
989 uint32_t numberOfCSNS = arg1;
990 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
992 // Enable and clear the trace
993 set_tracing(TRUE);
994 clear_trace();
995 //Use the emulator memory for SIM
996 uint8_t *emulator = BigBuf_get_EM_addr();
998 if(simType == 0) {
999 // Use the CSN from commandline
1000 memcpy(emulator, datain, 8);
1001 doIClassSimulation(MODE_SIM_CSN,NULL);
1002 }else if(simType == 1)
1004 //Default CSN
1005 uint8_t csn_crc[] = { 0x03, 0x1f, 0xec, 0x8a, 0xf7, 0xff, 0x12, 0xe0, 0x00, 0x00 };
1006 // Use the CSN from commandline
1007 memcpy(emulator, csn_crc, 8);
1008 doIClassSimulation(MODE_SIM_CSN,NULL);
1010 else if(simType == 2)
1013 uint8_t mac_responses[USB_CMD_DATA_SIZE] = { 0 };
1014 Dbprintf("Going into attack mode, %d CSNS sent", numberOfCSNS);
1015 // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
1016 // in order to collect MAC's from the reader. This can later be used in an offlne-attack
1017 // in order to obtain the keys, as in the "dismantling iclass"-paper.
1018 int i = 0;
1019 for( ; i < numberOfCSNS && i*8+8 < USB_CMD_DATA_SIZE; i++)
1021 // The usb data is 512 bytes, fitting 65 8-byte CSNs in there.
1023 memcpy(emulator, datain+(i*8), 8);
1024 if(doIClassSimulation(MODE_EXIT_AFTER_MAC,mac_responses+i*8))
1026 cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
1027 return; // Button pressed
1030 cmd_send(CMD_ACK,CMD_SIMULATE_TAG_ICLASS,i,0,mac_responses,i*8);
1032 }else if(simType == 3){
1033 //This is 'full sim' mode, where we use the emulator storage for data.
1034 doIClassSimulation(MODE_FULLSIM, NULL);
1036 else{
1037 // We may want a mode here where we hardcode the csns to use (from proxclone).
1038 // That will speed things up a little, but not required just yet.
1039 Dbprintf("The mode is not implemented, reserved for future use");
1041 Dbprintf("Done...");
1046 * @brief Does the actual simulation
1047 * @param csn - csn to use
1048 * @param breakAfterMacReceived if true, returns after reader MAC has been received.
1050 int doIClassSimulation( int simulationMode, uint8_t *reader_mac_buf)
1052 // free eventually allocated BigBuf memory
1053 BigBuf_free_keep_EM();
1055 uint8_t *csn = BigBuf_get_EM_addr();
1056 uint8_t *emulator = csn;
1057 uint8_t sof_data[] = { 0x0F} ;
1058 // CSN followed by two CRC bytes
1059 uint8_t anticoll_data[10] = { 0 };
1060 uint8_t csn_data[10] = { 0 };
1061 memcpy(csn_data,csn,sizeof(csn_data));
1062 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]);
1064 // Construct anticollision-CSN
1065 rotateCSN(csn_data,anticoll_data);
1067 // Compute CRC on both CSNs
1068 ComputeCrc14443(CRC_ICLASS, anticoll_data, 8, &anticoll_data[8], &anticoll_data[9]);
1069 ComputeCrc14443(CRC_ICLASS, csn_data, 8, &csn_data[8], &csn_data[9]);
1071 // e-Purse
1072 uint8_t card_challenge_data[8] = { 0x00 };
1073 if(simulationMode == MODE_FULLSIM)
1075 //Card challenge, a.k.a e-purse is on block 2
1076 memcpy(card_challenge_data,emulator + (8 * 2) , 8);
1079 int exitLoop = 0;
1080 // Reader 0a
1081 // Tag 0f
1082 // Reader 0c
1083 // Tag anticoll. CSN
1084 // Reader 81 anticoll. CSN
1085 // Tag CSN
1087 uint8_t *modulated_response;
1088 int modulated_response_size = 0;
1089 uint8_t* trace_data = NULL;
1090 int trace_data_size = 0;
1093 // Respond SOF -- takes 1 bytes
1094 uint8_t *resp_sof = BigBuf_malloc(2);
1095 int resp_sof_Len;
1097 // Anticollision CSN (rotated CSN)
1098 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
1099 uint8_t *resp_anticoll = BigBuf_malloc(28);
1100 int resp_anticoll_len;
1102 // CSN
1103 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
1104 uint8_t *resp_csn = BigBuf_malloc(30);
1105 int resp_csn_len;
1107 // e-Purse
1108 // 18: Takes 2 bytes for SOF/EOF and 8 * 2 = 16 bytes (2 bytes/bit)
1109 uint8_t *resp_cc = BigBuf_malloc(20);
1110 int resp_cc_len;
1112 uint8_t *receivedCmd = BigBuf_malloc(MAX_FRAME_SIZE);
1113 memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
1114 int len;
1116 // Prepare card messages
1117 ToSendMax = 0;
1119 // First card answer: SOF
1120 CodeIClassTagSOF();
1121 memcpy(resp_sof, ToSend, ToSendMax); resp_sof_Len = ToSendMax;
1123 // Anticollision CSN
1124 CodeIClassTagAnswer(anticoll_data, sizeof(anticoll_data));
1125 memcpy(resp_anticoll, ToSend, ToSendMax); resp_anticoll_len = ToSendMax;
1127 // CSN
1128 CodeIClassTagAnswer(csn_data, sizeof(csn_data));
1129 memcpy(resp_csn, ToSend, ToSendMax); resp_csn_len = ToSendMax;
1131 // e-Purse
1132 CodeIClassTagAnswer(card_challenge_data, sizeof(card_challenge_data));
1133 memcpy(resp_cc, ToSend, ToSendMax); resp_cc_len = ToSendMax;
1135 //This is used for responding to READ-block commands or other data which is dynamically generated
1136 uint8_t *data_response = BigBuf_malloc(8 * 2 + 2);
1137 //This is used for responding to READ-block commands or other data which is dynamically generated
1138 uint8_t *data_generic_trace = BigBuf_malloc(8 * 2 + 2);
1140 // Start from off (no field generated)
1141 //FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1142 //SpinDelay(200);
1143 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_TAGSIM_LISTEN);
1144 SpinDelay(100);
1145 StartCountSspClk();
1146 // We need to listen to the high-frequency, peak-detected path.
1147 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1148 FpgaSetupSsc();
1150 // To control where we are in the protocol
1151 int cmdsRecvd = 0;
1152 uint32_t time_0 = GetCountSspClk();
1153 uint32_t t2r_time =0;
1154 uint32_t r2t_time =0;
1156 LED_A_ON();
1157 bool buttonPressed = false;
1159 while(!exitLoop) {
1161 LED_B_OFF();
1162 //Signal tracer
1163 // Can be used to get a trigger for an oscilloscope..
1164 LED_C_OFF();
1166 if(!GetIClassCommandFromReader(receivedCmd, &len, 100)) {
1167 buttonPressed = true;
1168 break;
1170 r2t_time = GetCountSspClk();
1171 //Signal tracer
1172 LED_C_ON();
1174 // Okay, look at the command now.
1175 if(receivedCmd[0] == ICLASS_CMD_ACTALL ) {
1176 // Reader in anticollission phase
1177 modulated_response = resp_sof; modulated_response_size = resp_sof_Len; //order = 1;
1178 trace_data = sof_data;
1179 trace_data_size = sizeof(sof_data);
1180 } else if(receivedCmd[0] == ICLASS_CMD_READ_OR_IDENTIFY && len == 1) {
1181 // Reader asks for anticollission CSN
1182 modulated_response = resp_anticoll; modulated_response_size = resp_anticoll_len; //order = 2;
1183 trace_data = anticoll_data;
1184 trace_data_size = sizeof(anticoll_data);
1185 //DbpString("Reader requests anticollission CSN:");
1186 } else if(receivedCmd[0] == ICLASS_CMD_SELECT) {
1187 // Reader selects anticollission CSN.
1188 // Tag sends the corresponding real CSN
1189 modulated_response = resp_csn; modulated_response_size = resp_csn_len; //order = 3;
1190 trace_data = csn_data;
1191 trace_data_size = sizeof(csn_data);
1192 //DbpString("Reader selects anticollission CSN:");
1193 } else if(receivedCmd[0] == ICLASS_CMD_READCHECK_KD) {
1194 // Read e-purse (88 02)
1195 modulated_response = resp_cc; modulated_response_size = resp_cc_len; //order = 4;
1196 trace_data = card_challenge_data;
1197 trace_data_size = sizeof(card_challenge_data);
1198 LED_B_ON();
1199 } else if(receivedCmd[0] == ICLASS_CMD_CHECK) {
1200 // Reader random and reader MAC!!!
1201 if(simulationMode == MODE_FULLSIM)
1202 { //This is what we must do..
1203 //Reader just sent us NR and MAC(k,cc * nr)
1204 //The diversified key should be stored on block 3
1205 //However, from a typical dump, the key will not be there
1206 uint8_t diversified_key[8] = { 0 };
1208 //Get the diversified key from emulator memory
1209 memcpy(diversified_key, emulator+(8*3),8);
1210 uint8_t ccnr[12] = { 0 };
1211 //Put our cc there (block 2)
1212 memcpy(ccnr, emulator + (8 * 2), 8);
1213 //Put nr there
1214 memcpy(ccnr+8, receivedCmd+1,4);
1215 //Now, calc MAC
1216 doMAC(ccnr,diversified_key, data_generic_trace);
1217 trace_data = data_generic_trace;
1218 trace_data_size = 4;
1219 CodeIClassTagAnswer(trace_data , trace_data_size);
1220 memcpy(data_response, ToSend, ToSendMax);
1221 modulated_response = data_response;
1222 modulated_response_size = ToSendMax;
1223 }else
1224 { //Not fullsim, we don't respond
1225 // We do not know what to answer, so lets keep quiet
1226 modulated_response = resp_sof; modulated_response_size = 0;
1227 trace_data = NULL;
1228 trace_data_size = 0;
1229 if (simulationMode == MODE_EXIT_AFTER_MAC){
1230 // dbprintf:ing ...
1231 Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x"
1232 ,csn[0],csn[1],csn[2],csn[3],csn[4],csn[5],csn[6],csn[7]);
1233 Dbprintf("RDR: (len=%02d): %02x %02x %02x %02x %02x %02x %02x %02x %02x",len,
1234 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1235 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1236 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1237 if (reader_mac_buf != NULL)
1239 memcpy(reader_mac_buf,receivedCmd+1,8);
1241 exitLoop = true;
1245 } else if(receivedCmd[0] == ICLASS_CMD_HALT && len == 1) {
1246 // Reader ends the session
1247 modulated_response = resp_sof; modulated_response_size = 0; //order = 0;
1248 trace_data = NULL;
1249 trace_data_size = 0;
1250 } else if(simulationMode == MODE_FULLSIM && receivedCmd[0] == ICLASS_CMD_READ_OR_IDENTIFY && len == 4){
1251 //Read block
1252 uint16_t blk = receivedCmd[1];
1253 trace_data = emulator+(blk << 3);
1254 trace_data_size = 8;
1255 CodeIClassTagAnswer(trace_data , trace_data_size);
1256 memcpy(data_response, ToSend, ToSendMax);
1257 modulated_response = data_response;
1258 modulated_response_size = ToSendMax;
1260 else if(receivedCmd[0] == ICLASS_CMD_PAGESEL)
1261 {//Pagesel
1262 //Pagesel enables to select a page in the selected chip memory and return its configuration block
1263 //Chips with a single page will not answer to this command
1264 // It appears we're fine ignoring this.
1265 //Otherwise, we should answer 8bytes (block) + 2bytes CRC
1267 else {
1268 //#db# Unknown command received from reader (len=5): 26 1 0 f6 a 44 44 44 44
1269 // Never seen this command before
1270 Dbprintf("Unknown command received from reader (len=%d): %x %x %x %x %x %x %x %x %x",
1271 len,
1272 receivedCmd[0], receivedCmd[1], receivedCmd[2],
1273 receivedCmd[3], receivedCmd[4], receivedCmd[5],
1274 receivedCmd[6], receivedCmd[7], receivedCmd[8]);
1275 // Do not respond
1276 modulated_response = resp_sof; modulated_response_size = 0; //order = 0;
1277 trace_data = NULL;
1278 trace_data_size = 0;
1281 if(cmdsRecvd > 100) {
1282 //DbpString("100 commands later...");
1283 //break;
1285 else {
1286 cmdsRecvd++;
1289 A legit tag has about 380us delay between reader EOT and tag SOF.
1291 if(modulated_response_size > 0) {
1292 SendIClassAnswer(modulated_response, modulated_response_size, 1);
1293 t2r_time = GetCountSspClk();
1296 if (tracing) {
1297 uint8_t parity[MAX_PARITY_SIZE];
1298 GetParity(receivedCmd, len, parity);
1299 LogTrace(receivedCmd,len, (r2t_time-time_0)<< 4, (r2t_time-time_0) << 4, parity, TRUE);
1301 if (trace_data != NULL) {
1302 GetParity(trace_data, trace_data_size, parity);
1303 LogTrace(trace_data, trace_data_size, (t2r_time-time_0) << 4, (t2r_time-time_0) << 4, parity, FALSE);
1305 if(!tracing) {
1306 DbpString("Trace full");
1307 //break;
1311 memset(receivedCmd, 0x44, MAX_FRAME_SIZE);
1314 //Dbprintf("%x", cmdsRecvd);
1315 LED_A_OFF();
1316 LED_B_OFF();
1317 LED_C_OFF();
1319 if(buttonPressed)
1321 DbpString("Button pressed");
1323 return buttonPressed;
1326 static int SendIClassAnswer(uint8_t *resp, int respLen, int delay)
1328 int i = 0, d=0;//, u = 0, d = 0;
1329 uint8_t b = 0;
1331 //FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K);
1332 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR|FPGA_HF_SIMULATOR_MODULATE_424K_8BIT);
1334 AT91C_BASE_SSC->SSC_THR = 0x00;
1335 FpgaSetupSsc();
1336 while(!BUTTON_PRESS()) {
1337 if((AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)){
1338 b = AT91C_BASE_SSC->SSC_RHR; (void) b;
1340 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)){
1341 b = 0x00;
1342 if(d < delay) {
1343 d++;
1345 else {
1346 if( i < respLen){
1347 b = resp[i];
1348 //Hack
1349 //b = 0xAC;
1351 i++;
1353 AT91C_BASE_SSC->SSC_THR = b;
1356 // if (i > respLen +4) break;
1357 if (i > respLen +1) break;
1360 return 0;
1363 /// THE READER CODE
1365 //-----------------------------------------------------------------------------
1366 // Transmit the command (to the tag) that was placed in ToSend[].
1367 //-----------------------------------------------------------------------------
1368 static void TransmitIClassCommand(const uint8_t *cmd, int len, int *samples, int *wait)
1370 int c;
1371 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1372 AT91C_BASE_SSC->SSC_THR = 0x00;
1373 FpgaSetupSsc();
1375 if (wait)
1377 if(*wait < 10) *wait = 10;
1379 for(c = 0; c < *wait;) {
1380 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1381 AT91C_BASE_SSC->SSC_THR = 0x00; // For exact timing!
1382 c++;
1384 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1385 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1386 (void)r;
1388 WDT_HIT();
1394 uint8_t sendbyte;
1395 bool firstpart = TRUE;
1396 c = 0;
1397 for(;;) {
1398 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1400 // DOUBLE THE SAMPLES!
1401 if(firstpart) {
1402 sendbyte = (cmd[c] & 0xf0) | (cmd[c] >> 4);
1404 else {
1405 sendbyte = (cmd[c] & 0x0f) | (cmd[c] << 4);
1406 c++;
1408 if(sendbyte == 0xff) {
1409 sendbyte = 0xfe;
1411 AT91C_BASE_SSC->SSC_THR = sendbyte;
1412 firstpart = !firstpart;
1414 if(c >= len) {
1415 break;
1418 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1419 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1420 (void)r;
1422 WDT_HIT();
1424 if (samples) *samples = (c + *wait) << 3;
1428 //-----------------------------------------------------------------------------
1429 // Prepare iClass reader command to send to FPGA
1430 //-----------------------------------------------------------------------------
1431 void CodeIClassCommand(const uint8_t * cmd, int len)
1433 int i, j, k;
1434 uint8_t b;
1436 ToSendReset();
1438 // Start of Communication: 1 out of 4
1439 ToSend[++ToSendMax] = 0xf0;
1440 ToSend[++ToSendMax] = 0x00;
1441 ToSend[++ToSendMax] = 0x0f;
1442 ToSend[++ToSendMax] = 0x00;
1444 // Modulate the bytes
1445 for (i = 0; i < len; i++) {
1446 b = cmd[i];
1447 for(j = 0; j < 4; j++) {
1448 for(k = 0; k < 4; k++) {
1449 if(k == (b & 3)) {
1450 ToSend[++ToSendMax] = 0x0f;
1452 else {
1453 ToSend[++ToSendMax] = 0x00;
1456 b >>= 2;
1460 // End of Communication
1461 ToSend[++ToSendMax] = 0x00;
1462 ToSend[++ToSendMax] = 0x00;
1463 ToSend[++ToSendMax] = 0xf0;
1464 ToSend[++ToSendMax] = 0x00;
1466 // Convert from last character reference to length
1467 ToSendMax++;
1470 void ReaderTransmitIClass(uint8_t* frame, int len)
1472 int wait = 0;
1473 int samples = 0;
1475 // This is tied to other size changes
1476 CodeIClassCommand(frame,len);
1478 // Select the card
1479 TransmitIClassCommand(ToSend, ToSendMax, &samples, &wait);
1480 if(trigger)
1481 LED_A_ON();
1483 // Store reader command in buffer
1484 if (tracing) {
1485 uint8_t par[MAX_PARITY_SIZE];
1486 GetParity(frame, len, par);
1487 LogTrace(frame, len, rsamples, rsamples, par, TRUE);
1491 //-----------------------------------------------------------------------------
1492 // Wait a certain time for tag response
1493 // If a response is captured return TRUE
1494 // If it takes too long return FALSE
1495 //-----------------------------------------------------------------------------
1496 static int GetIClassAnswer(uint8_t *receivedResponse, int maxLen, int *samples, int *elapsed) //uint8_t *buffer
1498 // buffer needs to be 512 bytes
1499 int c;
1501 // Set FPGA mode to "reader listen mode", no modulation (listen
1502 // only, since we are receiving, not transmitting).
1503 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_LISTEN);
1505 // Now get the answer from the card
1506 Demod.output = receivedResponse;
1507 Demod.len = 0;
1508 Demod.state = DEMOD_UNSYNCD;
1510 uint8_t b;
1511 if (elapsed) *elapsed = 0;
1513 bool skip = FALSE;
1515 c = 0;
1516 for(;;) {
1517 WDT_HIT();
1519 if(BUTTON_PRESS()) return FALSE;
1521 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1522 AT91C_BASE_SSC->SSC_THR = 0x00; // To make use of exact timing of next command from reader!!
1523 if (elapsed) (*elapsed)++;
1525 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1526 if(c < timeout) { c++; } else { return FALSE; }
1527 b = (uint8_t)AT91C_BASE_SSC->SSC_RHR;
1528 skip = !skip;
1529 if(skip) continue;
1531 if(ManchesterDecoding(b & 0x0f)) {
1532 *samples = c << 3;
1533 return TRUE;
1539 int ReaderReceiveIClass(uint8_t* receivedAnswer)
1541 int samples = 0;
1542 if (!GetIClassAnswer(receivedAnswer,160,&samples,0)) return FALSE;
1543 rsamples += samples;
1544 if (tracing) {
1545 uint8_t parity[MAX_PARITY_SIZE];
1546 GetParity(receivedAnswer, Demod.len, parity);
1547 LogTrace(receivedAnswer,Demod.len,rsamples,rsamples,parity,FALSE);
1549 if(samples == 0) return FALSE;
1550 return Demod.len;
1553 void setupIclassReader()
1555 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1556 // Reset trace buffer
1557 set_tracing(TRUE);
1558 clear_trace();
1560 // Setup SSC
1561 FpgaSetupSsc();
1562 // Start from off (no field generated)
1563 // Signal field is off with the appropriate LED
1564 LED_D_OFF();
1565 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1566 SpinDelay(200);
1568 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1570 // Now give it time to spin up.
1571 // Signal field is on with the appropriate LED
1572 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1573 SpinDelay(200);
1574 LED_A_ON();
1578 size_t sendCmdGetResponseWithRetries(uint8_t* command, size_t cmdsize, uint8_t* resp, uint8_t expected_size, uint8_t retries)
1580 while(retries-- > 0)
1582 ReaderTransmitIClass(command, cmdsize);
1583 if(expected_size == ReaderReceiveIClass(resp)){
1584 return 0;
1587 return 1;//Error
1591 * @brief Talks to an iclass tag, sends the commands to get CSN and CC.
1592 * @param card_data where the CSN and CC are stored for return
1593 * @return 0 = fail
1594 * 1 = Got CSN
1595 * 2 = Got CSN and CC
1597 uint8_t handshakeIclassTag(uint8_t *card_data)
1599 static uint8_t act_all[] = { 0x0a };
1600 static uint8_t identify[] = { 0x0c };
1601 static uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1602 static uint8_t readcheck_cc[]= { 0x88, 0x02 };
1603 uint8_t resp[ICLASS_BUFFER_SIZE];
1605 uint8_t read_status = 0;
1607 // Send act_all
1608 ReaderTransmitIClass(act_all, 1);
1609 // Card present?
1610 if(!ReaderReceiveIClass(resp)) return read_status;//Fail
1611 //Send Identify
1612 ReaderTransmitIClass(identify, 1);
1613 //We expect a 10-byte response here, 8 byte anticollision-CSN and 2 byte CRC
1614 uint8_t len = ReaderReceiveIClass(resp);
1615 if(len != 10) return read_status;//Fail
1617 //Copy the Anti-collision CSN to our select-packet
1618 memcpy(&select[1],resp,8);
1619 //Select the card
1620 ReaderTransmitIClass(select, sizeof(select));
1621 //We expect a 10-byte response here, 8 byte CSN and 2 byte CRC
1622 len = ReaderReceiveIClass(resp);
1623 if(len != 10) return read_status;//Fail
1625 //Success - level 1, we got CSN
1626 //Save CSN in response data
1627 memcpy(card_data,resp,8);
1629 //Flag that we got to at least stage 1, read CSN
1630 read_status = 1;
1632 // Card selected, now read e-purse (cc)
1633 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1634 if(ReaderReceiveIClass(resp) == 8) {
1635 //Save CC (e-purse) in response data
1636 memcpy(card_data+8,resp,8);
1638 //Got both
1639 read_status = 2;
1642 return read_status;
1645 // Reader iClass Anticollission
1646 void ReaderIClass(uint8_t arg0) {
1648 uint8_t card_data[24]={0};
1649 uint8_t last_csn[8]={0};
1651 int read_status= 0;
1652 bool abort_after_read = arg0 & FLAG_ICLASS_READER_ONLY_ONCE;
1653 bool get_cc = arg0 & FLAG_ICLASS_READER_GET_CC;
1654 set_tracing(TRUE);
1655 setupIclassReader();
1657 size_t datasize = 0;
1658 while(!BUTTON_PRESS())
1661 if(!tracing) {
1662 DbpString("Trace full");
1663 break;
1665 WDT_HIT();
1667 read_status = handshakeIclassTag(card_data);
1669 if(read_status == 0) continue;
1670 if(read_status == 1) datasize = 8;
1671 if(read_status == 2) datasize = 16;
1673 //Todo, read the public blocks 1,5 aswell:
1675 // 0 : CSN (we already have)
1676 // 1 : Configuration
1677 // 2 : e-purse (we already have)
1678 // (3,4 write-only)
1679 // 5 Application issuer area
1681 //Then we can 'ship' back the 8 * 5 bytes of data,
1682 // with 0xFF:s in block 3 and 4.
1684 LED_B_ON();
1685 //Send back to client, but don't bother if we already sent this
1686 if(memcmp(last_csn, card_data, 8) != 0)
1689 if(!get_cc || (get_cc && read_status == 2))
1691 cmd_send(CMD_ACK,read_status,0,0,card_data,datasize);
1692 if(abort_after_read) {
1693 LED_A_OFF();
1694 return;
1696 //Save that we already sent this....
1697 memcpy(last_csn, card_data, 8);
1699 //If 'get_cc' was specified and we didn't get a CC, we'll just keep trying...
1701 LED_B_OFF();
1703 cmd_send(CMD_ACK,0,0,0,card_data, 0);
1704 LED_A_OFF();
1707 void ReaderIClass_Replay(uint8_t arg0, uint8_t *MAC) {
1709 uint8_t card_data[USB_CMD_DATA_SIZE]={0};
1710 uint16_t block_crc_LUT[255] = {0};
1712 {//Generate a lookup table for block crc
1713 for(int block = 0; block < 255; block++){
1714 char bl = block;
1715 block_crc_LUT[block] = iclass_crc16(&bl ,1);
1718 //Dbprintf("Lookup table: %02x %02x %02x" ,block_crc_LUT[0],block_crc_LUT[1],block_crc_LUT[2]);
1720 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1721 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1723 uint16_t crc = 0;
1724 uint8_t cardsize=0;
1725 uint8_t mem=0;
1727 static struct memory_t{
1728 int k16;
1729 int book;
1730 int k2;
1731 int lockauth;
1732 int keyaccess;
1733 } memory;
1735 uint8_t resp[ICLASS_BUFFER_SIZE];
1737 setupIclassReader();
1738 set_tracing(TRUE);
1740 while(!BUTTON_PRESS()) {
1742 WDT_HIT();
1744 if(!tracing) {
1745 DbpString("Trace full");
1746 break;
1749 uint8_t read_status = handshakeIclassTag(card_data);
1750 if(read_status < 2) continue;
1752 //for now replay captured auth (as cc not updated)
1753 memcpy(check+5,MAC,4);
1755 if(sendCmdGetResponseWithRetries(check, sizeof(check),resp, 4, 5))
1757 Dbprintf("Error: Authentication Fail!");
1758 continue;
1761 //first get configuration block (block 1)
1762 crc = block_crc_LUT[1];
1763 read[1]=1;
1764 read[2] = crc >> 8;
1765 read[3] = crc & 0xff;
1767 if(sendCmdGetResponseWithRetries(read, sizeof(read),resp, 10, 10))
1769 Dbprintf("Dump config (block 1) failed");
1770 continue;
1773 mem=resp[5];
1774 memory.k16= (mem & 0x80);
1775 memory.book= (mem & 0x20);
1776 memory.k2= (mem & 0x8);
1777 memory.lockauth= (mem & 0x2);
1778 memory.keyaccess= (mem & 0x1);
1780 cardsize = memory.k16 ? 255 : 32;
1781 WDT_HIT();
1782 //Set card_data to all zeroes, we'll fill it with data
1783 memset(card_data,0x0,USB_CMD_DATA_SIZE);
1784 uint8_t failedRead =0;
1785 uint32_t stored_data_length =0;
1786 //then loop around remaining blocks
1787 for(int block=0; block < cardsize; block++){
1789 read[1]= block;
1790 crc = block_crc_LUT[block];
1791 read[2] = crc >> 8;
1792 read[3] = crc & 0xff;
1794 if(!sendCmdGetResponseWithRetries(read, sizeof(read), resp, 10, 10))
1796 Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
1797 block, resp[0], resp[1], resp[2],
1798 resp[3], resp[4], resp[5],
1799 resp[6], resp[7]);
1801 //Fill up the buffer
1802 memcpy(card_data+stored_data_length,resp,8);
1803 stored_data_length += 8;
1804 if(stored_data_length +8 > USB_CMD_DATA_SIZE)
1805 {//Time to send this off and start afresh
1806 cmd_send(CMD_ACK,
1807 stored_data_length,//data length
1808 failedRead,//Failed blocks?
1809 0,//Not used ATM
1810 card_data, stored_data_length);
1811 //reset
1812 stored_data_length = 0;
1813 failedRead = 0;
1816 }else{
1817 failedRead = 1;
1818 stored_data_length +=8;//Otherwise, data becomes misaligned
1819 Dbprintf("Failed to dump block %d", block);
1823 //Send off any remaining data
1824 if(stored_data_length > 0)
1826 cmd_send(CMD_ACK,
1827 stored_data_length,//data length
1828 failedRead,//Failed blocks?
1829 0,//Not used ATM
1830 card_data, stored_data_length);
1832 //If we got here, let's break
1833 break;
1835 //Signal end of transmission
1836 cmd_send(CMD_ACK,
1837 0,//data length
1838 0,//Failed blocks?
1839 0,//Not used ATM
1840 card_data, 0);
1842 LED_A_OFF();
1845 //2. Create Read method (cut-down from above) based off responses from 1.
1846 // Since we have the MAC could continue to use replay function.
1847 //3. Create Write method
1849 void IClass_iso14443A_write(uint8_t arg0, uint8_t blockNo, uint8_t *data, uint8_t *MAC) {
1850 uint8_t act_all[] = { 0x0a };
1851 uint8_t identify[] = { 0x0c };
1852 uint8_t select[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1853 uint8_t readcheck_cc[]= { 0x88, 0x02 };
1854 uint8_t check[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1855 uint8_t read[] = { 0x0c, 0x00, 0x00, 0x00 };
1856 uint8_t write[] = { 0x87, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1858 uint16_t crc = 0;
1860 uint8_t* resp = (((uint8_t *)BigBuf) + 3560);
1862 // Reset trace buffer
1863 memset(trace, 0x44, RECV_CMD_OFFSET);
1864 traceLen = 0;
1866 // Setup SSC
1867 FpgaSetupSsc();
1868 // Start from off (no field generated)
1869 // Signal field is off with the appropriate LED
1870 LED_D_OFF();
1871 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1872 SpinDelay(200);
1874 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1876 // Now give it time to spin up.
1877 // Signal field is on with the appropriate LED
1878 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A | FPGA_HF_ISO14443A_READER_MOD);
1879 SpinDelay(200);
1881 LED_A_ON();
1883 for(int i=0;i<1;i++) {
1885 if(traceLen > TRACE_SIZE) {
1886 DbpString("Trace full");
1887 break;
1890 if (BUTTON_PRESS()) break;
1892 // Send act_all
1893 ReaderTransmitIClass(act_all, 1);
1894 // Card present?
1895 if(ReaderReceiveIClass(resp)) {
1896 ReaderTransmitIClass(identify, 1);
1897 if(ReaderReceiveIClass(resp) == 10) {
1898 // Select card
1899 memcpy(&select[1],resp,8);
1900 ReaderTransmitIClass(select, sizeof(select));
1902 if(ReaderReceiveIClass(resp) == 10) {
1903 Dbprintf(" Selected CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1904 resp[0], resp[1], resp[2],
1905 resp[3], resp[4], resp[5],
1906 resp[6], resp[7]);
1908 // Card selected
1909 Dbprintf("Readcheck on Sector 2");
1910 ReaderTransmitIClass(readcheck_cc, sizeof(readcheck_cc));
1911 if(ReaderReceiveIClass(resp) == 8) {
1912 Dbprintf(" CC: %02x %02x %02x %02x %02x %02x %02x %02x",
1913 resp[0], resp[1], resp[2],
1914 resp[3], resp[4], resp[5],
1915 resp[6], resp[7]);
1916 }else return;
1917 Dbprintf("Authenticate");
1918 //for now replay captured auth (as cc not updated)
1919 memcpy(check+5,MAC,4);
1920 Dbprintf(" AA: %02x %02x %02x %02x",
1921 check[5], check[6], check[7],check[8]);
1922 ReaderTransmitIClass(check, sizeof(check));
1923 if(ReaderReceiveIClass(resp) == 4) {
1924 Dbprintf(" AR: %02x %02x %02x %02x",
1925 resp[0], resp[1], resp[2],resp[3]);
1926 }else {
1927 Dbprintf("Error: Authentication Fail!");
1928 return;
1930 Dbprintf("Write Block");
1932 //read configuration for max block number
1933 read_success=false;
1934 read[1]=1;
1935 uint8_t *blockno=&read[1];
1936 crc = iclass_crc16((char *)blockno,1);
1937 read[2] = crc >> 8;
1938 read[3] = crc & 0xff;
1939 while(!read_success){
1940 ReaderTransmitIClass(read, sizeof(read));
1941 if(ReaderReceiveIClass(resp) == 10) {
1942 read_success=true;
1943 mem=resp[5];
1944 memory.k16= (mem & 0x80);
1945 memory.book= (mem & 0x20);
1946 memory.k2= (mem & 0x8);
1947 memory.lockauth= (mem & 0x2);
1948 memory.keyaccess= (mem & 0x1);
1952 if (memory.k16){
1953 cardsize=255;
1954 }else cardsize=32;
1955 //check card_size
1957 memcpy(write+1,blockNo,1);
1958 memcpy(write+2,data,8);
1959 memcpy(write+10,mac,4);
1960 while(!send_success){
1961 ReaderTransmitIClass(write, sizeof(write));
1962 if(ReaderReceiveIClass(resp) == 10) {
1963 write_success=true;
1967 WDT_HIT();
1970 LED_A_OFF();