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