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