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
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
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
16 // Please feel free to contribute and extend iClass support!!
17 //-----------------------------------------------------------------------------
21 // We still have sometimes a demodulation error when snooping iClass communication.
22 // The resulting trace of a read-block-03 command may look something like this:
24 // + 22279: : 0c 03 e8 01
26 // ...with an incorrect answer...
28 // + 85: 0: TAG ff! ff! ff! ff! ff! ff! ff! ff! bb 33 bb 00 01! 0e! 04! bb !crc
30 // We still left the error signalling bytes in the traces like 0xbb
32 // A correct trace should look like this:
34 // + 21112: : 0c 03 e8 01
35 // + 85: 0: TAG ff ff ff ff ff ff ff ff ea f5
37 //-----------------------------------------------------------------------------
41 #include "proxmark3.h"
48 #include "iso14443a.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"
60 static int timeout
= 4096;
62 //-----------------------------------------------------------------------------
63 // The software UART that receives commands from the reader, and its state
65 //-----------------------------------------------------------------------------
69 STATE_START_OF_COMMUNICATION
,
89 static RAMFUNC
int OutOfNDecoding(int bit
) {
93 if (!Uart
.bitBuffer
) {
94 Uart
.bitBuffer
= bit
^ 0xFF0;
98 Uart
.bitBuffer
^= bit
;
101 /*if (Uart.swapper) {
102 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
105 if (Uart.byteCnt > 15) { return true; }
111 if (Uart
.state
!= STATE_UNSYNCD
) {
114 if ((Uart
.bitBuffer
& Uart
.syncBit
) ^ Uart
.syncBit
) {
119 if (((Uart
.bitBuffer
<< 1) & Uart
.syncBit
) ^ Uart
.syncBit
) {
124 if (bit
!= bitright
) {
129 // So, now we only have to deal with *bit*, lets see...
130 if (Uart
.posCnt
== 1) {
131 // measurement first half bitperiod
133 // Drop in first half means that we are either seeing
136 if (Uart
.nOutOfCnt
== 1) {
137 // End of Communication
138 Uart
.state
= STATE_UNSYNCD
;
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;
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
;
156 // measurement second half bitperiod
157 // Count the bitslot we are in... (ISO 15693)
161 if (Uart
.dropPosition
) {
162 if (Uart
.state
== STATE_START_OF_COMMUNICATION
) {
167 // It is an error if we already have seen a drop in current frame
168 Uart
.state
= STATE_UNSYNCD
;
171 Uart
.dropPosition
= Uart
.nOutOfCnt
;
178 if (Uart
.nOutOfCnt
== Uart
.OutOfCnt
&& Uart
.OutOfCnt
== 4) {
181 if (Uart
.state
== STATE_START_OF_COMMUNICATION
) {
182 if (Uart
.dropPosition
== 4) {
183 Uart
.state
= STATE_RECEIVING
;
185 } else if (Uart
.dropPosition
== 3) {
186 Uart
.state
= STATE_RECEIVING
;
188 //Uart.output[Uart.byteCnt] = 0xdd;
191 Uart
.state
= STATE_UNSYNCD
;
194 Uart
.dropPosition
= 0;
198 if (!Uart
.dropPosition
) {
199 Uart
.state
= STATE_UNSYNCD
;
207 //if (Uart.dropPosition == 1) { Uart.dropPosition = 2; }
208 //else if (Uart.dropPosition == 2) { Uart.dropPosition = 1; }
210 Uart
.shiftReg
^= ((Uart
.dropPosition
& 0x03) << 6);
212 Uart
.dropPosition
= 0;
214 if (Uart
.bitCnt
== 8) {
215 Uart
.output
[Uart
.byteCnt
] = (Uart
.shiftReg
& 0xff);
222 } else if (Uart
.nOutOfCnt
== Uart
.OutOfCnt
) {
225 if (!Uart
.dropPosition
) {
226 Uart
.state
= STATE_UNSYNCD
;
231 Uart
.output
[Uart
.byteCnt
] = (Uart
.dropPosition
& 0xff);
236 Uart
.dropPosition
= 0;
241 Uart.output[Uart.byteCnt] = 0xAA;
243 Uart.output[Uart.byteCnt] = error & 0xFF;
245 Uart.output[Uart.byteCnt] = 0xAA;
247 Uart.output[Uart.byteCnt] = (Uart.bitBuffer >> 8) & 0xFF;
249 Uart.output[Uart.byteCnt] = Uart.bitBuffer & 0xFF;
251 Uart.output[Uart.byteCnt] = (Uart.syncBit >> 3) & 0xFF;
253 Uart.output[Uart.byteCnt] = 0xAA;
260 bit
= Uart
.bitBuffer
& 0xf0;
262 bit
^= 0x0F; // drops become 1s ;-)
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;
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)) {
281 // the first half bit period is expected in next sample
285 } else if (bit
& 1) { Uart
.syncBit
= bit
& 1; Uart
.samples
= 0; }
288 Uart
.state
= STATE_START_OF_COMMUNICATION
;
292 Uart
.OutOfCnt
= 4; // Start at 1/4, could switch to 1/256
293 Uart
.dropPosition
= 0;
299 } else if (Uart
.highCnt
< 8) {
308 //=============================================================================
310 //=============================================================================
315 DEMOD_START_OF_COMMUNICATION
,
316 DEMOD_START_OF_COMMUNICATION2
,
317 DEMOD_START_OF_COMMUNICATION3
,
321 DEMOD_END_OF_COMMUNICATION
,
322 DEMOD_END_OF_COMMUNICATION2
,
345 static RAMFUNC
int ManchesterDecoding(int v
) {
351 Demod
.buffer
= Demod
.buffer2
;
352 Demod
.buffer2
= Demod
.buffer3
;
355 if (Demod
.buff
< 3) {
360 if (Demod
.state
==DEMOD_UNSYNCD
) {
361 Demod
.output
[Demod
.len
] = 0xfa;
364 Demod
.posCount
= 1; // This is the first half bit period, so after syncing handle the second part
367 Demod
.syncBit
= 0x08;
374 Demod
.syncBit
= 0x04;
381 Demod
.syncBit
= 0x02;
384 if (bit
& 0x01 && Demod
.syncBit
) {
385 Demod
.syncBit
= 0x01;
390 Demod
.state
= DEMOD_START_OF_COMMUNICATION
;
391 Demod
.sub
= SUB_FIRST_HALF
;
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;
402 // SOF must be long burst... otherwise stay unsynced!!!
403 if (!(Demod
.buffer
& Demod
.syncBit
) || !(Demod
.buffer2
& Demod
.syncBit
)) {
404 Demod
.state
= DEMOD_UNSYNCD
;
407 // SOF must be long burst... otherwise stay unsynced!!!
408 if (!(Demod
.buffer2
& Demod
.syncBit
) || !(Demod
.buffer3
& Demod
.syncBit
)) {
409 Demod
.state
= DEMOD_UNSYNCD
;
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
;
424 if (Demod
.posCount
== 0) {
427 Demod
.sub
= SUB_FIRST_HALF
;
429 Demod
.sub
= SUB_NONE
;
434 if (Demod
.sub
== SUB_FIRST_HALF
) {
435 Demod
.sub
= SUB_BOTH
;
437 Demod
.sub
= SUB_SECOND_HALF
;
439 } else if (Demod
.sub
== SUB_NONE
) {
440 if (Demod
.state
== DEMOD_SOF_COMPLETE
) {
441 Demod
.output
[Demod
.len
] = 0x0f;
443 Demod
.state
= DEMOD_UNSYNCD
;
446 Demod
.state
= DEMOD_ERROR_WAIT
;
451 switch(Demod
.state
) {
452 case DEMOD_START_OF_COMMUNICATION
:
453 if (Demod
.sub
== SUB_BOTH
) {
454 Demod
.state
= DEMOD_START_OF_COMMUNICATION2
;
456 Demod
.sub
= SUB_NONE
;
458 Demod
.output
[Demod
.len
] = 0xab;
459 Demod
.state
= DEMOD_ERROR_WAIT
;
463 case DEMOD_START_OF_COMMUNICATION2
:
464 if (Demod
.sub
== SUB_SECOND_HALF
) {
465 Demod
.state
= DEMOD_START_OF_COMMUNICATION3
;
467 Demod
.output
[Demod
.len
] = 0xab;
468 Demod
.state
= DEMOD_ERROR_WAIT
;
472 case DEMOD_START_OF_COMMUNICATION3
:
473 if (Demod
.sub
== SUB_SECOND_HALF
) {
474 Demod
.state
= DEMOD_SOF_COMPLETE
;
476 Demod
.output
[Demod
.len
] = 0xab;
477 Demod
.state
= DEMOD_ERROR_WAIT
;
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
488 Demod
.shiftReg
= (Demod
.shiftReg
>> 1) ^ 0x100;
489 Demod
.state
= DEMOD_MANCHESTER_D
;
490 } else if (Demod
.sub
== SUB_FIRST_HALF
) { // SUB_SECOND_HALF
492 Demod
.shiftReg
>>= 1;
493 Demod
.state
= DEMOD_MANCHESTER_E
;
494 } else if (Demod
.sub
== SUB_BOTH
) {
495 Demod
.state
= DEMOD_MANCHESTER_F
;
497 Demod
.state
= DEMOD_ERROR_WAIT
;
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;
511 Demod
.state
= DEMOD_UNSYNCD
;
514 Demod
.output
[Demod
.len
] = 0xad;
515 Demod
.state
= DEMOD_ERROR_WAIT
;
520 case DEMOD_ERROR_WAIT
:
521 Demod
.state
= DEMOD_UNSYNCD
;
525 Demod
.output
[Demod
.len
] = 0xdd;
526 Demod
.state
= DEMOD_UNSYNCD
;
530 if (Demod
.bitCount
>= 8) {
531 Demod
.shiftReg
>>= 1;
532 Demod
.output
[Demod
.len
] = (Demod
.shiftReg
& 0xff);
539 Demod
.output
[Demod
.len
] = 0xBB;
541 Demod
.output
[Demod
.len
] = error
& 0xFF;
543 Demod
.output
[Demod
.len
] = 0xBB;
545 Demod
.output
[Demod
.len
] = bit
& 0xFF;
547 Demod
.output
[Demod
.len
] = Demod
.buffer
& 0xFF;
550 Demod
.output
[Demod
.len
] = Demod
.buffer2
& 0xFF;
552 Demod
.output
[Demod
.len
] = Demod
.syncBit
& 0xFF;
554 Demod
.output
[Demod
.len
] = 0xBB;
561 } // end (state != UNSYNCED)
566 //=============================================================================
567 // Finally, a `sniffer' for iClass communication
568 // Both sides of communication!
569 //=============================================================================
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
575 //-----------------------------------------------------------------------------
576 void RAMFUNC
SnoopIClass(void) {
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
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
];
591 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
593 // free all BigBuf memory
595 // The DMA buffer, used to stream samples from the FPGA
596 uint8_t *dmaBuf
= BigBuf_malloc(DMA_BUFFER_SIZE
);
600 iso14a_set_trigger(false);
607 // Count of samples received so far, so that we can include timing
608 // information in the trace buffer.
612 // Set up the demodulator for tag -> reader responses.
613 Demod
.output
= tagToReaderResponse
;
615 Demod
.state
= DEMOD_UNSYNCD
;
617 // Setup for the DMA.
618 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A
);
620 lastRxCounter
= DMA_BUFFER_SIZE
;
621 FpgaSetupSscDma((uint8_t *)dmaBuf
, DMA_BUFFER_SIZE
);
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
;
629 // And put the FPGA in the appropriate mode
630 // Signal field is off with the appropriate LED
632 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_SNIFFER
);
633 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
635 uint32_t time_0
= GetCountSspClk();
636 uint32_t time_start
= 0;
637 uint32_t time_stop
= 0;
644 // And now we loop, receiving samples.
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
);
656 if (behindBy
< 1) continue;
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
;
673 decbyte
^= (1 << (3 - div
));
676 // FOR READER SIDE COMMUMICATION...
679 decbyter
^= (smpl
& 0x30);
683 if ((div
+ 1) % 2 == 0) {
685 if (OutOfNDecoding((smpl
& 0xF0) >> 4)) {
686 rsamples
= samples
- Uart
.samples
;
687 time_stop
= (GetCountSspClk()-time_0
) << 4;
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);
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
;
704 time_start
= (GetCountSspClk()-time_0
) << 4;
711 if (ManchesterDecoding(smpl
& 0x0F)) {
712 time_stop
= (GetCountSspClk()-time_0
) << 4;
714 rsamples
= samples
- Demod
.samples
;
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);
721 // And ready to receive another response.
722 memset(&Demod
, 0, sizeof(Demod
));
723 Demod
.output
= tagToReaderResponse
;
724 Demod
.state
= DEMOD_UNSYNCD
;
727 time_start
= (GetCountSspClk()-time_0
) << 4;
734 if (BUTTON_PRESS()) {
735 DbpString("cancelled_a");
740 DbpString("COMMAND FINISHED");
742 Dbprintf("%x %x %x", maxBehindBy
, Uart
.state
, Uart
.byteCnt
);
743 Dbprintf("%x %x %x", Uart
.byteCntMax
, BigBuf_get_traceLen(), (int)Uart
.output
[0]);
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]);
752 void rotateCSN(uint8_t* originalCSN
, uint8_t* rotatedCSN
) {
754 for (i
= 0; i
< 8; i
++) {
755 rotatedCSN
[i
] = (originalCSN
[i
] >> 3) | (originalCSN
[(i
+1)%8] << 5);
760 static void CodeIClassTagSOF() {
761 //So far a dummy implementation, not used
762 //int lastProxToAirDuration =0;
766 ToSend
[++ToSendMax
] = 0x1D;
767 // lastProxToAirDuration = 8*ToSendMax - 3*8;//Not counting zeroes in the beginning
769 // Convert from last byte pos to length
773 static void AppendCrc(uint8_t *data
, int len
) {
774 ComputeCrc14443(CRC_ICLASS
, data
, len
, data
+len
, data
+len
+1);
779 * @brief Does the actual simulation
780 * @param csn - csn to use
781 * @param breakAfterMacReceived if true, returns after reader MAC has been received.
783 int doIClassSimulation(int simulationMode
, uint8_t *reader_mac_buf
) {
785 // free eventually allocated BigBuf memory
786 BigBuf_free_keep_EM();
790 uint8_t *emulator
= BigBuf_get_EM_addr();
791 uint8_t *csn
= emulator
;
792 uint8_t sof_data
[] = { 0x0F } ;
794 // CSN followed by two CRC bytes
795 uint8_t anticoll_data
[10] = { 0 };
796 uint8_t csn_data
[10] = { 0 };
797 memcpy(csn_data
, csn
, sizeof(csn_data
));
798 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]);
800 // Construct anticollision-CSN
801 rotateCSN(csn_data
, anticoll_data
);
803 // Compute CRC on both CSNs
804 AppendCrc(anticoll_data
, 8);
805 AppendCrc(csn_data
, 8);
807 uint8_t diversified_key
[8] = { 0 };
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 // The diversified key should be stored on block 3
813 // Get the diversified key from emulator memory
814 memcpy(diversified_key
, emulator
+ (8 * 3), 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 state, feeding it the CC
818 cipher_state
= opt_doTagMAC_1(card_challenge_data
, diversified_key
);
820 // save card challenge for sim2,4 attack
821 if (reader_mac_buf
!= NULL
) {
822 memcpy(reader_mac_buf
, card_challenge_data
, 8);
830 // Reader 81 anticoll. CSN
833 uint8_t *modulated_response
;
834 int modulated_response_size
= 0;
835 uint8_t *trace_data
= NULL
;
836 int trace_data_size
= 0;
838 // Respond SOF -- takes 1 bytes
839 uint8_t *resp_sof
= BigBuf_malloc(2);
842 // Anticollision CSN (rotated CSN)
843 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
844 uint8_t *resp_anticoll
= BigBuf_malloc(22);
845 int resp_anticoll_len
;
848 // 22: Takes 2 bytes for SOF/EOF and 10 * 2 = 20 bytes (2 bytes/byte)
849 uint8_t *resp_csn
= BigBuf_malloc(22);
852 // configuration (block 1) picopass 2ks
853 uint8_t *resp_conf
= BigBuf_malloc(22);
855 uint8_t conf_data
[10] = {0x12, 0xFF, 0xFF, 0xFF, 0x7F, 0x1F, 0xFF, 0x3C, 0x00, 0x00};
856 AppendCrc(conf_data
, 8);
859 // 18: Takes 2 bytes for SOF/EOF and 8 * 2 = 16 bytes (2 bytes/bit)
860 uint8_t *resp_cc
= BigBuf_malloc(18);
863 // Kd, Kc (blocks 3 and 4). Cannot be read. Always respond with 0xff bytes only
864 uint8_t *resp_ff
= BigBuf_malloc(22);
866 uint8_t ff_data
[10] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00};
867 AppendCrc(ff_data
, 8);
869 // Application Issuer Area (block 5)
870 uint8_t *resp_aia
= BigBuf_malloc(22);
872 uint8_t aia_data
[10] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00};
873 AppendCrc(aia_data
, 8);
875 uint8_t *receivedCmd
= BigBuf_malloc(MAX_FRAME_SIZE
);
878 // Prepare card messages
881 // First card answer: SOF only
883 memcpy(resp_sof
, ToSend
, ToSendMax
);
884 resp_sof_Len
= ToSendMax
;
887 CodeIso15693AsTag(anticoll_data
, sizeof(anticoll_data
));
888 memcpy(resp_anticoll
, ToSend
, ToSendMax
);
889 resp_anticoll_len
= ToSendMax
;
892 CodeIso15693AsTag(csn_data
, sizeof(csn_data
));
893 memcpy(resp_csn
, ToSend
, ToSendMax
);
894 resp_csn_len
= ToSendMax
;
896 // Configuration (block 1)
897 CodeIso15693AsTag(conf_data
, sizeof(conf_data
));
898 memcpy(resp_conf
, ToSend
, ToSendMax
);
899 resp_conf_len
= ToSendMax
;
902 CodeIso15693AsTag(card_challenge_data
, sizeof(card_challenge_data
));
903 memcpy(resp_cc
, ToSend
, ToSendMax
);
904 resp_cc_len
= ToSendMax
;
906 // Kd, Kc (blocks 3 and 4)
907 CodeIso15693AsTag(ff_data
, sizeof(ff_data
));
908 memcpy(resp_ff
, ToSend
, ToSendMax
);
909 resp_ff_len
= ToSendMax
;
911 // Application Issuer Area (block 5)
912 CodeIso15693AsTag(aia_data
, sizeof(aia_data
));
913 memcpy(resp_aia
, ToSend
, ToSendMax
);
914 resp_aia_len
= ToSendMax
;
916 //This is used for responding to READ-block commands or other data which is dynamically generated
917 uint8_t *data_generic_trace
= BigBuf_malloc(32 + 2); // 32 bytes data + 2byte CRC is max tag answer
918 uint8_t *data_response
= BigBuf_malloc( (32 + 2) * 2 + 2);
921 bool buttonPressed
= false;
926 // Can be used to get a trigger for an oscilloscope..
929 uint32_t reader_eof_time
= 0;
930 len
= GetIso15693CommandFromReader(receivedCmd
, MAX_FRAME_SIZE
, &reader_eof_time
);
932 buttonPressed
= true;
939 // Now look at the reader command and provide appropriate responses
940 // default is no response:
941 modulated_response
= NULL
;
942 modulated_response_size
= 0;
946 if (receivedCmd
[0] == ICLASS_CMD_ACTALL
) {
947 // Reader in anticollission phase
948 modulated_response
= resp_sof
;
949 modulated_response_size
= resp_sof_Len
;
950 trace_data
= sof_data
;
951 trace_data_size
= sizeof(sof_data
);
953 } else if (receivedCmd
[0] == ICLASS_CMD_READ_OR_IDENTIFY
&& len
== 1) { // identify
954 // Reader asks for anticollission CSN
955 modulated_response
= resp_anticoll
;
956 modulated_response_size
= resp_anticoll_len
;
957 trace_data
= anticoll_data
;
958 trace_data_size
= sizeof(anticoll_data
);
960 } else if (receivedCmd
[0] == ICLASS_CMD_READ_OR_IDENTIFY
&& len
== 4) { // read block
961 uint16_t blockNo
= receivedCmd
[1];
962 if (simulationMode
== ICLASS_SIM_MODE_EXIT_AFTER_MAC
) {
963 // provide defaults for blocks 0 ... 5
965 case 0: // csn (block 00)
966 modulated_response
= resp_csn
;
967 modulated_response_size
= resp_csn_len
;
968 trace_data
= csn_data
;
969 trace_data_size
= sizeof(csn_data
);
971 case 1: // configuration (block 01)
972 modulated_response
= resp_conf
;
973 modulated_response_size
= resp_conf_len
;
974 trace_data
= conf_data
;
975 trace_data_size
= sizeof(conf_data
);
977 case 2: // e-purse (block 02)
978 modulated_response
= resp_cc
;
979 modulated_response_size
= resp_cc_len
;
980 trace_data
= card_challenge_data
;
981 trace_data_size
= sizeof(card_challenge_data
);
982 // set epurse of sim2,4 attack
983 if (reader_mac_buf
!= NULL
) {
984 memcpy(reader_mac_buf
, card_challenge_data
, 8);
988 case 4: // Kd, Kd, always respond with 0xff bytes
989 modulated_response
= resp_ff
;
990 modulated_response_size
= resp_ff_len
;
991 trace_data
= ff_data
;
992 trace_data_size
= sizeof(ff_data
);
994 case 5: // Application Issuer Area (block 05)
995 modulated_response
= resp_aia
;
996 modulated_response_size
= resp_aia_len
;
997 trace_data
= aia_data
;
998 trace_data_size
= sizeof(aia_data
);
1000 // default: don't respond
1002 } else if (simulationMode
== ICLASS_SIM_MODE_FULL
) {
1003 if (blockNo
== 3 || blockNo
== 4) { // Kd, Kc, always respond with 0xff bytes
1004 modulated_response
= resp_ff
;
1005 modulated_response_size
= resp_ff_len
;
1006 trace_data
= ff_data
;
1007 trace_data_size
= sizeof(ff_data
);
1008 } else { // use data from emulator memory
1009 memcpy(data_generic_trace
, emulator
+ (receivedCmd
[1] << 3), 8);
1010 AppendCrc(data_generic_trace
, 8);
1011 trace_data
= data_generic_trace
;
1012 trace_data_size
= 10;
1013 CodeIso15693AsTag(trace_data
, trace_data_size
);
1014 memcpy(data_response
, ToSend
, ToSendMax
);
1015 modulated_response
= data_response
;
1016 modulated_response_size
= ToSendMax
;
1020 } else if (receivedCmd
[0] == ICLASS_CMD_SELECT
) {
1021 // Reader selects anticollission CSN.
1022 // Tag sends the corresponding real CSN
1023 modulated_response
= resp_csn
;
1024 modulated_response_size
= resp_csn_len
;
1025 trace_data
= csn_data
;
1026 trace_data_size
= sizeof(csn_data
);
1028 } else if (receivedCmd
[0] == ICLASS_CMD_READCHECK_KD
1029 || receivedCmd
[0] == ICLASS_CMD_READCHECK_KC
) {
1030 // Read e-purse (88 02 || 18 02)
1031 modulated_response
= resp_cc
;
1032 modulated_response_size
= resp_cc_len
;
1033 trace_data
= card_challenge_data
;
1034 trace_data_size
= sizeof(card_challenge_data
);
1037 } else if (receivedCmd
[0] == ICLASS_CMD_CHECK
) {
1038 // Reader random and reader MAC!!!
1039 if (simulationMode
== ICLASS_SIM_MODE_FULL
) {
1040 //NR, from reader, is in receivedCmd+1
1041 opt_doTagMAC_2(cipher_state
, receivedCmd
+1, data_generic_trace
, diversified_key
);
1042 trace_data
= data_generic_trace
;
1043 trace_data_size
= 4;
1044 CodeIso15693AsTag(trace_data
, trace_data_size
);
1045 memcpy(data_response
, ToSend
, ToSendMax
);
1046 modulated_response
= data_response
;
1047 modulated_response_size
= ToSendMax
;
1049 } else { // Not fullsim, we don't respond
1050 // We do not know what to answer, so lets keep quiet
1051 if (simulationMode
== ICLASS_SIM_MODE_EXIT_AFTER_MAC
) {
1052 if (reader_mac_buf
!= NULL
) {
1053 // save NR and MAC for sim 2,4
1054 memcpy(reader_mac_buf
+ 8, receivedCmd
+ 1, 8);
1060 } else if (receivedCmd
[0] == ICLASS_CMD_HALT
&& len
== 1) {
1061 // Reader ends the session
1062 modulated_response
= resp_sof
;
1063 modulated_response_size
= 0;
1065 trace_data_size
= 0;
1067 } else if (simulationMode
== ICLASS_SIM_MODE_FULL
&& receivedCmd
[0] == ICLASS_CMD_READ4
&& len
== 4) { // 0x06
1070 memcpy(data_generic_trace
, emulator
+ (receivedCmd
[1] << 3), 8 * 4);
1071 AppendCrc(data_generic_trace
, 8 * 4);
1072 trace_data
= data_generic_trace
;
1073 trace_data_size
= 8 * 4 + 2;
1074 CodeIso15693AsTag(trace_data
, trace_data_size
);
1075 memcpy(data_response
, ToSend
, ToSendMax
);
1076 modulated_response
= data_response
;
1077 modulated_response_size
= ToSendMax
;
1079 } else if (receivedCmd
[0] == ICLASS_CMD_UPDATE
&& simulationMode
== ICLASS_SIM_MODE_FULL
) {
1080 // Probably the reader wants to update the nonce. Let's just ignore that for now.
1081 // OBS! If this is implemented, don't forget to regenerate the cipher_state
1082 // We're expected to respond with the data+crc, exactly what's already in the receivedCmd
1083 // receivedCmd is now UPDATE 1b | ADDRESS 1b | DATA 8b | Signature 4b or CRC 2b
1084 memcpy(data_generic_trace
, receivedCmd
+ 2, 8);
1085 AppendCrc(data_generic_trace
, 8);
1086 trace_data
= data_generic_trace
;
1087 trace_data_size
= 10;
1088 CodeIso15693AsTag(trace_data
, trace_data_size
);
1089 memcpy(data_response
, ToSend
, ToSendMax
);
1090 modulated_response
= data_response
;
1091 modulated_response_size
= ToSendMax
;
1093 } else if (receivedCmd
[0] == ICLASS_CMD_PAGESEL
) {
1095 // Pagesel enables to select a page in the selected chip memory and return its configuration block
1096 // Chips with a single page will not answer to this command
1097 // It appears we're fine ignoring this.
1098 // Otherwise, we should answer 8bytes (block) + 2bytes CRC
1101 // Never seen this command before
1102 char debug_message
[250]; // should be enough
1103 sprintf(debug_message
, "Unhandled command (len = %d) received from reader:", len
);
1104 for (int i
= 0; i
< len
&& strlen(debug_message
) < sizeof(debug_message
) - 3 - 1; i
++) {
1105 sprintf(debug_message
+ strlen(debug_message
), " %02x", receivedCmd
[i
]);
1107 Dbprintf("%s", debug_message
);
1112 A legit tag has about 311,5us delay between reader EOT and tag SOF.
1114 if (modulated_response_size
> 0) {
1115 uint32_t response_time
= reader_eof_time
+ DELAY_ISO15693_VCD_TO_VICC_SIM
- DELAY_ARM_TO_READER_SIM
;
1116 TransmitTo15693Reader(modulated_response
, modulated_response_size
, response_time
, false);
1117 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);
1128 DbpString("Button pressed");
1130 return buttonPressed
;
1134 * @brief SimulateIClass simulates an iClass card.
1135 * @param arg0 type of simulation
1136 * - 0 uses the first 8 bytes in usb data as CSN
1137 * - 2 "dismantling iclass"-attack. This mode iterates through all CSN's specified
1138 * in the usb data. This mode collects MAC from the reader, in order to do an offline
1139 * attack on the keys. For more info, see "dismantling iclass" and proxclone.com.
1140 * - Other : Uses the default CSN (031fec8af7ff12e0)
1141 * @param arg1 - number of CSN's contained in datain (applicable for mode 2 only)
1145 void SimulateIClass(uint32_t arg0
, uint32_t arg1
, uint32_t arg2
, uint8_t *datain
) {
1146 uint32_t simType
= arg0
;
1147 uint32_t numberOfCSNS
= arg1
;
1149 // setup hardware for simulation:
1150 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1151 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1152 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR
| FPGA_HF_SIMULATOR_NO_MODULATION
);
1153 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR
);
1156 // Enable and clear the trace
1159 //Use the emulator memory for SIM
1160 uint8_t *emulator
= BigBuf_get_EM_addr();
1162 if (simType
== ICLASS_SIM_MODE_CSN
) {
1163 // Use the CSN from commandline
1164 memcpy(emulator
, datain
, 8);
1165 doIClassSimulation(ICLASS_SIM_MODE_CSN
, NULL
);
1166 } else if (simType
== ICLASS_SIM_MODE_CSN_DEFAULT
) {
1168 uint8_t csn_crc
[] = { 0x03, 0x1f, 0xec, 0x8a, 0xf7, 0xff, 0x12, 0xe0, 0x00, 0x00 };
1169 // Use the CSN from commandline
1170 memcpy(emulator
, csn_crc
, 8);
1171 doIClassSimulation(ICLASS_SIM_MODE_CSN
, NULL
);
1172 } else if (simType
== ICLASS_SIM_MODE_READER_ATTACK
) {
1173 uint8_t mac_responses
[USB_CMD_DATA_SIZE
] = { 0 };
1174 Dbprintf("Going into attack mode, %d CSNS sent", numberOfCSNS
);
1175 // In this mode, a number of csns are within datain. We'll simulate each one, one at a time
1176 // in order to collect MAC's from the reader. This can later be used in an offline-attack
1177 // in order to obtain the keys, as in the "dismantling iclass"-paper.
1179 for (i
= 0; i
< numberOfCSNS
&& i
*16+16 <= USB_CMD_DATA_SIZE
; i
++) {
1180 // The usb data is 512 bytes, fitting 32 responses (8 byte CC + 4 Byte NR + 4 Byte MAC = 16 Byte response).
1181 memcpy(emulator
, datain
+(i
*8), 8);
1182 if (doIClassSimulation(ICLASS_SIM_MODE_EXIT_AFTER_MAC
, mac_responses
+i
*16)) {
1186 Dbprintf("CSN: %02x %02x %02x %02x %02x %02x %02x %02x",
1187 datain
[i
*8+0], datain
[i
*8+1], datain
[i
*8+2], datain
[i
*8+3],
1188 datain
[i
*8+4], datain
[i
*8+5], datain
[i
*8+6], datain
[i
*8+7]);
1189 Dbprintf("NR,MAC: %02x %02x %02x %02x %02x %02x %02x %02x",
1190 datain
[i
*8+ 8], datain
[i
*8+ 9], datain
[i
*8+10], datain
[i
*8+11],
1191 datain
[i
*8+12], datain
[i
*8+13], datain
[i
*8+14], datain
[i
*8+15]);
1193 cmd_send(CMD_ACK
, CMD_SIMULATE_TAG_ICLASS
, i
, 0, mac_responses
, i
*16);
1194 } else if (simType
== ICLASS_SIM_MODE_FULL
) {
1195 //This is 'full sim' mode, where we use the emulator storage for data.
1196 doIClassSimulation(ICLASS_SIM_MODE_FULL
, NULL
);
1198 // We may want a mode here where we hardcode the csns to use (from proxclone).
1199 // That will speed things up a little, but not required just yet.
1200 Dbprintf("The mode is not implemented, reserved for future use");
1202 Dbprintf("Done...");
1209 //-----------------------------------------------------------------------------
1210 // Transmit the command (to the tag) that was placed in ToSend[].
1211 //-----------------------------------------------------------------------------
1212 static void TransmitIClassCommand(const uint8_t *cmd
, int len
, int *samples
, int *wait
) {
1214 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1215 AT91C_BASE_SSC
->SSC_THR
= 0x00;
1216 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A
);
1219 if (*wait
< 10) *wait
= 10;
1221 for (c
= 0; c
< *wait
;) {
1222 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1223 AT91C_BASE_SSC
->SSC_THR
= 0x00; // For exact timing!
1226 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1227 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1235 bool firstpart
= true;
1238 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1240 // DOUBLE THE SAMPLES!
1242 sendbyte
= (cmd
[c
] & 0xf0) | (cmd
[c
] >> 4);
1244 sendbyte
= (cmd
[c
] & 0x0f) | (cmd
[c
] << 4);
1247 if (sendbyte
== 0xff) {
1250 AT91C_BASE_SSC
->SSC_THR
= sendbyte
;
1251 firstpart
= !firstpart
;
1257 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1258 volatile uint32_t r
= AT91C_BASE_SSC
->SSC_RHR
;
1263 if (samples
&& wait
) *samples
= (c
+ *wait
) << 3;
1267 //-----------------------------------------------------------------------------
1268 // Prepare iClass reader command to send to FPGA
1269 //-----------------------------------------------------------------------------
1270 void CodeIClassCommand(const uint8_t *cmd
, int len
) {
1275 // Start of Communication: 1 out of 4
1276 ToSend
[++ToSendMax
] = 0xf0;
1277 ToSend
[++ToSendMax
] = 0x00;
1278 ToSend
[++ToSendMax
] = 0x0f;
1279 ToSend
[++ToSendMax
] = 0x00;
1281 // Modulate the bytes
1282 for (i
= 0; i
< len
; i
++) {
1284 for (j
= 0; j
< 4; j
++) {
1285 for (k
= 0; k
< 4; k
++) {
1287 ToSend
[++ToSendMax
] = 0xf0;
1289 ToSend
[++ToSendMax
] = 0x00;
1296 // End of Communication
1297 ToSend
[++ToSendMax
] = 0x00;
1298 ToSend
[++ToSendMax
] = 0x00;
1299 ToSend
[++ToSendMax
] = 0xf0;
1300 ToSend
[++ToSendMax
] = 0x00;
1302 // Convert from last character reference to length
1306 static void ReaderTransmitIClass(uint8_t *frame
, int len
) {
1310 // This is tied to other size changes
1311 CodeIClassCommand(frame
, len
);
1314 TransmitIClassCommand(ToSend
, ToSendMax
, &samples
, &wait
);
1318 // Store reader command in buffer
1319 uint8_t par
[MAX_PARITY_SIZE
];
1320 GetParity(frame
, len
, par
);
1321 LogTrace(frame
, len
, rsamples
, rsamples
, par
, true);
1324 //-----------------------------------------------------------------------------
1325 // Wait a certain time for tag response
1326 // If a response is captured return true
1327 // If it takes too long return false
1328 //-----------------------------------------------------------------------------
1329 static int GetIClassAnswer(uint8_t *receivedResponse
, int maxLen
, int *samples
, int *elapsed
) {
1331 // buffer needs to be 512 bytes
1334 // Set FPGA mode to "reader listen mode", no modulation (listen
1335 // only, since we are receiving, not transmitting).
1336 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_LISTEN
);
1338 // Now get the answer from the card
1339 Demod
.output
= receivedResponse
;
1341 Demod
.state
= DEMOD_UNSYNCD
;
1344 if (elapsed
) *elapsed
= 0;
1352 if (BUTTON_PRESS()) return false;
1354 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_TXRDY
)) {
1355 AT91C_BASE_SSC
->SSC_THR
= 0x00; // To make use of exact timing of next command from reader!!
1356 if (elapsed
) (*elapsed
)++;
1358 if (AT91C_BASE_SSC
->SSC_SR
& (AT91C_SSC_RXRDY
)) {
1364 b
= (uint8_t)AT91C_BASE_SSC
->SSC_RHR
;
1368 if (ManchesterDecoding(b
& 0x0f)) {
1376 static int ReaderReceiveIClass(uint8_t *receivedAnswer
) {
1378 if (!GetIClassAnswer(receivedAnswer
, 160, &samples
, 0)) {
1381 rsamples
+= samples
;
1382 uint8_t parity
[MAX_PARITY_SIZE
];
1383 GetParity(receivedAnswer
, Demod
.len
, parity
);
1384 LogTrace(receivedAnswer
, Demod
.len
, rsamples
, rsamples
, parity
, false);
1385 if (samples
== 0) return false;
1389 static void setupIclassReader() {
1390 FpgaDownloadAndGo(FPGA_BITSTREAM_HF
);
1391 // Reset trace buffer
1396 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_ISO14443A
);
1397 // Start from off (no field generated)
1398 // Signal field is off with the appropriate LED
1400 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1403 SetAdcMuxFor(GPIO_MUXSEL_HIPKD
);
1405 // Now give it time to spin up.
1406 // Signal field is on with the appropriate LED
1407 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_ISO14443A
| FPGA_HF_ISO14443A_READER_MOD
);
1413 static bool sendCmdGetResponseWithRetries(uint8_t* command
, size_t cmdsize
, uint8_t* resp
, uint8_t expected_size
, uint8_t retries
) {
1414 while (retries
-- > 0) {
1415 ReaderTransmitIClass(command
, cmdsize
);
1416 if (expected_size
== ReaderReceiveIClass(resp
)) {
1420 return false;//Error
1424 * @brief Talks to an iclass tag, sends the commands to get CSN and CC.
1425 * @param card_data where the CSN and CC are stored for return
1428 * 2 = Got CSN and CC
1430 static uint8_t handshakeIclassTag_ext(uint8_t *card_data
, bool use_credit_key
) {
1431 static uint8_t act_all
[] = { 0x0a };
1432 //static uint8_t identify[] = { 0x0c };
1433 static uint8_t identify
[] = { 0x0c, 0x00, 0x73, 0x33 };
1434 static uint8_t select
[] = { 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1435 static uint8_t readcheck_cc
[]= { 0x88, 0x02 };
1437 readcheck_cc
[0] = 0x18;
1439 readcheck_cc
[0] = 0x88;
1441 uint8_t resp
[ICLASS_BUFFER_SIZE
];
1443 uint8_t read_status
= 0;
1446 ReaderTransmitIClass(act_all
, 1);
1448 if (!ReaderReceiveIClass(resp
)) return read_status
;//Fail
1450 ReaderTransmitIClass(identify
, 1);
1451 //We expect a 10-byte response here, 8 byte anticollision-CSN and 2 byte CRC
1452 uint8_t len
= ReaderReceiveIClass(resp
);
1453 if (len
!= 10) return read_status
;//Fail
1455 //Copy the Anti-collision CSN to our select-packet
1456 memcpy(&select
[1], resp
, 8);
1458 ReaderTransmitIClass(select
, sizeof(select
));
1459 //We expect a 10-byte response here, 8 byte CSN and 2 byte CRC
1460 len
= ReaderReceiveIClass(resp
);
1461 if (len
!= 10) return read_status
;//Fail
1463 //Success - level 1, we got CSN
1464 //Save CSN in response data
1465 memcpy(card_data
, resp
, 8);
1467 //Flag that we got to at least stage 1, read CSN
1470 // Card selected, now read e-purse (cc) (only 8 bytes no CRC)
1471 ReaderTransmitIClass(readcheck_cc
, sizeof(readcheck_cc
));
1472 if (ReaderReceiveIClass(resp
) == 8) {
1473 //Save CC (e-purse) in response data
1474 memcpy(card_data
+8, resp
, 8);
1481 static uint8_t handshakeIclassTag(uint8_t *card_data
) {
1482 return handshakeIclassTag_ext(card_data
, false);
1486 // Reader iClass Anticollission
1487 void ReaderIClass(uint8_t arg0
) {
1489 uint8_t card_data
[6 * 8] = {0};
1490 memset(card_data
, 0xFF, sizeof(card_data
));
1491 uint8_t last_csn
[8] = {0,0,0,0,0,0,0,0};
1492 uint8_t resp
[ICLASS_BUFFER_SIZE
];
1493 memset(resp
, 0xFF, sizeof(resp
));
1494 //Read conf block CRC(0x01) => 0xfa 0x22
1495 uint8_t readConf
[] = { ICLASS_CMD_READ_OR_IDENTIFY
, 0x01, 0xfa, 0x22};
1496 //Read App Issuer Area block CRC(0x05) => 0xde 0x64
1497 uint8_t readAA
[] = { ICLASS_CMD_READ_OR_IDENTIFY
, 0x05, 0xde, 0x64};
1500 uint8_t result_status
= 0;
1501 // flag to read until one tag is found successfully
1502 bool abort_after_read
= arg0
& FLAG_ICLASS_READER_ONLY_ONCE
;
1503 // flag to only try 5 times to find one tag then return
1504 bool try_once
= arg0
& FLAG_ICLASS_READER_ONE_TRY
;
1505 // if neither abort_after_read nor try_once then continue reading until button pressed.
1507 bool use_credit_key
= arg0
& FLAG_ICLASS_READER_CEDITKEY
;
1508 // test flags for what blocks to be sure to read
1509 uint8_t flagReadConfig
= arg0
& FLAG_ICLASS_READER_CONF
;
1510 uint8_t flagReadCC
= arg0
& FLAG_ICLASS_READER_CC
;
1511 uint8_t flagReadAA
= arg0
& FLAG_ICLASS_READER_AA
;
1514 setupIclassReader();
1516 uint16_t tryCnt
= 0;
1517 bool userCancelled
= BUTTON_PRESS() || usb_poll_validate_length();
1518 while (!userCancelled
) {
1519 // if only looking for one card try 2 times if we missed it the first time
1520 if (try_once
&& tryCnt
> 2) {
1524 if (!get_tracing()) {
1525 DbpString("Trace full");
1530 read_status
= handshakeIclassTag_ext(card_data
, use_credit_key
);
1532 if (read_status
== 0) continue;
1533 if (read_status
== 1) result_status
= FLAG_ICLASS_READER_CSN
;
1534 if (read_status
== 2) result_status
= FLAG_ICLASS_READER_CSN
| FLAG_ICLASS_READER_CC
;
1536 // handshakeIclass returns CSN|CC, but the actual block
1537 // layout is CSN|CONFIG|CC, so here we reorder the data,
1538 // moving CC forward 8 bytes
1539 memcpy(card_data
+16, card_data
+8, 8);
1540 //Read block 1, config
1541 if (flagReadConfig
) {
1542 if (sendCmdGetResponseWithRetries(readConf
, sizeof(readConf
), resp
, 10, 10)) {
1543 result_status
|= FLAG_ICLASS_READER_CONF
;
1544 memcpy(card_data
+8, resp
, 8);
1546 Dbprintf("Failed to dump config block");
1552 if (sendCmdGetResponseWithRetries(readAA
, sizeof(readAA
), resp
, 10, 10)) {
1553 result_status
|= FLAG_ICLASS_READER_AA
;
1554 memcpy(card_data
+ (8*5), resp
, 8);
1556 //Dbprintf("Failed to dump AA block");
1561 // 1 : Configuration
1563 // 3 : kd / debit / aa2 (write-only)
1564 // 4 : kc / credit / aa1 (write-only)
1565 // 5 : AIA, Application issuer area
1566 //Then we can 'ship' back the 6 * 8 bytes of data,
1567 // with 0xFF:s in block 3 and 4.
1570 //Send back to client, but don't bother if we already sent this -
1571 // only useful if looping in arm (not try_once && not abort_after_read)
1572 if (memcmp(last_csn
, card_data
, 8) != 0) {
1573 // If caller requires that we get Conf, CC, AA, continue until we got it
1574 if ( (result_status
^ FLAG_ICLASS_READER_CSN
^ flagReadConfig
^ flagReadCC
^ flagReadAA
) == 0) {
1575 cmd_send(CMD_ACK
, result_status
, 0, 0, card_data
, sizeof(card_data
));
1576 if (abort_after_read
) {
1581 //Save that we already sent this....
1582 memcpy(last_csn
, card_data
, 8);
1587 userCancelled
= BUTTON_PRESS() || usb_poll_validate_length();
1589 if (userCancelled
) {
1590 cmd_send(CMD_ACK
, 0xFF, 0, 0, card_data
, 0);
1592 cmd_send(CMD_ACK
, 0, 0, 0, card_data
, 0);
1597 void ReaderIClass_Replay(uint8_t arg0
, uint8_t *MAC
) {
1599 uint8_t card_data
[USB_CMD_DATA_SIZE
]={0};
1600 uint16_t block_crc_LUT
[255] = {0};
1602 //Generate a lookup table for block crc
1603 for (int block
= 0; block
< 255; block
++){
1605 block_crc_LUT
[block
] = iclass_crc16(&bl
,1);
1607 //Dbprintf("Lookup table: %02x %02x %02x" ,block_crc_LUT[0],block_crc_LUT[1],block_crc_LUT[2]);
1609 uint8_t check
[] = { 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1610 uint8_t read
[] = { 0x0c, 0x00, 0x00, 0x00 };
1613 uint8_t cardsize
= 0;
1616 static struct memory_t
{
1624 uint8_t resp
[ICLASS_BUFFER_SIZE
];
1626 setupIclassReader();
1629 while (!BUTTON_PRESS()) {
1633 if (!get_tracing()) {
1634 DbpString("Trace full");
1638 uint8_t read_status
= handshakeIclassTag(card_data
);
1639 if (read_status
< 2) continue;
1641 //for now replay captured auth (as cc not updated)
1642 memcpy(check
+5, MAC
, 4);
1644 if (!sendCmdGetResponseWithRetries(check
, sizeof(check
), resp
, 4, 5)) {
1645 Dbprintf("Error: Authentication Fail!");
1649 //first get configuration block (block 1)
1650 crc
= block_crc_LUT
[1];
1653 read
[3] = crc
& 0xff;
1655 if (!sendCmdGetResponseWithRetries(read
, sizeof(read
),resp
, 10, 10)) {
1656 Dbprintf("Dump config (block 1) failed");
1661 memory
.k16
= (mem
& 0x80);
1662 memory
.book
= (mem
& 0x20);
1663 memory
.k2
= (mem
& 0x8);
1664 memory
.lockauth
= (mem
& 0x2);
1665 memory
.keyaccess
= (mem
& 0x1);
1667 cardsize
= memory
.k16
? 255 : 32;
1669 //Set card_data to all zeroes, we'll fill it with data
1670 memset(card_data
, 0x0, USB_CMD_DATA_SIZE
);
1671 uint8_t failedRead
= 0;
1672 uint32_t stored_data_length
= 0;
1673 //then loop around remaining blocks
1674 for (int block
= 0; block
< cardsize
; block
++) {
1676 crc
= block_crc_LUT
[block
];
1678 read
[3] = crc
& 0xff;
1680 if (sendCmdGetResponseWithRetries(read
, sizeof(read
), resp
, 10, 10)) {
1681 Dbprintf(" %02x: %02x %02x %02x %02x %02x %02x %02x %02x",
1682 block
, resp
[0], resp
[1], resp
[2],
1683 resp
[3], resp
[4], resp
[5],
1686 //Fill up the buffer
1687 memcpy(card_data
+stored_data_length
, resp
, 8);
1688 stored_data_length
+= 8;
1689 if (stored_data_length
+8 > USB_CMD_DATA_SIZE
) {
1690 //Time to send this off and start afresh
1692 stored_data_length
,//data length
1693 failedRead
,//Failed blocks?
1695 card_data
, stored_data_length
);
1697 stored_data_length
= 0;
1703 stored_data_length
+= 8;//Otherwise, data becomes misaligned
1704 Dbprintf("Failed to dump block %d", block
);
1708 //Send off any remaining data
1709 if (stored_data_length
> 0) {
1711 stored_data_length
,//data length
1712 failedRead
,//Failed blocks?
1715 stored_data_length
);
1717 //If we got here, let's break
1720 //Signal end of transmission
1731 void iClass_ReadCheck(uint8_t blockNo
, uint8_t keyType
) {
1732 uint8_t readcheck
[] = { keyType
, blockNo
};
1733 uint8_t resp
[] = {0,0,0,0,0,0,0,0};
1735 isOK
= sendCmdGetResponseWithRetries(readcheck
, sizeof(readcheck
), resp
, sizeof(resp
), 6);
1736 cmd_send(CMD_ACK
,isOK
, 0, 0, 0, 0);
1739 void iClass_Authentication(uint8_t *MAC
) {
1740 uint8_t check
[] = { ICLASS_CMD_CHECK
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1741 uint8_t resp
[ICLASS_BUFFER_SIZE
];
1742 memcpy(check
+5, MAC
, 4);
1744 isOK
= sendCmdGetResponseWithRetries(check
, sizeof(check
), resp
, 4, 6);
1745 cmd_send(CMD_ACK
,isOK
, 0, 0, 0, 0);
1748 bool iClass_ReadBlock(uint8_t blockNo
, uint8_t *readdata
) {
1749 uint8_t readcmd
[] = {ICLASS_CMD_READ_OR_IDENTIFY
, blockNo
, 0x00, 0x00}; //0x88, 0x00 // can i use 0C?
1751 uint16_t rdCrc
= iclass_crc16(&bl
, 1);
1752 readcmd
[2] = rdCrc
>> 8;
1753 readcmd
[3] = rdCrc
& 0xff;
1754 uint8_t resp
[] = {0,0,0,0,0,0,0,0,0,0};
1757 //readcmd[1] = blockNo;
1758 isOK
= sendCmdGetResponseWithRetries(readcmd
, sizeof(readcmd
), resp
, 10, 10);
1759 memcpy(readdata
, resp
, sizeof(resp
));
1764 void iClass_ReadBlk(uint8_t blockno
) {
1765 uint8_t readblockdata
[] = {0,0,0,0,0,0,0,0,0,0};
1767 isOK
= iClass_ReadBlock(blockno
, readblockdata
);
1768 cmd_send(CMD_ACK
, isOK
, 0, 0, readblockdata
, 8);
1771 void iClass_Dump(uint8_t blockno
, uint8_t numblks
) {
1772 uint8_t readblockdata
[] = {0,0,0,0,0,0,0,0,0,0};
1777 uint8_t *dataout
= BigBuf_malloc(255*8);
1778 if (dataout
== NULL
) {
1779 Dbprintf("out of memory");
1780 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1782 cmd_send(CMD_ACK
, 0, 1, 0, 0, 0);
1786 memset(dataout
, 0xFF, 255*8);
1788 for ( ; blkCnt
< numblks
; blkCnt
++) {
1789 isOK
= iClass_ReadBlock(blockno
+blkCnt
, readblockdata
);
1790 if (!isOK
|| (readblockdata
[0] == 0xBB || readblockdata
[7] == 0xBB || readblockdata
[2] == 0xBB)) { //try again
1791 isOK
= iClass_ReadBlock(blockno
+blkCnt
, readblockdata
);
1793 Dbprintf("Block %02X failed to read", blkCnt
+blockno
);
1797 memcpy(dataout
+ (blkCnt
*8), readblockdata
, 8);
1799 //return pointer to dump memory in arg3
1800 cmd_send(CMD_ACK
, isOK
, blkCnt
, BigBuf_max_traceLen(), 0, 0);
1801 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);
1806 static bool iClass_WriteBlock_ext(uint8_t blockNo
, uint8_t *data
) {
1807 uint8_t write
[] = { ICLASS_CMD_UPDATE
, blockNo
, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
1808 //uint8_t readblockdata[10];
1809 //write[1] = blockNo;
1810 memcpy(write
+2, data
, 12); // data + mac
1811 char *wrCmd
= (char *)(write
+1);
1812 uint16_t wrCrc
= iclass_crc16(wrCmd
, 13);
1813 write
[14] = wrCrc
>> 8;
1814 write
[15] = wrCrc
& 0xff;
1815 uint8_t resp
[] = {0,0,0,0,0,0,0,0,0,0};
1818 isOK
= sendCmdGetResponseWithRetries(write
, sizeof(write
), resp
, sizeof(resp
), 10);
1819 if (isOK
) { //if reader responded correctly
1820 //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]);
1821 if (memcmp(write
+2, resp
, 8)) { //if response is not equal to write values
1822 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)
1824 isOK
= sendCmdGetResponseWithRetries(write
, sizeof(write
), resp
, sizeof(resp
), 10);
1831 void iClass_WriteBlock(uint8_t blockNo
, uint8_t *data
) {
1832 bool isOK
= iClass_WriteBlock_ext(blockNo
, data
);
1834 Dbprintf("Write block [%02x] successful", blockNo
);
1836 Dbprintf("Write block [%02x] failed", blockNo
);
1838 cmd_send(CMD_ACK
, isOK
, 0, 0, 0, 0);
1841 void iClass_Clone(uint8_t startblock
, uint8_t endblock
, uint8_t *data
) {
1844 int total_block
= (endblock
- startblock
) + 1;
1845 for (i
= 0; i
< total_block
; i
++) {
1847 if (iClass_WriteBlock_ext(i
+startblock
, data
+ (i
*12))){
1848 Dbprintf("Write block [%02x] successful", i
+ startblock
);
1851 if (iClass_WriteBlock_ext(i
+startblock
, data
+ (i
*12))){
1852 Dbprintf("Write block [%02x] successful", i
+ startblock
);
1855 Dbprintf("Write block [%02x] failed", i
+ startblock
);
1859 if (written
== total_block
)
1860 Dbprintf("Clone complete");
1862 Dbprintf("Clone incomplete");
1864 cmd_send(CMD_ACK
, 1, 0, 0, 0, 0);
1865 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF
);