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